From 40eadc995e5ca6a909064dddc255e30630bea81f Mon Sep 17 00:00:00 2001 From: Prad Nukala Date: Fri, 10 Oct 2025 11:47:18 -0400 Subject: [PATCH] Feat/1285 es ucan formatting (#1302) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add Enclave Usage Examples * feat(es/ucan): Add comprehensive integration tests - Create integration.test.ts with full UCAN token lifecycle testing - Cover end-to-end token creation, parsing, and validation - Test capability attenuation and delegation chains - Validate multi-algorithm support and timestamp scenarios - Implement error recovery and performance test scenarios 🤖 Generated with Claude Code Co-Authored-By: Claude * No commit suggestions generated * No commit suggestions generated * chore: Remove migrated components and add migration documentation Removed all code and references for components that have been moved to separate repositories: **Moved to sonr-io/hway:** - bridge/ - HTTP service with OAuth2/OIDC/WebAuthn handlers - cmd/hway/ - Highway service binary - internal/migrations/ - PostgreSQL schema migrations **Moved to sonr-io/motr:** - cmd/motr/ - Motor worker service (WASM vault operations) - cmd/vault/ - Vault CLI tool - crypto/ - Comprehensive cryptographic library - packages/ - TypeScript SDK packages (es, sdk, ui, com, pkl) - web/auth/ - Authentication web application - web/dash/ - Dashboard web application **Updated Configuration:** - Makefile: Removed build/test/release targets for moved components - CLAUDE.md: Simplified to focus on core blockchain components - devbox.json: Removed scripts for moved services - docker-compose.yml: Removed hway, postgres, redis, auth, dash services - .github/scopes.yml: Removed CI scopes for migrated components - .goreleaser.yml: Updated release configuration **Added Migration Documentation:** - MIGRATE_HWAY.md: Comprehensive Highway service architecture and migration guide - MIGRATE_MOTR.md: Comprehensive Motor/Worker/Vault architecture and migration guide These migration documents provide complete context for setting up the new repositories including architecture diagrams, component breakdowns, API documentation, and migration checklists. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * No commit suggestions generated * chore: Remove contracts references and documentation Removed all references to the contracts directory that was migrated to a separate repository. **Changes:** - .gitignore: Removed contract-specific ignore patterns for DAO and wSNR contracts - .gitignore: Removed hway and motr binary references (already migrated) - .rgignore: Removed contracts, chains, and crypto directory references - docs/reference/contracts/: Removed DAO.mdx and wSNR.mdx documentation files This completes the cleanup of migrated components from the repository. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * docs: add crypto library migration documentation Added comprehensive migration documentation for the crypto library that was moved to sonr-io/crypto repository. This documentation provides complete context for understanding the cryptographic primitives and protocols used throughout the Sonr ecosystem. ## Key Documentation Added ### MIGRATE_CRYPTO.md Complete documentation of the crypto library covering: **Core Cryptographic Primitives** - Elliptic curve implementations (Ed25519, Secp256k1, P-256, BLS12-381, Pallas/Vesta) - Native curve arithmetic with optimized field operations - Pairing-friendly curves for BLS signatures **Multi-Party Computation (MPC)** - MPC enclave for vault key generation and management - Threshold cryptography (TECDSA, TED25519 with FROST protocol) - Distributed Key Generation (DKG) via Gennaro and FROST protocols - Secret sharing schemes (Shamir, Feldman VSS, Pedersen VSS) **Digital Signature Schemes** - BLS signatures with aggregation support - BBS+ signatures for selective disclosure - Schnorr signatures (standard and Mina/NEM variants) - ECDSA with deterministic nonce generation **Zero-Knowledge Proofs** - Bulletproofs for range proofs - Inner Product Arguments (IPA) - Batch verification support **Advanced Cryptographic Protocols** - Cryptographic accumulators for set membership proofs - Paillier homomorphic encryption - Oblivious Transfer (OT) protocols - Verifiable Random Functions (VRF) **Key Management & Identity** - DID key management with multi-chain support - Multi-algorithm public key handling - Wallet address derivation (Bitcoin, Ethereum, Cosmos, Solana, etc.) **UCAN Integration** - User-Controlled Authorization Networks - Capability delegation and attenuation - JWT-based capability tokens - MPC-enabled UCAN signing **Security Utilities** - AEAD encryption (AES-GCM, AES-SIV) - Argon2 key derivation - ECIES encryption - Secure memory handling ### MIGRATE_MOTR.md Updates Updated Motor migration documentation to clarify that the crypto library is now a separate external dependency at github.com/sonr-io/crypto v1.0.1 ## Repository Context The crypto library has been successfully migrated to its own repository and is published as a Go module. It serves as the foundational cryptographic layer for: - Sonr blockchain (snrd) - DID signatures, vault operations - Highway service (hway) - UCAN token signing, WebAuthn - Motor/Worker (motr) - MPC vault operations, threshold signatures ## Integration Impact All Sonr ecosystem components now depend on the external crypto library: ```go require github.com/sonr-io/crypto v1.0.1 ``` The migration enables independent versioning and maintenance of cryptographic primitives while maintaining security and compatibility across the ecosystem. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * No commit suggestions generated * No commit suggestions generated * No commit suggestions generated --------- Co-authored-by: Claude --- cmd/snrd/.cz.toml => .cz.toml | 0 .github/scopes.yml | 41 +- .gitignore | 19 - .goreleaser.yml | 328 +- .rgignore | 3 - MIGRATE_CRYPTO.md | 847 + MIGRATE_HWAY.md | 435 + MIGRATE_MOTR.md | 653 + Makefile | 95 +- app/ante/ucan_decorator.go | 4 +- app/ante/ucan_decorator_test.go | 2 +- app/commands/enhance_init.go | 2 +- app/commands/keys_vrf.go | 2 +- app/context/context.go | 2 +- app/context/context_test.go | 2 +- biome.json | 103 - bridge/bridge.go | 118 - bridge/bridge_test.go | 31 - bridge/config.go | 202 - bridge/handlers/auth.go | 265 - bridge/handlers/benchmark_test.go | 60 - bridge/handlers/broadcast.go | 333 - bridge/handlers/errors.go | 33 - bridge/handlers/handlers_test.go | 27 - bridge/handlers/health.go | 201 - bridge/handlers/oauth2_clients.go | 422 - bridge/handlers/oauth2_delegation.go | 323 - bridge/handlers/oauth2_provider.go | 923 - bridge/handlers/oauth2_refresh.go | 563 - bridge/handlers/oauth2_register.go | 383 - bridge/handlers/oauth2_scopes.go | 412 - bridge/handlers/oauth2_security.go | 449 - bridge/handlers/oauth2_token_exchange.go | 650 - bridge/handlers/oauth2_types.go | 269 - bridge/handlers/oidc.go | 466 - bridge/handlers/oidc_test.go | 360 - bridge/handlers/siop.go | 384 - bridge/handlers/siop_test.go | 353 - bridge/handlers/types.go | 265 - bridge/handlers/ucan_signer.go | 602 - bridge/handlers/vault.go | 535 - bridge/handlers/webauthn.go | 558 - bridge/handlers/websocket.go | 284 - bridge/queue.go | 62 - bridge/server/benchmark_test.go | 223 - bridge/server/server.go | 118 - bridge/server/server_test.go | 110 - bridge/tasks/attenuation.go | 156 - bridge/tasks/generate.go | 96 - bridge/tasks/signing.go | 149 - bridge/tasks/tasks_test.go | 425 - bridge/tasks/types.go | 22 - bridge/testutils_test.go | 101 - client/auth/webauthn.go | 6 +- client/go.mod | 4 +- cmd/hway/.cz.toml | 18 - cmd/hway/.goreleaser.yml | 293 - cmd/hway/CHANGELOG.md | 5 - cmd/hway/Dockerfile | 77 - cmd/hway/Makefile | 110 - cmd/hway/README.md | Bin 8814 -> 0 bytes cmd/hway/go.mod | 312 - cmd/hway/go.sum | 1382 -- cmd/hway/main.go | 20 - cmd/hway/version.go | 4 - cmd/motr/.cz.toml | 18 - cmd/motr/.goreleaser.yml | 75 - cmd/motr/CHANGELOG.md | 5 - cmd/motr/Makefile | 154 - cmd/motr/README.md | 385 - cmd/motr/go.mod | 10 - cmd/motr/go.sum | 6 - cmd/motr/handlers.go | 446 - cmd/motr/integration_test.go | 405 - cmd/motr/jwt.go | 273 - cmd/motr/main.go | 50 - cmd/motr/oidc.go | 364 - cmd/motr/payment.go | 354 - cmd/motr/payment_security.go | 454 - cmd/motr/security.go | 242 - cmd/motr/version.go | 4 - cmd/snrd/.goreleaser.yml | 331 - cmd/snrd/CHANGELOG.md | 5 - cmd/snrd/Dockerfile | 89 - cmd/snrd/Makefile | 6 +- cmd/snrd/go.mod | 441 - cmd/vault/.cz.toml | 18 - cmd/vault/.goreleaser.yml | 71 - cmd/vault/CHANGELOG.md | 6 - cmd/vault/Makefile | 120 - cmd/vault/README.md | 477 - cmd/vault/go.mod | 26 - cmd/vault/go.sum | 38 - cmd/vault/main.go | 483 - cmd/vault/version.go | 4 - contracts/DAO/COMPLIANCE.md | 353 - contracts/DAO/Cargo.toml | 72 - contracts/DAO/IBC_INTEGRATION.md | 458 - contracts/DAO/README.md | 366 - contracts/DAO/SECURITY_AUDIT.md | 286 - contracts/DAO/contracts/core/Cargo.toml | 30 - contracts/DAO/contracts/core/src/contract.rs | 318 - contracts/DAO/contracts/core/src/lib.rs | 6 - contracts/DAO/contracts/core/src/msg.rs | 33 - contracts/DAO/contracts/core/src/query.rs | 43 - contracts/DAO/contracts/core/src/state.rs | 36 - contracts/DAO/contracts/core/src/tests.rs | 424 - .../DAO/contracts/pre-propose/Cargo.toml | 30 - .../DAO/contracts/pre-propose/src/contract.rs | 381 - .../DAO/contracts/pre-propose/src/lib.rs | 7 - .../DAO/contracts/pre-propose/src/state.rs | 41 - .../contracts/pre-propose/src/verification.rs | 151 - contracts/DAO/contracts/proposals/Cargo.toml | 30 - .../DAO/contracts/proposals/src/contract.rs | 404 - .../DAO/contracts/proposals/src/identity.rs | 104 - contracts/DAO/contracts/proposals/src/lib.rs | 7 - contracts/DAO/contracts/proposals/src/msg.rs | 35 - .../DAO/contracts/proposals/src/query.rs | 73 - .../DAO/contracts/proposals/src/state.rs | 35 - contracts/DAO/contracts/voting/Cargo.toml | 30 - .../DAO/contracts/voting/src/bindings.rs | 96 - .../DAO/contracts/voting/src/contract.rs | 487 - contracts/DAO/contracts/voting/src/lib.rs | 7 - contracts/DAO/contracts/voting/src/msg.rs | 29 - contracts/DAO/contracts/voting/src/query.rs | 68 - contracts/DAO/contracts/voting/src/state.rs | 19 - contracts/DAO/contracts/voting/src/tests.rs | 475 - contracts/DAO/docs/IMPLEMENTATION_SUMMARY.md | 194 - contracts/DAO/packages/shared/Cargo.toml | 27 - contracts/DAO/packages/shared/src/bindings.rs | 148 - contracts/DAO/packages/shared/src/error.rs | 48 - contracts/DAO/packages/shared/src/lib.rs | 12 - contracts/DAO/packages/shared/src/msg.rs | 156 - contracts/DAO/packages/shared/src/query.rs | 237 - contracts/DAO/packages/shared/src/types.rs | 127 - contracts/DAO/scripts/build_contracts.sh | 203 - contracts/DAO/scripts/deploy-cosmos-hub.sh | 364 - contracts/DAO/scripts/deploy.sh | 301 - contracts/DAO/scripts/deploy_mainnet.sh | 365 - contracts/DAO/scripts/deploy_testnet.sh | 357 - contracts/DAO/scripts/migrate.sh | 221 - contracts/DAO/scripts/setup_ibc.sh | 392 - contracts/DAO/scripts/test-ibc-integration.sh | 245 - contracts/DAO/scripts/testnet-config.json | 68 - contracts/DAO/scripts/verify_deployment.sh | 356 - .../tests/e2e/identity_dao_test.go.template | 515 - .../tests/integration/did_integration_test.rs | 421 - contracts/wSNR/.env.example | 15 - contracts/wSNR/.gitignore | 19 - contracts/wSNR/DEPLOY.md | 153 - contracts/wSNR/Makefile | 105 - contracts/wSNR/README.md | 122 - contracts/wSNR/build.sh | 34 - contracts/wSNR/foundry.toml | 25 - contracts/wSNR/script/DeployWSNR.s.sol | 54 - contracts/wSNR/src/WSNR.sol | 98 - contracts/wSNR/src/interfaces/IWSNR.sol | 53 - contracts/wSNR/test/WSNR.t.sol | 371 - crypto/Makefile | 283 - crypto/README.md | 27 - crypto/accumulator/accumulator.go | 179 - crypto/accumulator/accumulator_test.go | 221 - crypto/accumulator/key.go | 247 - crypto/accumulator/key_test.go | 88 - crypto/accumulator/lib.go | 204 - crypto/accumulator/lib_test.go | 404 - crypto/accumulator/proof.go | 527 - crypto/accumulator/proof_test.go | 182 - crypto/accumulator/witness.go | 392 - crypto/accumulator/witness_test.go | 229 - crypto/aead/aes_gcm.go | 121 - crypto/aead/aes_gcm_test.go | 349 - crypto/argon2/kdf.go | 213 - crypto/argon2/kdf_test.go | 396 - crypto/bulletproof/generators.go | 57 - crypto/bulletproof/generators_test.go | 61 - crypto/bulletproof/helpers.go | 181 - crypto/bulletproof/helpers_test.go | 85 - crypto/bulletproof/ipp_prover.go | 415 - crypto/bulletproof/ipp_prover_test.go | 99 - crypto/bulletproof/ipp_verifier.go | 236 - crypto/bulletproof/ipp_verifier_test.go | 79 - crypto/bulletproof/range_batch_prover.go | 386 - crypto/bulletproof/range_batch_prover_test.go | 102 - crypto/bulletproof/range_batch_verifier.go | 133 - .../bulletproof/range_batch_verifier_test.go | 148 - crypto/bulletproof/range_prover.go | 514 - crypto/bulletproof/range_prover_test.go | 86 - crypto/bulletproof/range_verifier.go | 235 - crypto/bulletproof/range_verifier_test.go | 87 - crypto/core/README.md | 14 - crypto/core/commit.go | 123 - crypto/core/commit_test.go | 396 - crypto/core/curves/bls12377_curve.go | 1226 - crypto/core/curves/bls12381_curve.go | 1131 - crypto/core/curves/curve.go | 863 - crypto/core/curves/curve_test.go | 93 - crypto/core/curves/ec_point.go | 251 - crypto/core/curves/ec_point_test.go | 369 - crypto/core/curves/ec_scalar.go | 353 - crypto/core/curves/ecdsa.go | 39 - crypto/core/curves/ed25519_curve.go | 864 - crypto/core/curves/ed25519_curve_test.go | 621 - crypto/core/curves/field.go | 282 - crypto/core/curves/field_test.go | 305 - crypto/core/curves/k256_bench_test.go | 446 - crypto/core/curves/k256_curve.go | 672 - crypto/core/curves/k256_curve_test.go | 620 - .../core/curves/native/bls12381/bls12381.go | 81 - crypto/core/curves/native/bls12381/fp.go | 697 - crypto/core/curves/native/bls12381/fp12.go | 231 - .../core/curves/native/bls12381/fp12_test.go | 417 - crypto/core/curves/native/bls12381/fp2.go | 344 - .../core/curves/native/bls12381/fp2_test.go | 424 - crypto/core/curves/native/bls12381/fp6.go | 340 - .../core/curves/native/bls12381/fp6_test.go | 217 - crypto/core/curves/native/bls12381/fp_test.go | 346 - crypto/core/curves/native/bls12381/fq.go | 455 - crypto/core/curves/native/bls12381/fq_test.go | 353 - crypto/core/curves/native/bls12381/g1.go | 1123 - crypto/core/curves/native/bls12381/g1_test.go | 431 - crypto/core/curves/native/bls12381/g2.go | 1122 - crypto/core/curves/native/bls12381/g2_test.go | 569 - crypto/core/curves/native/bls12381/gt.go | 434 - .../core/curves/native/bls12381/pairings.go | 254 - .../curves/native/bls12381/pairings_test.go | 64 - crypto/core/curves/native/field.go | 388 - crypto/core/curves/native/hash2field.go | 107 - crypto/core/curves/native/isogeny.go | 62 - crypto/core/curves/native/k256/fp/fp.go | 207 - crypto/core/curves/native/k256/fp/fp_test.go | 330 - .../curves/native/k256/fp/secp256k1_fp.go | 1942 -- crypto/core/curves/native/k256/fq/fq.go | 493 - crypto/core/curves/native/k256/fq/fq_test.go | 330 - .../curves/native/k256/fq/secp256k1_fq.go | 2002 -- crypto/core/curves/native/k256/point.go | 475 - crypto/core/curves/native/k256/point_test.go | 19 - crypto/core/curves/native/osswu.go | 82 - crypto/core/curves/native/p256/fp/fp.go | 206 - crypto/core/curves/native/p256/fp/fp_test.go | 330 - crypto/core/curves/native/p256/fp/p256_fp.go | 1463 -- crypto/core/curves/native/p256/fq/fq.go | 510 - crypto/core/curves/native/p256/fq/fq_test.go | 330 - crypto/core/curves/native/p256/fq/p256_fq.go | 1651 -- crypto/core/curves/native/p256/point.go | 350 - crypto/core/curves/native/p256/point_test.go | 38 - crypto/core/curves/native/pasta/README.md | 10 - crypto/core/curves/native/pasta/fp/fp.go | 375 - crypto/core/curves/native/pasta/fp/fp_test.go | 273 - .../core/curves/native/pasta/fp/pasta_fp.go | 1518 -- crypto/core/curves/native/pasta/fq/fq.go | 369 - crypto/core/curves/native/pasta/fq/fq_test.go | 273 - .../core/curves/native/pasta/fq/pasta_fq.go | 1518 -- crypto/core/curves/native/pasta/pallas.go | 7 - crypto/core/curves/native/point.go | 471 - crypto/core/curves/p256_bench_test.go | 756 - crypto/core/curves/p256_curve.go | 670 - crypto/core/curves/p256_curve_test.go | 556 - crypto/core/curves/pallas_curve.go | 1216 - crypto/core/curves/pallas_curve_test.go | 244 - crypto/core/curves/secp256k1/secp256k1.go | 327 - crypto/core/curves/sp256_curve.go | 11 - crypto/core/hash.go | 339 - crypto/core/hash_test.go | 323 - crypto/core/mod.go | 178 - crypto/core/mod_test.go | 589 - crypto/core/primes.go | 42 - crypto/core/protocol/protocol.go | 114 - crypto/daed/aes_siv.go | 246 - crypto/daed/aes_siv_test.go | 303 - crypto/dkg/frost/README.md | 13 - crypto/dkg/frost/dkg_round1.go | 153 - crypto/dkg/frost/dkg_round2.go | 162 - crypto/dkg/frost/dkg_rounds_test.go | 206 - crypto/dkg/frost/participant.go | 70 - crypto/dkg/gennaro/README.md | 13 - crypto/dkg/gennaro/participant.go | 102 - crypto/dkg/gennaro/participant_test.go | 48 - crypto/dkg/gennaro/round1.go | 79 - crypto/dkg/gennaro/round2.go | 93 - crypto/dkg/gennaro/round3.go | 89 - crypto/dkg/gennaro/round4.go | 76 - crypto/dkg/gennaro/rounds_test.go | 419 - crypto/dkg/gennaro2p/README.md | 12 - crypto/dkg/gennaro2p/genarro2p.go | 151 - crypto/dkg/gennaro2p/genarro2p_test.go | 181 - crypto/ecdsa/canonical.go | 193 - crypto/ecdsa/canonical_test.go | 276 - crypto/ecdsa/deterministic.go | 224 - crypto/ecdsa/deterministic_test.go | 286 - crypto/ecies/encrypt.go | 13 - crypto/ecies/keys.go | 57 - crypto/ecies/keys_test.go | 24 - crypto/empty-module/bip39.go | 33 - crypto/empty-module/go.mod | 3 - crypto/go.mod | 46 - crypto/go.sum | 102 - crypto/internal/ed25519/edwards25519/const.go | 10217 --------- .../ed25519/edwards25519/edwards25519.go | 2308 -- .../ed25519/edwards25519/edwards25519_test.go | 267 - .../internal/ed25519/extra25519/extra25519.go | 377 - .../ed25519/extra25519/extra25519_test.go | 126 - crypto/internal/err.go | 22 - crypto/internal/hash.go | 97 - crypto/internal/hash_test.go | 62 - crypto/internal/point.go | 44 - crypto/internal/testutils.go | 21 - crypto/keys/didkey.go | 300 - crypto/keys/didkey_test.go | 279 - crypto/keys/methods.go | 17 - crypto/keys/parsers/btc_parser.go | 1 - crypto/keys/parsers/cosmos_parser.go | 12 - crypto/keys/parsers/eth_parser.go | 1 - crypto/keys/parsers/fil_parser.go | 1 - crypto/keys/parsers/key_parser.go | 157 - crypto/keys/parsers/sol_parser.go | 1 - crypto/keys/parsers/ton_parser.go | 1 - crypto/keys/pubkey.go | 85 - crypto/keys/utils.go | 34 - crypto/mpc/README.md | 499 - crypto/mpc/codec.go | 110 - crypto/mpc/codec_test.go | 178 - crypto/mpc/enclave.go | 158 - crypto/mpc/enclave_test.go | 307 - crypto/mpc/import.go | 140 - crypto/mpc/protocol.go | 91 - crypto/mpc/spec/jwt.go | 116 - crypto/mpc/spec/source.go | 305 - crypto/mpc/spec/ucan.go | 125 - crypto/mpc/utils.go | 160 - crypto/mpc/verify.go | 29 - crypto/ot/base/simplest/ot.go | 437 - crypto/ot/base/simplest/ot_test.go | 96 - crypto/ot/base/simplest/stream.go | 100 - crypto/ot/base/simplest/util.go | 55 - crypto/ot/extension/kos/kos.go | 475 - crypto/ot/extension/kos/kos_test.go | 153 - crypto/ot/extension/kos/stream.go | 67 - crypto/ot/ottest/util.go | 54 - crypto/paillier/README.md | 23 - crypto/paillier/paillier.go | 377 - crypto/paillier/psf.go | 235 - crypto/paillier/psf_test.go | 394 - crypto/password/validator.go | 185 - crypto/password/validator_test.go | 207 - crypto/salt/salt.go | 227 - crypto/salt/salt_test.go | 421 - crypto/secure/memory.go | 325 - crypto/secure/memory_test.go | 523 - crypto/security_test.go | 466 - crypto/sharing/README.md | 16 - crypto/sharing/ed25519_feldman_test.go | 132 - crypto/sharing/feldman.go | 115 - crypto/sharing/pedersen.go | 154 - crypto/sharing/polynomial.go | 35 - crypto/sharing/polynomial_test.go | 32 - crypto/sharing/shamir.go | 209 - crypto/sharing/shamir_test.go | 186 - crypto/sharing/v1/bls12381g1_feldman_test.go | 177 - crypto/sharing/v1/bls12381g1curve.go | 120 - crypto/sharing/v1/bls12381g2_feldman_test.go | 167 - crypto/sharing/v1/bls12381g2curve.go | 119 - crypto/sharing/v1/common.go | 14 - crypto/sharing/v1/ed25519_feldman_test.go | 167 - crypto/sharing/v1/ed25519_pedersen_test.go | 198 - crypto/sharing/v1/ed25519curve.go | 147 - crypto/sharing/v1/ed25519curve_test.go | 28 - crypto/sharing/v1/feldman.go | 107 - crypto/sharing/v1/k256_feldman_test.go | 168 - crypto/sharing/v1/k256_pedersen_test.go | 201 - crypto/sharing/v1/p256_feldman_test.go | 168 - crypto/sharing/v1/pedersen.go | 178 - crypto/sharing/v1/polynomial.go | 49 - crypto/sharing/v1/polynomial_test.go | 29 - crypto/sharing/v1/shamir.go | 214 - crypto/sharing/v1/shamir_test.go | 241 - crypto/signatures/bbs/blind_signature.go | 79 - .../signatures/bbs/blind_signature_context.go | 271 - .../bbs/blind_signature_context_test.go | 98 - crypto/signatures/bbs/message_generators.go | 77 - crypto/signatures/bbs/pok_signature.go | 159 - crypto/signatures/bbs/pok_signature_proof.go | 214 - .../bbs/pok_signature_proof_test.go | 319 - crypto/signatures/bbs/public_key.go | 77 - crypto/signatures/bbs/secret_key.go | 185 - crypto/signatures/bbs/signature.go | 67 - crypto/signatures/bbs/signature_test.go | 81 - crypto/signatures/bls/README.md | 114 - crypto/signatures/bls/bls_sig/lib.go | 208 - crypto/signatures/bls/bls_sig/lib_test.go | 481 - crypto/signatures/bls/bls_sig/tiny_bls.go | 484 - crypto/signatures/bls/bls_sig/tiny_bls_sig.go | 516 - .../bls/bls_sig/tiny_bls_sig_aug_test.go | 389 - .../bls/bls_sig/tiny_bls_sig_basic_test.go | 385 - .../bls/bls_sig/tiny_bls_sig_pop_test.go | 962 - crypto/signatures/bls/bls_sig/usual_bls.go | 478 - .../signatures/bls/bls_sig/usual_bls_sig.go | 507 - .../bls/bls_sig/usual_bls_sig_aug_test.go | 417 - .../bls/bls_sig/usual_bls_sig_basic_test.go | 417 - .../bls/bls_sig/usual_bls_sig_pop_test.go | 936 - crypto/signatures/bls/rust/Cargo.toml | 19 - crypto/signatures/bls/rust/README.md | 13 - crypto/signatures/bls/rust/src/main.rs | 388 - crypto/signatures/bls/tests/bls/main.go | 236 - crypto/signatures/common/challenge.go | 14 - crypto/signatures/common/commitment.go | 15 - crypto/signatures/common/hmacdrbg.go | 99 - crypto/signatures/common/nonce.go | 15 - .../common/proof_committed_builder.go | 89 - crypto/signatures/common/proof_message.go | 79 - .../signatures/common/signature_blinding.go | 14 - crypto/signatures/schnorr/mina/bitvector.go | 232 - .../schnorr/mina/challenge_derive.go | 46 - crypto/signatures/schnorr/mina/keys.go | 282 - crypto/signatures/schnorr/mina/keys_test.go | 132 - .../schnorr/mina/poseidon_config.go | 112 - .../signatures/schnorr/mina/poseidon_hash.go | 1182 - .../schnorr/mina/poseidon_hash_test.go | 122 - crypto/signatures/schnorr/mina/roinput.go | 136 - crypto/signatures/schnorr/mina/signature.go | 49 - crypto/signatures/schnorr/mina/txn.go | 224 - .../signatures/schnorr/nem/ed25519_keccak.go | 323 - .../schnorr/nem/ed25519_keccak_test.go | 190 - crypto/subtle/hkdf.go | 58 - crypto/subtle/random/random.go | 22 - crypto/subtle/subtle.go | 130 - crypto/subtle/x25519.go | 25 - crypto/tecdsa/dklsv1/README.md | 13 - crypto/tecdsa/dklsv1/boilerplate.go | 436 - crypto/tecdsa/dklsv1/dealer/dealer.go | 87 - crypto/tecdsa/dklsv1/dealer/dealer_test.go | 57 - crypto/tecdsa/dklsv1/dkg/dkg.go | 309 - crypto/tecdsa/dklsv1/dkg/dkg_test.go | 104 - crypto/tecdsa/dklsv1/dkgserializers.go | 327 - crypto/tecdsa/dklsv1/protocol.go | 33 - crypto/tecdsa/dklsv1/protocol_test.go | 428 - crypto/tecdsa/dklsv1/refresh/refresh.go | 193 - crypto/tecdsa/dklsv1/refresh/refresh_test.go | 215 - crypto/tecdsa/dklsv1/refreshserializers.go | 253 - crypto/tecdsa/dklsv1/sign/multiply.go | 299 - crypto/tecdsa/dklsv1/sign/multiply_test.go | 52 - crypto/tecdsa/dklsv1/sign/sign.go | 409 - crypto/tecdsa/dklsv1/sign/sign_test.go | 121 - crypto/tecdsa/dklsv1/signserializers.go | 128 - crypto/ted25519/frost/README.md | 13 - crypto/ted25519/frost/challenge_derive.go | 31 - crypto/ted25519/frost/participant.go | 89 - crypto/ted25519/frost/round1.go | 78 - crypto/ted25519/frost/round2.go | 189 - crypto/ted25519/frost/round3.go | 169 - crypto/ted25519/frost/rounds_test.go | 439 - crypto/ted25519/ted25519/ed25519.go | 291 - crypto/ted25519/ted25519/ed25519_test.go | 164 - crypto/ted25519/ted25519/ext.go | 123 - crypto/ted25519/ted25519/ext_test.go | 143 - crypto/ted25519/ted25519/keygen.go | 243 - crypto/ted25519/ted25519/keygen_test.go | 125 - crypto/ted25519/ted25519/noncegen.go | 123 - crypto/ted25519/ted25519/noncegen_test.go | 111 - crypto/ted25519/ted25519/partialsig.go | 61 - crypto/ted25519/ted25519/partialsig_test.go | 56 - crypto/ted25519/ted25519/sigagg.go | 62 - crypto/ted25519/ted25519/sigagg_test.go | 97 - crypto/ted25519/ted25519/twobytwo_test.go | 55 - crypto/ucan/capability.go | 860 - crypto/ucan/crypto.go | 352 - crypto/ucan/jwt.go | 595 - crypto/ucan/mpc.go | 625 - crypto/ucan/source.go | 302 - crypto/ucan/stubs.go | 87 - crypto/ucan/ucan_test.go | 313 - crypto/ucan/vault.go | 485 - crypto/ucan/verifier.go | 984 - crypto/vrf/vrf.go | 231 - crypto/vrf/vrf_test.go | 112 - crypto/wasm/signer.go | 336 - crypto/wasm/signer_test.go | 361 - crypto/wasm/verifier.go | 224 - crypto/wasm/verifier_test.go | 226 - crypto/zkp/schnorr/schnorr.go | 157 - crypto/zkp/schnorr/schnorr_test.go | 36 - devbox.json | 44 +- docker-compose.yml | 152 - .../architecture/decentralized-identity.mdx | 4 +- docs/reference/contracts/DAO.mdx | 0 docs/reference/contracts/wSNR.mdx | 0 go.mod | 194 +- go.sum | 507 +- scripts/install.sh => install.sh | 0 internal/migrations/001_accounts_table.sql | 44 - internal/migrations/002_credentials_table.sql | 36 - internal/migrations/003_profiles_table.sql | 30 - internal/migrations/004_vaults_table.sql | 33 - .../migrations/005_create_cosmos_registry.sql | 368 - .../006_execute_cosmos_registry.sql | 16 - .../migrations/007_webauthn_to_vc_func.sql | 29 - .../008_create_coinpaprika_market_data.sql | 486 - .../009_webauthn_options_functions.sql | 139 - .../010_crypto_asset_symbol_linking.sql | 176 - internal/migrations/011_common_functions.sql | 21 - .../migrations/012_crypto_coin_price_data.sql | 507 - .../013_add_asset_quality_filters.sql | 420 - internal/migrations/014_sessions_table.sql | 26 - package.json | 68 - packages/com/.cz.toml | 16 - packages/com/package.json | 70 - packages/com/src/constants/index.ts | 199 - packages/com/src/index.ts | 79 - packages/com/src/types/analytics.ts | 91 - packages/com/src/types/api.ts | 69 - packages/com/src/types/common.ts | 97 - packages/com/src/types/domain.ts | 69 - packages/com/src/types/index.ts | 75 - packages/com/src/types/permission.ts | 88 - packages/com/src/types/service.ts | 74 - packages/com/src/types/user.ts | 47 - packages/com/src/utils/array.ts | 167 - packages/com/src/utils/chart.ts | 175 - packages/com/src/utils/date.ts | 153 - packages/com/src/utils/format.ts | 162 - packages/com/src/utils/index.ts | 79 - packages/com/src/utils/validation.ts | 184 - packages/com/tsconfig.json | 21 - packages/com/tsup.config.ts | 18 - packages/es/.cz.toml | 16 - packages/es/.gitignore | 41 - packages/es/README.md | 692 - packages/es/biome.json | 21 - packages/es/buf.gen.yaml | 10 - packages/es/buf.lock | 2 - packages/es/examples/autoloader.html | 263 - packages/es/examples/ipfs-enclave-usage.ts | 489 - packages/es/examples/motor-browser-test.html | 442 - packages/es/examples/motor-usage.ts | 310 - packages/es/examples/plugins-usage.ts | 136 - packages/es/examples/webauthn-enhanced.html | 382 - packages/es/package.json | 151 - packages/es/scripts/gen-protobufs.mjs | 199 - packages/es/scripts/gen-registry.mjs | 53 - packages/es/scripts/protoc-gen-cosmes.mjs | 50 - packages/es/src/autoloader.js | 203 - packages/es/src/client/apis/broadcastTx.ts | 16 - packages/es/src/client/apis/getAccount.ts | 26 - packages/es/src/client/apis/getCw20Balance.ts | 30 - .../es/src/client/apis/getNativeBalances.ts | 53 - packages/es/src/client/apis/getTx.ts | 21 - packages/es/src/client/apis/pollTx.ts | 28 - packages/es/src/client/apis/queryContract.ts | 25 - .../apis/simulateAstroportSinglePoolSwap.ts | 44 - .../apis/simulateKujiraSinglePoolSwap.ts | 44 - packages/es/src/client/apis/simulateTx.ts | 20 - packages/es/src/client/auth/README.md | 190 - packages/es/src/client/auth/examples.ts | 206 - packages/es/src/client/auth/index.ts | 27 - .../es/src/client/auth/test-webauthn.html | 119 - packages/es/src/client/auth/webauthn.test.ts | 412 - packages/es/src/client/auth/webauthn.ts | 621 - packages/es/src/client/clients/FetchClient.ts | 33 - packages/es/src/client/clients/RpcClient.ts | 199 - packages/es/src/client/index.ts | 67 - packages/es/src/client/models/Adapter.ts | 12 - .../src/client/models/MsgBeginRedelegate.ts | 43 - packages/es/src/client/models/MsgDelegate.ts | 48 - .../es/src/client/models/MsgIbcTransfer.ts | 45 - packages/es/src/client/models/MsgSend.ts | 49 - packages/es/src/client/models/MsgStoreCode.ts | 33 - .../es/src/client/models/MsgUndelegate.ts | 42 - .../models/MsgWithdrawDelegatorRewards.ts | 43 - .../models/MsgWithdrawValidatorCommission.ts | 38 - .../es/src/client/models/Secp256k1PubKey.ts | 45 - packages/es/src/client/models/Tx.ts | 208 - packages/es/src/client/utils/calculateFee.ts | 22 - packages/es/src/client/utils/toAny.ts | 8 - packages/es/src/client/utils/toBaseAccount.ts | 52 - packages/es/src/client/utils/wait.ts | 6 - packages/es/src/codec/address.test.ts | 43 - packages/es/src/codec/address.ts | 40 - packages/es/src/codec/ethhex.ts | 13 - packages/es/src/codec/index.ts | 14 - packages/es/src/codec/key.test.ts | 32 - packages/es/src/codec/key.ts | 27 - packages/es/src/codec/serialise.test.ts | 38 - packages/es/src/codec/serialise.ts | 35 - packages/es/src/codec/sign.test.ts | 64 - packages/es/src/codec/sign.ts | 83 - packages/es/src/codec/verify.test.ts | 109 - packages/es/src/codec/verify.ts | 79 - packages/es/src/index.ts | 93 - packages/es/src/plugin/README.md | 224 - .../es/src/plugin/__tests__/enclave.test.ts | 305 - packages/es/src/plugin/client-ipfs.ts | 416 - packages/es/src/plugin/client.ts | 515 - packages/es/src/plugin/enclave.ts | 398 - packages/es/src/plugin/index.ts | 18 - packages/es/src/plugin/loader.ts | 201 - packages/es/src/plugin/storage.e2e.test.ts | 586 - packages/es/src/plugin/storage.test.ts | 234 - packages/es/src/plugin/storage.ts | 264 - packages/es/src/plugin/types.ts | 264 - .../cosmos/app/runtime/v1alpha1/module_pb.ts | 248 - .../cosmos/app/v1alpha1/config_pb.ts | 226 - .../cosmos/app/v1alpha1/module_pb.ts | 229 - .../cosmos/app/v1alpha1/query_cosmes.ts | 20 - .../protobufs/cosmos/app/v1alpha1/query_pb.ts | 100 - .../protobufs/cosmos/autocli/v1/options_pb.ts | 495 - .../cosmos/autocli/v1/query_cosmes.ts | 20 - .../protobufs/cosmos/autocli/v1/query_pb.ts | 103 - .../cosmos/base/abci/v1beta1/abci_pb.ts | 792 - .../cosmos/base/node/v1beta1/query_cosmes.ts | 32 - .../cosmos/base/node/v1beta1/query_pb.ts | 250 - .../base/query/v1beta1/pagination_pb.ts | 167 - .../reflection/v1beta1/reflection_cosmes.ts | 39 - .../base/reflection/v1beta1/reflection_pb.ts | 234 - .../reflection/v2alpha1/reflection_cosmes.ts | 97 - .../base/reflection/v2alpha1/reflection_pb.ts | 1515 -- .../base/tendermint/v1beta1/query_cosmes.ts | 111 - .../base/tendermint/v1beta1/query_pb.ts | 1158 - .../base/tendermint/v1beta1/types_pb.ts | 265 - .../protobufs/cosmos/base/v1beta1/coin_pb.ts | 202 - .../cosmos/crypto/ed25519/keys_pb.ts | 103 - .../protobufs/cosmos/crypto/hd/v1/hd_pb.ts | 98 - .../cosmos/crypto/keyring/v1/record_pb.ts | 278 - .../cosmos/crypto/multisig/keys_pb.ts | 64 - .../crypto/multisig/v1beta1/multisig_pb.ts | 120 - .../cosmos/crypto/secp256k1/keys_pb.ts | 102 - .../cosmos/crypto/secp256r1/keys_pb.ts | 105 - .../protobufs/cosmos/ics23/v1/proofs_pb.ts | 1149 - .../cosmos/reflection/v1/reflection_cosmes.ts | 21 - .../cosmos/reflection/v1/reflection_pb.ts | 117 - .../cosmos/store/internal/kv/v1beta1/kv_pb.ts | 104 - .../cosmos/store/snapshots/v1/snapshot_pb.ts | 451 - .../store/streaming/abci/grpc_cosmes.ts | 37 - .../cosmos/store/streaming/abci/grpc_pb.ts | 229 - .../cosmos/store/v1beta1/commit_info_pb.ts | 173 - .../cosmos/store/v1beta1/listening_pb.ts | 154 - .../cosmos/tx/config/v1/config_pb.ts | 78 - .../cosmos/tx/signing/v1beta1/signing_pb.ts | 432 - .../cosmos/tx/v1beta1/service_cosmes.ts | 145 - .../protobufs/cosmos/tx/v1beta1/service_pb.ts | 1128 - .../src/protobufs/cosmos/tx/v1beta1/tx_pb.ts | 971 - .../protobufs/cosmwasm/wasm/v1/authz_pb.ts | 505 - .../protobufs/cosmwasm/wasm/v1/genesis_pb.ts | 227 - .../src/protobufs/cosmwasm/wasm/v1/ibc_pb.ts | 189 - .../cosmwasm/wasm/v1/proposal_legacy_pb.ts | 1080 - .../cosmwasm/wasm/v1/query_cosmes.ts | 178 - .../protobufs/cosmwasm/wasm/v1/query_pb.ts | 1357 -- .../protobufs/cosmwasm/wasm/v1/tx_cosmes.ts | 239 - .../src/protobufs/cosmwasm/wasm/v1/tx_pb.ts | 1807 -- .../protobufs/cosmwasm/wasm/v1/types_pb.ts | 533 - .../src/protobufs/dex/module/v1/module_pb.ts | 42 - packages/es/src/protobufs/dex/v1/events_pb.ts | 698 - .../es/src/protobufs/dex/v1/genesis_pb.ts | 293 - packages/es/src/protobufs/dex/v1/ica_pb.ts | 311 - .../es/src/protobufs/dex/v1/query_cosmes.ts | 128 - packages/es/src/protobufs/dex/v1/query_pb.ts | 933 - packages/es/src/protobufs/dex/v1/tx_cosmes.ts | 111 - packages/es/src/protobufs/dex/v1/tx_pb.ts | 845 - .../src/protobufs/did/module/v1/module_pb.ts | 42 - packages/es/src/protobufs/did/v1/events_pb.ts | 771 - .../es/src/protobufs/did/v1/genesis_pb.ts | 320 - .../es/src/protobufs/did/v1/query_cosmes.ts | 158 - packages/es/src/protobufs/did/v1/query_pb.ts | 1240 - packages/es/src/protobufs/did/v1/state_pb.ts | 873 - packages/es/src/protobufs/did/v1/tx_cosmes.ts | 170 - packages/es/src/protobufs/did/v1/tx_pb.ts | 1222 - packages/es/src/protobufs/did/v1/types_pb.ts | 586 - .../src/protobufs/dwn/module/v1/module_pb.ts | 42 - packages/es/src/protobufs/dwn/v1/events_pb.ts | 600 - .../es/src/protobufs/dwn/v1/genesis_pb.ts | 258 - .../es/src/protobufs/dwn/v1/query_cosmes.ts | 170 - packages/es/src/protobufs/dwn/v1/query_pb.ts | 1325 -- packages/es/src/protobufs/dwn/v1/state_pb.ts | 1277 -- packages/es/src/protobufs/dwn/v1/tx_cosmes.ts | 94 - packages/es/src/protobufs/dwn/v1/tx_pb.ts | 929 - .../crypto/v1/ethsecp256k1/keys_pb.ts | 93 - .../protobufs/ethermint/evm/v1/events_pb.ts | 236 - .../src/protobufs/ethermint/evm/v1/evm_pb.ts | 745 - .../protobufs/ethermint/evm/v1/genesis_pb.ts | 117 - .../ethermint/evm/v1/query_cosmes.ts | 157 - .../protobufs/ethermint/evm/v1/query_pb.ts | 1187 - .../protobufs/ethermint/evm/v1/tx_cosmes.ts | 34 - .../src/protobufs/ethermint/evm/v1/tx_pb.ts | 627 - .../ethermint/feemarket/v1/events_pb.ts | 98 - .../ethermint/feemarket/v1/feemarket_pb.ts | 100 - .../ethermint/feemarket/v1/genesis_pb.ts | 59 - .../ethermint/feemarket/v1/query_cosmes.ts | 45 - .../ethermint/feemarket/v1/query_pb.ts | 233 - .../ethermint/feemarket/v1/tx_cosmes.ts | 22 - .../protobufs/ethermint/feemarket/v1/tx_pb.ts | 93 - .../ethermint/types/v1/account_pb.ts | 59 - .../ethermint/types/v1/dynamic_fee_pb.ts | 49 - .../ethermint/types/v1/indexer_pb.ts | 100 - .../protobufs/ethermint/types/v1/web3_pb.ts | 69 - .../controller/v1/controller_pb.ts | 50 - .../controller/v1/query_cosmes.ts | 33 - .../controller/v1/query_pb.ts | 167 - .../controller/v1/tx_cosmes.ts | 45 - .../controller/v1/tx_pb.ts | 296 - .../genesis/v1/genesis_pb.ts | 278 - .../interchain_accounts/host/v1/host_pb.ts | 110 - .../host/v1/query_cosmes.ts | 21 - .../interchain_accounts/host/v1/query_pb.ts | 83 - .../interchain_accounts/host/v1/tx_cosmes.ts | 33 - .../interchain_accounts/host/v1/tx_pb.ts | 191 - .../interchain_accounts/v1/account_pb.ts | 54 - .../interchain_accounts/v1/metadata_pb.ts | 91 - .../interchain_accounts/v1/packet_pb.ts | 125 - .../v1/genesis_pb.ts | 158 - .../rate_limiting/v1/genesis_pb.ts | 72 - .../rate_limiting/v1/query_cosmes.ts | 83 - .../applications/rate_limiting/v1/query_pb.ts | 465 - .../rate_limiting/v1/rate_limiting_pb.ts | 354 - .../rate_limiting/v1/tx_cosmes.ts | 57 - .../applications/rate_limiting/v1/tx_pb.ts | 426 - .../ibc/applications/transfer/v1/authz_pb.ts | 125 - .../applications/transfer/v1/denomtrace_pb.ts | 60 - .../applications/transfer/v1/genesis_pb.ts | 71 - .../ibc/applications/transfer/v1/packet_pb.ts | 83 - .../applications/transfer/v1/query_cosmes.ts | 81 - .../ibc/applications/transfer/v1/query_pb.ts | 514 - .../ibc/applications/transfer/v1/token_pb.ts | 151 - .../applications/transfer/v1/transfer_pb.ts | 62 - .../ibc/applications/transfer/v1/tx_cosmes.ts | 33 - .../ibc/applications/transfer/v1/tx_pb.ts | 261 - .../ibc/core/channel/v1/channel_pb.ts | 650 - .../ibc/core/channel/v1/genesis_pb.ts | 144 - .../ibc/core/channel/v1/query_cosmes.ts | 185 - .../protobufs/ibc/core/channel/v1/query_pb.ts | 1584 -- .../ibc/core/channel/v1/tx_cosmes.ts | 130 - .../protobufs/ibc/core/channel/v1/tx_pb.ts | 1074 - .../ibc/core/channel/v2/genesis_pb.ts | 180 - .../ibc/core/channel/v2/packet_pb.ts | 291 - .../ibc/core/channel/v2/query_cosmes.ts | 105 - .../protobufs/ibc/core/channel/v2/query_pb.ts | 845 - .../ibc/core/channel/v2/tx_cosmes.ts | 57 - .../protobufs/ibc/core/channel/v2/tx_pb.ts | 442 - .../protobufs/ibc/core/client/v1/client_pb.ts | 262 - .../ibc/core/client/v1/genesis_pb.ts | 186 - .../ibc/core/client/v1/query_cosmes.ts | 143 - .../protobufs/ibc/core/client/v1/query_pb.ts | 1054 - .../protobufs/ibc/core/client/v1/tx_cosmes.ts | 93 - .../src/protobufs/ibc/core/client/v1/tx_pb.ts | 666 - .../protobufs/ibc/core/client/v2/config_pb.ts | 52 - .../ibc/core/client/v2/counterparty_pb.ts | 57 - .../ibc/core/client/v2/genesis_pb.ts | 99 - .../ibc/core/client/v2/query_cosmes.ts | 33 - .../protobufs/ibc/core/client/v2/query_pb.ts | 172 - .../protobufs/ibc/core/client/v2/tx_cosmes.ts | 33 - .../src/protobufs/ibc/core/client/v2/tx_pb.ts | 199 - .../ibc/core/commitment/v1/commitment_pb.ts | 133 - .../ibc/core/commitment/v2/commitment_pb.ts | 77 - .../ibc/core/connection/v1/connection_pb.ts | 457 - .../ibc/core/connection/v1/genesis_pb.ts | 68 - .../ibc/core/connection/v1/query_cosmes.ts | 84 - .../ibc/core/connection/v1/query_pb.ts | 604 - .../ibc/core/connection/v1/tx_cosmes.ts | 71 - .../protobufs/ibc/core/connection/v1/tx_pb.ts | 603 - .../protobufs/ibc/core/types/v1/genesis_pb.ts | 86 - .../solomachine/v2/solomachine_pb.ts | 929 - .../solomachine/v3/solomachine_pb.ts | 458 - .../tendermint/v1/tendermint_pb.ts | 365 - .../ibc/lightclients/wasm/v1/genesis_pb.ts | 90 - .../ibc/lightclients/wasm/v1/query_cosmes.ts | 33 - .../ibc/lightclients/wasm/v1/query_pb.ts | 179 - .../ibc/lightclients/wasm/v1/tx_cosmes.ts | 45 - .../ibc/lightclients/wasm/v1/tx_pb.ts | 278 - .../ibc/lightclients/wasm/v1/wasm_pb.ts | 144 - packages/es/src/protobufs/index.ts | 2711 --- .../osmosis/accum/v1beta1/accum_pb.ts | 172 - .../concentratedliquidity/params_pb.ts | 120 - .../concentrated/v1beta1/tx_cosmes.ts | 19 - .../poolmodel/concentrated/v1beta1/tx_pb.ts | 110 - .../v1beta1/genesis_pb.ts | 324 - .../concentratedliquidity/v1beta1/gov_pb.ts | 216 - .../v1beta1/incentive_record_pb.ts | 135 - .../concentratedliquidity/v1beta1/pool_pb.ts | 138 - .../v1beta1/position_pb.ts | 209 - .../v1beta1/query_cosmes.ts | 199 - .../concentratedliquidity/v1beta1/query_pb.ts | 1452 -- .../v1beta1/tick_info_pb.ts | 164 - .../v1beta1/tx_cosmes.ts | 78 - .../concentratedliquidity/v1beta1/tx_pb.ts | 721 - .../cosmwasmpool/v1beta1/genesis_pb.ts | 56 - .../osmosis/cosmwasmpool/v1beta1/gov_pb.ts | 171 - .../v1beta1/model/instantiate_msg_pb.ts | 50 - .../v1beta1/model/module_query_msg_pb.ts | 281 - .../v1beta1/model/module_sudo_msg_pb.ts | 311 - .../cosmwasmpool/v1beta1/model/pool_pb.ts | 80 - .../v1beta1/model/pool_query_msg_pb.ts | 411 - .../v1beta1/model/transmuter_msgs_pb.ts | 185 - .../cosmwasmpool/v1beta1/model/tx_cosmes.ts | 19 - .../cosmwasmpool/v1beta1/model/tx_pb.ts | 98 - .../v1beta1/model/v3/pool_query_msg_pb.ts | 182 - .../osmosis/cosmwasmpool/v1beta1/params_pb.ts | 59 - .../cosmwasmpool/v1beta1/query_cosmes.ts | 53 - .../osmosis/cosmwasmpool/v1beta1/query_pb.ts | 351 - .../osmosis/cosmwasmpool/v1beta1/tx_cosmes.ts | 7 - .../v1beta1/downtime_duration_pb.ts | 165 - .../downtimedetector/v1beta1/genesis_pb.ts | 97 - .../downtimedetector/v1beta1/query_cosmes.ts | 19 - .../downtimedetector/v1beta1/query_pb.ts | 92 - .../osmosis/epochs/v1beta1/genesis_pb.ts | 163 - .../osmosis/epochs/v1beta1/query_cosmes.ts | 33 - .../osmosis/epochs/v1beta1/query_pb.ts | 151 - .../poolmodels/balancer/v1beta1/tx_cosmes.ts | 19 - .../gamm/poolmodels/balancer/v1beta1/tx_pb.ts | 105 - .../stableswap/v1beta1/stableswap_pool_pb.ts | 159 - .../stableswap/v1beta1/tx_cosmes.ts | 29 - .../poolmodels/stableswap/v1beta1/tx_pb.ts | 201 - .../osmosis/gamm/v1beta1/balancerPool_pb.ts | 307 - .../osmosis/gamm/v1beta1/genesis_pb.ts | 69 - .../protobufs/osmosis/gamm/v1beta1/gov_pb.ts | 299 - .../osmosis/gamm/v1beta1/params_pb.ts | 48 - .../osmosis/gamm/v1beta1/query_cosmes.ts | 226 - .../osmosis/gamm/v1beta1/query_pb.ts | 1497 -- .../osmosis/gamm/v1beta1/shared_pb.ts | 98 - .../osmosis/gamm/v1beta1/tx_cosmes.ts | 89 - .../protobufs/osmosis/gamm/v1beta1/tx_pb.ts | 785 - .../protobufs/osmosis/gamm/v2/query_cosmes.ts | 22 - .../src/protobufs/osmosis/gamm/v2/query_pb.ts | 111 - .../protobufs/osmosis/ibchooks/genesis_pb.ts | 46 - .../protobufs/osmosis/ibchooks/params_pb.ts | 45 - .../protobufs/osmosis/ibchooks/tx_cosmes.ts | 22 - .../src/protobufs/osmosis/ibchooks/tx_pb.ts | 100 - .../ibcratelimit/v1beta1/genesis_pb.ts | 50 - .../osmosis/ibcratelimit/v1beta1/params_pb.ts | 47 - .../ibcratelimit/v1beta1/query_cosmes.ts | 22 - .../osmosis/ibcratelimit/v1beta1/query_pb.ts | 83 - .../protobufs/osmosis/incentives/gauge_pb.ts | 156 - .../osmosis/incentives/genesis_pb.ts | 96 - .../protobufs/osmosis/incentives/gov_pb.ts | 62 - .../protobufs/osmosis/incentives/group_pb.ts | 272 - .../protobufs/osmosis/incentives/params_pb.ts | 101 - .../osmosis/incentives/query_cosmes.ts | 224 - .../protobufs/osmosis/incentives/query_pb.ts | 1494 -- .../protobufs/osmosis/incentives/tx_cosmes.ts | 39 - .../src/protobufs/osmosis/incentives/tx_pb.ts | 335 - .../osmosis/ingest/v1beta1/ingest_cosmes.ts | 21 - .../osmosis/ingest/v1beta1/ingest_pb.ts | 158 - .../protobufs/osmosis/lockup/genesis_pb.ts | 67 - .../src/protobufs/osmosis/lockup/lock_pb.ts | 280 - .../src/protobufs/osmosis/lockup/params_pb.ts | 45 - .../protobufs/osmosis/lockup/query_cosmes.ts | 253 - .../src/protobufs/osmosis/lockup/query_pb.ts | 1535 -- .../src/protobufs/osmosis/lockup/tx_cosmes.ts | 79 - .../es/src/protobufs/osmosis/lockup/tx_pb.ts | 616 - .../osmosis/mint/v1beta1/genesis_pb.ts | 67 - .../protobufs/osmosis/mint/v1beta1/mint_pb.ts | 272 - .../osmosis/mint/v1beta1/query_cosmes.ts | 45 - .../osmosis/mint/v1beta1/query_pb.ts | 234 - .../poolincentives/v1beta1/genesis_pb.ts | 82 - .../osmosis/poolincentives/v1beta1/gov_pb.ts | 123 - .../poolincentives/v1beta1/incentives_pb.ts | 296 - .../poolincentives/v1beta1/query_cosmes.ts | 81 - .../poolincentives/v1beta1/query_pb.ts | 522 - .../poolincentives/v1beta1/shared_pb.ts | 104 - .../osmosis/poolmanager/v1beta1/genesis_pb.ts | 427 - .../osmosis/poolmanager/v1beta1/gov_pb.ts | 61 - .../poolmanager/v1beta1/module_route_pb.ts | 103 - .../poolmanager/v1beta1/query_cosmes.ts | 325 - .../osmosis/poolmanager/v1beta1/query_pb.ts | 1820 -- .../poolmanager/v1beta1/swap_route_pb.ts | 180 - .../poolmanager/v1beta1/taker_fee_share_pb.ts | 182 - .../poolmanager/v1beta1/tracked_volume_pb.ts | 46 - .../osmosis/poolmanager/v1beta1/tx_cosmes.ts | 79 - .../osmosis/poolmanager/v1beta1/tx_pb.ts | 715 - .../osmosis/poolmanager/v2/query_cosmes.ts | 25 - .../osmosis/poolmanager/v2/query_pb.ts | 102 - .../osmosis/protorev/v1beta1/genesis_pb.ts | 161 - .../osmosis/protorev/v1beta1/gov_pb.ts | 113 - .../osmosis/protorev/v1beta1/params_pb.ts | 57 - .../osmosis/protorev/v1beta1/protorev_pb.ts | 786 - .../osmosis/protorev/v1beta1/query_cosmes.ts | 212 - .../osmosis/protorev/v1beta1/query_pb.ts | 1256 - .../osmosis/protorev/v1beta1/tx_cosmes.ts | 87 - .../osmosis/protorev/v1beta1/tx_pb.ts | 559 - .../smartaccount/v1beta1/genesis_pb.ts | 120 - .../osmosis/smartaccount/v1beta1/models_pb.ts | 72 - .../osmosis/smartaccount/v1beta1/params_pb.ts | 70 - .../smartaccount/v1beta1/query_cosmes.ts | 41 - .../osmosis/smartaccount/v1beta1/query_pb.ts | 246 - .../osmosis/smartaccount/v1beta1/tx_cosmes.ts | 42 - .../osmosis/smartaccount/v1beta1/tx_pb.ts | 301 - .../osmosis/store/v1beta1/tree_pb.ts | 125 - .../osmosis/superfluid/genesis_pb.ts | 82 - .../protobufs/osmosis/superfluid/params_pb.ts | 52 - .../osmosis/superfluid/query_cosmes.ts | 227 - .../protobufs/osmosis/superfluid/query_pb.ts | 1510 -- .../osmosis/superfluid/superfluid_pb.ts | 414 - .../protobufs/osmosis/superfluid/tx_cosmes.ts | 123 - .../src/protobufs/osmosis/superfluid/tx_pb.ts | 959 - .../osmosis/superfluid/v1beta1/gov_pb.ts | 171 - .../v1beta1/authorityMetadata_pb.ts | 51 - .../tokenfactory/v1beta1/genesis_pb.ts | 104 - .../osmosis/tokenfactory/v1beta1/params_pb.ts | 63 - .../tokenfactory/v1beta1/query_cosmes.ts | 77 - .../osmosis/tokenfactory/v1beta1/query_pb.ts | 398 - .../osmosis/tokenfactory/v1beta1/tx_cosmes.ts | 79 - .../osmosis/tokenfactory/v1beta1/tx_pb.ts | 613 - .../osmosis/twap/v1beta1/genesis_pb.ts | 103 - .../osmosis/twap/v1beta1/query_cosmes.ts | 59 - .../osmosis/twap/v1beta1/query_pb.ts | 457 - .../osmosis/twap/v1beta1/twap_record_pb.ts | 203 - .../osmosis/txfees/v1beta1/feetoken_pb.ts | 56 - .../osmosis/txfees/v1beta1/genesis_pb.ts | 116 - .../osmosis/txfees/v1beta1/gov_pb.ts | 64 - .../osmosis/txfees/v1beta1/params_pb.ts | 47 - .../osmosis/txfees/v1beta1/query_cosmes.ts | 71 - .../osmosis/txfees/v1beta1/query_pb.ts | 373 - .../osmosis/txfees/v1beta1/tx_cosmes.ts | 19 - .../protobufs/osmosis/txfees/v1beta1/tx_pb.ts | 85 - .../valsetpref/v1beta1/query_cosmes.ts | 21 - .../osmosis/valsetpref/v1beta1/query_pb.ts | 89 - .../osmosis/valsetpref/v1beta1/state_pb.ts | 106 - .../osmosis/valsetpref/v1beta1/tx_cosmes.ts | 102 - .../osmosis/valsetpref/v1beta1/tx_pb.ts | 573 - .../src/protobufs/svc/module/v1/module_pb.ts | 42 - packages/es/src/protobufs/svc/v1/events_pb.ts | 235 - .../es/src/protobufs/svc/v1/genesis_pb.ts | 258 - .../es/src/protobufs/svc/v1/query_cosmes.ts | 110 - packages/es/src/protobufs/svc/v1/query_pb.ts | 842 - packages/es/src/protobufs/svc/v1/state_pb.ts | 764 - packages/es/src/protobufs/svc/v1/tx_cosmes.ts | 64 - packages/es/src/protobufs/svc/v1/tx_pb.ts | 417 - .../apis/getChainRegistryAssetList.ts | 8 - .../apis/getChainRegistryChainInfo.ts | 8 - packages/es/src/registry/index.ts | 5 - .../registry/types/ChainRegistryAssetList.ts | 270 - .../registry/types/ChainRegistryChainInfo.ts | 239 - packages/es/src/typeutils/prettify.ts | 18 - .../es/src/wallet/constants/WalletName.ts | 14 - .../es/src/wallet/constants/WalletType.ts | 8 - packages/es/src/wallet/index.ts | 17 - packages/es/src/wallet/utils/os.ts | 18 - packages/es/src/wallet/utils/sequence.test.ts | 25 - packages/es/src/wallet/utils/sequence.ts | 14 - packages/es/src/wallet/utils/verify.ts | 58 - packages/es/src/wallet/utils/window.ts | 17 - .../src/wallet/walletconnect/QRCodeModal.ts | 145 - .../wallet/walletconnect/WalletConnectV1.ts | 85 - .../wallet/walletconnect/WalletConnectV2.ts | 289 - .../es/src/wallet/walletconnect/qrcodegen.ts | 956 - .../es/src/wallet/wallets/ConnectedWallet.ts | 219 - .../es/src/wallet/wallets/WalletController.ts | 186 - packages/es/src/wallet/wallets/WalletError.ts | 41 - .../wallet/wallets/mnemonic/MnemonicWallet.ts | 169 - packages/es/src/wallet/wallets/window.d.ts | 21 - packages/es/src/worker/README.md | 443 - packages/es/src/worker/client.ts | 486 - packages/es/src/worker/global.d.ts | 30 - packages/es/src/worker/index.ts | 228 - packages/es/src/worker/motor-worker.js | 149 - packages/es/src/worker/motor.test.ts.bak | 715 - packages/es/src/worker/oidc.ts | 529 - packages/es/src/worker/payment-handler.d.ts | 42 - packages/es/src/worker/payment.ts | 323 - packages/es/src/worker/plugin.ts | 349 - packages/es/src/worker/register.ts | 446 - packages/es/src/worker/types.ts | 783 - packages/es/src/worker/worker.ts | 394 - packages/es/test/plugins.test.ts | 111 - packages/es/test/setup.ts | 42 - .../integration/ipfs-integration.test.ts | 425 - packages/es/tsconfig.json | 48 - packages/es/vitest.config.ts | 34 - packages/pkl/.cz.toml | 16 - packages/pkl/Makefile | 83 - packages/pkl/README.md | 294 - packages/pkl/cli/index.js | 171 - packages/pkl/package.json | 39 - packages/pkl/src/base.web/Manifest.pkl | 56 - packages/pkl/src/base.web/OpenIDPayload.pkl | 62 - packages/pkl/src/base.web/PklProject | 5 - .../pkl/src/base.web/PklProject.deps.json | 4 - .../pkl/src/base.web/VerifiableCredential.pkl | 19 - packages/pkl/src/basePklProject.pkl | 55 - packages/pkl/src/cosmos.chain/App.pkl | 81 - packages/pkl/src/cosmos.chain/Client.pkl | 16 - packages/pkl/src/cosmos.chain/Config.pkl | 141 - packages/pkl/src/cosmos.chain/Genesis.pkl | 518 - packages/pkl/src/cosmos.chain/PklProject | 12 - .../pkl/src/cosmos.chain/PklProject.deps.json | 12 - packages/pkl/src/cosmos.params/Asset.pkl | 51 - packages/pkl/src/cosmos.params/Chain.pkl | 74 - packages/pkl/src/cosmos.params/PklProject | 5 - .../src/cosmos.params/PklProject.deps.json | 4 - packages/pkl/src/ipfs.node/Config.pkl | 275 - packages/pkl/src/ipfs.node/PklProject | 5 - .../pkl/src/ipfs.node/PklProject.deps.json | 4 - packages/pkl/src/matrix.element/Config.pkl | 186 - packages/pkl/src/matrix.element/PklProject | 6 - .../src/matrix.element/PklProject.deps.json | 4 - packages/pkl/src/matrix.server/AppService.pkl | 35 - packages/pkl/src/matrix.server/PklProject | 5 - .../src/matrix.server/PklProject.deps.json | 4 - packages/pkl/src/matrix.server/Synapse.pkl | 53 - packages/pkl/src/sonr.testnet/Config.pkl | 13 - packages/pkl/src/sonr.testnet/PklProject | 5 - .../pkl/src/sonr.testnet/PklProject.deps.json | 4 - packages/pkl/src/sonr.testnet/chain/app.pkl | 70 - .../pkl/src/sonr.testnet/chain/client.pkl | 7 - .../pkl/src/sonr.testnet/chain/config.pkl | 139 - .../pkl/src/sonr.testnet/chain/genesis.pkl | 2 - packages/sdk/.cz.toml | 16 - packages/sdk/README.md | 298 - packages/sdk/package.json | 38 - packages/sdk/src/index.ts | 17 - packages/sdk/src/webauthn/client.ts | 318 - packages/sdk/src/webauthn/index.ts | 6 - packages/sdk/src/webauthn/types.ts | 121 - packages/sdk/tsconfig.json | 24 - packages/ui/.cz.toml | 16 - packages/ui/README.md | 168 - packages/ui/components.json | 21 - packages/ui/package.json | 81 - packages/ui/src/components/SignInWithSonr.tsx | 268 - .../ui/src/components/SignInWithSonrModal.tsx | 350 - .../ui/src/components/blocks/sign-in-flow.tsx | 896 - .../dashboard/analytics/ActivityChart.tsx | 205 - .../dashboard/analytics/MetricsCard.tsx | 103 - .../analytics/PerformanceMetrics.tsx | 206 - .../analytics/RequestPatternChart.tsx | 223 - .../dashboard/analytics/TimeRangeSelector.tsx | 136 - .../dashboard/analytics/UsageChart.tsx | 90 - .../components/dashboard/analytics/index.ts | 6 - .../dashboard/domain/DNSInstructions.tsx | 97 - .../dashboard/domain/DNSRecordDisplay.tsx | 159 - .../dashboard/domain/DomainDashboard.tsx | 471 - .../dashboard/domain/DomainList.tsx | 127 - .../dashboard/domain/DomainSelector.tsx | 80 - .../dashboard/domain/DomainStatus.tsx | 247 - .../domain/DomainVerificationFlow.tsx | 144 - .../dashboard/domain/VerificationProgress.tsx | 156 - .../src/components/dashboard/domain/index.ts | 12 - .../dashboard/layout/BreadcrumbNav.tsx | 114 - .../dashboard/layout/DashboardContent.tsx | 14 - .../dashboard/layout/DashboardHeader.tsx | 314 - .../dashboard/layout/DashboardSidebar.tsx | 292 - .../components/dashboard/layout/MobileNav.tsx | 74 - .../dashboard/layout/ThemeToggle.tsx | 90 - .../src/components/dashboard/layout/index.ts | 6 - .../permissions/PermissionAuditLog.tsx | 275 - .../dashboard/permissions/PermissionGrid.tsx | 141 - .../permissions/PermissionRequest.tsx | 336 - .../permissions/PermissionSelector.tsx | 160 - .../dashboard/permissions/UCANViewer.tsx | 276 - .../components/dashboard/permissions/index.ts | 5 - packages/ui/src/components/index.ts | 311 - packages/ui/src/components/ui/alert.tsx | 59 - packages/ui/src/components/ui/badge.tsx | 43 - packages/ui/src/components/ui/breadcrumb.tsx | 98 - packages/ui/src/components/ui/button.tsx | 79 - packages/ui/src/components/ui/calendar.tsx | 54 - packages/ui/src/components/ui/card.tsx | 55 - packages/ui/src/components/ui/chart.tsx | 339 - packages/ui/src/components/ui/checkbox.tsx | 29 - packages/ui/src/components/ui/collapsible.tsx | 11 - packages/ui/src/components/ui/command.tsx | 155 - packages/ui/src/components/ui/dialog.tsx | 129 - .../ui/src/components/ui/dropdown-menu.tsx | 187 - packages/ui/src/components/ui/error-alert.tsx | 34 - packages/ui/src/components/ui/form.tsx | 152 - packages/ui/src/components/ui/input.tsx | 44 - packages/ui/src/components/ui/label.tsx | 21 - packages/ui/src/components/ui/popover.tsx | 31 - packages/ui/src/components/ui/progress.tsx | 27 - packages/ui/src/components/ui/select.tsx | 151 - packages/ui/src/components/ui/separator.tsx | 26 - packages/ui/src/components/ui/sheet.tsx | 130 - packages/ui/src/components/ui/sidebar.tsx | 734 - packages/ui/src/components/ui/skeleton.tsx | 13 - packages/ui/src/components/ui/table.tsx | 90 - packages/ui/src/components/ui/tabs.tsx | 54 - packages/ui/src/components/ui/textarea.tsx | 23 - packages/ui/src/components/ui/toggle.tsx | 47 - packages/ui/src/components/ui/tooltip.tsx | 30 - packages/ui/src/hooks/use-mobile.ts | 19 - packages/ui/src/hooks/useSignInWithSonr.ts | 442 - packages/ui/src/lib/oauth.ts | 424 - packages/ui/src/lib/utils.ts | 25 - packages/ui/src/styles/globals.css | 75 - packages/ui/tailwind.config.js | 71 - packages/ui/tsconfig.json | 32 - cmd/snrd/plugin.json => plugin.json | 0 pnpm-lock.yaml | 18895 ---------------- pnpm-workspace.yaml | 13 - process-compose.yaml | 297 - scripts/convert-swagger.js | 58 - test/e2e/go.mod | 4 +- test/e2e/ucan_blockchain_e2e_test.go | 4 +- test/e2e/ucan_wallet_e2e_test.go | 4 +- test/integration/cross_module_auth_test.go | 820 - test/integration/encryption_security_test.go | 234 - test/integration/oidc_ucan_flow_test.go | 844 - .../integration/performance_benchmark_test.go | 632 - test/integration/security_audit_test.go | 788 - test/integration/ucan_workflow_test.go | 643 - test/integration/webauthn_flow_test.go | 4 +- test/ucan_integration_test.go | 221 - tsconfig.json | 67 - turbo.json | 122 - types/coins/coins.go | 194 - types/coins/coins_test.go | 214 - types/coins/derivation.go | 272 - types/coins/derivation_test.go | 181 - types/coins/transaction.go | 284 - types/coins/transaction_test.go | 224 - types/coins/wallet.go | 196 - types/coins/wallet_test.go | 238 - types/ipfs/client.go | 240 - types/ipfs/file.go | 43 - types/ipfs/folder.go | 30 - types/txns/address.go | 363 - types/txns/builder.go | 414 - types/txns/builder_test.go | 415 - types/txns/encoding.go | 318 - types/txns/errors.go | 89 - types/txns/examples_test.go | 457 - types/txns/fees.go | 397 - types/txns/fees_test.go | 406 - types/txns/types.go | 369 - types/ucan_capabilities.go | 2 - types/webauthn/ATTESTATION.md | 185 - types/webauthn/assertion.go | 234 - types/webauthn/assertion_test.go | 420 - types/webauthn/attestation.go | 254 - types/webauthn/attestation_androidkey.go | 263 - types/webauthn/attestation_androidkey_test.go | 103 - types/webauthn/attestation_apple.go | 112 - types/webauthn/attestation_apple_test.go | 70 - types/webauthn/attestation_packed.go | 312 - types/webauthn/attestation_packed_test.go | 135 - types/webauthn/attestation_safetynet.go | 181 - types/webauthn/attestation_safetynet_test.go | 145 - types/webauthn/attestation_test.go | 221 - types/webauthn/attestation_tpm.go | 488 - types/webauthn/attestation_tpm_test.go | 669 - types/webauthn/attestation_u2f.go | 149 - types/webauthn/attestation_u2f_test.go | 71 - types/webauthn/authenticator.go | 444 - types/webauthn/authenticator_test.go | 623 - types/webauthn/base64.go | 52 - types/webauthn/base64_test.go | 56 - types/webauthn/challenge.go | 20 - types/webauthn/challenge_test.go | 67 - types/webauthn/client.go | 235 - types/webauthn/client_test.go | 165 - types/webauthn/const.go | 19 - types/webauthn/credential.go | 469 - types/webauthn/credential_test.go | 367 - types/webauthn/decoder.go | 40 - types/webauthn/doc.go | 8 - types/webauthn/entities.go | 46 - types/webauthn/errors.go | 107 - types/webauthn/extensions.go | 13 - types/webauthn/func_test.go | 19 - types/webauthn/metadata.go | 166 - types/webauthn/metadata/const.go | 35 - types/webauthn/metadata/decode.go | 299 - types/webauthn/metadata/doc.go | 2 - types/webauthn/metadata/metadata.go | 1123 - types/webauthn/metadata/metadata_test.go | 431 - .../metadata/passkey_authenticator.go | 16 - .../webauthn/metadata/providers/cached/doc.go | 8 - .../metadata/providers/cached/options.go | 92 - .../metadata/providers/cached/provider.go | 148 - .../metadata/providers/cached/util.go | 51 - .../webauthn/metadata/providers/memory/doc.go | 4 - .../metadata/providers/memory/options.go | 90 - .../metadata/providers/memory/provider.go | 97 - types/webauthn/metadata/status.go | 75 - types/webauthn/metadata/types.go | 415 - types/webauthn/options.go | 278 - types/webauthn/options_test.go | 65 - types/webauthn/performance.go | 235 - types/webauthn/revoke/LICENSE | 24 - types/webauthn/revoke/README.md | 4 - types/webauthn/revoke/doc.go | 4 - types/webauthn/revoke/err.go | 450 - types/webauthn/revoke/helpers.go | 78 - types/webauthn/revoke/pkcs7.go | 196 - types/webauthn/revoke/revoke.go | 244 - types/webauthn/revoke/revoke_legacy.go | 87 - types/webauthn/revoke/revoke_modern.go | 80 - types/webauthn/sonr_services.go | 310 - types/webauthn/sonr_utils.go | 188 - types/webauthn/sonr_validation.go | 437 - types/webauthn/webauthncbor/webauthncbor.go | 33 - types/webauthn/webauthncose/const.go | 5 - types/webauthn/webauthncose/ed25519.go | 10 - types/webauthn/webauthncose/webauthncose.go | 547 - .../webauthncose/webauthncose_test.go | 140 - web/auth/.cz.toml | 16 - web/auth/.env.example | 135 - web/auth/.env.staging | 23 - web/auth/Dockerfile | 71 - web/auth/README.md | 158 - web/auth/biome.json | 33 - web/auth/components.json | 21 - web/auth/jest.config.js | 16 - web/auth/next-env.d.ts | 6 - web/auth/next.config.js | 69 - web/auth/open-next.config.ts | 3 - web/auth/package.json | 39 - .../.well-known/openid-configuration/route.ts | 76 - .../app/api/oidc/__tests__/discovery.test.ts | 30 - .../src/app/api/oidc/__tests__/token.test.ts | 71 - web/auth/src/app/api/oidc/authorize/route.ts | 227 - web/auth/src/app/api/oidc/jwks/route.ts | 158 - web/auth/src/app/api/oidc/token/route.ts | 196 - web/auth/src/app/api/oidc/userinfo/route.ts | 227 - web/auth/src/app/capabilities/page.tsx | 299 - web/auth/src/app/dashboard/page.tsx | 189 - web/auth/src/app/globals.css | 71 - web/auth/src/app/layout.tsx | 26 - web/auth/src/app/login/page.tsx | 150 - web/auth/src/app/oauth/authorize/page.tsx | 325 - .../src/app/oauth/authorize/themed-page.tsx | 451 - web/auth/src/app/oauth/callback/page.tsx | 262 - web/auth/src/app/oauth/consent/page.tsx | 325 - web/auth/src/app/page.tsx | 179 - web/auth/src/app/register/page.tsx | 162 - .../src/components/DelegationChainViewer.tsx | 186 - .../src/components/WebAuthnRegistration.tsx | 241 - web/auth/src/hooks/useSession.ts | 147 - web/auth/src/hooks/useWebAuthn.ts | 481 - web/auth/src/lib/oidc.ts | 885 - web/auth/src/lib/siop.ts | 995 - web/auth/src/lib/ucan/delegation.ts | 375 - web/auth/src/lib/ucan/scopes.ts | 415 - web/auth/tailwind.config.js | 100 - web/auth/tsconfig.json | 28 - web/auth/wrangler.toml | 28 - web/dash/.cz.toml | 16 - web/dash/.env.example | 61 - web/dash/.env.staging | 24 - web/dash/Dockerfile | 71 - web/dash/README.md | 113 - web/dash/biome.json | 17 - web/dash/components.json | 21 - web/dash/next-env.d.ts | 6 - web/dash/next.config.js | 90 - web/dash/open-next.config.ts | 3 - web/dash/package.json | 75 - web/dash/postcss.config.js | 6 - web/dash/src/app/domains/page.tsx | 311 - web/dash/src/app/globals.css | 77 - web/dash/src/app/layout.tsx | 38 - web/dash/src/app/page.tsx | 212 - web/dash/src/app/test-echo/page.tsx | 29 - web/dash/src/components/APIKeyManager.tsx | 326 - .../components/DomainVerificationStatus.tsx | 167 - web/dash/src/components/PermissionManager.tsx | 210 - .../components/ServiceRegistrationForm.tsx | 267 - web/dash/src/components/auth-wrapper.tsx | 53 - web/dash/src/components/theme-provider.tsx | 74 - web/dash/src/hooks/useDomainVerification.ts | 230 - web/dash/src/hooks/useService.ts | 259 - web/dash/src/hooks/useServiceMetrics.ts | 99 - web/dash/src/hooks/useServices.ts | 177 - web/dash/src/lib/api/auth.ts | 349 - web/dash/src/lib/api/index.ts | 215 - web/dash/src/lib/api/svc.ts | 318 - web/dash/src/types/analytics.ts | 444 - web/dash/src/types/api.ts | 394 - web/dash/src/types/domain.ts | 394 - web/dash/src/types/index.ts | 77 - web/dash/src/types/service.ts | 351 - web/dash/tailwind.config.js | 137 - web/dash/tsconfig.json | 28 - web/dash/wrangler.toml | 28 - x/dex/keeper/keeper.go | 2 +- x/dex/keeper/permission_validator.go | 4 +- x/dex/types/ucan_capabilities.go | 2 +- x/did/client/cli/register.go | 15 +- x/did/client/server/handlers.go | 21 +- x/did/keeper/keeper.go | 6 +- x/did/keeper/permission_validator.go | 4 +- x/did/keeper/query_server.go | 2 +- x/did/keeper/ucan_handler.go | 2 +- x/did/keeper/webauthn_controller.go | 6 +- x/did/keeper/webauthn_registration.go | 12 +- x/did/keeper/webauthn_security_test.go | 6 +- x/did/types/expected_keepers.go | 2 +- x/did/types/ucan_capabilities.go | 2 +- x/did/types/validation.go | 239 + x/did/types/webauthn.go | 88 +- x/dwn/README.md | 2 +- x/dwn/client/cli/query_wallet.go | 2 +- x/dwn/client/plugin/config.go | 2 +- x/dwn/client/plugin/config_test.go | 2 +- x/dwn/client/plugin/embed.go | 2 +- x/dwn/client/plugin/example_test.go | 2 +- x/dwn/client/plugin/manager.go | 4 +- .../plugin/security_integration_test.go | 2 +- x/dwn/keeper/ipfs.go | 6 +- x/dwn/keeper/ipfs_test.go | 4 +- x/dwn/keeper/keeper.go | 6 +- x/dwn/keeper/permission_validator.go | 4 +- x/dwn/keeper/vault_operations.go | 2 +- x/dwn/keeper/vault_secure.go | 6 +- x/dwn/types/ucan_capabilities.go | 2 +- x/svc/keeper/capability.go | 2 +- x/svc/keeper/keeper.go | 4 +- x/svc/keeper/permission_validator.go | 4 +- x/svc/types/ucan_capabilities.go | 2 +- 1306 files changed, 2854 insertions(+), 316038 deletions(-) rename cmd/snrd/.cz.toml => .cz.toml (100%) create mode 100644 MIGRATE_CRYPTO.md create mode 100644 MIGRATE_HWAY.md create mode 100644 MIGRATE_MOTR.md delete mode 100644 biome.json delete mode 100644 bridge/bridge.go delete mode 100644 bridge/bridge_test.go delete mode 100644 bridge/config.go delete mode 100644 bridge/handlers/auth.go delete mode 100644 bridge/handlers/benchmark_test.go delete mode 100644 bridge/handlers/broadcast.go delete mode 100644 bridge/handlers/errors.go delete mode 100644 bridge/handlers/handlers_test.go delete mode 100644 bridge/handlers/health.go delete mode 100644 bridge/handlers/oauth2_clients.go delete mode 100644 bridge/handlers/oauth2_delegation.go delete mode 100644 bridge/handlers/oauth2_provider.go delete mode 100644 bridge/handlers/oauth2_refresh.go delete mode 100644 bridge/handlers/oauth2_register.go delete mode 100644 bridge/handlers/oauth2_scopes.go delete mode 100644 bridge/handlers/oauth2_security.go delete mode 100644 bridge/handlers/oauth2_token_exchange.go delete mode 100644 bridge/handlers/oauth2_types.go delete mode 100644 bridge/handlers/oidc.go delete mode 100644 bridge/handlers/oidc_test.go delete mode 100644 bridge/handlers/siop.go delete mode 100644 bridge/handlers/siop_test.go delete mode 100644 bridge/handlers/types.go delete mode 100644 bridge/handlers/ucan_signer.go delete mode 100644 bridge/handlers/vault.go delete mode 100644 bridge/handlers/webauthn.go delete mode 100644 bridge/handlers/websocket.go delete mode 100644 bridge/queue.go delete mode 100644 bridge/server/benchmark_test.go delete mode 100644 bridge/server/server.go delete mode 100644 bridge/server/server_test.go delete mode 100644 bridge/tasks/attenuation.go delete mode 100644 bridge/tasks/generate.go delete mode 100644 bridge/tasks/signing.go delete mode 100644 bridge/tasks/tasks_test.go delete mode 100644 bridge/tasks/types.go delete mode 100644 bridge/testutils_test.go delete mode 100644 cmd/hway/.cz.toml delete mode 100644 cmd/hway/.goreleaser.yml delete mode 100644 cmd/hway/CHANGELOG.md delete mode 100644 cmd/hway/Dockerfile delete mode 100644 cmd/hway/Makefile delete mode 100644 cmd/hway/README.md delete mode 100644 cmd/hway/go.mod delete mode 100644 cmd/hway/go.sum delete mode 100644 cmd/hway/main.go delete mode 100644 cmd/hway/version.go delete mode 100644 cmd/motr/.cz.toml delete mode 100644 cmd/motr/.goreleaser.yml delete mode 100644 cmd/motr/CHANGELOG.md delete mode 100644 cmd/motr/Makefile delete mode 100644 cmd/motr/README.md delete mode 100644 cmd/motr/go.mod delete mode 100644 cmd/motr/go.sum delete mode 100644 cmd/motr/handlers.go delete mode 100644 cmd/motr/integration_test.go delete mode 100644 cmd/motr/jwt.go delete mode 100644 cmd/motr/main.go delete mode 100644 cmd/motr/oidc.go delete mode 100644 cmd/motr/payment.go delete mode 100644 cmd/motr/payment_security.go delete mode 100644 cmd/motr/security.go delete mode 100644 cmd/motr/version.go delete mode 100644 cmd/snrd/.goreleaser.yml delete mode 100644 cmd/snrd/CHANGELOG.md delete mode 100644 cmd/snrd/Dockerfile delete mode 100644 cmd/snrd/go.mod delete mode 100644 cmd/vault/.cz.toml delete mode 100644 cmd/vault/.goreleaser.yml delete mode 100644 cmd/vault/CHANGELOG.md delete mode 100644 cmd/vault/Makefile delete mode 100644 cmd/vault/README.md delete mode 100644 cmd/vault/go.mod delete mode 100644 cmd/vault/go.sum delete mode 100644 cmd/vault/main.go delete mode 100644 cmd/vault/version.go delete mode 100644 contracts/DAO/COMPLIANCE.md delete mode 100644 contracts/DAO/Cargo.toml delete mode 100644 contracts/DAO/IBC_INTEGRATION.md delete mode 100644 contracts/DAO/README.md delete mode 100644 contracts/DAO/SECURITY_AUDIT.md delete mode 100644 contracts/DAO/contracts/core/Cargo.toml delete mode 100644 contracts/DAO/contracts/core/src/contract.rs delete mode 100644 contracts/DAO/contracts/core/src/lib.rs delete mode 100644 contracts/DAO/contracts/core/src/msg.rs delete mode 100644 contracts/DAO/contracts/core/src/query.rs delete mode 100644 contracts/DAO/contracts/core/src/state.rs delete mode 100644 contracts/DAO/contracts/core/src/tests.rs delete mode 100644 contracts/DAO/contracts/pre-propose/Cargo.toml delete mode 100644 contracts/DAO/contracts/pre-propose/src/contract.rs delete mode 100644 contracts/DAO/contracts/pre-propose/src/lib.rs delete mode 100644 contracts/DAO/contracts/pre-propose/src/state.rs delete mode 100644 contracts/DAO/contracts/pre-propose/src/verification.rs delete mode 100644 contracts/DAO/contracts/proposals/Cargo.toml delete mode 100644 contracts/DAO/contracts/proposals/src/contract.rs delete mode 100644 contracts/DAO/contracts/proposals/src/identity.rs delete mode 100644 contracts/DAO/contracts/proposals/src/lib.rs delete mode 100644 contracts/DAO/contracts/proposals/src/msg.rs delete mode 100644 contracts/DAO/contracts/proposals/src/query.rs delete mode 100644 contracts/DAO/contracts/proposals/src/state.rs delete mode 100644 contracts/DAO/contracts/voting/Cargo.toml delete mode 100644 contracts/DAO/contracts/voting/src/bindings.rs delete mode 100644 contracts/DAO/contracts/voting/src/contract.rs delete mode 100644 contracts/DAO/contracts/voting/src/lib.rs delete mode 100644 contracts/DAO/contracts/voting/src/msg.rs delete mode 100644 contracts/DAO/contracts/voting/src/query.rs delete mode 100644 contracts/DAO/contracts/voting/src/state.rs delete mode 100644 contracts/DAO/contracts/voting/src/tests.rs delete mode 100644 contracts/DAO/docs/IMPLEMENTATION_SUMMARY.md delete mode 100644 contracts/DAO/packages/shared/Cargo.toml delete mode 100644 contracts/DAO/packages/shared/src/bindings.rs delete mode 100644 contracts/DAO/packages/shared/src/error.rs delete mode 100644 contracts/DAO/packages/shared/src/lib.rs delete mode 100644 contracts/DAO/packages/shared/src/msg.rs delete mode 100644 contracts/DAO/packages/shared/src/query.rs delete mode 100644 contracts/DAO/packages/shared/src/types.rs delete mode 100644 contracts/DAO/scripts/build_contracts.sh delete mode 100755 contracts/DAO/scripts/deploy-cosmos-hub.sh delete mode 100755 contracts/DAO/scripts/deploy.sh delete mode 100644 contracts/DAO/scripts/deploy_mainnet.sh delete mode 100644 contracts/DAO/scripts/deploy_testnet.sh delete mode 100644 contracts/DAO/scripts/migrate.sh delete mode 100644 contracts/DAO/scripts/setup_ibc.sh delete mode 100755 contracts/DAO/scripts/test-ibc-integration.sh delete mode 100644 contracts/DAO/scripts/testnet-config.json delete mode 100644 contracts/DAO/scripts/verify_deployment.sh delete mode 100644 contracts/DAO/tests/e2e/identity_dao_test.go.template delete mode 100644 contracts/DAO/tests/integration/did_integration_test.rs delete mode 100644 contracts/wSNR/.env.example delete mode 100644 contracts/wSNR/.gitignore delete mode 100644 contracts/wSNR/DEPLOY.md delete mode 100644 contracts/wSNR/Makefile delete mode 100644 contracts/wSNR/README.md delete mode 100755 contracts/wSNR/build.sh delete mode 100644 contracts/wSNR/foundry.toml delete mode 100644 contracts/wSNR/script/DeployWSNR.s.sol delete mode 100644 contracts/wSNR/src/WSNR.sol delete mode 100644 contracts/wSNR/src/interfaces/IWSNR.sol delete mode 100644 contracts/wSNR/test/WSNR.t.sol delete mode 100644 crypto/Makefile delete mode 100644 crypto/README.md delete mode 100644 crypto/accumulator/accumulator.go delete mode 100644 crypto/accumulator/accumulator_test.go delete mode 100644 crypto/accumulator/key.go delete mode 100644 crypto/accumulator/key_test.go delete mode 100644 crypto/accumulator/lib.go delete mode 100644 crypto/accumulator/lib_test.go delete mode 100644 crypto/accumulator/proof.go delete mode 100644 crypto/accumulator/proof_test.go delete mode 100644 crypto/accumulator/witness.go delete mode 100644 crypto/accumulator/witness_test.go delete mode 100644 crypto/aead/aes_gcm.go delete mode 100644 crypto/aead/aes_gcm_test.go delete mode 100644 crypto/argon2/kdf.go delete mode 100644 crypto/argon2/kdf_test.go delete mode 100644 crypto/bulletproof/generators.go delete mode 100644 crypto/bulletproof/generators_test.go delete mode 100644 crypto/bulletproof/helpers.go delete mode 100644 crypto/bulletproof/helpers_test.go delete mode 100644 crypto/bulletproof/ipp_prover.go delete mode 100644 crypto/bulletproof/ipp_prover_test.go delete mode 100644 crypto/bulletproof/ipp_verifier.go delete mode 100644 crypto/bulletproof/ipp_verifier_test.go delete mode 100644 crypto/bulletproof/range_batch_prover.go delete mode 100644 crypto/bulletproof/range_batch_prover_test.go delete mode 100644 crypto/bulletproof/range_batch_verifier.go delete mode 100644 crypto/bulletproof/range_batch_verifier_test.go delete mode 100644 crypto/bulletproof/range_prover.go delete mode 100644 crypto/bulletproof/range_prover_test.go delete mode 100644 crypto/bulletproof/range_verifier.go delete mode 100644 crypto/bulletproof/range_verifier_test.go delete mode 100755 crypto/core/README.md delete mode 100755 crypto/core/commit.go delete mode 100755 crypto/core/commit_test.go delete mode 100644 crypto/core/curves/bls12377_curve.go delete mode 100644 crypto/core/curves/bls12381_curve.go delete mode 100644 crypto/core/curves/curve.go delete mode 100644 crypto/core/curves/curve_test.go delete mode 100644 crypto/core/curves/ec_point.go delete mode 100644 crypto/core/curves/ec_point_test.go delete mode 100644 crypto/core/curves/ec_scalar.go delete mode 100755 crypto/core/curves/ecdsa.go delete mode 100644 crypto/core/curves/ed25519_curve.go delete mode 100644 crypto/core/curves/ed25519_curve_test.go delete mode 100755 crypto/core/curves/field.go delete mode 100755 crypto/core/curves/field_test.go delete mode 100644 crypto/core/curves/k256_bench_test.go delete mode 100644 crypto/core/curves/k256_curve.go delete mode 100755 crypto/core/curves/k256_curve_test.go delete mode 100644 crypto/core/curves/native/bls12381/bls12381.go delete mode 100644 crypto/core/curves/native/bls12381/fp.go delete mode 100755 crypto/core/curves/native/bls12381/fp12.go delete mode 100755 crypto/core/curves/native/bls12381/fp12_test.go delete mode 100755 crypto/core/curves/native/bls12381/fp2.go delete mode 100755 crypto/core/curves/native/bls12381/fp2_test.go delete mode 100755 crypto/core/curves/native/bls12381/fp6.go delete mode 100755 crypto/core/curves/native/bls12381/fp6_test.go delete mode 100644 crypto/core/curves/native/bls12381/fp_test.go delete mode 100644 crypto/core/curves/native/bls12381/fq.go delete mode 100644 crypto/core/curves/native/bls12381/fq_test.go delete mode 100644 crypto/core/curves/native/bls12381/g1.go delete mode 100644 crypto/core/curves/native/bls12381/g1_test.go delete mode 100644 crypto/core/curves/native/bls12381/g2.go delete mode 100644 crypto/core/curves/native/bls12381/g2_test.go delete mode 100644 crypto/core/curves/native/bls12381/gt.go delete mode 100755 crypto/core/curves/native/bls12381/pairings.go delete mode 100644 crypto/core/curves/native/bls12381/pairings_test.go delete mode 100644 crypto/core/curves/native/field.go delete mode 100755 crypto/core/curves/native/hash2field.go delete mode 100755 crypto/core/curves/native/isogeny.go delete mode 100644 crypto/core/curves/native/k256/fp/fp.go delete mode 100644 crypto/core/curves/native/k256/fp/fp_test.go delete mode 100755 crypto/core/curves/native/k256/fp/secp256k1_fp.go delete mode 100644 crypto/core/curves/native/k256/fq/fq.go delete mode 100644 crypto/core/curves/native/k256/fq/fq_test.go delete mode 100755 crypto/core/curves/native/k256/fq/secp256k1_fq.go delete mode 100644 crypto/core/curves/native/k256/point.go delete mode 100644 crypto/core/curves/native/k256/point_test.go delete mode 100755 crypto/core/curves/native/osswu.go delete mode 100644 crypto/core/curves/native/p256/fp/fp.go delete mode 100644 crypto/core/curves/native/p256/fp/fp_test.go delete mode 100755 crypto/core/curves/native/p256/fp/p256_fp.go delete mode 100644 crypto/core/curves/native/p256/fq/fq.go delete mode 100644 crypto/core/curves/native/p256/fq/fq_test.go delete mode 100755 crypto/core/curves/native/p256/fq/p256_fq.go delete mode 100644 crypto/core/curves/native/p256/point.go delete mode 100644 crypto/core/curves/native/p256/point_test.go delete mode 100755 crypto/core/curves/native/pasta/README.md delete mode 100644 crypto/core/curves/native/pasta/fp/fp.go delete mode 100755 crypto/core/curves/native/pasta/fp/fp_test.go delete mode 100755 crypto/core/curves/native/pasta/fp/pasta_fp.go delete mode 100644 crypto/core/curves/native/pasta/fq/fq.go delete mode 100755 crypto/core/curves/native/pasta/fq/fq_test.go delete mode 100755 crypto/core/curves/native/pasta/fq/pasta_fq.go delete mode 100755 crypto/core/curves/native/pasta/pallas.go delete mode 100755 crypto/core/curves/native/point.go delete mode 100644 crypto/core/curves/p256_bench_test.go delete mode 100644 crypto/core/curves/p256_curve.go delete mode 100755 crypto/core/curves/p256_curve_test.go delete mode 100644 crypto/core/curves/pallas_curve.go delete mode 100644 crypto/core/curves/pallas_curve_test.go delete mode 100644 crypto/core/curves/secp256k1/secp256k1.go delete mode 100644 crypto/core/curves/sp256_curve.go delete mode 100644 crypto/core/hash.go delete mode 100755 crypto/core/hash_test.go delete mode 100644 crypto/core/mod.go delete mode 100644 crypto/core/mod_test.go delete mode 100755 crypto/core/primes.go delete mode 100644 crypto/core/protocol/protocol.go delete mode 100644 crypto/daed/aes_siv.go delete mode 100644 crypto/daed/aes_siv_test.go delete mode 100755 crypto/dkg/frost/README.md delete mode 100644 crypto/dkg/frost/dkg_round1.go delete mode 100644 crypto/dkg/frost/dkg_round2.go delete mode 100644 crypto/dkg/frost/dkg_rounds_test.go delete mode 100644 crypto/dkg/frost/participant.go delete mode 100755 crypto/dkg/gennaro/README.md delete mode 100644 crypto/dkg/gennaro/participant.go delete mode 100644 crypto/dkg/gennaro/participant_test.go delete mode 100644 crypto/dkg/gennaro/round1.go delete mode 100644 crypto/dkg/gennaro/round2.go delete mode 100644 crypto/dkg/gennaro/round3.go delete mode 100644 crypto/dkg/gennaro/round4.go delete mode 100644 crypto/dkg/gennaro/rounds_test.go delete mode 100755 crypto/dkg/gennaro2p/README.md delete mode 100644 crypto/dkg/gennaro2p/genarro2p.go delete mode 100644 crypto/dkg/gennaro2p/genarro2p_test.go delete mode 100644 crypto/ecdsa/canonical.go delete mode 100644 crypto/ecdsa/canonical_test.go delete mode 100644 crypto/ecdsa/deterministic.go delete mode 100644 crypto/ecdsa/deterministic_test.go delete mode 100644 crypto/ecies/encrypt.go delete mode 100644 crypto/ecies/keys.go delete mode 100644 crypto/ecies/keys_test.go delete mode 100644 crypto/empty-module/bip39.go delete mode 100644 crypto/empty-module/go.mod delete mode 100644 crypto/go.mod delete mode 100644 crypto/go.sum delete mode 100644 crypto/internal/ed25519/edwards25519/const.go delete mode 100644 crypto/internal/ed25519/edwards25519/edwards25519.go delete mode 100644 crypto/internal/ed25519/edwards25519/edwards25519_test.go delete mode 100644 crypto/internal/ed25519/extra25519/extra25519.go delete mode 100644 crypto/internal/ed25519/extra25519/extra25519_test.go delete mode 100755 crypto/internal/err.go delete mode 100755 crypto/internal/hash.go delete mode 100755 crypto/internal/hash_test.go delete mode 100755 crypto/internal/point.go delete mode 100755 crypto/internal/testutils.go delete mode 100644 crypto/keys/didkey.go delete mode 100644 crypto/keys/didkey_test.go delete mode 100644 crypto/keys/methods.go delete mode 100644 crypto/keys/parsers/btc_parser.go delete mode 100644 crypto/keys/parsers/cosmos_parser.go delete mode 100644 crypto/keys/parsers/eth_parser.go delete mode 100644 crypto/keys/parsers/fil_parser.go delete mode 100644 crypto/keys/parsers/key_parser.go delete mode 100644 crypto/keys/parsers/sol_parser.go delete mode 100644 crypto/keys/parsers/ton_parser.go delete mode 100644 crypto/keys/pubkey.go delete mode 100644 crypto/keys/utils.go delete mode 100644 crypto/mpc/README.md delete mode 100644 crypto/mpc/codec.go delete mode 100644 crypto/mpc/codec_test.go delete mode 100644 crypto/mpc/enclave.go delete mode 100644 crypto/mpc/enclave_test.go delete mode 100644 crypto/mpc/import.go delete mode 100644 crypto/mpc/protocol.go delete mode 100644 crypto/mpc/spec/jwt.go delete mode 100644 crypto/mpc/spec/source.go delete mode 100644 crypto/mpc/spec/ucan.go delete mode 100644 crypto/mpc/utils.go delete mode 100644 crypto/mpc/verify.go delete mode 100644 crypto/ot/base/simplest/ot.go delete mode 100644 crypto/ot/base/simplest/ot_test.go delete mode 100644 crypto/ot/base/simplest/stream.go delete mode 100755 crypto/ot/base/simplest/util.go delete mode 100644 crypto/ot/extension/kos/kos.go delete mode 100644 crypto/ot/extension/kos/kos_test.go delete mode 100644 crypto/ot/extension/kos/stream.go delete mode 100644 crypto/ot/ottest/util.go delete mode 100755 crypto/paillier/README.md delete mode 100644 crypto/paillier/paillier.go delete mode 100644 crypto/paillier/psf.go delete mode 100644 crypto/paillier/psf_test.go delete mode 100644 crypto/password/validator.go delete mode 100644 crypto/password/validator_test.go delete mode 100644 crypto/salt/salt.go delete mode 100644 crypto/salt/salt_test.go delete mode 100644 crypto/secure/memory.go delete mode 100644 crypto/secure/memory_test.go delete mode 100644 crypto/security_test.go delete mode 100755 crypto/sharing/README.md delete mode 100644 crypto/sharing/ed25519_feldman_test.go delete mode 100644 crypto/sharing/feldman.go delete mode 100644 crypto/sharing/pedersen.go delete mode 100644 crypto/sharing/polynomial.go delete mode 100644 crypto/sharing/polynomial_test.go delete mode 100644 crypto/sharing/shamir.go delete mode 100644 crypto/sharing/shamir_test.go delete mode 100644 crypto/sharing/v1/bls12381g1_feldman_test.go delete mode 100644 crypto/sharing/v1/bls12381g1curve.go delete mode 100755 crypto/sharing/v1/bls12381g2_feldman_test.go delete mode 100644 crypto/sharing/v1/bls12381g2curve.go delete mode 100644 crypto/sharing/v1/common.go delete mode 100755 crypto/sharing/v1/ed25519_feldman_test.go delete mode 100644 crypto/sharing/v1/ed25519_pedersen_test.go delete mode 100644 crypto/sharing/v1/ed25519curve.go delete mode 100755 crypto/sharing/v1/ed25519curve_test.go delete mode 100644 crypto/sharing/v1/feldman.go delete mode 100755 crypto/sharing/v1/k256_feldman_test.go delete mode 100644 crypto/sharing/v1/k256_pedersen_test.go delete mode 100755 crypto/sharing/v1/p256_feldman_test.go delete mode 100644 crypto/sharing/v1/pedersen.go delete mode 100644 crypto/sharing/v1/polynomial.go delete mode 100755 crypto/sharing/v1/polynomial_test.go delete mode 100644 crypto/sharing/v1/shamir.go delete mode 100644 crypto/sharing/v1/shamir_test.go delete mode 100644 crypto/signatures/bbs/blind_signature.go delete mode 100644 crypto/signatures/bbs/blind_signature_context.go delete mode 100644 crypto/signatures/bbs/blind_signature_context_test.go delete mode 100644 crypto/signatures/bbs/message_generators.go delete mode 100644 crypto/signatures/bbs/pok_signature.go delete mode 100644 crypto/signatures/bbs/pok_signature_proof.go delete mode 100644 crypto/signatures/bbs/pok_signature_proof_test.go delete mode 100644 crypto/signatures/bbs/public_key.go delete mode 100644 crypto/signatures/bbs/secret_key.go delete mode 100644 crypto/signatures/bbs/signature.go delete mode 100644 crypto/signatures/bbs/signature_test.go delete mode 100755 crypto/signatures/bls/README.md delete mode 100644 crypto/signatures/bls/bls_sig/lib.go delete mode 100644 crypto/signatures/bls/bls_sig/lib_test.go delete mode 100755 crypto/signatures/bls/bls_sig/tiny_bls.go delete mode 100644 crypto/signatures/bls/bls_sig/tiny_bls_sig.go delete mode 100644 crypto/signatures/bls/bls_sig/tiny_bls_sig_aug_test.go delete mode 100644 crypto/signatures/bls/bls_sig/tiny_bls_sig_basic_test.go delete mode 100644 crypto/signatures/bls/bls_sig/tiny_bls_sig_pop_test.go delete mode 100755 crypto/signatures/bls/bls_sig/usual_bls.go delete mode 100644 crypto/signatures/bls/bls_sig/usual_bls_sig.go delete mode 100644 crypto/signatures/bls/bls_sig/usual_bls_sig_aug_test.go delete mode 100644 crypto/signatures/bls/bls_sig/usual_bls_sig_basic_test.go delete mode 100644 crypto/signatures/bls/bls_sig/usual_bls_sig_pop_test.go delete mode 100755 crypto/signatures/bls/rust/Cargo.toml delete mode 100755 crypto/signatures/bls/rust/README.md delete mode 100755 crypto/signatures/bls/rust/src/main.rs delete mode 100644 crypto/signatures/bls/tests/bls/main.go delete mode 100644 crypto/signatures/common/challenge.go delete mode 100644 crypto/signatures/common/commitment.go delete mode 100755 crypto/signatures/common/hmacdrbg.go delete mode 100644 crypto/signatures/common/nonce.go delete mode 100644 crypto/signatures/common/proof_committed_builder.go delete mode 100644 crypto/signatures/common/proof_message.go delete mode 100644 crypto/signatures/common/signature_blinding.go delete mode 100755 crypto/signatures/schnorr/mina/bitvector.go delete mode 100644 crypto/signatures/schnorr/mina/challenge_derive.go delete mode 100644 crypto/signatures/schnorr/mina/keys.go delete mode 100644 crypto/signatures/schnorr/mina/keys_test.go delete mode 100644 crypto/signatures/schnorr/mina/poseidon_config.go delete mode 100644 crypto/signatures/schnorr/mina/poseidon_hash.go delete mode 100644 crypto/signatures/schnorr/mina/poseidon_hash_test.go delete mode 100644 crypto/signatures/schnorr/mina/roinput.go delete mode 100644 crypto/signatures/schnorr/mina/signature.go delete mode 100644 crypto/signatures/schnorr/mina/txn.go delete mode 100644 crypto/signatures/schnorr/nem/ed25519_keccak.go delete mode 100755 crypto/signatures/schnorr/nem/ed25519_keccak_test.go delete mode 100644 crypto/subtle/hkdf.go delete mode 100644 crypto/subtle/random/random.go delete mode 100644 crypto/subtle/subtle.go delete mode 100644 crypto/subtle/x25519.go delete mode 100755 crypto/tecdsa/dklsv1/README.md delete mode 100644 crypto/tecdsa/dklsv1/boilerplate.go delete mode 100644 crypto/tecdsa/dklsv1/dealer/dealer.go delete mode 100644 crypto/tecdsa/dklsv1/dealer/dealer_test.go delete mode 100644 crypto/tecdsa/dklsv1/dkg/dkg.go delete mode 100644 crypto/tecdsa/dklsv1/dkg/dkg_test.go delete mode 100644 crypto/tecdsa/dklsv1/dkgserializers.go delete mode 100644 crypto/tecdsa/dklsv1/protocol.go delete mode 100644 crypto/tecdsa/dklsv1/protocol_test.go delete mode 100644 crypto/tecdsa/dklsv1/refresh/refresh.go delete mode 100644 crypto/tecdsa/dklsv1/refresh/refresh_test.go delete mode 100644 crypto/tecdsa/dklsv1/refreshserializers.go delete mode 100644 crypto/tecdsa/dklsv1/sign/multiply.go delete mode 100644 crypto/tecdsa/dklsv1/sign/multiply_test.go delete mode 100644 crypto/tecdsa/dklsv1/sign/sign.go delete mode 100644 crypto/tecdsa/dklsv1/sign/sign_test.go delete mode 100644 crypto/tecdsa/dklsv1/signserializers.go delete mode 100755 crypto/ted25519/frost/README.md delete mode 100644 crypto/ted25519/frost/challenge_derive.go delete mode 100644 crypto/ted25519/frost/participant.go delete mode 100644 crypto/ted25519/frost/round1.go delete mode 100644 crypto/ted25519/frost/round2.go delete mode 100644 crypto/ted25519/frost/round3.go delete mode 100644 crypto/ted25519/frost/rounds_test.go delete mode 100644 crypto/ted25519/ted25519/ed25519.go delete mode 100644 crypto/ted25519/ted25519/ed25519_test.go delete mode 100644 crypto/ted25519/ted25519/ext.go delete mode 100644 crypto/ted25519/ted25519/ext_test.go delete mode 100644 crypto/ted25519/ted25519/keygen.go delete mode 100644 crypto/ted25519/ted25519/keygen_test.go delete mode 100644 crypto/ted25519/ted25519/noncegen.go delete mode 100644 crypto/ted25519/ted25519/noncegen_test.go delete mode 100755 crypto/ted25519/ted25519/partialsig.go delete mode 100644 crypto/ted25519/ted25519/partialsig_test.go delete mode 100644 crypto/ted25519/ted25519/sigagg.go delete mode 100755 crypto/ted25519/ted25519/sigagg_test.go delete mode 100644 crypto/ted25519/ted25519/twobytwo_test.go delete mode 100644 crypto/ucan/capability.go delete mode 100644 crypto/ucan/crypto.go delete mode 100644 crypto/ucan/jwt.go delete mode 100644 crypto/ucan/mpc.go delete mode 100644 crypto/ucan/source.go delete mode 100644 crypto/ucan/stubs.go delete mode 100644 crypto/ucan/ucan_test.go delete mode 100644 crypto/ucan/vault.go delete mode 100644 crypto/ucan/verifier.go delete mode 100644 crypto/vrf/vrf.go delete mode 100644 crypto/vrf/vrf_test.go delete mode 100644 crypto/wasm/signer.go delete mode 100644 crypto/wasm/signer_test.go delete mode 100644 crypto/wasm/verifier.go delete mode 100644 crypto/wasm/verifier_test.go delete mode 100644 crypto/zkp/schnorr/schnorr.go delete mode 100644 crypto/zkp/schnorr/schnorr_test.go delete mode 100644 docs/reference/contracts/DAO.mdx delete mode 100644 docs/reference/contracts/wSNR.mdx rename scripts/install.sh => install.sh (100%) delete mode 100644 internal/migrations/001_accounts_table.sql delete mode 100644 internal/migrations/002_credentials_table.sql delete mode 100644 internal/migrations/003_profiles_table.sql delete mode 100644 internal/migrations/004_vaults_table.sql delete mode 100644 internal/migrations/005_create_cosmos_registry.sql delete mode 100644 internal/migrations/006_execute_cosmos_registry.sql delete mode 100644 internal/migrations/007_webauthn_to_vc_func.sql delete mode 100644 internal/migrations/008_create_coinpaprika_market_data.sql delete mode 100644 internal/migrations/009_webauthn_options_functions.sql delete mode 100644 internal/migrations/010_crypto_asset_symbol_linking.sql delete mode 100644 internal/migrations/011_common_functions.sql delete mode 100644 internal/migrations/012_crypto_coin_price_data.sql delete mode 100644 internal/migrations/013_add_asset_quality_filters.sql delete mode 100644 internal/migrations/014_sessions_table.sql delete mode 100644 package.json delete mode 100644 packages/com/.cz.toml delete mode 100644 packages/com/package.json delete mode 100644 packages/com/src/constants/index.ts delete mode 100644 packages/com/src/index.ts delete mode 100644 packages/com/src/types/analytics.ts delete mode 100644 packages/com/src/types/api.ts delete mode 100644 packages/com/src/types/common.ts delete mode 100644 packages/com/src/types/domain.ts delete mode 100644 packages/com/src/types/index.ts delete mode 100644 packages/com/src/types/permission.ts delete mode 100644 packages/com/src/types/service.ts delete mode 100644 packages/com/src/types/user.ts delete mode 100644 packages/com/src/utils/array.ts delete mode 100644 packages/com/src/utils/chart.ts delete mode 100644 packages/com/src/utils/date.ts delete mode 100644 packages/com/src/utils/format.ts delete mode 100644 packages/com/src/utils/index.ts delete mode 100644 packages/com/src/utils/validation.ts delete mode 100644 packages/com/tsconfig.json delete mode 100644 packages/com/tsup.config.ts delete mode 100644 packages/es/.cz.toml delete mode 100644 packages/es/.gitignore delete mode 100644 packages/es/README.md delete mode 100644 packages/es/biome.json delete mode 100644 packages/es/buf.gen.yaml delete mode 100644 packages/es/buf.lock delete mode 100644 packages/es/examples/autoloader.html delete mode 100644 packages/es/examples/ipfs-enclave-usage.ts delete mode 100644 packages/es/examples/motor-browser-test.html delete mode 100644 packages/es/examples/motor-usage.ts delete mode 100644 packages/es/examples/plugins-usage.ts delete mode 100644 packages/es/examples/webauthn-enhanced.html delete mode 100644 packages/es/package.json delete mode 100644 packages/es/scripts/gen-protobufs.mjs delete mode 100644 packages/es/scripts/gen-registry.mjs delete mode 100755 packages/es/scripts/protoc-gen-cosmes.mjs delete mode 100644 packages/es/src/autoloader.js delete mode 100644 packages/es/src/client/apis/broadcastTx.ts delete mode 100644 packages/es/src/client/apis/getAccount.ts delete mode 100644 packages/es/src/client/apis/getCw20Balance.ts delete mode 100644 packages/es/src/client/apis/getNativeBalances.ts delete mode 100644 packages/es/src/client/apis/getTx.ts delete mode 100644 packages/es/src/client/apis/pollTx.ts delete mode 100644 packages/es/src/client/apis/queryContract.ts delete mode 100644 packages/es/src/client/apis/simulateAstroportSinglePoolSwap.ts delete mode 100644 packages/es/src/client/apis/simulateKujiraSinglePoolSwap.ts delete mode 100644 packages/es/src/client/apis/simulateTx.ts delete mode 100644 packages/es/src/client/auth/README.md delete mode 100644 packages/es/src/client/auth/examples.ts delete mode 100644 packages/es/src/client/auth/index.ts delete mode 100644 packages/es/src/client/auth/test-webauthn.html delete mode 100644 packages/es/src/client/auth/webauthn.test.ts delete mode 100644 packages/es/src/client/auth/webauthn.ts delete mode 100644 packages/es/src/client/clients/FetchClient.ts delete mode 100644 packages/es/src/client/clients/RpcClient.ts delete mode 100644 packages/es/src/client/index.ts delete mode 100644 packages/es/src/client/models/Adapter.ts delete mode 100644 packages/es/src/client/models/MsgBeginRedelegate.ts delete mode 100644 packages/es/src/client/models/MsgDelegate.ts delete mode 100644 packages/es/src/client/models/MsgIbcTransfer.ts delete mode 100644 packages/es/src/client/models/MsgSend.ts delete mode 100644 packages/es/src/client/models/MsgStoreCode.ts delete mode 100644 packages/es/src/client/models/MsgUndelegate.ts delete mode 100644 packages/es/src/client/models/MsgWithdrawDelegatorRewards.ts delete mode 100644 packages/es/src/client/models/MsgWithdrawValidatorCommission.ts delete mode 100644 packages/es/src/client/models/Secp256k1PubKey.ts delete mode 100644 packages/es/src/client/models/Tx.ts delete mode 100644 packages/es/src/client/utils/calculateFee.ts delete mode 100644 packages/es/src/client/utils/toAny.ts delete mode 100644 packages/es/src/client/utils/toBaseAccount.ts delete mode 100644 packages/es/src/client/utils/wait.ts delete mode 100644 packages/es/src/codec/address.test.ts delete mode 100644 packages/es/src/codec/address.ts delete mode 100644 packages/es/src/codec/ethhex.ts delete mode 100644 packages/es/src/codec/index.ts delete mode 100644 packages/es/src/codec/key.test.ts delete mode 100644 packages/es/src/codec/key.ts delete mode 100644 packages/es/src/codec/serialise.test.ts delete mode 100644 packages/es/src/codec/serialise.ts delete mode 100644 packages/es/src/codec/sign.test.ts delete mode 100644 packages/es/src/codec/sign.ts delete mode 100644 packages/es/src/codec/verify.test.ts delete mode 100644 packages/es/src/codec/verify.ts delete mode 100644 packages/es/src/index.ts delete mode 100644 packages/es/src/plugin/README.md delete mode 100644 packages/es/src/plugin/__tests__/enclave.test.ts delete mode 100644 packages/es/src/plugin/client-ipfs.ts delete mode 100644 packages/es/src/plugin/client.ts delete mode 100644 packages/es/src/plugin/enclave.ts delete mode 100644 packages/es/src/plugin/index.ts delete mode 100644 packages/es/src/plugin/loader.ts delete mode 100644 packages/es/src/plugin/storage.e2e.test.ts delete mode 100644 packages/es/src/plugin/storage.test.ts delete mode 100644 packages/es/src/plugin/storage.ts delete mode 100644 packages/es/src/plugin/types.ts delete mode 100644 packages/es/src/protobufs/cosmos/app/runtime/v1alpha1/module_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/app/v1alpha1/config_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/app/v1alpha1/module_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/app/v1alpha1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/app/v1alpha1/query_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/autocli/v1/options_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/autocli/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/autocli/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/abci/v1beta1/abci_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/node/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/node/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/query/v1beta1/pagination_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/types_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/base/v1beta1/coin_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/ed25519/keys_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/hd/v1/hd_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/keyring/v1/record_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/multisig/keys_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/multisig/v1beta1/multisig_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/secp256k1/keys_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/crypto/secp256r1/keys_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/ics23/v1/proofs_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/reflection/v1/reflection_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/reflection/v1/reflection_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/internal/kv/v1beta1/kv_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/snapshots/v1/snapshot_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/v1beta1/commit_info_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/store/v1beta1/listening_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/tx/config/v1/config_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/tx/signing/v1beta1/signing_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/tx/v1beta1/service_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmos/tx/v1beta1/service_pb.ts delete mode 100644 packages/es/src/protobufs/cosmos/tx/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/authz_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/ibc_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/proposal_legacy_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/cosmwasm/wasm/v1/types_pb.ts delete mode 100644 packages/es/src/protobufs/dex/module/v1/module_pb.ts delete mode 100644 packages/es/src/protobufs/dex/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/dex/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/dex/v1/ica_pb.ts delete mode 100644 packages/es/src/protobufs/dex/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/dex/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/dex/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/dex/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/did/module/v1/module_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/did/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/state_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/did/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/did/v1/types_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/module/v1/module_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/state_pb.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/dwn/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/crypto/v1/ethsecp256k1/keys_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/evm_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ethermint/evm/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/feemarket_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ethermint/feemarket/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/types/v1/account_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/types/v1/dynamic_fee_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/types/v1/indexer_pb.ts delete mode 100644 packages/es/src/protobufs/ethermint/types/v1/web3_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/controller_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/genesis/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/host_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/account_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/metadata_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/packet_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/packet_forward_middleware/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/rate_limiting_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/authz_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/denomtrace_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/packet_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/token_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/transfer_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/applications/transfer/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/channel_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/packet_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/channel/v2/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/client_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/config_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/counterparty_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/client/v2/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/commitment/v1/commitment_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/commitment/v2/commitment_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/connection_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/core/connection/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/core/types/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/solomachine/v2/solomachine_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/solomachine/v3/solomachine_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/tendermint/v1/tendermint_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/ibc/lightclients/wasm/v1/wasm_pb.ts delete mode 100644 packages/es/src/protobufs/index.ts delete mode 100644 packages/es/src/protobufs/osmosis/accum/v1beta1/accum_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/incentive_record_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/pool_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/position_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tick_info_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/instantiate_msg_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_query_msg_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_query_msg_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/downtime_duration_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/epochs/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/epochs/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/epochs/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/balancerPool_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/shared_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v2/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/gamm/v2/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibchooks/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibchooks/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibchooks/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibchooks/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/gauge_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/group_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/incentives/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/lock_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/lockup/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/mint/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/mint/v1beta1/mint_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/mint/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/mint/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/incentives_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolincentives/v1beta1/shared_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/module_route_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/swap_route_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/taker_fee_share_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tracked_volume_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v2/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/poolmanager/v2/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/protorev_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/models_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/store/v1beta1/tree_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/superfluid_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/superfluid/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/authorityMetadata_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/twap/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/twap/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/twap/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/twap/v1beta1/twap_record_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/feetoken_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/gov_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/params_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/valsetpref/v1beta1/state_pb.ts delete mode 100644 packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_pb.ts delete mode 100644 packages/es/src/protobufs/svc/module/v1/module_pb.ts delete mode 100644 packages/es/src/protobufs/svc/v1/events_pb.ts delete mode 100644 packages/es/src/protobufs/svc/v1/genesis_pb.ts delete mode 100644 packages/es/src/protobufs/svc/v1/query_cosmes.ts delete mode 100644 packages/es/src/protobufs/svc/v1/query_pb.ts delete mode 100644 packages/es/src/protobufs/svc/v1/state_pb.ts delete mode 100644 packages/es/src/protobufs/svc/v1/tx_cosmes.ts delete mode 100644 packages/es/src/protobufs/svc/v1/tx_pb.ts delete mode 100644 packages/es/src/registry/apis/getChainRegistryAssetList.ts delete mode 100644 packages/es/src/registry/apis/getChainRegistryChainInfo.ts delete mode 100644 packages/es/src/registry/index.ts delete mode 100644 packages/es/src/registry/types/ChainRegistryAssetList.ts delete mode 100644 packages/es/src/registry/types/ChainRegistryChainInfo.ts delete mode 100644 packages/es/src/typeutils/prettify.ts delete mode 100644 packages/es/src/wallet/constants/WalletName.ts delete mode 100644 packages/es/src/wallet/constants/WalletType.ts delete mode 100644 packages/es/src/wallet/index.ts delete mode 100644 packages/es/src/wallet/utils/os.ts delete mode 100644 packages/es/src/wallet/utils/sequence.test.ts delete mode 100644 packages/es/src/wallet/utils/sequence.ts delete mode 100644 packages/es/src/wallet/utils/verify.ts delete mode 100644 packages/es/src/wallet/utils/window.ts delete mode 100644 packages/es/src/wallet/walletconnect/QRCodeModal.ts delete mode 100644 packages/es/src/wallet/walletconnect/WalletConnectV1.ts delete mode 100644 packages/es/src/wallet/walletconnect/WalletConnectV2.ts delete mode 100644 packages/es/src/wallet/walletconnect/qrcodegen.ts delete mode 100644 packages/es/src/wallet/wallets/ConnectedWallet.ts delete mode 100644 packages/es/src/wallet/wallets/WalletController.ts delete mode 100644 packages/es/src/wallet/wallets/WalletError.ts delete mode 100644 packages/es/src/wallet/wallets/mnemonic/MnemonicWallet.ts delete mode 100644 packages/es/src/wallet/wallets/window.d.ts delete mode 100644 packages/es/src/worker/README.md delete mode 100644 packages/es/src/worker/client.ts delete mode 100644 packages/es/src/worker/global.d.ts delete mode 100644 packages/es/src/worker/index.ts delete mode 100644 packages/es/src/worker/motor-worker.js delete mode 100644 packages/es/src/worker/motor.test.ts.bak delete mode 100644 packages/es/src/worker/oidc.ts delete mode 100644 packages/es/src/worker/payment-handler.d.ts delete mode 100644 packages/es/src/worker/payment.ts delete mode 100644 packages/es/src/worker/plugin.ts delete mode 100644 packages/es/src/worker/register.ts delete mode 100644 packages/es/src/worker/types.ts delete mode 100644 packages/es/src/worker/worker.ts delete mode 100644 packages/es/test/plugins.test.ts delete mode 100644 packages/es/test/setup.ts delete mode 100644 packages/es/tests/integration/ipfs-integration.test.ts delete mode 100644 packages/es/tsconfig.json delete mode 100644 packages/es/vitest.config.ts delete mode 100644 packages/pkl/.cz.toml delete mode 100755 packages/pkl/Makefile delete mode 100644 packages/pkl/README.md delete mode 100755 packages/pkl/cli/index.js delete mode 100644 packages/pkl/package.json delete mode 100644 packages/pkl/src/base.web/Manifest.pkl delete mode 100644 packages/pkl/src/base.web/OpenIDPayload.pkl delete mode 100644 packages/pkl/src/base.web/PklProject delete mode 100644 packages/pkl/src/base.web/PklProject.deps.json delete mode 100644 packages/pkl/src/base.web/VerifiableCredential.pkl delete mode 100644 packages/pkl/src/basePklProject.pkl delete mode 100644 packages/pkl/src/cosmos.chain/App.pkl delete mode 100644 packages/pkl/src/cosmos.chain/Client.pkl delete mode 100644 packages/pkl/src/cosmos.chain/Config.pkl delete mode 100644 packages/pkl/src/cosmos.chain/Genesis.pkl delete mode 100644 packages/pkl/src/cosmos.chain/PklProject delete mode 100644 packages/pkl/src/cosmos.chain/PklProject.deps.json delete mode 100644 packages/pkl/src/cosmos.params/Asset.pkl delete mode 100644 packages/pkl/src/cosmos.params/Chain.pkl delete mode 100644 packages/pkl/src/cosmos.params/PklProject delete mode 100644 packages/pkl/src/cosmos.params/PklProject.deps.json delete mode 100644 packages/pkl/src/ipfs.node/Config.pkl delete mode 100644 packages/pkl/src/ipfs.node/PklProject delete mode 100644 packages/pkl/src/ipfs.node/PklProject.deps.json delete mode 100644 packages/pkl/src/matrix.element/Config.pkl delete mode 100644 packages/pkl/src/matrix.element/PklProject delete mode 100644 packages/pkl/src/matrix.element/PklProject.deps.json delete mode 100644 packages/pkl/src/matrix.server/AppService.pkl delete mode 100644 packages/pkl/src/matrix.server/PklProject delete mode 100644 packages/pkl/src/matrix.server/PklProject.deps.json delete mode 100644 packages/pkl/src/matrix.server/Synapse.pkl delete mode 100644 packages/pkl/src/sonr.testnet/Config.pkl delete mode 100644 packages/pkl/src/sonr.testnet/PklProject delete mode 100644 packages/pkl/src/sonr.testnet/PklProject.deps.json delete mode 100644 packages/pkl/src/sonr.testnet/chain/app.pkl delete mode 100644 packages/pkl/src/sonr.testnet/chain/client.pkl delete mode 100644 packages/pkl/src/sonr.testnet/chain/config.pkl delete mode 100644 packages/pkl/src/sonr.testnet/chain/genesis.pkl delete mode 100644 packages/sdk/.cz.toml delete mode 100644 packages/sdk/README.md delete mode 100644 packages/sdk/package.json delete mode 100644 packages/sdk/src/index.ts delete mode 100644 packages/sdk/src/webauthn/client.ts delete mode 100644 packages/sdk/src/webauthn/index.ts delete mode 100644 packages/sdk/src/webauthn/types.ts delete mode 100644 packages/sdk/tsconfig.json delete mode 100644 packages/ui/.cz.toml delete mode 100644 packages/ui/README.md delete mode 100644 packages/ui/components.json delete mode 100644 packages/ui/package.json delete mode 100644 packages/ui/src/components/SignInWithSonr.tsx delete mode 100644 packages/ui/src/components/SignInWithSonrModal.tsx delete mode 100644 packages/ui/src/components/blocks/sign-in-flow.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/ActivityChart.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/MetricsCard.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/PerformanceMetrics.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/RequestPatternChart.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/TimeRangeSelector.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/UsageChart.tsx delete mode 100644 packages/ui/src/components/dashboard/analytics/index.ts delete mode 100644 packages/ui/src/components/dashboard/domain/DNSInstructions.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DNSRecordDisplay.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DomainDashboard.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DomainList.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DomainSelector.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DomainStatus.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/DomainVerificationFlow.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/VerificationProgress.tsx delete mode 100644 packages/ui/src/components/dashboard/domain/index.ts delete mode 100644 packages/ui/src/components/dashboard/layout/BreadcrumbNav.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/DashboardContent.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/DashboardHeader.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/DashboardSidebar.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/MobileNav.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/ThemeToggle.tsx delete mode 100644 packages/ui/src/components/dashboard/layout/index.ts delete mode 100644 packages/ui/src/components/dashboard/permissions/PermissionAuditLog.tsx delete mode 100644 packages/ui/src/components/dashboard/permissions/PermissionGrid.tsx delete mode 100644 packages/ui/src/components/dashboard/permissions/PermissionRequest.tsx delete mode 100644 packages/ui/src/components/dashboard/permissions/PermissionSelector.tsx delete mode 100644 packages/ui/src/components/dashboard/permissions/UCANViewer.tsx delete mode 100644 packages/ui/src/components/dashboard/permissions/index.ts delete mode 100644 packages/ui/src/components/index.ts delete mode 100644 packages/ui/src/components/ui/alert.tsx delete mode 100644 packages/ui/src/components/ui/badge.tsx delete mode 100644 packages/ui/src/components/ui/breadcrumb.tsx delete mode 100644 packages/ui/src/components/ui/button.tsx delete mode 100644 packages/ui/src/components/ui/calendar.tsx delete mode 100644 packages/ui/src/components/ui/card.tsx delete mode 100644 packages/ui/src/components/ui/chart.tsx delete mode 100644 packages/ui/src/components/ui/checkbox.tsx delete mode 100644 packages/ui/src/components/ui/collapsible.tsx delete mode 100644 packages/ui/src/components/ui/command.tsx delete mode 100644 packages/ui/src/components/ui/dialog.tsx delete mode 100644 packages/ui/src/components/ui/dropdown-menu.tsx delete mode 100644 packages/ui/src/components/ui/error-alert.tsx delete mode 100644 packages/ui/src/components/ui/form.tsx delete mode 100644 packages/ui/src/components/ui/input.tsx delete mode 100644 packages/ui/src/components/ui/label.tsx delete mode 100644 packages/ui/src/components/ui/popover.tsx delete mode 100644 packages/ui/src/components/ui/progress.tsx delete mode 100644 packages/ui/src/components/ui/select.tsx delete mode 100644 packages/ui/src/components/ui/separator.tsx delete mode 100644 packages/ui/src/components/ui/sheet.tsx delete mode 100644 packages/ui/src/components/ui/sidebar.tsx delete mode 100644 packages/ui/src/components/ui/skeleton.tsx delete mode 100644 packages/ui/src/components/ui/table.tsx delete mode 100644 packages/ui/src/components/ui/tabs.tsx delete mode 100644 packages/ui/src/components/ui/textarea.tsx delete mode 100644 packages/ui/src/components/ui/toggle.tsx delete mode 100644 packages/ui/src/components/ui/tooltip.tsx delete mode 100644 packages/ui/src/hooks/use-mobile.ts delete mode 100644 packages/ui/src/hooks/useSignInWithSonr.ts delete mode 100644 packages/ui/src/lib/oauth.ts delete mode 100644 packages/ui/src/lib/utils.ts delete mode 100644 packages/ui/src/styles/globals.css delete mode 100644 packages/ui/tailwind.config.js delete mode 100644 packages/ui/tsconfig.json rename cmd/snrd/plugin.json => plugin.json (100%) delete mode 100644 pnpm-lock.yaml delete mode 100644 pnpm-workspace.yaml delete mode 100644 process-compose.yaml delete mode 100644 scripts/convert-swagger.js delete mode 100644 test/integration/cross_module_auth_test.go delete mode 100644 test/integration/encryption_security_test.go delete mode 100644 test/integration/oidc_ucan_flow_test.go delete mode 100644 test/integration/performance_benchmark_test.go delete mode 100644 test/integration/security_audit_test.go delete mode 100644 test/integration/ucan_workflow_test.go delete mode 100644 test/ucan_integration_test.go delete mode 100644 tsconfig.json delete mode 100644 turbo.json delete mode 100644 types/coins/coins.go delete mode 100644 types/coins/coins_test.go delete mode 100644 types/coins/derivation.go delete mode 100644 types/coins/derivation_test.go delete mode 100644 types/coins/transaction.go delete mode 100644 types/coins/transaction_test.go delete mode 100644 types/coins/wallet.go delete mode 100644 types/coins/wallet_test.go delete mode 100644 types/ipfs/client.go delete mode 100644 types/ipfs/file.go delete mode 100644 types/ipfs/folder.go delete mode 100644 types/txns/address.go delete mode 100644 types/txns/builder.go delete mode 100644 types/txns/builder_test.go delete mode 100644 types/txns/encoding.go delete mode 100644 types/txns/errors.go delete mode 100644 types/txns/examples_test.go delete mode 100644 types/txns/fees.go delete mode 100644 types/txns/fees_test.go delete mode 100644 types/txns/types.go delete mode 100644 types/ucan_capabilities.go delete mode 100644 types/webauthn/ATTESTATION.md delete mode 100644 types/webauthn/assertion.go delete mode 100644 types/webauthn/assertion_test.go delete mode 100644 types/webauthn/attestation.go delete mode 100644 types/webauthn/attestation_androidkey.go delete mode 100644 types/webauthn/attestation_androidkey_test.go delete mode 100644 types/webauthn/attestation_apple.go delete mode 100644 types/webauthn/attestation_apple_test.go delete mode 100644 types/webauthn/attestation_packed.go delete mode 100644 types/webauthn/attestation_packed_test.go delete mode 100644 types/webauthn/attestation_safetynet.go delete mode 100644 types/webauthn/attestation_safetynet_test.go delete mode 100644 types/webauthn/attestation_test.go delete mode 100644 types/webauthn/attestation_tpm.go delete mode 100644 types/webauthn/attestation_tpm_test.go delete mode 100644 types/webauthn/attestation_u2f.go delete mode 100644 types/webauthn/attestation_u2f_test.go delete mode 100644 types/webauthn/authenticator.go delete mode 100644 types/webauthn/authenticator_test.go delete mode 100644 types/webauthn/base64.go delete mode 100644 types/webauthn/base64_test.go delete mode 100644 types/webauthn/challenge.go delete mode 100644 types/webauthn/challenge_test.go delete mode 100644 types/webauthn/client.go delete mode 100644 types/webauthn/client_test.go delete mode 100644 types/webauthn/const.go delete mode 100644 types/webauthn/credential.go delete mode 100644 types/webauthn/credential_test.go delete mode 100644 types/webauthn/decoder.go delete mode 100644 types/webauthn/doc.go delete mode 100644 types/webauthn/entities.go delete mode 100644 types/webauthn/errors.go delete mode 100644 types/webauthn/extensions.go delete mode 100644 types/webauthn/func_test.go delete mode 100644 types/webauthn/metadata.go delete mode 100644 types/webauthn/metadata/const.go delete mode 100644 types/webauthn/metadata/decode.go delete mode 100644 types/webauthn/metadata/doc.go delete mode 100644 types/webauthn/metadata/metadata.go delete mode 100644 types/webauthn/metadata/metadata_test.go delete mode 100644 types/webauthn/metadata/passkey_authenticator.go delete mode 100644 types/webauthn/metadata/providers/cached/doc.go delete mode 100644 types/webauthn/metadata/providers/cached/options.go delete mode 100644 types/webauthn/metadata/providers/cached/provider.go delete mode 100644 types/webauthn/metadata/providers/cached/util.go delete mode 100644 types/webauthn/metadata/providers/memory/doc.go delete mode 100644 types/webauthn/metadata/providers/memory/options.go delete mode 100644 types/webauthn/metadata/providers/memory/provider.go delete mode 100644 types/webauthn/metadata/status.go delete mode 100644 types/webauthn/metadata/types.go delete mode 100644 types/webauthn/options.go delete mode 100644 types/webauthn/options_test.go delete mode 100644 types/webauthn/performance.go delete mode 100644 types/webauthn/revoke/LICENSE delete mode 100644 types/webauthn/revoke/README.md delete mode 100644 types/webauthn/revoke/doc.go delete mode 100644 types/webauthn/revoke/err.go delete mode 100644 types/webauthn/revoke/helpers.go delete mode 100644 types/webauthn/revoke/pkcs7.go delete mode 100644 types/webauthn/revoke/revoke.go delete mode 100644 types/webauthn/revoke/revoke_legacy.go delete mode 100644 types/webauthn/revoke/revoke_modern.go delete mode 100644 types/webauthn/sonr_services.go delete mode 100644 types/webauthn/sonr_utils.go delete mode 100644 types/webauthn/sonr_validation.go delete mode 100644 types/webauthn/webauthncbor/webauthncbor.go delete mode 100644 types/webauthn/webauthncose/const.go delete mode 100644 types/webauthn/webauthncose/ed25519.go delete mode 100644 types/webauthn/webauthncose/webauthncose.go delete mode 100644 types/webauthn/webauthncose/webauthncose_test.go delete mode 100644 web/auth/.cz.toml delete mode 100644 web/auth/.env.example delete mode 100644 web/auth/.env.staging delete mode 100644 web/auth/Dockerfile delete mode 100644 web/auth/README.md delete mode 100644 web/auth/biome.json delete mode 100644 web/auth/components.json delete mode 100644 web/auth/jest.config.js delete mode 100644 web/auth/next-env.d.ts delete mode 100644 web/auth/next.config.js delete mode 100644 web/auth/open-next.config.ts delete mode 100644 web/auth/package.json delete mode 100644 web/auth/src/app/.well-known/openid-configuration/route.ts delete mode 100644 web/auth/src/app/api/oidc/__tests__/discovery.test.ts delete mode 100644 web/auth/src/app/api/oidc/__tests__/token.test.ts delete mode 100644 web/auth/src/app/api/oidc/authorize/route.ts delete mode 100644 web/auth/src/app/api/oidc/jwks/route.ts delete mode 100644 web/auth/src/app/api/oidc/token/route.ts delete mode 100644 web/auth/src/app/api/oidc/userinfo/route.ts delete mode 100644 web/auth/src/app/capabilities/page.tsx delete mode 100644 web/auth/src/app/dashboard/page.tsx delete mode 100644 web/auth/src/app/globals.css delete mode 100644 web/auth/src/app/layout.tsx delete mode 100644 web/auth/src/app/login/page.tsx delete mode 100644 web/auth/src/app/oauth/authorize/page.tsx delete mode 100644 web/auth/src/app/oauth/authorize/themed-page.tsx delete mode 100644 web/auth/src/app/oauth/callback/page.tsx delete mode 100644 web/auth/src/app/oauth/consent/page.tsx delete mode 100644 web/auth/src/app/page.tsx delete mode 100644 web/auth/src/app/register/page.tsx delete mode 100644 web/auth/src/components/DelegationChainViewer.tsx delete mode 100644 web/auth/src/components/WebAuthnRegistration.tsx delete mode 100644 web/auth/src/hooks/useSession.ts delete mode 100644 web/auth/src/hooks/useWebAuthn.ts delete mode 100644 web/auth/src/lib/oidc.ts delete mode 100644 web/auth/src/lib/siop.ts delete mode 100644 web/auth/src/lib/ucan/delegation.ts delete mode 100644 web/auth/src/lib/ucan/scopes.ts delete mode 100644 web/auth/tailwind.config.js delete mode 100644 web/auth/tsconfig.json delete mode 100644 web/auth/wrangler.toml delete mode 100644 web/dash/.cz.toml delete mode 100644 web/dash/.env.example delete mode 100644 web/dash/.env.staging delete mode 100644 web/dash/Dockerfile delete mode 100644 web/dash/README.md delete mode 100644 web/dash/biome.json delete mode 100644 web/dash/components.json delete mode 100644 web/dash/next-env.d.ts delete mode 100644 web/dash/next.config.js delete mode 100644 web/dash/open-next.config.ts delete mode 100644 web/dash/package.json delete mode 100644 web/dash/postcss.config.js delete mode 100644 web/dash/src/app/domains/page.tsx delete mode 100644 web/dash/src/app/globals.css delete mode 100644 web/dash/src/app/layout.tsx delete mode 100644 web/dash/src/app/page.tsx delete mode 100644 web/dash/src/app/test-echo/page.tsx delete mode 100644 web/dash/src/components/APIKeyManager.tsx delete mode 100644 web/dash/src/components/DomainVerificationStatus.tsx delete mode 100644 web/dash/src/components/PermissionManager.tsx delete mode 100644 web/dash/src/components/ServiceRegistrationForm.tsx delete mode 100644 web/dash/src/components/auth-wrapper.tsx delete mode 100644 web/dash/src/components/theme-provider.tsx delete mode 100644 web/dash/src/hooks/useDomainVerification.ts delete mode 100644 web/dash/src/hooks/useService.ts delete mode 100644 web/dash/src/hooks/useServiceMetrics.ts delete mode 100644 web/dash/src/hooks/useServices.ts delete mode 100644 web/dash/src/lib/api/auth.ts delete mode 100644 web/dash/src/lib/api/index.ts delete mode 100644 web/dash/src/lib/api/svc.ts delete mode 100644 web/dash/src/types/analytics.ts delete mode 100644 web/dash/src/types/api.ts delete mode 100644 web/dash/src/types/domain.ts delete mode 100644 web/dash/src/types/index.ts delete mode 100644 web/dash/src/types/service.ts delete mode 100644 web/dash/tailwind.config.js delete mode 100644 web/dash/tsconfig.json delete mode 100644 web/dash/wrangler.toml mode change 100755 => 100644 x/dex/keeper/keeper.go create mode 100644 x/did/types/validation.go diff --git a/cmd/snrd/.cz.toml b/.cz.toml similarity index 100% rename from cmd/snrd/.cz.toml rename to .cz.toml diff --git a/.github/scopes.yml b/.github/scopes.yml index 05b83bc6f..0014f8f55 100644 --- a/.github/scopes.yml +++ b/.github/scopes.yml @@ -7,9 +7,6 @@ - app/** - go.mod - go.sum -- name: crypto - include: - - crypto/** - name: devops include: - .github/** @@ -22,52 +19,20 @@ - name: docs include: - docs/** -- name: hway - include: - - cmd/hway/** - - bridge/** - - types/** - name: dex include: - proto/dex/** - x/dex/** - name: did include: - - proto/dex/** + - proto/did/** - x/did/** - name: dwn include: - - proto/dex/** + - proto/dwn/** - x/dwn/** - name: svc include: - - proto/dex/** + - proto/svc/** - x/svc/** -- name: motr - include: - - cmd/motr/** -- name: vault - include: - - cmd/vault/** -- name: com - include: - - packages/com/** -- name: es - include: - - packages/es/** -- name: pkl - include: - - packages/pkl/** -- name: sdk - include: - - packages/sdk/** -- name: ui - include: - - packages/ui/** -- name: auth - include: - - web/auth/** -- name: dash - include: - - web/dash/** diff --git a/.gitignore b/.gitignore index 716afd682..beb4f0018 100755 --- a/.gitignore +++ b/.gitignore @@ -31,13 +31,7 @@ out/ # Go binaries (but allow docs references) snrd -hway -motr -!cmd/motr/ -!cmd/hway/ !cmd/snrd/ -!docs/**/motr -!docs/**/hway # Allow specific CLI binaries !cli/join-testnet/bin/ @@ -73,21 +67,8 @@ artifacts/ **/target/ **/Cargo.lock -# Contract-specific -contracts/DAO/deployment_ids.env -contracts/DAO/deployment_report_*.md -contracts/DAO/relayer.pid -contracts/DAO/*.mnemonic -contracts/DAO/tx_*.json -contracts/DAO/signed_*.json -contracts/DAO/init_*.json -contracts/DAO/MAINNET_DEPLOYMENT_INSTRUCTIONS.md -contracts/DAO/backups/ -contracts/wSNR/remappings.txt - # ===== Blockchain & Cosmos SDK ===== .snrd/ -.hway/ keyring-test/ mytestnet/ docker/testnet/testnet-data diff --git a/.goreleaser.yml b/.goreleaser.yml index ed695a3b8..9b01f3606 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,5 +1,329 @@ # yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json --- version: 2 -monorepo: - tag_prefix: v +dist: dist/snrd + +project_name: snrd + +before: + hooks: + - go mod download + +builds: + # Darwin AMD64 Build + - id: snrd-darwin-amd64 + main: ./cmd/snrd + binary: snrd + mod_timestamp: "{{ .CommitTimestamp }}" + env: + - CGO_ENABLED=1 + - CC=o64-clang + - CXX=o64-clang++ + - CGO_LDFLAGS=-lm + goos: + - darwin + goarch: + - amd64 + flags: + - -mod=readonly + - -trimpath + ldflags: + - -X github.com/cosmos/cosmos-sdk/version.Name=sonr + - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd + - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} + - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} + - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" + - -s -w + tags: + - netgo + - ledger + + # Darwin ARM64 Build + - id: snrd-darwin-arm64 + main: ./cmd/snrd + binary: snrd + mod_timestamp: "{{ .CommitTimestamp }}" + env: + - CGO_ENABLED=1 + - CC=oa64-clang + - CXX=oa64-clang++ + - CGO_LDFLAGS=-lm + goos: + - darwin + goarch: + - arm64 + flags: + - -mod=readonly + - -trimpath + ldflags: + - -X github.com/cosmos/cosmos-sdk/version.Name=sonr + - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd + - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} + - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} + - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" + - -s -w + tags: + - netgo + - ledger + + # Linux AMD64 Build + - id: snrd-linux-amd64 + main: ./cmd/snrd + binary: snrd + mod_timestamp: "{{ .CommitTimestamp }}" + env: + - CGO_ENABLED=1 + - CC=x86_64-linux-gnu-gcc + - CXX=x86_64-linux-gnu-g++ + - CGO_LDFLAGS=-lm + goos: + - linux + goarch: + - amd64 + goamd64: + - v1 + flags: + - -mod=readonly + - -trimpath + ldflags: + - -X github.com/cosmos/cosmos-sdk/version.Name=sonr + - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd + - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} + - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} + - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" + - -s -w + tags: + - netgo + - ledger + + # Linux ARM64 Build + - id: snrd-linux-arm64 + main: ./cmd/snrd + binary: snrd + mod_timestamp: "{{ .CommitTimestamp }}" + env: + - CGO_ENABLED=1 + - CC=aarch64-linux-gnu-gcc + - CXX=aarch64-linux-gnu-g++ + - CGO_LDFLAGS=-lm + goos: + - linux + goarch: + - arm64 + flags: + - -mod=readonly + - -trimpath + ldflags: + - -X github.com/cosmos/cosmos-sdk/version.Name=sonr + - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd + - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} + - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} + - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" + - -s -w + tags: + - netgo + - ledger + +aur_sources: + - name: snrd + disable: true + homepage: "https://sonr.io" + description: "Sonr blockchain daemon - decentralized identity and data storage network" + maintainers: + - "Sonr " + license: "GPL-3.0" + private_key: "{{ .Env.AUR_KEY }}" + git_url: "ssh://[email protected]/snrd.git" + skip_upload: auto + provides: + - snrd + conflicts: + - snrd-bin + depends: + - glibc + makedepends: + - go + - git + - make + commit_msg_template: "Update to {{ .Tag }}" + commit_author: + name: goreleaserbot + email: "prad@sonr.io" + prepare: |- + cd "${pkgname}_${pkgver}" + go mod download + build: |- + cd "${pkgname}_${pkgver}" + export CGO_ENABLED=1 + export CGO_CPPFLAGS="${CPPFLAGS}" + export CGO_CFLAGS="${CFLAGS}" + export CGO_CXXFLAGS="${CXXFLAGS}" + export CGO_LDFLAGS="${LDFLAGS}" + export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw" + go build \ + -ldflags="-w -s -buildid='' -linkmode=external \ + -X github.com/cosmos/cosmos-sdk/version.Name=sonr \ + -X github.com/cosmos/cosmos-sdk/version.AppName=snrd \ + -X github.com/cosmos/cosmos-sdk/version.Version=${pkgver} \ + -X 'github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger'" \ + -tags "netgo,ledger" \ + -o snrd ./cmd/snrd + chmod +x ./snrd + package: |- + cd "${pkgname}_${pkgver}" + + # bin + install -Dm755 "./snrd" "${pkgdir}/usr/bin/snrd" + + # license + if [ -f "./LICENSE" ]; then + install -Dm644 "./LICENSE" "${pkgdir}/usr/share/licenses/snrd/LICENSE" + fi + + # readme + if [ -f "./README.md" ]; then + install -Dm644 "./README.md" "${pkgdir}/usr/share/doc/snrd/README.md" + fi + + # config directory + install -dm755 "${pkgdir}/etc/snrd" + install -dm755 "${pkgdir}/var/lib/snrd" + backup: + - /etc/snrd/config.toml + - /etc/snrd/app.toml + +nix: + - name: snrd + ids: + - snrd + homepage: "https://sonr.io" + description: "Sonr blockchain daemon - decentralized identity network" + license: "gpl3" + path: pkgs/snrd/default.nix + commit_msg_template: "snrd: {{ .Tag }}" + dependencies: + - stdenv + - glibc + extra_install: |- + wrapProgram $out/bin/snrd --prefix PATH : ${lib.makeBinPath [ glibc stdenv.cc.cc.lib ]} + repository: + owner: sonr-io + name: nur + branch: main + token: "{{ .Env.GITHUB_TOKEN }}" + +archives: + - id: snrd + ids: + - snrd-linux-amd64 + - snrd-linux-arm64 + - snrd-darwin-amd64 + - snrd-darwin-arm64 + name_template: >- + snrd_{{ .Os }}_{{- if eq .Arch "amd64" }}x86_64 {{- else if eq .Arch "386" }}i386 {{- else }}{{ .Arch }}{{ end }} + formats: ["tar.gz"] + files: + - src: README* + wrap_in_directory: false + +homebrew_casks: + - name: snrd + ids: + - snrd + homepage: "https://sonr.io" + description: "Sonr blockchain daemon - decentralized identity and data storage network" + commit_msg_template: "Brew cask update for {{ .ProjectName }} version {{ .Tag }}" + directory: Casks + repository: + owner: sonr-io + name: homebrew-tap + branch: main + token: "{{ .Env.GITHUB_TOKEN }}" + commit_author: + name: goreleaserbot + email: "prad@sonr.io" + hooks: + post: + install: | + if OS.mac? + system_command "/usr/bin/xattr", args: ["-dr", "com.apple.quarantine", "#{staged_path}/snrd"] + end + +nfpms: + - id: snrd + package_name: snrd + ids: + - snrd-linux-amd64 + - snrd-linux-arm64 + file_name_template: "snrd_{{ .Os }}_{{ .Arch }}{{ .ConventionalExtension }}" + vendor: Sonr + homepage: "https://sonr.io" + maintainer: "Sonr " + description: "Sonr is a decentralized, permissionless, and censorship-resistant identity network." + license: "GPL-3.0" + formats: + - rpm + - deb + - apk + - archlinux + contents: + - src: README* + dst: /usr/share/doc/snrd + bindir: /usr/bin + section: net + priority: optional + +blobs: + - provider: s3 + endpoint: https://eb37925850388bca807b7fab964c12bb.r2.cloudflarestorage.com + bucket: releases + region: auto + directory: "snrd/{{ .Tag }}" + ids: + - snrd + +release: + disable: false + github: + owner: sonr-io + name: sonr + name_template: "{{ .Tag }}" + draft: false + replace_existing_draft: false # Don't replace drafts + replace_existing_artifacts: false # Append, don't replace + mode: append # Explicitly set to append mode + +checksum: + name_template: "snrd_checksums.txt" + +npms: + - name: "@sonr.io/snrd" + ids: + - snrd + description: "Sonr blockchain daemon - decentralized identity and data storage network" + homepage: "https://sonr.io" + license: "GPL-3.0" + author: "Sonr " + repository: "https://github.com/sonr-io/sonr" + bugs: "https://github.com/sonr-io/sonr/issues" + keywords: + - blockchain + - cosmos + - did + - identity + - web3 + - sonr + access: public + format: tar.gz + +snapshot: + version_template: "{{ .Branch }}-{{ .ShortCommit }}-dev" + +# Changelog configuration +changelog: + sort: asc + filters: + exclude: + - "^docs:" + - "^test:" + - "^chore:" diff --git a/.rgignore b/.rgignore index 672aaf2ad..e06ff1250 100644 --- a/.rgignore +++ b/.rgignore @@ -1,9 +1,6 @@ .dockerignore .goreleaser.yml api -contracts -chains -crypto proto test **/_test.go diff --git a/MIGRATE_CRYPTO.md b/MIGRATE_CRYPTO.md new file mode 100644 index 000000000..3f3431a7e --- /dev/null +++ b/MIGRATE_CRYPTO.md @@ -0,0 +1,847 @@ +# Sonr Cryptography Library Migration Context + +> **Repository Migration**: `sonr-io/sonr/crypto/` → `sonr-io/crypto` +> **Package Name**: `github.com/sonr-io/crypto` +> **Current Version**: `v1.0.1` + +## Overview + +The Sonr Cryptography Library is a comprehensive collection of cryptographic primitives designed for secure decentralized applications. It provides enterprise-grade implementations of elliptic curve cryptography, multi-party computation, threshold cryptography, zero-knowledge proofs, and advanced signature schemes. + +**Key Features:** +- **Multi-Party Computation (MPC)**: Secure distributed key generation and signing +- **Threshold Cryptography**: TECDSA and TED25519 with FROST protocol +- **Advanced Signatures**: BLS aggregation, BBS+ selective disclosure, Schnorr variants +- **Secret Sharing**: Shamir, Feldman VSS, Pedersen VSS implementations +- **Zero-Knowledge Proofs**: Bulletproofs for range proofs +- **Multiple Elliptic Curves**: Ed25519, Secp256k1, P-256, BLS12-381, Pallas/Vesta +- **UCAN Integration**: Capability-based authorization tokens +- **DID Key Management**: Multi-chain wallet address derivation + +## Repository Structure + +``` +sonr-io/crypto/ +├── core/ # Core cryptographic primitives +│ ├── curves/ # Elliptic curve implementations +│ │ ├── native/ # Native curve arithmetic +│ │ │ ├── bls12381/ # BLS12-381 pairing-friendly curve +│ │ │ ├── k256/ # Secp256k1 (Bitcoin/Ethereum) +│ │ │ ├── p256/ # NIST P-256 +│ │ │ └── pasta/ # Pallas/Vesta for ZK proofs +│ │ ├── bls12377_curve.go +│ │ ├── bls12381_curve.go +│ │ ├── ed25519_curve.go +│ │ ├── k256_curve.go +│ │ ├── p256_curve.go +│ │ └── pallas_curve.go +│ ├── protocol/ # MPC protocol framework +│ ├── commit.go # Pedersen commitments +│ ├── hash.go # Cryptographic hash utilities +│ └── mod.go # Modular arithmetic +│ +├── mpc/ # Multi-Party Computation +│ ├── enclave.go # MPC enclave management +│ ├── protocol.go # DKG and signing protocols +│ ├── codec.go # Serialization/deserialization +│ ├── import.go # Enclave import/export +│ ├── verify.go # Signature verification +│ └── spec/ # UCAN/JWT specifications +│ +├── tecdsa/ # Threshold ECDSA +│ └── dklsv1/ # 2-party ECDSA (DKLS v1) +│ ├── dkg/ # Distributed key generation +│ ├── sign/ # Threshold signing +│ ├── refresh/ # Key refresh protocol +│ └── dealer/ # Trusted dealer mode +│ +├── ted25519/ # Threshold Ed25519 +│ ├── frost/ # FROST protocol (DKG + signing) +│ └── ted25519/ # Core threshold Ed25519 +│ +├── signatures/ # Digital signature schemes +│ ├── bls/ # BLS signatures +│ │ └── bls_sig/ # Aggregatable BLS +│ ├── bbs/ # BBS+ selective disclosure +│ ├── schnorr/ # Schnorr variants +│ │ ├── mina/ # Mina protocol integration +│ │ └── nem/ # NEM blockchain support +│ └── common/ # Shared signature utilities +│ +├── sharing/ # Secret sharing schemes +│ ├── shamir.go # Shamir's Secret Sharing +│ ├── feldman.go # Feldman VSS +│ ├── pedersen.go # Pedersen VSS +│ └── v1/ # Version 1 implementations +│ +├── dkg/ # Distributed Key Generation +│ ├── frost/ # FROST DKG for Ed25519 +│ ├── gennaro/ # Gennaro DKG protocol +│ └── gennaro2p/ # 2-party simplified DKG +│ +├── bulletproof/ # Bulletproofs (range proofs) +│ ├── range_prover.go # Range proof generation +│ ├── range_verifier.go # Range proof verification +│ ├── ipp_prover.go # Inner product argument +│ └── generators.go # Generator points +│ +├── accumulator/ # Cryptographic accumulators +│ ├── accumulator.go # RSA accumulator +│ ├── witness.go # Membership witnesses +│ └── proof.go # Inclusion/exclusion proofs +│ +├── paillier/ # Paillier homomorphic encryption +│ ├── paillier.go # Public/private key operations +│ └── psf.go # Proof of safe factorization +│ +├── ot/ # Oblivious Transfer +│ ├── base/simplest/ # Simplest OT protocol +│ └── extension/kos/ # KOS OT extension +│ +├── zkp/ # Zero-Knowledge Proofs +│ └── schnorr/ # Schnorr proofs of knowledge +│ +├── ucan/ # User-Controlled Authorization Networks +│ ├── capability.go # Capability management +│ ├── crypto.go # UCAN cryptographic operations +│ ├── jwt.go # JWT-based UCAN tokens +│ ├── verifier.go # Delegation chain verification +│ └── vault.go # Vault-specific capabilities +│ +├── keys/ # Key management utilities +│ ├── didkey.go # DID key format support +│ ├── pubkey.go # Public key operations +│ └── parsers/ # Multi-chain key parsers +│ ├── btc_parser.go # Bitcoin key parsing +│ ├── eth_parser.go # Ethereum key parsing +│ ├── cosmos_parser.go # Cosmos SDK parsing +│ ├── sol_parser.go # Solana key parsing +│ └── ... # Other blockchain parsers +│ +├── aead/ # Authenticated encryption +│ └── aes_gcm.go # AES-GCM AEAD +│ +├── daed/ # Deterministic AEAD +│ └── aes_siv.go # AES-SIV encryption +│ +├── ecies/ # Elliptic Curve IES +│ ├── encrypt.go # ECIES encryption +│ └── keys.go # Key generation +│ +├── argon2/ # Password hashing +│ └── kdf.go # Argon2 key derivation +│ +├── vrf/ # Verifiable Random Functions +│ └── vrf.go # Curve25519 VRF +│ +├── ecdsa/ # ECDSA utilities +│ ├── canonical.go # Canonical signature encoding +│ └── deterministic.go # RFC 6979 deterministic signing +│ +├── subtle/ # Low-level crypto utilities +│ ├── hkdf.go # HKDF key derivation +│ ├── random/ # Secure randomness +│ └── x25519.go # X25519 key exchange +│ +└── internal/ # Internal utilities + ├── ed25519/ # Extended Ed25519 operations + ├── hash.go # Hash utilities + └── point.go # Point operations +``` + +## Core Modules + +### 1. Multi-Party Computation (`mpc/`) + +**Purpose**: Secure distributed key generation and threshold signing without trusted dealers. + +#### MPC Enclave Structure + +```go +type EnclaveData struct { + PubHex string `json:"pub_hex"` // Compressed public key (hex) + PubBytes []byte `json:"pub_bytes"` // Uncompressed public key + ValShare Message `json:"val_share"` // Alice (validator) keyshare + UserShare Message `json:"user_share"`// Bob (user) keyshare + Nonce []byte `json:"nonce"` // Encryption nonce + Curve CurveName `json:"curve"` // Elliptic curve name +} +``` + +#### Key Functions + +```go +// Generate new MPC enclave (2-of-2 threshold) +func NewEnclave() (Enclave, error) + +// Import enclave from various sources +func ImportEnclave(options ...ImportOption) (Enclave, error) + +// Execute distributed signing protocol +func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) ([]byte, error) + +// Execute keyshare refresh protocol +func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc, + curve CurveName) (Enclave, error) + +// Verify signature with public key +func VerifyWithPubKey(pubKeyCompressed []byte, data []byte, sig []byte) (bool, error) +``` + +#### Security Features + +- **2-of-2 Threshold**: Both parties required for signing +- **No Single Point of Failure**: Neither party can sign alone +- **Proactive Refresh**: Key rotation without changing public key +- **AES-GCM Encryption**: Secure enclave data encryption +- **SHA3-256 Hashing**: Cryptographic hash operations + +#### Supported Curves + +- `K256` - Secp256k1 (Bitcoin, Ethereum) +- `P256` - NIST P-256 +- `ED25519` - Twisted Edwards curve +- `BLS12381` - Pairing-friendly curve + +### 2. Elliptic Curves (`core/curves/`) + +**Purpose**: Comprehensive elliptic curve implementations with unified interfaces. + +#### Supported Curves + +**Ed25519** +- Twisted Edwards curve for EdDSA signatures +- High-performance, constant-time operations +- Used in: Cosmos SDK, Solana, many modern systems + +**Secp256k1 (K256)** +- Bitcoin and Ethereum standard curve +- ECDSA signature support +- Native field arithmetic implementations + +**P-256 (Secp256r1)** +- NIST standard curve +- FIPS 186-4 compliant +- Wide hardware acceleration support + +**BLS12-381** +- Pairing-friendly curve for BLS signatures +- Optimal ate pairing support +- Signature aggregation capabilities +- G1, G2, and GT group operations + +**BLS12-377** +- Alternative pairing curve +- Used in certain ZK-SNARK constructions + +**Pallas/Vesta** +- Pasta curves for recursive ZK proofs +- Cycle of curves for composition + +#### Curve Interface + +```go +type Curve interface { + Scalar + Point + Name() string + NewIdentityPoint() Point + NewGeneratorPoint() Point + Hash(input []byte) Point + // ... additional methods +} +``` + +### 3. Signature Schemes (`signatures/`) + +#### BLS Signatures (`signatures/bls/`) + +**Features:** +- Signature aggregation (combine multiple signatures) +- Threshold signatures (t-of-n) +- Multi-signatures with proof of possession +- Both G1 and G2 variants (tiny_bls and usual_bls) + +**Key Operations:** +```go +// Sign message +func (sk *SecretKey) Sign(msg []byte) *Signature + +// Aggregate multiple signatures +func AggregateSignatures(sigs ...*Signature) (*MultiSignature, error) + +// Verify aggregated signature +func (sig *Signature) AggregateVerify(pks []*PublicKey, msgs [][]byte) (bool, error) + +// Threshold key generation +func ThresholdGenerateKeys(threshold, total int) (*PublicKey, []*SecretKeyShare, error) +``` + +#### BBS+ Signatures (`signatures/bbs/`) + +**Purpose**: Privacy-preserving signatures with selective disclosure + +**Features:** +- Blind signatures for credential issuance +- Selective disclosure of attributes +- Zero-knowledge proofs of possession +- Unlinkable presentations + +**Use Cases:** +- Verifiable credentials +- Anonymous authentication +- Privacy-preserving identity systems + +#### Schnorr Signatures (`signatures/schnorr/`) + +**Mina Protocol** (`mina/`): +- Poseidon hash function +- Schnorr signatures for Mina blockchain +- Challenge derivation + +**NEM/Symbol** (`nem/`): +- Ed25519-Keccak variant +- NEM blockchain compatibility + +### 4. Secret Sharing (`sharing/`) + +#### Shamir's Secret Sharing + +```go +type Shamir struct { + Threshold int + Limit int + Curve Curve +} + +// Split secret into shares +func (s *Shamir) Split(secret []byte) ([]*ShamirShare, error) + +// Reconstruct secret from shares +func (s *Shamir) Combine(shares []*ShamirShare) ([]byte, error) +``` + +#### Feldman Verifiable Secret Sharing + +**Added Security**: Public commitments for share verification + +```go +type FeldmanVerifier struct { + Commitments []curves.Point +} + +// Verify share validity +func (v *FeldmanVerifier) Verify(share *ShamirShare) error +``` + +#### Pedersen Verifiable Secret Sharing + +**Enhanced Privacy**: Computationally binding commitments + +```go +// Split with verifiable commitments +func (p *Pedersen) Split(secret []byte) (*PedersenResult, error) +``` + +### 5. Threshold Cryptography + +#### TECDSA (`tecdsa/dklsv1/`) + +**Protocol**: Two-party threshold ECDSA (DKLS v1) + +**Components:** +- **DKG**: Distributed key generation without trusted dealer +- **Signing**: Threshold signature generation +- **Refresh**: Proactive keyshare rotation +- **Dealer**: Optional trusted dealer mode + +**Key Features:** +- No trusted third party required +- Active security against malicious adversaries +- Compatible with standard ECDSA verification + +#### TED25519 (`ted25519/`) + +**FROST Protocol** (`frost/`): +- Flexible Round-Optimized Schnorr Threshold signatures +- Efficient threshold Ed25519 signatures +- Three-round signing protocol + +**Core Operations** (`ted25519/`): +```go +// Threshold key generation +func KeyGen(threshold, total int) ([]*SecretKeyShare, *PublicKey, error) + +// Partial signature generation +func ThresholdSign(expandedSecretKeyShare []byte, publicKey []byte, + rShare []byte, R []byte, message []byte) []byte + +// Signature aggregation +func AggregateSignatures(partialSigs [][]byte, R []byte) ([]byte, error) +``` + +### 6. Distributed Key Generation (`dkg/`) + +#### Gennaro DKG (`dkg/gennaro/`) + +**Standard DKG protocol** with: +- Four-round protocol +- Pedersen commitments +- Complaint handling +- Byzantine fault tolerance + +#### FROST DKG (`dkg/frost/`) + +**Optimized for Ed25519**: +- Two-round DKG +- Simplified complaint phase +- Integration with FROST signing + +#### 2-Party DKG (`dkg/gennaro2p/`) + +**Simplified protocol** for two parties: +- Reduced communication overhead +- Faster execution +- Suitable for client-server architectures + +### 7. Zero-Knowledge Proofs + +#### Bulletproofs (`bulletproof/`) + +**Range Proofs without Trusted Setup**: + +```go +// Prove value in range [0, 2^n] +func (p *RangeProver) Prove(v *big.Int, n int) (*RangeProof, error) + +// Verify range proof +func (v *RangeVerifier) Verify(proof *RangeProof, commitment Point, n int) (bool, error) + +// Batched range proofs (aggregate multiple proofs) +func BatchProve(values []*big.Int, n int) (*RangeProof, error) +``` + +**Features:** +- Logarithmic proof size: O(log n) +- Inner product arguments +- Batch verification support +- No trusted setup required + +**Applications:** +- Confidential transactions +- Private smart contracts +- Privacy-preserving audits + +#### Schnorr Proofs (`zkp/schnorr/`) + +**Proof of Knowledge**: +- Discrete logarithm proofs +- Commitment proofs +- Non-interactive via Fiat-Shamir + +### 8. Advanced Cryptography + +#### Cryptographic Accumulators (`accumulator/`) + +**RSA Accumulator** for set membership: + +```go +// Add element to accumulator +func (acc *Accumulator) Add(element []byte) (*Witness, error) + +// Generate membership proof +func (w *Witness) GenerateProof() (*Proof, error) + +// Verify membership +func (acc *Accumulator) Verify(element []byte, proof *Proof) bool +``` + +**Use Cases:** +- Revocation lists +- Anonymous credentials +- Blockchain state commitments + +#### Paillier Encryption (`paillier/`) + +**Homomorphic Properties**: +- Additive homomorphism: E(m1) * E(m2) = E(m1 + m2) +- Scalar multiplication: E(m)^k = E(k * m) +- Threshold decryption support + +**Applications:** +- Private computation +- Secure multi-party computation +- E-voting systems + +#### Oblivious Transfer (`ot/`) + +**Simplest OT** (`base/simplest/`): +- 1-out-of-2 OT protocol +- Based on Curve25519 + +**KOS Extension** (`extension/kos/`): +- Extend base OT to many OTs +- Efficient batch operations +- Correlated randomness generation + +**Applications:** +- Private set intersection +- Secure two-party computation +- Password-authenticated key exchange + +### 9. UCAN (User-Controlled Authorization Networks) (`ucan/`) + +**Capability-Based Authorization**: + +```go +// Create UCAN token +func CreateUCAN(issuer DID, audience DID, capabilities []Capability) (string, error) + +// Attenuate capabilities (reduce permissions) +func AttenuateUCAN(parentToken string, newCapabilities []Capability) (string, error) + +// Verify delegation chain +func VerifyDelegationChain(tokenString string, rootDID string) error +``` + +**Capability Types**: +- DID capabilities (read, write, update) +- DWN capabilities (records, protocols) +- Vault capabilities (sign, decrypt) +- DEX capabilities (swap, provide liquidity) + +**Features:** +- JWT-based tokens +- Delegation chains +- Capability attenuation +- Proof-of-possession +- Expiration and not-before timestamps + +### 10. Key Management (`keys/`) + +#### DID Key Support (`didkey.go`) + +```go +// Create DID from public key +func NewDID(publicKey []byte, keyType crypto.KeyType) (*DID, error) + +// Derive blockchain address from DID +func (did *DID) Address() (string, error) + +// Get raw public key bytes +func (did *DID) Raw() ([]byte, error) +``` + +#### Multi-Chain Parsers (`parsers/`) + +**Supported Blockchains**: +- Bitcoin (BTC) - BIP32/BIP44 derivation +- Ethereum (ETH) - Keccak addresses +- Cosmos SDK - Bech32 encoding +- Solana (SOL) - Ed25519 keys +- Filecoin (FIL) - Secp256k1 keys +- TON - Ed25519 keys + +### 11. Encryption Utilities + +#### AEAD (`aead/`) + +**AES-GCM Authenticated Encryption**: + +```go +const ( + KeySize = 32 // 256-bit key + NonceSize = 12 // 96-bit nonce + TagSize = 16 // 128-bit auth tag +) + +// Encrypt with automatic nonce generation +func (c *AESGCMCipher) Encrypt(plaintext, aad []byte) ([]byte, error) + +// Decrypt and verify +func (c *AESGCMCipher) Decrypt(ciphertext, aad []byte) ([]byte, error) +``` + +#### DAED (`daed/`) + +**Deterministic AES-SIV**: +- Same plaintext → same ciphertext +- Useful for encrypted indices +- Misuse-resistant + +#### ECIES (`ecies/`) + +**Elliptic Curve Integrated Encryption Scheme**: + +```go +// Generate ECIES keypair +func GenerateKey(curve Curve) (*PrivateKey, error) + +// Encrypt message to public key +func Encrypt(recipientPubKey *PublicKey, message []byte) ([]byte, error) + +// Decrypt with private key +func (sk *PrivateKey) Decrypt(ciphertext []byte) ([]byte, error) +``` + +### 12. Utility Modules + +#### VRF (`vrf/`) + +**Verifiable Random Function (Curve25519)**: + +```go +// Generate VRF output and proof +func (sk *PrivateKey) Prove(message []byte) (vrf []byte, proof []byte) + +// Verify VRF proof +func (pk *PublicKey) Verify(message, vrf, proof []byte) bool +``` + +**Applications:** +- Leader election +- Lottery systems +- Randomness beacons +- Sortition algorithms + +#### Argon2 (`argon2/`) + +**Password-Based Key Derivation**: + +```go +// Derive key from password +func DeriveKey(password, salt []byte, keyLen uint32) []byte +``` + +**Parameters**: +- Time cost: 1 iteration (configurable) +- Memory cost: 64 MB (configurable) +- Parallelism: 4 threads (configurable) + +#### ECDSA Utilities (`ecdsa/`) + +**Canonical Encoding**: +- BIP 66 / RFC 6979 compliance +- Deterministic signature generation +- Low-S normalization + +## Integration Patterns + +### Usage in Sonr Blockchain + +The crypto library is heavily integrated throughout the Sonr ecosystem: + +#### DID Module +```go +import "github.com/sonr-io/crypto/keys" +import "github.com/sonr-io/crypto/mpc" + +// DID creation from MPC enclave +enclave, _ := mpc.NewEnclave() +pubKey := enclave.GetPubPoint() +did := keys.NewDID(pubKey.Bytes(), crypto.Secp256k1) +``` + +#### DWN Module +```go +import "github.com/sonr-io/crypto/mpc" +import "github.com/sonr-io/crypto/aead" + +// Vault operations +enclave := keeper.LoadEnclave(ctx, vaultID) +signature, _ := enclave.Sign(message) + +// Encrypted data storage +cipher := aead.NewAESGCMCipher(key) +encrypted, _ := cipher.Encrypt(data, nil) +``` + +#### Service Module +```go +import "github.com/sonr-io/crypto/ucan" + +// UCAN capability verification +verifier := ucan.NewVerifier(didResolver) +err := verifier.VerifyDelegationChain(ctx, tokenString) +``` + +### Motor Worker Integration + +The WASM worker uses the crypto library extensively: + +```go +import ( + "github.com/sonr-io/crypto/mpc" + "github.com/sonr-io/crypto/core/curves" +) + +//go:wasmexport sign +func sign() int32 { + // Load enclave from WASM memory + enclave := loadEnclave() + + // Sign message + signature, _ := enclave.Sign(message) + + return writeOutput(signature) +} +``` + +## Security Considerations + +### Threat Model + +The library is designed to protect against: + +**Key Compromise**: +- MPC threshold schemes prevent single points of failure +- Proactive refresh rotates keyshares + +**Insider Threats**: +- Multi-party protocols require cooperation +- No single party can perform operations alone + +**Network Attacks**: +- Protocol messages are cryptographically protected +- Authentication prevents man-in-the-middle attacks + +**Side-Channel Attacks**: +- Constant-time implementations where critical +- Secure memory handling +- Zeroization of sensitive data + +### Best Practices + +1. **Key Management**: + - Use hardware security modules when available + - Implement secure key backup and recovery + - Regular keyshare rotation via refresh protocols + +2. **MPC Operations**: + - Secure communication channels (TLS) + - Proper authentication of parties + - Audit logging of all operations + +3. **Random Number Generation**: + - Use `crypto/rand` for all random values + - Never reuse nonces in AEAD + - Verify randomness quality in production + +4. **Error Handling**: + - Don't leak sensitive information in errors + - Validate all inputs + - Use constant-time comparisons for secrets + +## Testing + +The library includes comprehensive tests: + +```bash +# Run all tests +go test ./... + +# Run with race detection +go test -race ./... + +# Generate coverage report +go test -cover ./... + +# Run specific module tests +go test ./mpc/... +go test ./signatures/bls/... +go test ./bulletproof/... + +# Benchmark performance +go test -bench=. ./core/curves/... +``` + +### Test Coverage + +- **MPC**: Enclave operations, protocol execution, refresh +- **Signatures**: BLS aggregation, BBS+ proofs, Schnorr +- **Secret Sharing**: Shamir, Feldman, Pedersen +- **Threshold Crypto**: TECDSA, TED25519, DKG protocols +- **ZK Proofs**: Bulletproofs range proofs, Schnorr proofs +- **Encryption**: AEAD, ECIES, Paillier +- **Curves**: All curve operations, point arithmetic + +## Dependencies + +### External Libraries + +```go +require ( + github.com/btcsuite/btcd/btcec/v2 v2.3.2 // Bitcoin crypto + github.com/consensys/gnark-crypto v0.19.0 // BLS12-377/381 + golang.org/x/crypto v0.42.0 // Standard crypto + github.com/golang-jwt/jwt/v5 v5.3.0 // JWT tokens +) +``` + +### Internal Dependencies + +The crypto library is **self-contained** and has no dependencies on other Sonr modules, making it suitable for independent use. + +## Performance Characteristics + +### Benchmarks (on AMD64, 2.5 GHz) + +**Elliptic Curve Operations**: +- K256 scalar multiplication: ~50 µs +- Ed25519 signing: ~25 µs +- BLS12-381 pairing: ~1.2 ms + +**MPC Operations**: +- DKG (2-party): ~15 ms +- Threshold signing: ~10 ms +- Key refresh: ~12 ms + +**Signature Schemes**: +- BLS aggregation (100 sigs): ~150 ms +- BBS+ proof generation: ~80 ms +- Schnorr signing: ~30 µs + +**Zero-Knowledge Proofs**: +- Bulletproof (64-bit range): ~40 ms +- Verification: ~25 ms + +## Migration Checklist + +When using the crypto library in a new project: + +- [ ] Add dependency: `go get github.com/sonr-io/crypto@v1.0.1` +- [ ] Import required modules +- [ ] Initialize curve instances as needed +- [ ] Set up secure random number generation +- [ ] Implement proper error handling +- [ ] Add comprehensive tests +- [ ] Review security best practices +- [ ] Benchmark critical operations +- [ ] Set up monitoring/logging +- [ ] Document cryptographic assumptions + +## Version Compatibility + +**Go Version**: 1.24.4+ + +**Cosmos SDK**: Compatible with v0.50.x (if using Cosmos integration) + +**Semantic Versioning**: The library follows semver +- Major: Breaking API changes +- Minor: New features, backwards compatible +- Patch: Bug fixes + +## Related Documentation + +- [Cosmos SDK Cryptography](https://docs.cosmos.network/main/learn/advanced/crypto) +- [BLS Signatures Spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature) +- [FROST Paper](https://eprint.iacr.org/2020/852) +- [Bulletproofs Paper](https://eprint.iacr.org/2017/1066) +- [UCAN Spec](https://github.com/ucan-wg/spec) +- [W3C DID Core](https://www.w3.org/TR/did-core/) + +## Support + +**Repository**: https://github.com/sonr-io/crypto +**Issues**: https://github.com/sonr-io/crypto/issues +**License**: Apache 2.0 diff --git a/MIGRATE_HWAY.md b/MIGRATE_HWAY.md new file mode 100644 index 000000000..76e846742 --- /dev/null +++ b/MIGRATE_HWAY.md @@ -0,0 +1,435 @@ +# Highway (hway) Migration Context + +> **Repository Migration**: `sonr-io/sonr` → `sonr-io/hway` +> **Components Moved**: `cmd/hway/`, `bridge/`, `internal/migrations/` + +## Overview + +Highway is a high-performance, PostgreSQL-backed HTTP service that handles OAuth2/OIDC authentication, WebAuthn flows, and asynchronous vault operations for the Sonr blockchain ecosystem. It serves as the authentication and task processing layer between clients and the Sonr blockchain. + +## Architecture + +### Core Technology Stack + +- **Go**: 1.24.4 +- **Task Queue**: Asynq (Redis-backed distributed task queue) +- **Actor System**: Proto.Actor for concurrency management +- **Database**: PostgreSQL with database/sql +- **Web Framework**: Echo v4 +- **Authentication**: OAuth2, OIDC, WebAuthn, SIOP +- **Cryptography**: UCAN tokens, JWT signing (RS256) + +### Service Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Highway Service (hway) │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ +│ │ Bridge │ │ Tasks │ │ Handlers │ │ +│ │ (HTTP) │──│ (Asynq) │──│ (Auth) │ │ +│ └────────────┘ └────────────┘ └────────────┘ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────────────────────────────────┐ │ +│ │ Proto.Actor System │ │ +│ │ (Vault Actor Management) │ │ +│ └─────────────────────────────────────────┘ │ +│ │ +└───────────┬───────────────────────┬─────────────────────────┘ + │ │ + ▼ ▼ + ┌──────────┐ ┌──────────┐ + │PostgreSQL│ │ Redis │ + │ (State) │ │ (Queue) │ + └──────────┘ └──────────┘ +``` + +## Component Breakdown + +### 1. Bridge Module (`bridge/`) + +**Purpose**: HTTP API layer providing authentication and authorization services + +**Key Files**: +- `bridge.go` - Main bridge server initialization +- `config.go` - Configuration management +- `queue.go` - Asynq task queue setup and management + +**Handlers** (`bridge/handlers/`): + +#### Authentication & Authorization +- `auth.go` - General authentication handlers +- `oidc.go` - OpenID Connect provider implementation + - Discovery endpoint (`.well-known/openid-configuration`) + - Authorization endpoint with PKCE support + - Token endpoint with JWT generation + - UserInfo endpoint + - JWKS endpoint for key rotation + +- `siop.go` - Self-Issued OpenID Provider (SIOP) flows + - DID-based authentication + - Verifiable presentation handling + +- `webauthn.go` - WebAuthn registration and authentication + - Challenge generation + - Credential verification + - Device binding + +#### OAuth2 Implementation +- `oauth2_provider.go` - Core OAuth2 provider + - Authorization code flow + - Client credentials flow + - Refresh token flow + - Token introspection + - Token revocation + +- `oauth2_register.go` - Dynamic client registration (RFC 7591) +- `oauth2_clients.go` - Client management and validation +- `oauth2_delegation.go` - Token delegation flows +- `oauth2_token_exchange.go` - Token exchange (RFC 8693) +- `oauth2_scopes.go` - Scope validation and management +- `oauth2_security.go` - Security utilities (PKCE, rate limiting) +- `oauth2_types.go` - OAuth2 type definitions + +#### Vault Operations +- `vault.go` - Vault operation handlers + - Generate vault enclaves + - Sign with vault + - Verify signatures + - Import/Export to IPFS + - Refresh vault state + +#### Utility Handlers +- `broadcast.go` - Transaction broadcasting +- `health.go` - Health check endpoints +- `websocket.go` - WebSocket connection management +- `types.go` - Shared type definitions + +### 2. Task Processing (`bridge/tasks/`) + +**Purpose**: Asynchronous task definitions and processing + +**Key Files**: +- `types.go` - Task type constants and definitions +- `generate.go` - Vault generation tasks +- `signing.go` - Signing operation tasks +- `attenuation.go` - UCAN token attenuation tasks + +**Task Types**: +```go +const ( + TypeVaultGenerate = "vault:generate" + TypeVaultSign = "vault:sign" + TypeVaultRefresh = "vault:refresh" + TypeUCANAttenuation = "ucan:attenuation" +) +``` + +**Queue Configuration**: +```go +Queues: map[string]int{ + "critical": 6, // High priority tasks + "default": 3, // Normal priority tasks + "low": 1, // Low priority tasks +} +``` + +### 3. Main Service (`cmd/hway/`) + +**Purpose**: Service entry point and initialization + +**Key Responsibilities**: +1. Initialize Asynq server with Redis connection +2. Configure worker pools and queue priorities +3. Register task handlers +4. Start HTTP server (Echo) +5. Setup signal handling for graceful shutdown + +**Configuration**: +```go +const ( + RedisAddr = "127.0.0.1:6379" + PostgresAddr = "127.0.0.1:5432" + HTTPPort = ":8090" + WorkerConcurrency = 10 +) +``` + +### 4. Database Migrations (`internal/migrations/`) + +**Purpose**: PostgreSQL schema management + +**Migration Files**: +- `001_accounts_table.sql` - User account storage +- `002_credentials_table.sql` - WebAuthn credential storage +- `003_profiles_table.sql` - User profile data +- `004_vaults_table.sql` - Vault state persistence +- `005_create_cosmos_registry.sql` - Cosmos chain registry +- `006_execute_cosmos_registry.sql` - Registry functions +- `007_webauthn_to_vc_func.sql` - WebAuthn to VC conversion +- `008_create_coinpaprika_market_data.sql` - Market data tables +- `009_webauthn_options_functions.sql` - WebAuthn helper functions +- `010_crypto_asset_symbol_linking.sql` - Asset metadata +- `011_common_functions.sql` - Shared SQL functions +- `012_crypto_coin_price_data.sql` - Price data storage +- `013_add_asset_quality_filters.sql` - Asset filtering +- `014_sessions_table.sql` - Session management + +## Integration Points + +### With Sonr Blockchain (`snrd`) +- **RPC/REST API**: Queries blockchain state via Cosmos SDK endpoints +- **Transaction Broadcasting**: Submits signed transactions to chain +- **DID Resolution**: Resolves DIDs from blockchain state +- **Vault State**: Stores vault metadata on-chain + +### With Motor/Worker (WASM Plugin) +- **Task Execution**: Highway enqueues tasks, Motor executes via WASM +- **Vault Operations**: Motor provides cryptographic operations +- **Enclave Management**: Actor system manages WASM plugin lifecycle + +### With Client Applications +- **OAuth2/OIDC**: Standard OAuth2 authorization flows +- **WebAuthn**: Browser-based passwordless authentication +- **WebSocket**: Real-time task status updates +- **SSE**: Server-Sent Events for progress tracking + +### With External Services +- **IPFS**: Vault backup/restore operations +- **Redis**: Distributed task queue and caching +- **PostgreSQL**: Persistent state storage + +## Key Features + +### 1. OAuth2/OIDC Provider +- Full OAuth2 authorization server implementation +- OpenID Connect provider with ID tokens +- Dynamic client registration (RFC 7591) +- Token exchange (RFC 8693) +- PKCE support for public clients +- Refresh token rotation +- Token revocation and introspection + +### 2. WebAuthn Support +- FIDO2/WebAuthn registration flows +- Authentication with platform authenticators +- Credential lifecycle management +- Challenge-response validation +- Attestation verification + +### 3. Vault Task Processing +- Asynchronous cryptographic operations +- Priority-based queue management +- Actor-based concurrency model +- Retry logic with exponential backoff +- Task status tracking and notifications + +### 4. UCAN Token Management +- UCAN token generation and signing +- Capability delegation and attenuation +- Token chain verification +- Integration with DID system + +## Security Considerations + +### Authentication & Authorization +- Multi-factor authentication support +- JWT token signing with RS256 +- PKCE for authorization code flow +- Origin validation for WebAuthn +- Rate limiting on all endpoints + +### Data Protection +- Password hashing with Argon2 +- Encrypted vault data in PostgreSQL +- Secure token generation (crypto/rand) +- HTTPS-only in production +- CORS configuration + +### Vault Security +- WASM sandbox isolation for cryptographic operations +- No private key exposure to server +- Encrypted backup to IPFS +- Session timeout and auto-lock + +## Configuration + +### Environment Variables +```bash +# Service Configuration +HIGHWAY_PORT=8090 +LOG_LEVEL=info + +# Database +POSTGRES_HOST=localhost +POSTGRES_PORT=5432 +POSTGRES_USER=postgres +POSTGRES_PASSWORD=password +POSTGRES_DB=hway + +# Redis +REDIS_URL=redis://localhost:6379 + +# IPFS +IPFS_API_URL=http://localhost:5001 + +# OAuth2/OIDC +OIDC_ISSUER=http://localhost:8090 +JWT_SIGNING_KEY_PATH=/path/to/private-key.pem +JWT_PUBLIC_KEY_PATH=/path/to/public-key.pem + +# Security +ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3100 +SESSION_SECRET=change-me-in-production +``` + +### Asynq Configuration +```go +asynq.Config{ + Concurrency: 10, + Queues: map[string]int{ + "critical": 6, + "default": 3, + "low": 1, + }, + StrictPriority: false, + ErrorHandler: asynq.ErrorHandlerFunc(handleError), + Logger: slog.Default(), +} +``` + +## API Endpoints + +### Authentication +- `POST /auth/register` - User registration +- `POST /auth/login` - User login +- `POST /auth/logout` - User logout +- `POST /auth/refresh` - Refresh access token + +### OAuth2/OIDC +- `GET /.well-known/openid-configuration` - OIDC discovery +- `GET /oauth2/authorize` - Authorization endpoint +- `POST /oauth2/token` - Token endpoint +- `GET /oauth2/userinfo` - User info endpoint +- `GET /oauth2/jwks` - JSON Web Key Set +- `POST /oauth2/register` - Dynamic client registration +- `POST /oauth2/revoke` - Token revocation +- `POST /oauth2/introspect` - Token introspection + +### WebAuthn +- `POST /webauthn/register/begin` - Start registration +- `POST /webauthn/register/finish` - Complete registration +- `POST /webauthn/login/begin` - Start authentication +- `POST /webauthn/login/finish` - Complete authentication + +### Vault Operations +- `POST /vault/generate` - Generate new vault +- `POST /vault/sign` - Sign with vault +- `POST /vault/verify` - Verify signature +- `POST /vault/refresh` - Refresh vault state +- `POST /vault/export` - Export to IPFS +- `POST /vault/import` - Import from IPFS + +### WebSocket +- `WS /ws/tasks/{task_id}` - Task status updates + +### Health & Monitoring +- `GET /health` - Health check +- `GET /health/ready` - Readiness probe +- `GET /health/live` - Liveness probe + +## Testing Strategy + +### Unit Tests +```bash +go test ./bridge/... +go test ./bridge/handlers/... +go test ./bridge/tasks/... +``` + +### Integration Tests +```bash +# Requires PostgreSQL and Redis +INTEGRATION=true go test ./... +``` + +### E2E Tests +```bash +# Requires full stack (PostgreSQL, Redis, IPFS) +E2E=true go test ./e2e/... +``` + +## Dependencies + +### Required Services +- PostgreSQL 14+ +- Redis 7+ +- IPFS node (for vault operations) + +### Go Modules (Key Dependencies) +- `github.com/hibiken/asynq` - Distributed task queue +- `github.com/labstack/echo/v4` - HTTP framework +- `github.com/asynkron/protoactor-go` - Actor system +- `github.com/lib/pq` - PostgreSQL driver +- `github.com/go-webauthn/webauthn` - WebAuthn library +- `github.com/golang-jwt/jwt/v5` - JWT handling +- `github.com/redis/go-redis/v9` - Redis client + +## Build & Deployment + +### Build Commands +```bash +# Build binary +go build -o hway ./cmd/hway + +# Build with specific tags +go build -tags production -o hway ./cmd/hway + +# Build Docker image +docker build -t sonr-hway:latest . +``` + +### Docker Deployment +```yaml +services: + hway: + image: onsonr/hway:latest + environment: + POSTGRES_HOST: postgres + REDIS_URL: redis://redis:6379 + depends_on: + - postgres + - redis + ports: + - "8090:8090" +``` + +## Migration Checklist + +When setting up the new `sonr-io/hway` repository: + +- [ ] Copy `cmd/hway/` directory +- [ ] Copy `bridge/` directory (all handlers and tasks) +- [ ] Copy `internal/migrations/` for database schema +- [ ] Update import paths from `github.com/sonr-io/sonr` to new repo +- [ ] Create standalone `go.mod` with required dependencies +- [ ] Setup CI/CD for independent releases +- [ ] Create Dockerfile for containerized deployment +- [ ] Document environment variables and configuration +- [ ] Add PostgreSQL and Redis setup instructions +- [ ] Create integration test suite with testcontainers +- [ ] Setup database migration tooling (e.g., golang-migrate) +- [ ] Configure monitoring and observability (Prometheus/Grafana) +- [ ] Document OAuth2 client registration process +- [ ] Create API documentation (OpenAPI/Swagger) + +## Related Documentation + +- OAuth2 RFC 6749: https://tools.ietf.org/html/rfc6749 +- OpenID Connect Core: https://openid.net/specs/openid-connect-core-1_0.html +- Dynamic Client Registration RFC 7591: https://tools.ietf.org/html/rfc7591 +- WebAuthn Spec: https://www.w3.org/TR/webauthn/ +- Asynq Documentation: https://github.com/hibiken/asynq +- Proto.Actor: https://proto.actor/ diff --git a/MIGRATE_MOTR.md b/MIGRATE_MOTR.md new file mode 100644 index 000000000..d15ea58b8 --- /dev/null +++ b/MIGRATE_MOTR.md @@ -0,0 +1,653 @@ +# Motor (motr) Migration Context + +> **Repository Migration**: `sonr-io/sonr` → `sonr-io/motr` +> **Components Moved**: `cmd/motr/`, `cmd/vault/`, `packages/`, `web/` +> **Note**: The `crypto/` library was moved to its own repository at `sonr-io/crypto` + +## Overview + +Motor (formerly "motr") is a multi-purpose WebAssembly service that provides: +1. **Worker**: WASM-based cryptographic vault operations (formerly "vault") +2. **Payment Gateway**: W3C Payment Handler API compliant payment processing +3. **TypeScript SDK**: Browser and Node.js client libraries for vault and payment operations +4. **Web Applications**: Authentication and dashboard web apps + +The name "Motor" reflects its role as the execution engine powering secure operations in the Sonr ecosystem. + +## Repository Structure + +``` +sonr-io/motr/ +├── worker/ # WASM vault operations (Go → WASM) +│ ├── main.go # Entrypoint with WASM exports +│ ├── vault/ # Vault operation implementations +│ └── mpc/ # Multi-party computation +│ +├── server/ # HTTP server mode (Go) +│ ├── main.go # HTTP/Payment Gateway server +│ ├── handlers/ # Payment & OIDC handlers +│ └── middleware/ # Security & rate limiting +│ +├── packages/ # TypeScript SDK and libraries +│ ├── es/ # @motr/es - Core SDK +│ │ ├── client/ # Vault client +│ │ ├── worker/ # Service worker integration +│ │ ├── plugin/ # Plugin system +│ │ └── codec/ # Encoding/signing utilities +│ │ +│ ├── sdk/ # @motr/sdk - High-level SDK +│ ├── ui/ # @motr/ui - UI components +│ └── com/ # @motr/com - Common utilities +│ +└── web/ # Web applications + ├── auth/ # Authentication app + └── dash/ # Dashboard app +``` + +## Dependencies + +Motor depends on the **Sonr Cryptography Library** (`github.com/sonr-io/crypto`), which was moved to its own repository. See MIGRATE_CRYPTO.md for details on the crypto library. + +## Component 1: Worker (WASM Vault) + +**Technology**: Go 1.24.4 → WebAssembly via TinyGo +**Runtime**: Extism (WebAssembly plugin host) +**Purpose**: Secure cryptographic operations in sandboxed environment + +### Architecture + +``` +┌──────────────────────────────────────────────┐ +│ Host Application │ +│ (Browser, Node.js, or Highway) │ +└───────────────┬──────────────────────────────┘ + │ + ▼ + ┌───────────────┐ + │ Extism │ ◄─── WASM Runtime + │ Runtime │ + └───────┬───────┘ + │ + ▼ +┌───────────────────────────────────────────────┐ +│ worker.wasm (Motor Worker) │ +├───────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ Vault │ │ MPC │ │ +│ │ Operations │ │ Enclave │ │ +│ └──────────────┘ └──────────────┘ │ +│ │ +│ ┌──────────────────────────────────┐ │ +│ │ Crypto Primitives │ │ +│ │ (Ed25519, ECDSA, BLS, etc.) │ │ +│ └──────────────────────────────────┘ │ +│ │ +└───────────────────────────────────────────────┘ +``` + +### WASM Exports (Go Functions) + +All exported functions follow the Extism PDK pattern: + +#### Core Vault Operations + +```go +//go:wasmexport generate +func generate() int32 +// Creates new MPC enclave with key generation +// Input: GenerateRequest{id: string} +// Output: GenerateResponse{data: EnclaveData, public_key: []byte} + +//go:wasmexport refresh +func refresh() int32 +// Refreshes enclave cryptographic material +// Input: RefreshRequest{enclave: EnclaveData} +// Output: RefreshResponse{okay: bool, data: EnclaveData} + +//go:wasmexport sign +func sign() int32 +// Signs arbitrary message with vault key +// Input: SignRequest{message: []byte, enclave: EnclaveData} +// Output: SignResponse{signature: []byte} + +//go:wasmexport verify +func verify() int32 +// Verifies signature against public key +// Input: VerifyRequest{public_key: []byte, message: []byte, signature: []byte} +// Output: VerifyResponse{valid: bool} +``` + +#### Multi-Chain Transaction Signing + +```go +//go:wasmexport sign_cosmos_transaction +func signCosmosTransaction() int32 +// Signs Cosmos SDK transaction +// Input: CosmosSignRequest{chain_id, account_number, sequence, tx_bytes} +// Output: SignedTransaction{signature, signed_doc} + +//go:wasmexport sign_evm_transaction +func signEvmTransaction() int32 +// Signs Ethereum/EVM transaction +// Input: EVMSignRequest{chain_id, nonce, tx_data, gas_limit} +// Output: SignedTransaction{v, r, s, raw_tx} + +//go:wasmexport sign_message +func signMessage() int32 +// Signs arbitrary message (EIP-191/EIP-712) +// Input: MessageSignRequest{message, encoding_type} +// Output: MessageSignature{signature, recovery_id} +``` + +#### Vault Import/Export (IPFS) + +```go +//go:wasmexport export +func export() int32 +// Exports encrypted vault to IPFS +// Input: ExportRequest{enclave: EnclaveData, password: []byte} +// Output: ExportResponse{cid: string, success: bool} + +//go:wasmexport import +func import() int32 +// Imports encrypted vault from IPFS +// Input: ImportRequest{cid: string, password: []byte} +// Output: ImportResponse{enclave: EnclaveData, success: bool} +``` + +#### WebAuthn Integration + +```go +//go:wasmexport create_vault_enclave +func createVaultEnclave() int32 +// Creates vault with WebAuthn configuration +// Input: VaultConfig{vault_id, webauthn_enabled, auto_lock_timeout} +// Output: VaultEnclave{enclave_data, webauthn_credentials} + +//go:wasmexport unlock_vault +func unlockVault() int32 +// Unlocks vault with WebAuthn or password +// Input: UnlockRequest{vault_id, auth_method, credentials} +// Output: UnlockResponse{success, session_token} + +//go:wasmexport lock_vault +func lockVault() int32 +// Locks vault and clears sensitive data +// Input: LockRequest{vault_id} +// Output: LockResponse{success} +``` + +#### Health & Monitoring + +```go +//go:wasmexport get_vault_health +func getVaultHealth() int32 +// Returns vault health status +// Output: EnclaveHealth{vault_id, status, last_activity, key_rotation_due} + +//go:wasmexport get_version +func getVersion() int32 +// Returns worker version and capabilities +// Output: VersionInfo{version, supported_chains, features} +``` + +### MPC Enclave Structure + +```go +type EnclaveData struct { + ID string `json:"id"` + PublicKey []byte `json:"public_key"` + PrivateKeyShare []byte `json:"private_key_share"` // Encrypted + Threshold uint32 `json:"threshold"` + Parties uint32 `json:"parties"` + ChainID string `json:"chain_id"` + CreatedAt int64 `json:"created_at"` + LastRefresh int64 `json:"last_refresh"` + Metadata map[string]string `json:"metadata"` +} +``` + +**Note**: Motor relies on the Sonr Cryptography Library (`github.com/sonr-io/crypto`) for all cryptographic operations. The crypto library provides comprehensive primitives including Ed25519, ECDSA, BLS signatures, MPC, threshold cryptography, and more. See `MIGRATE_CRYPTO.md` for the complete crypto library documentation. + +### Build Configuration + +```bash +# Build WASM module with TinyGo +tinygo build -o worker.wasm -target wasi \ + -no-debug \ + -opt 2 \ + -scheduler none \ + ./worker/main.go + +# Optimize with wasm-opt +wasm-opt -O3 -o worker.optimized.wasm worker.wasm + +# Build with Extism toolchain +extism compile worker.wasm -o worker.plugin.wasm +``` + +### IPFS Integration + +```go +// IPFS Configuration +const ( + IPFSStorageEndpoint = "http://127.0.0.1:5001/api/v0/add" + IPFSRetrievalEndpoint = "http://127.0.0.1:5001/api/v0/cat" + IPFSGateway = "https://ipfs.did.run/ipfs/" +) + +// Export vault to IPFS +func ExportToIPFS(enclave *EnclaveData, password []byte) (cid string, error) { + // 1. Serialize enclave data + // 2. Encrypt with AES-256-GCM using password + // 3. Upload to IPFS + // 4. Return content ID (CID) +} +``` + +## Component 2: Server (Payment Gateway) + +**Technology**: Go 1.24.4 HTTP Server +**Framework**: `go-wasm-http-server` (can run as service worker or HTTP) +**Purpose**: Payment processing and OIDC authorization + +### Features + +#### W3C Payment Handler API +- Payment request processing +- Card validation (Luhn algorithm, CVV, expiry) +- PCI DSS compliant tokenization +- Transaction signing with HMAC-SHA256 +- AES-256-GCM encryption for card data +- Refund processing +- Audit logging + +#### OIDC Authorization Server +- Full OpenID Connect provider +- Discovery endpoint +- Authorization with PKCE +- Token endpoint (JWT generation) +- UserInfo endpoint +- JWKS endpoint +- Refresh tokens + +#### Security +- Rate limiting (100 req/min per client) +- Origin validation +- Security headers (CSP, X-Frame-Options) +- CORS configuration +- Secure token generation +- Card number masking + +### API Endpoints + +``` +POST /api/payment/process - Process payment +POST /api/payment/validate - Validate payment method +POST /api/payment/refund - Process refund + +GET /.well-known/openid-configuration +GET /oauth2/authorize +POST /oauth2/token +GET /oauth2/userinfo +GET /oauth2/jwks +``` + +## Component 3: TypeScript SDK (`packages/`) + +**Purpose**: Browser and Node.js integration for Motor services + +### Package Structure + +#### `@motr/es` (Core SDK) + +**Client Module** (`client/`): +- `VaultClient`: Main vault operations client +- `VaultClientWithIPFS`: IPFS-enabled vault client +- RPC/REST API integration +- Transaction broadcasting + +**Worker Module** (`worker/`): +- `MotorServiceWorkerManager`: Service worker lifecycle +- `MotorClient`: HTTP client for Motor API +- Payment gateway client +- OIDC client integration + +**Plugin Module** (`plugin/`): +- Plugin loading and caching +- WASM module verification +- Enclave storage (IndexedDB, localStorage) +- IPFS pinning integration + +**Codec Module** (`codec/`): +- Address encoding (Bech32, EIP-55) +- Key management +- Transaction signing +- Signature verification +- Message serialization + +**Auth Module** (`auth/`): +- WebAuthn registration +- WebAuthn authentication +- Credential management +- Passkey integration + +**Generated Protobufs** (`protobufs/`): +- Cosmos SDK types +- Sonr blockchain types +- IBC types +- CosmWasm types + +#### `@motr/sdk` (High-Level SDK) +- Simplified API wrappers +- Common operation helpers +- Error handling utilities +- TypeScript type definitions + +#### `@motr/ui` (UI Components) +- React components for vault operations +- WebAuthn UI flows +- Payment forms +- Dashboard widgets + +#### `@motr/com` (Common Utilities) +- Validation helpers +- Formatting utilities +- Type definitions +- Constants + +### Usage Examples + +```typescript +// Initialize vault client +import { createVaultClient } from '@motr/es'; + +const client = await createVaultClient({ + rpcUrl: 'http://localhost:26657', + restUrl: 'http://localhost:1317', +}); + +// Generate vault +const vault = await client.generate({ id: 'my-vault' }); + +// Sign message +const signature = await client.sign({ + message: new Uint8Array([1, 2, 3]), + enclave: vault.data, +}); + +// Export to IPFS +const cid = await client.export({ + enclave: vault.data, + password: new Uint8Array([/* password */]), +}); +``` + +```typescript +// Service worker integration +import { registerMotorServiceWorker } from '@motr/es'; + +const registration = await registerMotorServiceWorker({ + workerUrl: '/worker.js', + scope: '/motor', +}); + +// Use in browser +const plugin = await createMotorPlugin({ + auto_register_worker: true, + prefer_service_worker: true, +}); + +await plugin.processPayment({ + amount: 100.00, + currency: 'USD', + method: 'card', +}); +``` + +## Component 4: Web Applications + +### Authentication App (`web/auth/`) + +**Framework**: Next.js 14+ +**Purpose**: WebAuthn registration and OIDC flows + +**Features**: +- Passkey registration UI +- Login flows +- Session management +- OIDC client implementation +- WebAuthn ceremony handling + +**Tech Stack**: +- Next.js (App Router) +- React 18 +- TailwindCSS +- Fumadocs (documentation) +- Sonr UI components + +### Dashboard App (`web/dash/`) + +**Framework**: Next.js 14+ +**Purpose**: Vault management and blockchain interaction + +**Features**: +- Vault creation and management +- Transaction signing UI +- DID document viewer +- DWN record browser +- Token management +- Network switcher + +**Tech Stack**: +- Next.js (App Router) +- React 18 +- TailwindCSS +- @motr/sdk for blockchain interaction +- Charts and visualizations + +### Shared Configuration + +Both apps use: +- `@motr/ui` for shared components +- `@motr/sdk` for blockchain operations +- Environment-based configuration +- SSR/SSG optimization +- Edge runtime compatibility + +## Build & Development + +### Worker (WASM) +```bash +# Build worker WASM +make worker + +# Or with TinyGo directly +tinygo build -o worker.wasm -target wasi ./worker/main.go +``` + +### Server (Payment Gateway) +```bash +# Build server +go build -o motr-server ./server/main.go + +# Run server +./motr-server --port 8080 +``` + +### TypeScript SDK +```bash +# Install dependencies +pnpm install + +# Build all packages +pnpm -r build + +# Build specific package +pnpm --filter @motr/es build + +# Run tests +pnpm test + +# Generate from protobufs +cd packages/es +pnpm gen:protobufs +``` + +### Web Applications +```bash +# Development +pnpm --filter @motr/auth dev +pnpm --filter @motr/dash dev + +# Build +pnpm --filter @motr/auth build +pnpm --filter @motr/dash build + +# Production +pnpm --filter @motr/auth start +``` + +## Testing Strategy + +### Go (Worker) +```bash +# Unit tests +go test ./worker/... +go test ./server/... + +# With race detection +go test -race ./... + +# Coverage +go test -cover ./... +``` + +### TypeScript (SDK/Apps) +```bash +# Unit tests +pnpm test + +# E2E tests +pnpm test:e2e + +# Type checking +pnpm typecheck +``` + +### Integration Tests +```bash +# Requires Motor server running +INTEGRATION=true pnpm test +``` + +## Configuration + +### Worker Environment Variables +```bash +# WASM runtime configuration (via Extism) +CHAIN_ID=sonr-testnet-1 +PASSWORD=default-password +IPFS_GATEWAY=https://ipfs.did.run/ipfs/ +``` + +### SDK Configuration +```typescript +interface MotorConfig { + // RPC endpoints + rpcUrl: string; + restUrl: string; + + // IPFS + ipfsGateways: string[]; + enableIPFSPersistence: boolean; + + // Service worker + workerUrl: string; + preferServiceWorker: boolean; + + // Security + timeout: number; + maxRetries: number; +} +``` + +### Web App Environment Variables +```bash +# Common +NODE_ENV=production +NEXT_PUBLIC_CHAIN_ID=sonr-testnet-1 + +# Auth App +NEXT_PUBLIC_AUTH_URL=http://localhost:3100 +NEXT_PUBLIC_WEBAUTHN_RP_ID=localhost +NEXT_PUBLIC_WEBAUTHN_RP_NAME="Sonr Auth" + +# Dashboard App +NEXT_PUBLIC_RPC_ENDPOINT=http://localhost:26657 +NEXT_PUBLIC_REST_ENDPOINT=http://localhost:1317 +NEXT_PUBLIC_IPFS_GATEWAY=https://ipfs.io/ipfs/ +``` + +## Migration Checklist + +When setting up the new `sonr-io/motr` repository: + +### Worker +- [ ] Copy `cmd/vault/` → `worker/` +- [ ] Update import paths to use `github.com/sonr-io/crypto` +- [ ] Create `worker/go.mod` with crypto dependency +- [ ] Setup TinyGo build scripts +- [ ] Add WASM optimization pipeline +- [ ] Document export functions and types +- [ ] Create test suite for WASM functions + +### Server +- [ ] Copy `cmd/motr/` → `server/` +- [ ] Update payment gateway handlers +- [ ] Configure OIDC provider +- [ ] Setup rate limiting +- [ ] Add monitoring/metrics +- [ ] Create Dockerfile +- [ ] Document API endpoints + +### TypeScript SDK +- [ ] Copy `packages/` directory +- [ ] Update package names to `@motr/*` +- [ ] Setup pnpm workspace +- [ ] Configure build pipeline (tsup/rollup) +- [ ] Setup Biome for linting/formatting +- [ ] Generate types from protobuf +- [ ] Create comprehensive tests +- [ ] Setup Changesets for versioning +- [ ] Publish to npm registry + +### Web Applications +- [ ] Copy `web/` directory +- [ ] Update dependencies to use `@motr/*` +- [ ] Configure environment variables +- [ ] Setup build and deployment +- [ ] Create Docker images +- [ ] Add E2E tests +- [ ] Document user flows + +### General +- [ ] Create monorepo structure +- [ ] Setup CI/CD pipelines +- [ ] Configure release automation +- [ ] Create API documentation +- [ ] Write migration guide +- [ ] Setup npm organization (@motr) +- [ ] Configure security scanning +- [ ] Setup monitoring and logging + +## Related Documentation + +- TinyGo: https://tinygo.org/ +- Extism: https://extism.org/ +- W3C Payment Handler API: https://www.w3.org/TR/payment-handler/ +- WebAuthn: https://www.w3.org/TR/webauthn/ +- IPFS: https://docs.ipfs.tech/ +- Next.js: https://nextjs.org/ +- pnpm Workspaces: https://pnpm.io/workspaces diff --git a/Makefile b/Makefile index c439a50f1..b1f59ae6f 100644 --- a/Makefile +++ b/Makefile @@ -104,7 +104,7 @@ stop: ######################################## ### Tools & dependencies ######################################## -format: go-format ts-format +format: go-format go-format: @gum log --level info "Formatting Go code with gofumpt and goimports..." @if command -v gofumpt > /dev/null; then \ @@ -119,12 +119,7 @@ go-format: fi @gum log --level info "✅ Code formatted" -ts-format: - @gum log --level info "Formatting all web applications..." - @pnpm biome format --config-path=$(PWD)/biome.json . - - -lint: go-lint ts-lint +lint: go-lint go-lint: @gum log --level info "Running golangci-lint..." @@ -137,11 +132,7 @@ go-lint: golangci-lint run --timeout=10m; \ fi -ts-lint: - @gum log --level info "Running Biome linter with auto-fix for TypeScript projects..." - @pnpm biome lint --config-path=./biome.json --write . - -.PHONY: lint go-lint ts-lint format +.PHONY: lint go-lint format go-mod-cache: go.sum @gum log --level info "Download go modules to local cache" @@ -152,10 +143,6 @@ go.sum: go.mod @go mod tidy @go mod verify -pnpm-install: - @gum log --level info "Installing pnpm dependencies" - @pnpm install - draw-deps: @# requires brew install graphviz or apt-get install graphviz go install github.com/RobotsAndPencils/goviz@latest @@ -165,18 +152,11 @@ draw-deps: tidy: @go mod tidy @make -C client tidy - @make -C crypto tidy - @make -C cmd/hway tidy - @make -C cmd/motr tidy - @make -C cmd/vault tidy clean: tidy @gum log --level info "Cleaning build artifacts..." rm -rf snapcraft-local.yaml build/ dist/ @$(MAKE) -C cmd/snrd clean - @$(MAKE) -C cmd/hway clean - @$(MAKE) -C cmd/vault clean - @$(MAKE) -C cmd/motr clean clean-docker: @gum log --level info "Removing all Docker volumes and networks..." @@ -197,28 +177,19 @@ build: go.sum build-snrd: build -build-client: go.sum build-vault build-motr +build-client: go.sum @$(MAKE) -C client build @cd /tmp && go mod init test || true @cd /tmp && go get github.com/sonr-io/sonr/client@main || true @cd /tmp && gum log --level info "Client SDK import successful" -build-hway: go.sum build-vault build-motr - @$(MAKE) -C cmd/hway build - -build-vault: - @$(MAKE) -C cmd/vault build - -build-motr: ## Build Motor WASM service worker - @$(MAKE) -C cmd/motr build - # Build all components in parallel build-all: go.sum @gum log --level info "Building all components in parallel..." - @$(MAKE) -j5 build build-hway build-client build-motr build-vault + @$(MAKE) -j2 build build-client @gum log --level info "✅ All components built successfully" -.PHONY: install build build-client build-hway build-snrd build-vault build-motr build-all +.PHONY: install build build-client build-snrd build-all ######################################## ### Docker & Services @@ -245,18 +216,12 @@ dockernet: ######################################## # Smart component release detection and automation release: - @$(MAKE) -C cmd/hway release - @$(MAKE) -C cmd/motr release @$(MAKE) -C cmd/snrd release - @$(MAKE) -C cmd/vault release # Snapshot builds for development snapshot: @gum log --level info "📦 Preparing component snapshot..." - @$(MAKE) -C cmd/vault snapshot - @$(MAKE) -C cmd/motr snapshot @$(MAKE) -C cmd/snrd snapshot - @$(MAKE) -C cmd/hway snapshot .PHONY: release snapshot @@ -290,31 +255,22 @@ test-build-snrd: build @chmod +x build/snrd @./build/snrd version -test-build-hway: build-hway - @ls -la build/hway - test-tdd: go test -json ./... 2>&1 | tdd-guard-go -project-root ${GIT_ROOT} test-app: - @VERSION=$(VERSION) go test -C . -mod=readonly -tags='ledger test_ledger_mock test' github.com/sonr-io/sonr/app/... github.com/sonr-io/sonr/x/... github.com/sonr-io/sonr/types/... github.com/sonr-io/sonr/internal/... + @VERSION=$(VERSION) CGO_LDFLAGS="-lm" go test -C . -mod=readonly -tags='ledger test_ledger_mock test' github.com/sonr-io/sonr/app/... github.com/sonr-io/sonr/x/... github.com/sonr-io/common/... github.com/sonr-io/sonr/internal/... test-devops: @echo "No devops tests" test-client: - @$(MAKE) -C cmd/vault build @$(MAKE) -C client test -test-crypto: - @$(MAKE) -C crypto test - test-dwn-ci: - @$(MAKE) -C cmd/vault build @go test -mod=readonly -tags='ledger test_ledger_mock test' -run='!IPFS' ./x/dwn/... test-internal: - @$(MAKE) -C cmd/vault build @VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock test' ./internal/... # Module testing - Simplified @@ -340,28 +296,14 @@ test-module: VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock test' ./x/$(MODULE)/...; \ fi \ fi - -# Specialized tests -test-hway: - @gum log --level info "Testing Highway service..." - @VERSION=$(VERSION) go test -C . -mod=readonly -v github.com/sonr-io/sonr/bridge/... - test-proto: @$(MAKE) -C proto lint @$(MAKE) -C proto check-breaking -test-motr: - @gum log --level info "Testing Motor WASM service worker..." - @$(MAKE) -C cmd/motr test - -test-vault: - @gum log --level info "Testing Vault WASM plugin..." - @$(MAKE) -C cmd/vault test - test-benchmark: @go test -mod=readonly -bench=. ./... -.PHONY: test test-all test-unit test-race test-cover test-tdd test-module test-hway test-motr test-vault test-benchmark +.PHONY: test test-all test-unit test-race test-cover test-tdd test-module test-benchmark ############################################################################### ### Protobuf ### @@ -373,12 +315,6 @@ climd-gen: proto-gen: @gum log --level info "Generating Go protobuf files..." @$(MAKE) -C proto gen - @gum log --level info "Generating TypeScript protobuf files..." - @if [ -d "packages/es" ]; then \ - cd packages/es && pnpm gen:protobufs || { gum log --level error "TypeScript protobuf generation failed"; exit 1; }; \ - else \ - gum log --level warn "Skipping TypeScript generation: packages/es not found"; \ - fi @gum log --level info "Auto-formatting generated protobuf files..." @$(MAKE) format @@ -400,8 +336,6 @@ swagger-gen: done @gum log --level info "Cleaning up empty source directories..." @find docs/static/openapi -mindepth 1 -maxdepth 1 -type d -exec rm -rf {} + - @gum log --level info "Converting Swagger 2.0 to OpenAPI 3.0..." - @pnpm run convert-swagger @gum log --level info "✅ API documentation processing complete." templ-gen: @@ -444,14 +378,15 @@ help: @gum log --level info "" @gum log --level info "🛠️ Build & Install:" @gum log --level info " install Install snrd binary" - @gum log --level info " build Build snrd binary with vault WASM" + @gum log --level info " build Build snrd binary" @gum log --level info " build-all Build all components in parallel" - @gum log --level info " build-hway Build Highway service" - @gum log --level info " build-vault Build vault WASM module" - @gum log --level info " build-motr Build Motor WASM service worker" @gum log --level info " build-client Build client SDK" @gum log --level info " docker Build Docker images" @gum log --level info "" + @gum log --level info "📦 Release & Distribution:" + @gum log --level info " release Create production release with GoReleaser" + @gum log --level info " snapshot Create development snapshot builds" + @gum log --level info "" @gum log --level info "🚀 Local Development:" @gum log --level info " localnet Start single-node testnet" @gum log --level info " start Start backend services" @@ -476,10 +411,6 @@ help: @gum log --level info " test-e2e Run e2e tests" @gum log --level info " test-e2e-all Run all e2e tests" @gum log --level info " test-module Test specific module (MODULE=did|dwn|svc)" - @gum log --level info " test-packages Test all packages (lint + build)" - @gum log --level info " test-ipfs Test vault with IPFS export/import" - @gum log --level info " test-vault Test vault operations" - @gum log --level info " test-web Test all web apps (lint + build)" @gum log --level info "" @gum log --level info "📚 Module Testing Examples:" @gum log --level info " make test-module MODULE=did # Test DID module" diff --git a/app/ante/ucan_decorator.go b/app/ante/ucan_decorator.go index d90d6fd13..21ba0972c 100644 --- a/app/ante/ucan_decorator.go +++ b/app/ante/ucan_decorator.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/sonr-io/sonr/crypto/keys" - "github.com/sonr-io/sonr/crypto/ucan" + "github.com/sonr-io/crypto/keys" + "github.com/sonr-io/crypto/ucan" ) // UCANDecorator validates UCAN tokens in transactions diff --git a/app/ante/ucan_decorator_test.go b/app/ante/ucan_decorator_test.go index 2a46e6c09..be32dda3e 100644 --- a/app/ante/ucan_decorator_test.go +++ b/app/ante/ucan_decorator_test.go @@ -9,7 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/sonr-io/sonr/crypto/ucan" + "github.com/sonr-io/crypto/ucan" ) // TestUCANDecorator tests the UCAN decorator functionality diff --git a/app/commands/enhance_init.go b/app/commands/enhance_init.go index 7751f5b98..be03499f8 100644 --- a/app/commands/enhance_init.go +++ b/app/commands/enhance_init.go @@ -13,7 +13,7 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/sonr-io/sonr/app" - "github.com/sonr-io/sonr/crypto/vrf" + "github.com/sonr-io/crypto/vrf" "github.com/spf13/cobra" ) diff --git a/app/commands/keys_vrf.go b/app/commands/keys_vrf.go index 6b5c5add5..20f42b710 100644 --- a/app/commands/keys_vrf.go +++ b/app/commands/keys_vrf.go @@ -9,7 +9,7 @@ import ( "path/filepath" "github.com/sonr-io/sonr/app" - "github.com/sonr-io/sonr/crypto/vrf" + "github.com/sonr-io/crypto/vrf" "github.com/spf13/cobra" ) diff --git a/app/context/context.go b/app/context/context.go index 15319641c..112be130d 100644 --- a/app/context/context.go +++ b/app/context/context.go @@ -10,7 +10,7 @@ import ( "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/client" - "github.com/sonr-io/sonr/crypto/vrf" + "github.com/sonr-io/crypto/vrf" ) // SonrContext manages node-specific state and configuration diff --git a/app/context/context_test.go b/app/context/context_test.go index 3468eedf1..4e5abd715 100644 --- a/app/context/context_test.go +++ b/app/context/context_test.go @@ -8,7 +8,7 @@ import ( "cosmossdk.io/log" "github.com/stretchr/testify/require" - "github.com/sonr-io/sonr/crypto/vrf" + "github.com/sonr-io/crypto/vrf" ) // TestSonrContextInitialization tests SonrContext initialization with VRF keys diff --git a/biome.json b/biome.json deleted file mode 100644 index ef476def2..000000000 --- a/biome.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "$schema": "https://biomejs.dev/schemas/2.1.4/schema.json", - "vcs": { - "enabled": true, - "clientKind": "git", - "useIgnoreFile": true - }, - "files": { - "ignoreUnknown": false - }, - "formatter": { - "enabled": true, - "indentStyle": "space", - "indentWidth": 2, - "lineEnding": "lf", - "lineWidth": 100 - }, - "linter": { - "enabled": true, - "rules": { - "recommended": true, - "correctness": { - "noUnusedVariables": "error", - "useExhaustiveDependencies": "warn" - }, - "style": { - "noNonNullAssertion": "warn", - "useConst": "error" - }, - "suspicious": { - "noExplicitAny": "warn", - "noArrayIndexKey": "warn" - } - } - }, - "javascript": { - "formatter": { - "quoteStyle": "single", - "trailingCommas": "es5", - "semicolons": "always" - } - }, - "overrides": [ - { - - "formatter": { - "enabled": false - }, - "linter": { - "enabled": false - } - }, - { - "linter": { - "rules": { - "suspicious": { - "noExplicitAny": "off" - }, - "correctness": { - "noUnusedVariables": "warn" - }, - "complexity": { - "noStaticOnlyClass": "off" - } - } - } - }, - { - "linter": { - "rules": { - "style": { - "useTemplate": "warn", - "noUnusedTemplateLiteral": "warn" - } - } - } - }, - { - "linter": { - "rules": { - "suspicious": { - "noExplicitAny": "off" - }, - "correctness": { - "noUnusedVariables": "warn" - } - } - } - }, - { - "linter": { - "rules": { - "suspicious": { - "noExplicitAny": "off" - }, - "correctness": { - "noUnusedVariables": "warn" - } - } - } - } - ] -} diff --git a/bridge/bridge.go b/bridge/bridge.go deleted file mode 100644 index 17d7e0197..000000000 --- a/bridge/bridge.go +++ /dev/null @@ -1,118 +0,0 @@ -// Package bridge provides the HTTP bridge server for the Highway service. -package bridge - -import ( - "context" - "fmt" - "log" - "os" - "os/signal" - "syscall" - - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/bridge/server" -) - -// HighwayService encapsulates the entire Highway service setup and lifecycle -type HighwayService struct { - config *Config - client *asynq.Client - httpServer *server.Server - queueManager *QueueManager - - // Internal channels for coordination - ctx context.Context - cancel context.CancelFunc - sigCh chan os.Signal -} - -// NewHighwayService creates a new Highway service with all components initialized -func NewHighwayService() *HighwayService { - // Setup graceful shutdown - ctx, cancel := context.WithCancel(context.Background()) - - // Handle shutdown signals - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) - - // Initialize configuration - config := NewConfig() - - // Initialize Redis-based task queue client - client := asynq.NewClient(asynq.RedisClientOpt{Addr: config.RedisAddr}) - log.Printf("Asynq client connected to Redis at %s", config.RedisAddr) - - // Create server configuration for bridge proxy - serverConfig := &server.Config{ - HTTPAddr: fmt.Sprintf(":%d", config.HTTPPort), - JWTSecret: config.JWTSecret, - IPFSClient: config.IPFSClient, - } - - // Create HTTP bridge server - httpServer := server.NewServer(serverConfig) - - // Initialize UCAN task processing server with queue manager - queueManager := NewQueueManager(config) - - return &HighwayService{ - config: config, - client: client, - httpServer: httpServer, - queueManager: queueManager, - ctx: ctx, - cancel: cancel, - sigCh: sigCh, - } -} - -// Start begins the Highway service with HTTP server and queue processing -func (hs *HighwayService) Start() error { - log.Println("Starting Highway Service - UCAN-based MPC Task Processor") - - // Create and start HTTP bridge server in a goroutine - go func() { - log.Printf("Starting HTTP bridge server on port %d", hs.config.HTTPPort) - if err := hs.httpServer.Start(hs.client); err != nil { - log.Fatalf("HTTP bridge server failed: %v", err) - } - }() - - // Start queue server with graceful shutdown support - go func() { - if err := hs.queueManager.Run(); err != nil { - log.Printf("Asynq server error: %v", err) - hs.cancel() - } - }() - - // Wait for shutdown signal - select { - case <-hs.sigCh: - log.Println("Received shutdown signal, initiating graceful shutdown...") - case <-hs.ctx.Done(): - log.Println("Context cancelled, shutting down...") - } - - return nil -} - -// Shutdown gracefully stops all service components -func (hs *HighwayService) Shutdown() { - log.Println("Shutting down Highway service...") - - // Close Asynq client - if hs.client != nil { - hs.client.Close() - } - - // Shutdown queue manager - if hs.queueManager != nil { - hs.queueManager.Shutdown() - } - - // Cancel context to signal shutdown to all components - hs.cancel() - - log.Println("Highway service stopped") -} diff --git a/bridge/bridge_test.go b/bridge/bridge_test.go deleted file mode 100644 index 43d6bc619..000000000 --- a/bridge/bridge_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package bridge - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewHighwayService(t *testing.T) { - service := NewHighwayService() - - require.NotNil(t, service) - assert.NotNil(t, service.config) - assert.NotNil(t, service.client) - assert.NotNil(t, service.httpServer) - assert.NotNil(t, service.queueManager) - assert.NotNil(t, service.ctx) - assert.NotNil(t, service.cancel) - assert.NotNil(t, service.sigCh) -} - -func TestHighwayServiceComponents(t *testing.T) { - service := NewHighwayService() - defer service.Shutdown() - - // Test that all components are properly initialized - assert.NotNil(t, service.config.RedisAddr) - assert.NotNil(t, service.config.JWTSecret) - assert.NotNil(t, service.config.AsynqConfig) -} diff --git a/bridge/config.go b/bridge/config.go deleted file mode 100644 index 1e896937f..000000000 --- a/bridge/config.go +++ /dev/null @@ -1,202 +0,0 @@ -package bridge - -import ( - "log" - "os" - "strconv" - "time" - - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/types/ipfs" -) - -const ( - DefaultRedisAddr = "127.0.0.1:6379" - DefaultJWTSecret = "highway-ucan-secret-key" - DefaultHTTPPort = 8090 - ShutdownTimeout = 30 * time.Second -) - -// OIDCProviderConfig contains OIDC provider configuration -type OIDCProviderConfig struct { - Issuer string - PublicURL string - SigningKeyPath string - EncryptionKeyPath string - AuthorizationCodeTTL time.Duration - AccessTokenTTL time.Duration - RefreshTokenTTL time.Duration - IDTokenTTL time.Duration - EnablePKCE bool - EnableRefreshTokens bool - EnableSIOP bool - SupportedScopes []string - SupportedResponseTypes []string - SupportedGrantTypes []string - AllowedRedirectURIs []string - WebAuthnRPID string - WebAuthnRPName string - WebAuthnTimeout int - AutoCreateVault bool -} - -type Config struct { - RedisAddr string - HTTPPort int - JWTSecret []byte - IPFSClient ipfs.IPFSClient - ShutdownTimeout time.Duration - AsynqConfig asynq.Config - OIDC OIDCProviderConfig -} - -func NewConfig() *Config { - jwtSecret := initializeJWTSecret() - redisAddr := getRedisAddr() - httpPort := getHTTPPort() - ipfsClient := initializeIPFS() - oidcConfig := initializeOIDCConfig() - - return &Config{ - RedisAddr: redisAddr, - HTTPPort: httpPort, - JWTSecret: jwtSecret, - IPFSClient: ipfsClient, - ShutdownTimeout: ShutdownTimeout, - AsynqConfig: asynq.Config{ - Concurrency: 10, - Queues: map[string]int{ - "critical": 6, - "default": 3, - "low": 1, - }, - ShutdownTimeout: ShutdownTimeout, - // Enhanced error handling and retry configuration - RetryDelayFunc: asynq.DefaultRetryDelayFunc, - IsFailure: func(err error) bool { - return err != nil - }, - }, - OIDC: oidcConfig, - } -} - -func initializeJWTSecret() []byte { - secret := os.Getenv("JWT_SECRET") - if secret == "" { - secret = DefaultJWTSecret - log.Printf("Warning: Using default JWT secret for UCAN operations") - log.Printf("Set JWT_SECRET environment variable for production deployment") - } else { - log.Println("JWT secret loaded from environment") - } - return []byte(secret) -} - -func getRedisAddr() string { - // Check for REDIS_URL first (Docker Compose style) - if url := os.Getenv("REDIS_URL"); url != "" { - // Parse redis://host:port format - if len(url) > 8 && url[:8] == "redis://" { - return url[8:] - } - return url - } - // Fall back to REDIS_ADDR - if addr := os.Getenv("REDIS_ADDR"); addr != "" { - return addr - } - log.Printf("Using default Redis address: %s", DefaultRedisAddr) - return DefaultRedisAddr -} - -func initializeIPFS() ipfs.IPFSClient { - ipfsClient, err := ipfs.GetClient() - if err != nil { - log.Printf("Warning: IPFS client initialization failed: %v", err) - log.Println("Enclave data will be handled directly without IPFS storage") - return nil - } - log.Println("IPFS client initialized successfully") - return ipfsClient -} - -func initializeOIDCConfig() OIDCProviderConfig { - issuer := os.Getenv("OIDC_ISSUER") - if issuer == "" { - issuer = "https://localhost:8080" - } - - publicURL := os.Getenv("OIDC_PUBLIC_URL") - if publicURL == "" { - publicURL = issuer - } - - rpID := os.Getenv("WEBAUTHN_RP_ID") - if rpID == "" { - rpID = "localhost" - } - - rpName := os.Getenv("WEBAUTHN_RP_NAME") - if rpName == "" { - rpName = "Sonr Identity Platform" - } - - return OIDCProviderConfig{ - Issuer: issuer, - PublicURL: publicURL, - SigningKeyPath: os.Getenv("OIDC_SIGNING_KEY_PATH"), - EncryptionKeyPath: os.Getenv("OIDC_ENCRYPTION_KEY_PATH"), - AuthorizationCodeTTL: 10 * time.Minute, - AccessTokenTTL: 1 * time.Hour, - RefreshTokenTTL: 7 * 24 * time.Hour, - IDTokenTTL: 1 * time.Hour, - EnablePKCE: true, - EnableRefreshTokens: true, - EnableSIOP: true, - SupportedScopes: []string{ - "openid", "profile", "email", "did", "vault", "offline_access", - }, - SupportedResponseTypes: []string{ - "code", "id_token", "code id_token", - }, - SupportedGrantTypes: []string{ - "authorization_code", "refresh_token", "client_credentials", - }, - AllowedRedirectURIs: getRedirectURIs(), - WebAuthnRPID: rpID, - WebAuthnRPName: rpName, - WebAuthnTimeout: 60000, - AutoCreateVault: true, - } -} - -// getRedirectURIs returns the allowed redirect URIs for OIDC -func getRedirectURIs() []string { - // Default URIs for development - uris := []string{ - "http://localhost:3000/callback", - "http://localhost:3001/callback", - "https://localhost:3000/callback", - "https://localhost:3001/callback", - } - - // Add additional URIs from environment if specified - if envURIs := os.Getenv("OIDC_ALLOWED_REDIRECT_URIS"); envURIs != "" { - // Parse comma-separated URIs - // This could be enhanced with proper validation - log.Printf("Additional redirect URIs configured from environment") - } - - return uris -} - -// getHTTPPort returns the HTTP port for the Highway service -func getHTTPPort() int { - if port := os.Getenv("HIGHWAY_PORT"); port != "" { - if p, err := strconv.Atoi(port); err == nil { - return p - } - } - return DefaultHTTPPort -} diff --git a/bridge/handlers/auth.go b/bridge/handlers/auth.go deleted file mode 100644 index 3e1f09d85..000000000 --- a/bridge/handlers/auth.go +++ /dev/null @@ -1,265 +0,0 @@ -// Package handlers provides HTTP handlers for the highway server -package handlers - -import ( - "crypto/rand" - "encoding/base64" - "fmt" - "net/http" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/labstack/echo/v4" -) - -// CustomClaims defines custom JWT claims for vault operations -type CustomClaims struct { - UserID string `json:"user_id"` - Permissions []string `json:"permissions"` - jwt.RegisteredClaims -} - -// LoginRequest represents the login request payload -type LoginRequest struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// LoginResponse represents the login response payload -type LoginResponse struct { - Token string `json:"token"` -} - -// LoginHandler generates JWT tokens for authentication -// This now supports both traditional login and OIDC-based authentication -func LoginHandler(jwtSecret []byte) echo.HandlerFunc { - return func(c echo.Context) error { - // Check if this is an OIDC callback - code := c.QueryParam("code") - if code != "" { - return handleOIDCCallback(c, code, jwtSecret) - } - - // Check if user has WebAuthn credentials - authHeader := c.Request().Header.Get("X-WebAuthn-Assertion") - if authHeader != "" { - return handleWebAuthnLogin(c, authHeader, jwtSecret) - } - - // Traditional login flow - var req LoginRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - // Simple authentication - in production, validate against a proper user database - if req.Username == "" || req.Password == "" { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Username and password are required"}, - ) - } - - // For demo purposes, accept any non-empty credentials - // In production, verify credentials against database/directory - if req.Username == "vault-user" && req.Password == "vault-pass" { - // Create custom claims - claims := &CustomClaims{ - UserID: req.Username, - Permissions: []string{ - "vault:generate", - "vault:sign", - "vault:verify", - "vault:export", - "vault:import", - "vault:refresh", - }, - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), // 24 hours - IssuedAt: jwt.NewNumericDate(time.Now()), - NotBefore: jwt.NewNumericDate(time.Now()), - Issuer: "highway-vault", - Subject: req.Username, - }, - } - - // Create token with claims - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - - // Sign token with secret - tokenString, err := token.SignedString(jwtSecret) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to generate token"}, - ) - } - - return c.JSON(http.StatusOK, LoginResponse{Token: tokenString}) - } - - return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid credentials"}) - } -} - -// handleOIDCCallback processes OIDC authorization code callback -func handleOIDCCallback(c echo.Context, code string, jwtSecret []byte) error { - // Exchange code for tokens using OIDC token endpoint - tokenReq := &OIDCTokenRequest{ - GrantType: "authorization_code", - Code: code, - RedirectURI: c.QueryParam("redirect_uri"), - ClientID: c.QueryParam("client_id"), - } - - // Call internal OIDC token handler - // In production, this would make an HTTP call to the OIDC provider - c.Set("oidc_token_request", tokenReq) - if err := handleAuthorizationCodeGrant(c, tokenReq); err != nil { - return err - } - - // Get the OIDC session from context - session, ok := c.Get("oidc_session").(*OIDCSession) - if !ok { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "Failed to establish OIDC session", - }) - } - - // Create JWT token from OIDC session - claims := &CustomClaims{ - UserID: session.UserDID, - Permissions: []string{ - "vault:generate", - "vault:sign", - "vault:verify", - "vault:export", - "vault:import", - "vault:refresh", - }, - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(session.ExpiresAt), - IssuedAt: jwt.NewNumericDate(time.Now()), - NotBefore: jwt.NewNumericDate(time.Now()), - Issuer: "highway-vault-oidc", - Subject: session.UserDID, - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - tokenString, err := token.SignedString(jwtSecret) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "Failed to generate token", - }) - } - - return c.JSON(http.StatusOK, LoginResponse{Token: tokenString}) -} - -// handleWebAuthnLogin processes WebAuthn-based login -func handleWebAuthnLogin(c echo.Context, assertion string, jwtSecret []byte) error { - // Verify WebAuthn assertion - // This would integrate with the WebAuthn handlers - - // For now, extract username from assertion (simplified) - username := c.Request().Header.Get("X-WebAuthn-Username") - if username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "WebAuthn username required", - }) - } - - // Verify the assertion matches a stored credential - webAuthnStore.mu.RLock() - credentials, exists := webAuthnStore.credentials[username] - webAuthnStore.mu.RUnlock() - - if !exists || len(credentials) == 0 { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "No WebAuthn credentials found for user", - }) - } - - // Create JWT token for WebAuthn authenticated user - claims := &CustomClaims{ - UserID: username, - Permissions: []string{ - "vault:generate", - "vault:sign", - "vault:verify", - "vault:export", - "vault:import", - "vault:refresh", - }, - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), - IssuedAt: jwt.NewNumericDate(time.Now()), - NotBefore: jwt.NewNumericDate(time.Now()), - Issuer: "highway-vault-webauthn", - Subject: username, - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - tokenString, err := token.SignedString(jwtSecret) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "Failed to generate token", - }) - } - - return c.JSON(http.StatusOK, LoginResponse{Token: tokenString}) -} - -// OIDCLoginHandler initiates OIDC login flow -func OIDCLoginHandler() echo.HandlerFunc { - return func(c echo.Context) error { - // Build authorization URL - authURL := buildOIDCAuthorizationURL( - c.QueryParam("client_id"), - c.QueryParam("redirect_uri"), - c.QueryParam("scope"), - c.QueryParam("state"), - ) - - // Redirect to OIDC authorization endpoint - return c.Redirect(http.StatusFound, authURL) - } -} - -// buildOIDCAuthorizationURL constructs the OIDC authorization URL -func buildOIDCAuthorizationURL(clientID, redirectURI, scope, state string) string { - // Default values if not provided - if clientID == "" { - clientID = "highway-vault-client" - } - if redirectURI == "" { - redirectURI = "http://localhost:8080/auth/callback" - } - if scope == "" { - scope = "openid profile did vault" - } - if state == "" { - state = generateState() - } - - // Build authorization URL - return fmt.Sprintf( - "https://localhost:8080/oidc/authorize?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&state=%s", - clientID, - redirectURI, - scope, - state, - ) -} - -// generateState generates a random state parameter for OIDC -func generateState() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - return "default-state" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} diff --git a/bridge/handlers/benchmark_test.go b/bridge/handlers/benchmark_test.go deleted file mode 100644 index ecd5664d6..000000000 --- a/bridge/handlers/benchmark_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package handlers - -import ( - "encoding/json" - "testing" - - "github.com/sonr-io/sonr/crypto/mpc" -) - -// getQueueFromPriority returns the queue name based on priority -func getQueueFromPriority(priority string) string { - return GetQueueFromPriority(priority) -} - -// BenchmarkJSONMarshaling measures JSON encoding/decoding performance -func BenchmarkJSONMarshaling(b *testing.B) { - payload := map[string]any{ - "message": []byte("benchmark test message for JSON marshaling performance"), - "enclave": &mpc.EnclaveData{}, - "priority": "critical", - } - - b.ResetTimer() - b.ReportAllocs() - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - // Marshal - data, err := json.Marshal(payload) - if err != nil { - b.Error(err) - } - - // Unmarshal - var decoded map[string]any - err = json.Unmarshal(data, &decoded) - if err != nil { - b.Error(err) - } - } - }) -} - -// BenchmarkQueuePrioritySelection measures queue selection performance -func BenchmarkQueuePrioritySelection(b *testing.B) { - priorities := []string{"critical", "high", "default", "low", "", "unknown"} - - b.ResetTimer() - b.ReportAllocs() - - b.RunParallel(func(pb *testing.PB) { - i := 0 - for pb.Next() { - priority := priorities[i%len(priorities)] - i++ - queue := getQueueFromPriority(priority) - _ = queue // Avoid compiler optimization - } - }) -} diff --git a/bridge/handlers/broadcast.go b/bridge/handlers/broadcast.go deleted file mode 100644 index eae89aedd..000000000 --- a/bridge/handlers/broadcast.go +++ /dev/null @@ -1,333 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - "time" - - "github.com/labstack/echo/v4" -) - -// BroadcastService handles blockchain broadcasting operations -type BroadcastService struct { - // TODO: Add cosmos SDK client for actual broadcasting -} - -var broadcastService = &BroadcastService{} - -// HandleBroadcast handles generic message broadcasting to blockchain -func HandleBroadcast(c echo.Context) error { - var req BroadcastRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid broadcast request", - }) - } - - // Validate request - if req.Message == nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Message is required", - }) - } - - // Process based on gasless flag - if req.Gasless { - return handleGaslessBroadcast(c, &req) - } - - return handleStandardBroadcast(c, &req) -} - -// handleGaslessBroadcast handles gasless transaction broadcasting -func handleGaslessBroadcast(c echo.Context, req *BroadcastRequest) error { - // Validate gasless eligibility - if !isGaslessEligible(req.Message) { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Message not eligible for gasless broadcast", - }) - } - - // TODO: Implement actual blockchain broadcast - // For now, simulate successful broadcast - response := &BroadcastResponse{ - TxHash: generateTxHash(), - Height: 12345, - Code: 0, - RawLog: "Transaction broadcast successfully", - Success: true, - } - - return c.JSON(http.StatusOK, response) -} - -// handleStandardBroadcast handles regular transaction broadcasting -func handleStandardBroadcast(c echo.Context, req *BroadcastRequest) error { - // Get sender address - fromAddress := req.FromAddress - if fromAddress == "" { - // Try to get from context - userDID := c.Get("user_did") - if userDID != nil { - fromAddress = deriveAddressFromDID(userDID.(string)) - } - } - - if fromAddress == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "From address is required for standard broadcast", - }) - } - - // TODO: Implement actual blockchain broadcast - // For now, simulate successful broadcast - response := &BroadcastResponse{ - TxHash: generateTxHash(), - Height: 12346, - Code: 0, - RawLog: "Transaction broadcast successfully", - Success: true, - } - - return c.JSON(http.StatusOK, response) -} - -// BroadcastWebAuthnRegistration broadcasts WebAuthn registration to blockchain -func BroadcastWebAuthnRegistration( - credential *WebAuthnCredential, - gasless bool, -) (*BroadcastResponse, error) { - // Create MsgRegisterWebAuthnCredential - msg := map[string]any{ - "@type": "/sonr.did.v1.MsgRegisterWebAuthnCredential", - "username": credential.Username, - "credential_id": credential.CredentialID, - "public_key": credential.PublicKey, - "attestation_object": credential.AttestationObject, - "client_data_json": credential.ClientDataJSON, - "origin": credential.Origin, - "algorithm": credential.Algorithm, - } - - // Create broadcast request (for future use with actual broadcast) - _ = &BroadcastRequest{ - Message: msg, - Gasless: gasless, - AutoSign: true, - } - - // Simulate broadcast (TODO: Implement actual broadcast) - return &BroadcastResponse{ - TxHash: generateTxHash(), - Height: 12347, - Code: 0, - RawLog: "WebAuthn credential registered successfully", - Success: true, - }, nil -} - -// BroadcastVaultCreation broadcasts vault creation to blockchain -func BroadcastVaultCreation( - userDID string, - vaultConfig map[string]any, -) (*BroadcastResponse, error) { - // Create MsgCreateVault - msg := map[string]any{ - "@type": "/sonr.vault.v1.MsgCreateVault", - "creator": userDID, - "config": vaultConfig, - } - - // Create broadcast request (for future use with actual broadcast) - _ = &BroadcastRequest{ - Message: msg, - Gasless: true, // Vault creation is gasless for new users - AutoSign: true, - FromAddress: deriveAddressFromDID(userDID), - } - - // Simulate broadcast (TODO: Implement actual broadcast) - return &BroadcastResponse{ - TxHash: generateTxHash(), - Height: 12348, - Code: 0, - RawLog: "Vault created successfully", - Success: true, - }, nil -} - -// BroadcastDIDDocument broadcasts DID document to blockchain -func BroadcastDIDDocument(didDoc map[string]any, gasless bool) (*BroadcastResponse, error) { - // Create MsgCreateDIDDocument or MsgUpdateDIDDocument - msg := map[string]any{ - "@type": "/sonr.did.v1.MsgCreateDIDDocument", - "did_document": didDoc, - } - - // Create broadcast request (for future use with actual broadcast) - _ = &BroadcastRequest{ - Message: msg, - Gasless: gasless, - AutoSign: true, - } - - // Simulate broadcast (TODO: Implement actual broadcast) - return &BroadcastResponse{ - TxHash: generateTxHash(), - Height: 12349, - Code: 0, - RawLog: "DID document created successfully", - Success: true, - }, nil -} - -// HandleTransactionStatus checks transaction status -func HandleTransactionStatus(c echo.Context) error { - txHash := c.Param("hash") - if txHash == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Transaction hash is required", - }) - } - - // TODO: Query actual blockchain for transaction status - // For now, return simulated status - status := map[string]any{ - "tx_hash": txHash, - "height": 12350, - "status": "confirmed", - "code": 0, - "gas_used": 50000, - "gas_wanted": 100000, - "timestamp": time.Now().Unix(), - } - - return c.JSON(http.StatusOK, status) -} - -// HandleEstimateGas estimates gas for a transaction -func HandleEstimateGas(c echo.Context) error { - var req BroadcastRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid request", - }) - } - - // Check if gasless eligible - if isGaslessEligible(req.Message) { - return c.JSON(http.StatusOK, map[string]any{ - "gas_estimate": 0, - "gasless": true, - "fee": "0usnr", - }) - } - - // TODO: Implement actual gas estimation - // For now, return default estimate - return c.JSON(http.StatusOK, map[string]any{ - "gas_estimate": 100000, - "gasless": false, - "fee": "100usnr", - }) -} - -// Helper functions - -// isGaslessEligible checks if a message is eligible for gasless broadcasting -func isGaslessEligible(message any) bool { - // Check message type - msgMap, ok := message.(map[string]any) - if !ok { - return false - } - - msgType, ok := msgMap["@type"].(string) - if !ok { - return false - } - - // WebAuthn registration and vault creation are gasless - gaslessTypes := []string{ - "/sonr.did.v1.MsgRegisterWebAuthnCredential", - "/sonr.vault.v1.MsgCreateVault", - "/sonr.did.v1.MsgCreateDIDDocument", - } - - for _, t := range gaslessTypes { - if msgType == t { - return true - } - } - - return false -} - -// deriveAddressFromDID derives a blockchain address from a DID -func deriveAddressFromDID(did string) string { - // TODO: Implement actual address derivation - // For now, return a placeholder address - return "sonr1placeholder" + did[len(did)-10:] -} - -// generateTxHash generates a mock transaction hash -func generateTxHash() string { - // TODO: Replace with actual tx hash from broadcast - return fmt.Sprintf("%X", time.Now().UnixNano()) -} - -// CreateWebAuthnBroadcastHandler creates a handler that broadcasts WebAuthn credentials -func CreateWebAuthnBroadcastHandler() echo.HandlerFunc { - return func(c echo.Context) error { - // Get WebAuthn credential from context - credential, ok := c.Get("webauthn_credential").(*WebAuthnCredential) - if !ok { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "No WebAuthn credential found", - }) - } - - // Broadcast to blockchain - response, err := BroadcastWebAuthnRegistration(credential, true) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": err.Error(), - }) - } - - return c.JSON(http.StatusOK, response) - } -} - -// CreateVaultBroadcastHandler creates a handler that broadcasts vault creation -func CreateVaultBroadcastHandler() echo.HandlerFunc { - return func(c echo.Context) error { - // Get user DID from context - userDID, ok := c.Get("user_did").(string) - if !ok { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "User DID not found", - }) - } - - // Get vault config from request - var vaultConfig map[string]any - if err := c.Bind(&vaultConfig); err != nil { - // Use default config - vaultConfig = map[string]any{ - "type": "standard", - "encryption": "AES256", - } - } - - // Broadcast vault creation - response, err := BroadcastVaultCreation(userDID, vaultConfig) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": err.Error(), - }) - } - - return c.JSON(http.StatusOK, response) - } -} diff --git a/bridge/handlers/errors.go b/bridge/handlers/errors.go deleted file mode 100644 index f0d07686b..000000000 --- a/bridge/handlers/errors.go +++ /dev/null @@ -1,33 +0,0 @@ -package handlers - -import "errors" - -// Common errors for OAuth2 and UCAN handling -var ( - // Client errors - ErrClientNotFound = errors.New("client not found") - ErrInvalidClientCredentials = errors.New("invalid client credentials") - - // Token errors - ErrTokenNotFound = errors.New("token not found") - ErrTokenExpired = errors.New("token has expired") - ErrInvalidToken = errors.New("invalid token") - ErrTokenRevoked = errors.New("token has been revoked") - - // Authorization errors - ErrUnauthorized = errors.New("unauthorized") - ErrInsufficientScope = errors.New("insufficient scope") - ErrInvalidScope = errors.New("invalid scope") - ErrScopeNotAllowed = errors.New("scope not allowed for client") - - // UCAN errors - ErrInvalidAttenuation = errors.New("invalid attenuation") - ErrInvalidDelegation = errors.New("invalid delegation") - ErrBrokenChain = errors.New("broken delegation chain") - ErrPrivilegeEscalation = errors.New("privilege escalation attempted") - - // OIDC errors - ErrInvalidRedirectURI = errors.New("invalid redirect URI") - ErrInvalidResponseType = errors.New("invalid response type") - ErrInvalidGrantType = errors.New("invalid grant type") -) diff --git a/bridge/handlers/handlers_test.go b/bridge/handlers/handlers_test.go deleted file mode 100644 index 603a1fc28..000000000 --- a/bridge/handlers/handlers_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package handlers - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetQueueFromPriority(t *testing.T) { - tests := []struct { - priority string - expected string - }{ - {"critical", "critical"}, - {"high", "critical"}, - {"low", "low"}, - {"", "default"}, - {"unknown", "default"}, - } - - for _, tt := range tests { - t.Run(tt.priority, func(t *testing.T) { - result := GetQueueFromPriority(tt.priority) - assert.Equal(t, tt.expected, result) - }) - } -} diff --git a/bridge/handlers/health.go b/bridge/handlers/health.go deleted file mode 100644 index 5ed2a4180..000000000 --- a/bridge/handlers/health.go +++ /dev/null @@ -1,201 +0,0 @@ -package handlers - -import ( - "context" - "net/http" - "sync" - "time" - - "github.com/hibiken/asynq" - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/types/ipfs" -) - -// HealthStatus represents the health status of the service -type HealthStatus struct { - Status string `json:"status"` - Timestamp string `json:"timestamp"` - Uptime string `json:"uptime"` - Dependencies map[string]string `json:"dependencies"` -} - -// HealthChecker manages health and readiness checks -type HealthChecker struct { - startTime time.Time - redisClient *asynq.Client - ipfsClient ipfs.IPFSClient - ready bool - readyMu sync.RWMutex - redisHealthy bool - ipfsHealthy bool -} - -// NewHealthChecker creates a new health checker -func NewHealthChecker(redisClient *asynq.Client, ipfsClient ipfs.IPFSClient) *HealthChecker { - hc := &HealthChecker{ - startTime: time.Now(), - redisClient: redisClient, - ipfsClient: ipfsClient, - ready: false, - } - - // Start background health checks - go hc.startHealthChecks() - - return hc -} - -// startHealthChecks runs periodic health checks -func (hc *HealthChecker) startHealthChecks() { - // Initial startup delay - time.Sleep(3 * time.Second) - - ticker := time.NewTicker(10 * time.Second) - defer ticker.Stop() - - // Run initial check - hc.checkDependencies() - - for range ticker.C { - hc.checkDependencies() - } -} - -// checkDependencies checks all service dependencies -func (hc *HealthChecker) checkDependencies() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - // Check Redis connectivity - hc.redisHealthy = hc.checkRedis(ctx) - - // Check IPFS connectivity (optional) - hc.ipfsHealthy = hc.checkIPFS(ctx) - - // Update readiness based on critical dependencies - hc.readyMu.Lock() - hc.ready = hc.redisHealthy // Redis is required - hc.readyMu.Unlock() -} - -// checkRedis verifies Redis connectivity -func (hc *HealthChecker) checkRedis(ctx context.Context) bool { - if hc.redisClient == nil { - return false - } - - // Try to ping Redis by enqueuing a test task - testTask := asynq.NewTask("health:check", nil) - _, err := hc.redisClient.EnqueueContext(ctx, testTask, - asynq.Queue("health"), - asynq.MaxRetry(0), - asynq.Retention(1*time.Second)) // Auto-delete after 1 second - if err != nil { - return false - } - - return true -} - -// checkIPFS verifies IPFS connectivity -func (hc *HealthChecker) checkIPFS(ctx context.Context) bool { - if hc.ipfsClient == nil { - return true // IPFS is optional - } - - // Check IPFS connectivity by getting version - ch := make(chan bool, 1) - go func() { - // Try a simple operation to check connectivity - if hc.ipfsClient != nil { - // IPFS client exists, assume healthy for now - // Real check would depend on actual IPFS client implementation - ch <- true - } else { - ch <- false - } - }() - - select { - case result := <-ch: - return result - case <-ctx.Done(): - return false - } -} - -// IsReady returns whether the service is ready to handle requests -func (hc *HealthChecker) IsReady() bool { - hc.readyMu.RLock() - defer hc.readyMu.RUnlock() - return hc.ready -} - -// GetStatus returns the current health status -func (hc *HealthChecker) GetStatus() HealthStatus { - uptime := time.Since(hc.startTime) - - deps := make(map[string]string) - if hc.redisHealthy { - deps["redis"] = "healthy" - } else { - deps["redis"] = "unhealthy" - } - - if hc.ipfsClient != nil { - if hc.ipfsHealthy { - deps["ipfs"] = "healthy" - } else { - deps["ipfs"] = "unhealthy" - } - } else { - deps["ipfs"] = "not_configured" - } - - status := "healthy" - if !hc.ready { - status = "unhealthy" - } - - return HealthStatus{ - Status: status, - Timestamp: time.Now().UTC().Format(time.RFC3339), - Uptime: uptime.String(), - Dependencies: deps, - } -} - -// Global health checker instance -var healthChecker *HealthChecker - -// InitHealthChecker initializes the global health checker -func InitHealthChecker(redisClient *asynq.Client, ipfsClient ipfs.IPFSClient) { - healthChecker = NewHealthChecker(redisClient, ipfsClient) -} - -// HealthCheckHandler returns health status (liveness probe) -func HealthCheckHandler(c echo.Context) error { - if healthChecker == nil { - return c.JSON(http.StatusOK, map[string]string{"status": "starting"}) - } - - status := healthChecker.GetStatus() - if status.Status == "healthy" { - return c.JSON(http.StatusOK, status) - } - return c.JSON(http.StatusServiceUnavailable, status) -} - -// ReadinessHandler returns readiness status (readiness probe) -func ReadinessHandler(c echo.Context) error { - if healthChecker == nil || !healthChecker.IsReady() { - return c.JSON(http.StatusServiceUnavailable, map[string]string{ - "ready": "false", - "reason": "service not ready", - }) - } - - return c.JSON(http.StatusOK, map[string]string{ - "ready": "true", - }) -} diff --git a/bridge/handlers/oauth2_clients.go b/bridge/handlers/oauth2_clients.go deleted file mode 100644 index 44eaad95a..000000000 --- a/bridge/handlers/oauth2_clients.go +++ /dev/null @@ -1,422 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "encoding/base64" - "fmt" - "net/url" - "strings" - "sync" - "time" -) - -const ( - // ClientTypePublic represents a public OAuth2 client - ClientTypePublic = "public" - // ClientTypeConfidential represents a confidential OAuth2 client - ClientTypeConfidential = "confidential" -) - -// ClientRegistry manages OAuth2 client registrations -type ClientRegistry struct { - mu sync.RWMutex - clients map[string]*OAuth2Client -} - -// NewClientRegistry creates a new client registry -func NewClientRegistry() *ClientRegistry { - registry := &ClientRegistry{ - clients: make(map[string]*OAuth2Client), - } - - // Initialize with default clients for development - registry.initializeDefaultClients() - - return registry -} - -// initializeDefaultClients adds default clients for development/testing -func (r *ClientRegistry) initializeDefaultClients() { - // Development public client (e.g., SPA) - _ = r.RegisterClient(&OAuth2Client{ - ClientID: "sonr-web-app", - ClientType: ClientTypePublic, - RedirectURIs: []string{ - "http://localhost:3000/callback", - "http://localhost:3001/callback", - }, - AllowedScopes: []string{ - "openid", - "profile", - "vault:read", - "vault:write", - "service:manage", - }, - AllowedGrants: []string{"authorization_code", "refresh_token"}, - TokenLifetime: time.Hour, - RequirePKCE: true, - TrustedClient: true, - RequiresConsent: false, - Metadata: map[string]string{ - "name": "Sonr Web Application", - "description": "Official Sonr web application", - "logo_uri": "https://sonr.io/logo.png", - "client_uri": "https://app.sonr.io", - }, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - - // Development confidential client (e.g., backend service) - _ = r.RegisterClient(&OAuth2Client{ - ClientID: "sonr-backend-service", - ClientSecret: "development-secret-change-in-production", - ClientType: ClientTypeConfidential, - RedirectURIs: []string{"http://localhost:8081/callback"}, - AllowedScopes: []string{"openid", "profile", "vault:admin", "service:manage"}, - AllowedGrants: []string{"authorization_code", "refresh_token", "client_credentials"}, - TokenLifetime: time.Hour * 2, - RequirePKCE: false, - TrustedClient: true, - RequiresConsent: false, - Metadata: map[string]string{ - "name": "Sonr Backend Service", - "description": "Backend service for Sonr ecosystem", - }, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - - // Example third-party client - _ = r.RegisterClient(&OAuth2Client{ - ClientID: "example-third-party", - ClientSecret: "third-party-secret", - ClientType: ClientTypeConfidential, - RedirectURIs: []string{"https://example.com/oauth/callback"}, - AllowedScopes: []string{"openid", "profile", "vault:read"}, - AllowedGrants: []string{"authorization_code", "refresh_token"}, - TokenLifetime: time.Hour, - RequirePKCE: true, - TrustedClient: false, - RequiresConsent: true, - Metadata: map[string]string{ - "name": "Example Third Party App", - "description": "Example integration partner", - "logo_uri": "https://example.com/logo.png", - "client_uri": "https://example.com", - "policy_uri": "https://example.com/privacy", - "tos_uri": "https://example.com/terms", - }, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) -} - -// RegisterClient registers a new OAuth2 client -func (r *ClientRegistry) RegisterClient(client *OAuth2Client) error { - r.mu.Lock() - defer r.mu.Unlock() - - // Validate client - if err := r.validateClient(client); err != nil { - return err - } - - // Generate client ID if not provided - if client.ClientID == "" { - client.ClientID = generateOAuth2ClientID() - } - - // Generate client secret for confidential clients - if client.ClientType == ClientTypeConfidential && client.ClientSecret == "" { - client.ClientSecret = generateClientSecret() - } - - // Set timestamps - if client.CreatedAt.IsZero() { - client.CreatedAt = time.Now() - } - client.UpdatedAt = time.Now() - - // Store client - r.clients[client.ClientID] = client - - return nil -} - -// GetClient retrieves a client by ID -func (r *ClientRegistry) GetClient(clientID string) (*OAuth2Client, error) { - r.mu.RLock() - defer r.mu.RUnlock() - - client, exists := r.clients[clientID] - if !exists { - return nil, fmt.Errorf("client not found: %s", clientID) - } - - return client, nil -} - -// UpdateClient updates an existing client -func (r *ClientRegistry) UpdateClient(clientID string, updates *OAuth2Client) error { - r.mu.Lock() - defer r.mu.Unlock() - - client, exists := r.clients[clientID] - if !exists { - return fmt.Errorf("client not found: %s", clientID) - } - - // Update allowed fields - if len(updates.RedirectURIs) > 0 { - client.RedirectURIs = updates.RedirectURIs - } - if len(updates.AllowedScopes) > 0 { - client.AllowedScopes = updates.AllowedScopes - } - if len(updates.AllowedGrants) > 0 { - client.AllowedGrants = updates.AllowedGrants - } - if updates.TokenLifetime > 0 { - client.TokenLifetime = updates.TokenLifetime - } - if updates.Metadata != nil { - client.Metadata = updates.Metadata - } - - client.RequirePKCE = updates.RequirePKCE - client.RequiresConsent = updates.RequiresConsent - client.UpdatedAt = time.Now() - - return nil -} - -// DeleteClient removes a client from the registry -func (r *ClientRegistry) DeleteClient(clientID string) error { - r.mu.Lock() - defer r.mu.Unlock() - - if _, exists := r.clients[clientID]; !exists { - return fmt.Errorf("client not found: %s", clientID) - } - - delete(r.clients, clientID) - return nil -} - -// ListClients returns all registered clients -func (r *ClientRegistry) ListClients() []*OAuth2Client { - r.mu.RLock() - defer r.mu.RUnlock() - - clients := make([]*OAuth2Client, 0, len(r.clients)) - for _, client := range r.clients { - clients = append(clients, client) - } - - return clients -} - -// ValidateRedirectURI checks if a redirect URI is valid for the client -func (c *OAuth2Client) ValidateRedirectURI(redirectURI string) bool { - if redirectURI == "" { - return false - } - - // Parse the redirect URI - parsedURI, err := url.Parse(redirectURI) - if err != nil { - return false - } - - // Check against registered redirect URIs - for _, registeredURI := range c.RedirectURIs { - registeredParsed, err := url.Parse(registeredURI) - if err != nil { - continue - } - - // For public clients, allow localhost with any port - if c.ClientType == ClientTypePublic && registeredParsed.Hostname() == "localhost" && - parsedURI.Hostname() == "localhost" { - if registeredParsed.Path == parsedURI.Path { - return true - } - } - - // Exact match for other cases - if registeredURI == redirectURI { - return true - } - - // Allow subdomain matching for trusted clients - if c.TrustedClient && matchesWithSubdomain(registeredParsed, parsedURI) { - return true - } - } - - return false -} - -// ValidateScopes checks if the requested scopes are allowed for the client -func (c *OAuth2Client) ValidateScopes(requestedScopes []string) bool { - if len(requestedScopes) == 0 { - return true // No scopes requested is valid - } - - for _, scope := range requestedScopes { - if !c.hasScope(scope) { - return false - } - } - - return true -} - -// hasScope checks if a client has a specific scope -func (c *OAuth2Client) hasScope(scope string) bool { - for _, allowedScope := range c.AllowedScopes { - if allowedScope == scope { - return true - } - // Check for hierarchical scopes (e.g., vault:admin includes vault:read) - if isHierarchicalScope(allowedScope, scope) { - return true - } - } - return false -} - -// HasGrantType checks if a client supports a specific grant type -func (c *OAuth2Client) HasGrantType(grantType string) bool { - for _, allowed := range c.AllowedGrants { - if allowed == grantType { - return true - } - } - return false -} - -// validateClient validates client configuration -func (r *ClientRegistry) validateClient(client *OAuth2Client) error { - // Validate client type - if client.ClientType != ClientTypePublic && client.ClientType != ClientTypeConfidential { - return fmt.Errorf("invalid client type: %s", client.ClientType) - } - - // Validate redirect URIs - if len(client.RedirectURIs) == 0 { - return fmt.Errorf("at least one redirect URI is required") - } - - for _, uri := range client.RedirectURIs { - if _, err := url.Parse(uri); err != nil { - return fmt.Errorf("invalid redirect URI: %s", uri) - } - } - - // Validate grant types - if len(client.AllowedGrants) == 0 { - client.AllowedGrants = []string{"authorization_code"} - } - - validGrants := map[string]bool{ - "authorization_code": true, - "implicit": true, - "refresh_token": true, - "client_credentials": true, - "password": true, - "urn:ietf:params:oauth:grant-type:device_code": true, - } - - for _, grant := range client.AllowedGrants { - if !validGrants[grant] { - return fmt.Errorf("invalid grant type: %s", grant) - } - } - - // Client credentials grant requires confidential client - if contains(client.AllowedGrants, "client_credentials") && - client.ClientType != ClientTypeConfidential { - return fmt.Errorf("client_credentials grant requires confidential client") - } - - // Public clients should use PKCE - if client.ClientType == ClientTypePublic && !client.RequirePKCE { - // Log warning but don't fail - fmt.Printf("Warning: Public client %s should use PKCE\n", client.ClientID) - } - - return nil -} - -// Helper functions - -func generateOAuth2ClientID() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return fmt.Sprintf("client_%s", base64.RawURLEncoding.EncodeToString(bytes)) -} - -func generateClientSecret() string { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -func matchesWithSubdomain(registered, requested *url.URL) bool { - if registered.Scheme != requested.Scheme { - return false - } - - if registered.Path != requested.Path { - return false - } - - // Check if requested hostname is a subdomain of registered - registeredHost := registered.Hostname() - requestedHost := requested.Hostname() - - if registeredHost == requestedHost { - return true - } - - // Check subdomain match (e.g., *.example.com matches sub.example.com) - if strings.HasPrefix(registeredHost, "*.") { - domain := strings.TrimPrefix(registeredHost, "*.") - return strings.HasSuffix(requestedHost, domain) - } - - return false -} - -func isHierarchicalScope(allowed, requested string) bool { - // Define scope hierarchy - hierarchy := map[string][]string{ - "vault:admin": {"vault:write", "vault:read", "vault:sign"}, - "vault:write": {"vault:read"}, - "service:manage": {"service:read", "service:write"}, - "did:write": {"did:read"}, - } - - childScopes, exists := hierarchy[allowed] - if !exists { - return false - } - - for _, child := range childScopes { - if child == requested { - return true - } - // Recursive check for nested hierarchies - if isHierarchicalScope(child, requested) { - return true - } - } - - return false -} diff --git a/bridge/handlers/oauth2_delegation.go b/bridge/handlers/oauth2_delegation.go deleted file mode 100644 index 4ac4d01c4..000000000 --- a/bridge/handlers/oauth2_delegation.go +++ /dev/null @@ -1,323 +0,0 @@ -package handlers - -import ( - "encoding/json" - "fmt" - "time" - - "github.com/sonr-io/sonr/crypto/ucan" -) - -// UCANDelegator handles UCAN token generation for OAuth flows -type UCANDelegator struct { - scopeMapper *ScopeMapper - signer UCANSigner -} - -// UCANSigner interface for signing UCAN tokens -type UCANSigner interface { - Sign(token *ucan.Token) (string, error) - GetIssuerDID() string -} - -// NewUCANDelegator creates a new UCAN delegator -func NewUCANDelegator(signer UCANSigner) *UCANDelegator { - if signer == nil { - // Use blockchain signer by default - signer, _ = NewBlockchainUCANSigner(nil, "did:sonr:oauth-provider") - } - return &UCANDelegator{ - scopeMapper: NewScopeMapper(), - signer: signer, - } -} - -// CreateDelegation creates a UCAN token for user-to-client delegation -func (d *UCANDelegator) CreateDelegation( - userDID string, - clientID string, - scopes []string, - expiresAt time.Time, -) (*ucan.Token, error) { - // Build resource context for the user - resourceContext := d.buildResourceContext(userDID) - - // Map OAuth scopes to UCAN attenuations - attenuations := d.scopeMapper.MapToUCAN(scopes, userDID, clientID, resourceContext) - if len(attenuations) == 0 { - return nil, fmt.Errorf("no valid attenuations for scopes: %v", scopes) - } - - // Create UCAN token - token := &ucan.Token{ - Issuer: userDID, - Audience: clientID, - ExpiresAt: expiresAt.Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Facts: []ucan.Fact{ - { - Data: d.createOAuthFact(scopes, "user_delegation"), - }, - }, - } - - // Sign the token - signedToken, err := d.signToken(token) - if err != nil { - return nil, fmt.Errorf("failed to sign UCAN token: %w", err) - } - - token.Raw = signedToken - return token, nil -} - -// CreateServiceDelegation creates a UCAN token for service-to-service delegation -func (d *UCANDelegator) CreateServiceDelegation( - clientID string, - scopes []string, - expiresAt time.Time, -) (*ucan.Token, error) { - // Service delegations use the OAuth provider as issuer - issuerDID := d.signer.GetIssuerDID() - - // Build resource context for service - resourceContext := map[string]string{ - "service_id": clientID, - "type": "service", - } - - // Map OAuth scopes to UCAN attenuations - attenuations := d.scopeMapper.MapToUCAN(scopes, issuerDID, clientID, resourceContext) - if len(attenuations) == 0 { - return nil, fmt.Errorf("no valid attenuations for scopes: %v", scopes) - } - - // Create UCAN token - token := &ucan.Token{ - Issuer: issuerDID, - Audience: clientID, - ExpiresAt: expiresAt.Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Facts: []ucan.Fact{ - { - Data: d.createOAuthFact(scopes, "service_delegation"), - }, - }, - } - - // Sign the token - signedToken, err := d.signToken(token) - if err != nil { - return nil, fmt.Errorf("failed to sign UCAN token: %w", err) - } - - token.Raw = signedToken - return token, nil -} - -// CreateDelegationChain creates a chain of UCAN tokens for complex delegations -func (d *UCANDelegator) CreateDelegationChain( - userDID string, - intermediaries []string, - finalAudience string, - scopes []string, - expiresAt time.Time, -) ([]*ucan.Token, error) { - chain := make([]*ucan.Token, 0, len(intermediaries)+1) - - currentIssuer := userDID - proofs := []ucan.Proof{} - - // Create delegation for each intermediary - for _, intermediary := range intermediaries { - token, err := d.createIntermediateDelegation( - currentIssuer, - intermediary, - scopes, - expiresAt, - proofs, - ) - if err != nil { - return nil, fmt.Errorf("failed to create intermediate delegation: %w", err) - } - - chain = append(chain, token) - proofs = append(proofs, ucan.Proof(token.Raw)) - currentIssuer = intermediary - } - - // Create final delegation - finalToken, err := d.createFinalDelegation( - currentIssuer, - finalAudience, - scopes, - expiresAt, - proofs, - ) - if err != nil { - return nil, fmt.Errorf("failed to create final delegation: %w", err) - } - - chain = append(chain, finalToken) - return chain, nil -} - -// RevokeDelegation revokes a UCAN delegation -func (d *UCANDelegator) RevokeDelegation(tokenID string) error { - // TODO: Implement delegation revocation - // This would typically involve: - // 1. Adding the token to a revocation list - // 2. Publishing revocation to a public ledger or database - // 3. Notifying relevant parties - return fmt.Errorf("delegation revocation not yet implemented") -} - -// ValidateDelegation validates a UCAN token delegation -func (d *UCANDelegator) ValidateDelegation(token *ucan.Token, requiredScopes []string) error { - // Check expiration - if time.Now().Unix() > token.ExpiresAt { - return fmt.Errorf("token expired") - } - - // Check not before - if token.NotBefore > 0 && time.Now().Unix() < token.NotBefore { - return fmt.Errorf("token not yet valid") - } - - // Verify the token has required capabilities - for _, scope := range requiredScopes { - if !d.tokenGrantsScope(token, scope) { - return fmt.Errorf("token does not grant required scope: %s", scope) - } - } - - // TODO: Verify signature - // TODO: Verify delegation chain if proofs exist - - return nil -} - -// Private helper methods - -func (d *UCANDelegator) buildResourceContext(userDID string) map[string]string { - // TODO: Fetch actual resource information for the user - return map[string]string{ - "vault_address": fmt.Sprintf("vault:%s", userDID), - "enclave_cid": fmt.Sprintf("cid:%s", userDID), - "dwn_id": fmt.Sprintf("dwn:%s", userDID), - "service_id": fmt.Sprintf("service:%s", userDID), - } -} - -func (d *UCANDelegator) createOAuthFact(scopes []string, delegationType string) json.RawMessage { - fact := map[string]any{ - "oauth_scopes": scopes, - "delegation_type": delegationType, - "issued_at": time.Now().Unix(), - "oauth_version": "2.0", - } - - data, _ := json.Marshal(fact) - return json.RawMessage(data) -} - -func (d *UCANDelegator) signToken(token *ucan.Token) (string, error) { - if d.signer == nil { - return "", fmt.Errorf("no signer configured") - } - - return d.signer.Sign(token) -} - -func (d *UCANDelegator) createIntermediateDelegation( - issuer, audience string, - scopes []string, - expiresAt time.Time, - proofs []ucan.Proof, -) (*ucan.Token, error) { - return d.createDelegationWithType( - issuer, - audience, - scopes, - expiresAt, - proofs, - "intermediate_delegation", - ) -} - -func (d *UCANDelegator) createFinalDelegation( - issuer, audience string, - scopes []string, - expiresAt time.Time, - proofs []ucan.Proof, -) (*ucan.Token, error) { - return d.createDelegationWithType( - issuer, - audience, - scopes, - expiresAt, - proofs, - "final_delegation", - ) -} - -// createDelegationWithType creates a delegation token with a specific type -func (d *UCANDelegator) createDelegationWithType( - issuer, audience string, - scopes []string, - expiresAt time.Time, - proofs []ucan.Proof, - delegationType string, -) (*ucan.Token, error) { - resourceContext := d.buildResourceContext(issuer) - attenuations := d.scopeMapper.MapToUCAN(scopes, issuer, audience, resourceContext) - - token := &ucan.Token{ - Issuer: issuer, - Audience: audience, - ExpiresAt: expiresAt.Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Proofs: proofs, - Facts: []ucan.Fact{ - { - Data: d.createOAuthFact(scopes, delegationType), - }, - }, - } - - signedToken, err := d.signToken(token) - if err != nil { - return nil, err - } - - token.Raw = signedToken - return token, nil -} - -func (d *UCANDelegator) tokenGrantsScope(token *ucan.Token, scope string) bool { - // Get the scope definition - scopeDef, exists := d.scopeMapper.GetScope(scope) - if !exists { - return false - } - - // Check if any attenuation grants the required capabilities - for _, attenuation := range token.Attenuations { - if attenuation.Capability.Grants(scopeDef.UCANActions) { - // Also check resource type matches - if d.resourceMatches(attenuation.Resource, scopeDef.ResourceType) { - return true - } - } - } - - return false -} - -func (d *UCANDelegator) resourceMatches(resource ucan.Resource, resourceType string) bool { - // Simple scheme matching for now - return resource.GetScheme() == resourceType || resource.GetScheme() == "*" -} diff --git a/bridge/handlers/oauth2_provider.go b/bridge/handlers/oauth2_provider.go deleted file mode 100644 index 3925e3a69..000000000 --- a/bridge/handlers/oauth2_provider.go +++ /dev/null @@ -1,923 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "crypto/subtle" - "encoding/base64" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/crypto/ucan" -) - -// OAuth2Provider extends OIDCProvider with full OAuth2 capabilities -type OAuth2Provider struct { - *OIDCProvider - clientRegistry *ClientRegistry - scopeMapper *ScopeMapper - ucanDelegator *UCANDelegator - authCodeStore *AuthCodeStore - accessTokenStore *AccessTokenStore - refreshTokenStore *RefreshTokenStore - consentStore *ConsentStore - config *OAuth2Config -} - -// AuthCodeStore manages authorization codes -type AuthCodeStore struct { - mu sync.RWMutex - codes map[string]*OAuth2AuthorizationCode -} - -// AccessTokenStore manages access tokens -type AccessTokenStore struct { - mu sync.RWMutex - tokens map[string]*OAuth2AccessToken -} - -// RefreshTokenStore manages refresh tokens -type RefreshTokenStore struct { - mu sync.RWMutex - tokens map[string]*OAuth2RefreshToken -} - -// ConsentStore manages user consent records -type ConsentStore struct { - mu sync.RWMutex - consents map[string]*UserConsent // key: userDID:clientID -} - -// UserConsent represents stored user consent -type UserConsent struct { - UserDID string `json:"user_did"` - ClientID string `json:"client_id"` - ApprovedScopes []string `json:"approved_scopes"` - CreatedAt time.Time `json:"created_at"` - ExpiresAt time.Time `json:"expires_at"` -} - -var oauth2Provider *OAuth2Provider - -// InitializeOAuth2Provider initializes the OAuth2 provider -func InitializeOAuth2Provider() { - oauth2Provider = &OAuth2Provider{ - OIDCProvider: oidcProvider, - clientRegistry: NewClientRegistry(), - scopeMapper: NewScopeMapper(), - ucanDelegator: NewUCANDelegator(nil), - authCodeStore: &AuthCodeStore{codes: make(map[string]*OAuth2AuthorizationCode)}, - accessTokenStore: &AccessTokenStore{tokens: make(map[string]*OAuth2AccessToken)}, - refreshTokenStore: &RefreshTokenStore{tokens: make(map[string]*OAuth2RefreshToken)}, - consentStore: &ConsentStore{consents: make(map[string]*UserConsent)}, - config: getDefaultOAuth2Config(), - } - - // Start cleanup goroutine for expired tokens - go oauth2Provider.cleanupExpiredTokens() -} - -// GetOAuth2Discovery returns OAuth2 discovery configuration -func GetOAuth2Discovery(c echo.Context) error { - if oauth2Provider == nil { - InitializeOAuth2Provider() - } - return c.JSON(http.StatusOK, oauth2Provider.config) -} - -// HandleOAuth2Authorize handles OAuth2 authorization requests -func HandleOAuth2Authorize(c echo.Context) error { - if oauth2Provider == nil { - InitializeOAuth2Provider() - } - - req := &OAuth2AuthorizationRequest{ - ResponseType: c.QueryParam("response_type"), - ClientID: c.QueryParam("client_id"), - RedirectURI: c.QueryParam("redirect_uri"), - Scope: c.QueryParam("scope"), - State: c.QueryParam("state"), - CodeChallenge: c.QueryParam("code_challenge"), - CodeChallengeMethod: c.QueryParam("code_challenge_method"), - Nonce: c.QueryParam("nonce"), - Prompt: c.QueryParam("prompt"), - LoginHint: c.QueryParam("login_hint"), - } - - // Validate client - client, err := oauth2Provider.clientRegistry.GetClient(req.ClientID) - if err != nil { - return oauth2Error(c, "invalid_client", "Unknown client", req.State) - } - - // Validate redirect URI - if !client.ValidateRedirectURI(req.RedirectURI) { - return oauth2Error(c, "invalid_request", "Invalid redirect URI", req.State) - } - - // Validate response type - if !isValidResponseType(req.ResponseType) { - return redirectError( - c, - req.RedirectURI, - "unsupported_response_type", - "Response type not supported", - req.State, - ) - } - - // Validate scopes - requestedScopes := parseScopes(req.Scope) - if !client.ValidateScopes(requestedScopes) { - return redirectError( - c, - req.RedirectURI, - "invalid_scope", - "Requested scope not allowed", - req.State, - ) - } - - // Validate PKCE for public clients - if client.ClientType == "public" && client.RequirePKCE { - if req.CodeChallenge == "" { - return redirectError( - c, - req.RedirectURI, - "invalid_request", - "PKCE required for public clients", - req.State, - ) - } - if req.CodeChallengeMethod != PKCEMethodS256 { - return redirectError( - c, - req.RedirectURI, - "invalid_request", - "Only S256 PKCE method supported", - req.State, - ) - } - } - - // Check authentication - userDID := c.Get("user_did") - if userDID == nil { - // Store authorization request and redirect to authentication - sessionID := generateSessionID() - // TODO: Store auth request in session store - authURL := fmt.Sprintf( - "/auth/login?session_id=%s&return_to=%s", - sessionID, - c.Request().URL.String(), - ) - return c.Redirect(http.StatusFound, authURL) - } - - // Check consent - if client.RequiresConsent && - !oauth2Provider.hasValidConsent(userDID.(string), req.ClientID, requestedScopes) { - // Render consent page - return renderOAuth2ConsentPage(c, req, client) - } - - // Generate authorization code - code := generateSecureToken(32) - authCode := &OAuth2AuthorizationCode{ - Code: code, - ClientID: req.ClientID, - UserDID: userDID.(string), - RedirectURI: req.RedirectURI, - Scopes: requestedScopes, - State: req.State, - Nonce: req.Nonce, - CodeChallenge: req.CodeChallenge, - CodeChallengeMethod: req.CodeChallengeMethod, - ExpiresAt: time.Now().Add(10 * time.Minute), - UCANContext: oauth2Provider.buildUCANContext(userDID.(string)), - } - - // Store authorization code - oauth2Provider.authCodeStore.Store(authCode) - - // Build redirect URL - redirectURL := buildAuthorizationRedirect(req.RedirectURI, code, req.State) - return c.Redirect(http.StatusFound, redirectURL) -} - -// HandleOAuth2Token handles OAuth2 token requests -func HandleOAuth2Token(c echo.Context) error { - if oauth2Provider == nil { - InitializeOAuth2Provider() - } - - var req OAuth2TokenRequest - if err := c.Bind(&req); err != nil { - return oauth2TokenError(c, "invalid_request", "Invalid token request") - } - - // Authenticate client - client, err := oauth2Provider.authenticateClient(c, &req) - if err != nil { - return oauth2TokenError(c, "invalid_client", "Client authentication failed") - } - - // Handle grant type - switch req.GrantType { - case "authorization_code": - return oauth2Provider.handleAuthorizationCodeGrant(c, client, &req) - case "refresh_token": - return oauth2Provider.handleRefreshTokenGrant(c, client, &req) - case "client_credentials": - return oauth2Provider.handleClientCredentialsGrant(c, client, &req) - default: - return oauth2TokenError(c, "unsupported_grant_type", "Grant type not supported") - } -} - -// HandleOAuth2Introspection handles token introspection requests -func HandleOAuth2Introspection(c echo.Context) error { - if oauth2Provider == nil { - InitializeOAuth2Provider() - } - - var req OAuth2IntrospectionRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, &OAuth2IntrospectionResponse{Active: false}) - } - - // Authenticate client - client, err := oauth2Provider.authenticateClient(c, &OAuth2TokenRequest{ - ClientID: req.ClientID, - ClientSecret: req.ClientSecret, - }) - if err != nil { - return c.JSON(http.StatusUnauthorized, &OAuth2IntrospectionResponse{Active: false}) - } - - // Introspect token - response := oauth2Provider.introspectToken(req.Token, req.TokenTypeHint, client) - return c.JSON(http.StatusOK, response) -} - -// HandleOAuth2Revocation handles token revocation requests -func HandleOAuth2Revocation(c echo.Context) error { - if oauth2Provider == nil { - InitializeOAuth2Provider() - } - - var req OAuth2RevocationRequest - if err := c.Bind(&req); err != nil { - return c.NoContent(http.StatusBadRequest) - } - - // Authenticate client - client, err := oauth2Provider.authenticateClient(c, &OAuth2TokenRequest{ - ClientID: req.ClientID, - ClientSecret: req.ClientSecret, - }) - if err != nil { - return c.NoContent(http.StatusUnauthorized) - } - - // Revoke token - oauth2Provider.revokeToken(req.Token, req.TokenTypeHint, client) - return c.NoContent(http.StatusOK) -} - -// Private methods - -func (p *OAuth2Provider) handleAuthorizationCodeGrant( - c echo.Context, - client *OAuth2Client, - req *OAuth2TokenRequest, -) error { - // Retrieve authorization code - authCode := p.authCodeStore.Exchange(req.Code) - if authCode == nil { - return oauth2TokenError(c, "invalid_grant", "Invalid authorization code") - } - - // Validate code hasn't expired - if time.Now().After(authCode.ExpiresAt) { - return oauth2TokenError(c, "invalid_grant", "Authorization code expired") - } - - // Validate client - if authCode.ClientID != client.ClientID { - return oauth2TokenError(c, "invalid_grant", "Code was issued to different client") - } - - // Validate redirect URI - if authCode.RedirectURI != req.RedirectURI { - return oauth2TokenError(c, "invalid_grant", "Redirect URI mismatch") - } - - // Validate PKCE if present - if authCode.CodeChallenge != "" { - if !p.validatePKCE(req.CodeVerifier, authCode.CodeChallenge, authCode.CodeChallengeMethod) { - return oauth2TokenError(c, "invalid_grant", "Invalid PKCE verifier") - } - } - - // Create UCAN delegation - ucanToken, err := p.ucanDelegator.CreateDelegation( - authCode.UserDID, - client.ClientID, - authCode.Scopes, - time.Now().Add(time.Hour), - ) - if err != nil { - return oauth2TokenError(c, "server_error", "Failed to create delegation") - } - - // Generate tokens - accessToken := p.generateAccessToken(authCode, ucanToken) - refreshToken := p.generateRefreshToken(authCode) - - // Store tokens - p.accessTokenStore.Store(accessToken) - p.refreshTokenStore.Store(refreshToken) - - // Generate ID token if openid scope present - var idToken string - if contains(authCode.Scopes, "openid") { - idToken, _ = generateIDToken(authCode.UserDID, client.ClientID, authCode.Nonce) - } - - // Return token response - response := &OAuth2TokenResponse{ - AccessToken: accessToken.Token, - TokenType: "Bearer", - ExpiresIn: 3600, - RefreshToken: refreshToken.Token, - Scope: strings.Join(authCode.Scopes, " "), - IDToken: idToken, - UCANToken: ucanToken.Raw, - } - - return c.JSON(http.StatusOK, response) -} - -func (p *OAuth2Provider) handleRefreshTokenGrant( - c echo.Context, - client *OAuth2Client, - req *OAuth2TokenRequest, -) error { - // Retrieve refresh token - oldRefreshToken := p.refreshTokenStore.Get(req.RefreshToken) - if oldRefreshToken == nil { - return oauth2TokenError(c, "invalid_grant", "Invalid refresh token") - } - - // Validate client - if oldRefreshToken.ClientID != client.ClientID { - return oauth2TokenError(c, "invalid_grant", "Token was issued to different client") - } - - // Validate expiration - if time.Now().After(oldRefreshToken.ExpiresAt) { - return oauth2TokenError(c, "invalid_grant", "Refresh token expired") - } - - // Rotate refresh token - p.refreshTokenStore.Revoke(req.RefreshToken) - - // Create new UCAN delegation - ucanToken, err := p.ucanDelegator.CreateDelegation( - oldRefreshToken.UserDID, - client.ClientID, - oldRefreshToken.Scopes, - time.Now().Add(time.Hour), - ) - if err != nil { - return oauth2TokenError(c, "server_error", "Failed to create delegation") - } - - // Generate new tokens - newAccessToken := &OAuth2AccessToken{ - Token: generateSecureToken(32), - UserDID: oldRefreshToken.UserDID, - ClientID: client.ClientID, - Scopes: oldRefreshToken.Scopes, - ExpiresAt: time.Now().Add(time.Hour), - IssuedAt: time.Now(), - UCANToken: ucanToken, - } - - newRefreshToken := &OAuth2RefreshToken{ - Token: generateSecureToken(32), - AccessToken: newAccessToken.Token, - ClientID: client.ClientID, - UserDID: oldRefreshToken.UserDID, - Scopes: oldRefreshToken.Scopes, - ExpiresAt: time.Now().Add(30 * 24 * time.Hour), - IssuedAt: time.Now(), - RotationCount: oldRefreshToken.RotationCount + 1, - } - - // Store new tokens - p.accessTokenStore.Store(newAccessToken) - p.refreshTokenStore.Store(newRefreshToken) - - // Return response - response := &OAuth2TokenResponse{ - AccessToken: newAccessToken.Token, - TokenType: "Bearer", - ExpiresIn: 3600, - RefreshToken: newRefreshToken.Token, - Scope: strings.Join(newAccessToken.Scopes, " "), - UCANToken: ucanToken.Raw, - } - - return c.JSON(http.StatusOK, response) -} - -func (p *OAuth2Provider) handleClientCredentialsGrant( - c echo.Context, - client *OAuth2Client, - req *OAuth2TokenRequest, -) error { - // Client credentials grant is only for confidential clients - if client.ClientType != "confidential" { - return oauth2TokenError( - c, - "unauthorized_client", - "Client type not authorized for this grant", - ) - } - - // Parse requested scopes - scopes := parseScopes(req.Scope) - if !client.ValidateScopes(scopes) { - return oauth2TokenError(c, "invalid_scope", "Requested scope not allowed") - } - - // Create service-to-service UCAN token - ucanToken, err := p.ucanDelegator.CreateServiceDelegation( - client.ClientID, - scopes, - time.Now().Add(time.Hour), - ) - if err != nil { - return oauth2TokenError(c, "server_error", "Failed to create delegation") - } - - // Generate access token - accessToken := &OAuth2AccessToken{ - Token: generateSecureToken(32), - UserDID: "", // No user for client credentials - ClientID: client.ClientID, - Scopes: scopes, - ExpiresAt: time.Now().Add(time.Hour), - IssuedAt: time.Now(), - UCANToken: ucanToken, - TokenType: "client_credentials", - } - - // Store token - p.accessTokenStore.Store(accessToken) - - // Return response - response := &OAuth2TokenResponse{ - AccessToken: accessToken.Token, - TokenType: "Bearer", - ExpiresIn: 3600, - Scope: strings.Join(scopes, " "), - UCANToken: ucanToken.Raw, - } - - return c.JSON(http.StatusOK, response) -} - -func (p *OAuth2Provider) authenticateClient( - c echo.Context, - req *OAuth2TokenRequest, -) (*OAuth2Client, error) { - // Try Basic Auth first - if username, password, ok := c.Request().BasicAuth(); ok { - client, err := p.clientRegistry.GetClient(username) - if err != nil { - return nil, err - } - if client.ClientType == "confidential" && - subtle.ConstantTimeCompare([]byte(client.ClientSecret), []byte(password)) == 1 { - return client, nil - } - return nil, fmt.Errorf("invalid client credentials") - } - - // Try client_secret_post - if req.ClientID != "" && req.ClientSecret != "" { - client, err := p.clientRegistry.GetClient(req.ClientID) - if err != nil { - return nil, err - } - if client.ClientType == "confidential" && - subtle.ConstantTimeCompare([]byte(client.ClientSecret), []byte(req.ClientSecret)) == 1 { - return client, nil - } - return nil, fmt.Errorf("invalid client credentials") - } - - // Try client_assertion (JWT) - if req.ClientAssertion != "" && - req.ClientAssertionType == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" { - // TODO: Implement JWT client assertion validation - return nil, fmt.Errorf("JWT client assertion not yet implemented") - } - - // Public client (no authentication) - if req.ClientID != "" { - client, err := p.clientRegistry.GetClient(req.ClientID) - if err != nil { - return nil, err - } - if client.ClientType == "public" { - return client, nil - } - } - - return nil, fmt.Errorf("client authentication required") -} - -func (p *OAuth2Provider) validatePKCE(verifier, challenge, method string) bool { - if method == "" { - method = PKCEMethodPlain - } - computed := computePKCEChallenge(verifier, method) - return subtle.ConstantTimeCompare([]byte(computed), []byte(challenge)) == 1 -} - -func (p *OAuth2Provider) hasValidConsent(userDID, clientID string, scopes []string) bool { - p.consentStore.mu.RLock() - defer p.consentStore.mu.RUnlock() - - key := fmt.Sprintf("%s:%s", userDID, clientID) - consent, exists := p.consentStore.consents[key] - if !exists { - return false - } - - // Check expiration - if time.Now().After(consent.ExpiresAt) { - return false - } - - // Check all requested scopes are approved - for _, scope := range scopes { - if !contains(consent.ApprovedScopes, scope) { - return false - } - } - - return true -} - -func (p *OAuth2Provider) buildUCANContext(userDID string) *UCANAuthContext { - // TODO: Fetch actual vault and DID document data - return &UCANAuthContext{ - VaultAddress: fmt.Sprintf("vault_%s", userDID), - EnclaveDataCID: fmt.Sprintf("cid_%s", userDID), - Capabilities: []string{"read", "write", "sign"}, - } -} - -func (p *OAuth2Provider) generateAccessToken( - authCode *OAuth2AuthorizationCode, - ucanToken *ucan.Token, -) *OAuth2AccessToken { - return &OAuth2AccessToken{ - Token: generateSecureToken(32), - UserDID: authCode.UserDID, - ClientID: authCode.ClientID, - Scopes: authCode.Scopes, - ExpiresAt: time.Now().Add(time.Hour), - IssuedAt: time.Now(), - UCANToken: ucanToken, - SessionID: generateSessionID(), - TokenType: "authorization_code", - } -} - -func (p *OAuth2Provider) generateRefreshToken( - authCode *OAuth2AuthorizationCode, -) *OAuth2RefreshToken { - return &OAuth2RefreshToken{ - Token: generateSecureToken(32), - ClientID: authCode.ClientID, - UserDID: authCode.UserDID, - Scopes: authCode.Scopes, - ExpiresAt: time.Now().Add(30 * 24 * time.Hour), - IssuedAt: time.Now(), - RotationCount: 0, - } -} - -func (p *OAuth2Provider) introspectToken( - token, tokenTypeHint string, - client *OAuth2Client, -) *OAuth2IntrospectionResponse { - // Try access token first - if accessToken := p.accessTokenStore.Get(token); accessToken != nil { - if accessToken.ClientID != client.ClientID { - return &OAuth2IntrospectionResponse{Active: false} - } - return &OAuth2IntrospectionResponse{ - Active: time.Now().Before(accessToken.ExpiresAt), - Scope: strings.Join(accessToken.Scopes, " "), - ClientID: accessToken.ClientID, - Username: accessToken.UserDID, - TokenType: "Bearer", - ExpiresAt: accessToken.ExpiresAt.Unix(), - IssuedAt: accessToken.IssuedAt.Unix(), - Subject: accessToken.UserDID, - UCANToken: accessToken.UCANToken.Raw, - } - } - - // Try refresh token - if refreshToken := p.refreshTokenStore.Get(token); refreshToken != nil { - if refreshToken.ClientID != client.ClientID { - return &OAuth2IntrospectionResponse{Active: false} - } - return &OAuth2IntrospectionResponse{ - Active: time.Now().Before(refreshToken.ExpiresAt), - Scope: strings.Join(refreshToken.Scopes, " "), - ClientID: refreshToken.ClientID, - Username: refreshToken.UserDID, - TokenType: "refresh_token", - ExpiresAt: refreshToken.ExpiresAt.Unix(), - IssuedAt: refreshToken.IssuedAt.Unix(), - Subject: refreshToken.UserDID, - } - } - - return &OAuth2IntrospectionResponse{Active: false} -} - -func (p *OAuth2Provider) revokeToken(token, tokenTypeHint string, client *OAuth2Client) { - // Try to revoke as access token - if p.accessTokenStore.Revoke(token) { - return - } - - // Try to revoke as refresh token - p.refreshTokenStore.Revoke(token) -} - -func (p *OAuth2Provider) cleanupExpiredTokens() { - ticker := time.NewTicker(5 * time.Minute) - defer ticker.Stop() - - for range ticker.C { - // Cleanup expired authorization codes - p.authCodeStore.CleanupExpired() - - // Cleanup expired access tokens - p.accessTokenStore.CleanupExpired() - - // Cleanup expired refresh tokens - p.refreshTokenStore.CleanupExpired() - } -} - -// Store methods for token stores - -func (s *AuthCodeStore) Store(code *OAuth2AuthorizationCode) { - s.mu.Lock() - defer s.mu.Unlock() - s.codes[code.Code] = code -} - -func (s *AuthCodeStore) Exchange(code string) *OAuth2AuthorizationCode { - s.mu.Lock() - defer s.mu.Unlock() - - authCode, exists := s.codes[code] - if !exists || authCode.Used { - return nil - } - - authCode.Used = true - return authCode -} - -func (s *AuthCodeStore) CleanupExpired() { - s.mu.Lock() - defer s.mu.Unlock() - - now := time.Now() - for code, authCode := range s.codes { - if now.After(authCode.ExpiresAt) { - delete(s.codes, code) - } - } -} - -func (s *AccessTokenStore) Store(token *OAuth2AccessToken) { - s.mu.Lock() - defer s.mu.Unlock() - s.tokens[token.Token] = token -} - -func (s *AccessTokenStore) Get(token string) *OAuth2AccessToken { - s.mu.RLock() - defer s.mu.RUnlock() - return s.tokens[token] -} - -func (s *AccessTokenStore) Revoke(token string) bool { - s.mu.Lock() - defer s.mu.Unlock() - - if _, exists := s.tokens[token]; exists { - delete(s.tokens, token) - return true - } - return false -} - -func (s *AccessTokenStore) CleanupExpired() { - s.mu.Lock() - defer s.mu.Unlock() - - now := time.Now() - for token, accessToken := range s.tokens { - if now.After(accessToken.ExpiresAt) { - delete(s.tokens, token) - } - } -} - -func (s *RefreshTokenStore) Store(token *OAuth2RefreshToken) { - s.mu.Lock() - defer s.mu.Unlock() - s.tokens[token.Token] = token -} - -func (s *RefreshTokenStore) Get(token string) *OAuth2RefreshToken { - s.mu.RLock() - defer s.mu.RUnlock() - return s.tokens[token] -} - -func (s *RefreshTokenStore) Revoke(token string) bool { - s.mu.Lock() - defer s.mu.Unlock() - - if _, exists := s.tokens[token]; exists { - delete(s.tokens, token) - return true - } - return false -} - -func (s *RefreshTokenStore) CleanupExpired() { - s.mu.Lock() - defer s.mu.Unlock() - - now := time.Now() - for token, refreshToken := range s.tokens { - if now.After(refreshToken.ExpiresAt) { - delete(s.tokens, token) - } - } -} - -// Helper functions - -func generateSecureToken(bytes int) string { - b := make([]byte, bytes) - if _, err := rand.Read(b); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(b) -} - -func parseScopes(scope string) []string { - if scope == "" { - return []string{} - } - return strings.Split(scope, " ") -} - -func contains(slice []string, item string) bool { - for _, s := range slice { - if s == item { - return true - } - } - return false -} - -func isValidResponseType(responseType string) bool { - validTypes := []string{ - "code", - "token", - "id_token", - "code id_token", - "code token", - "id_token token", - "code id_token token", - } - return contains(validTypes, responseType) -} - -func oauth2Error(c echo.Context, error, description, state string) error { - return c.JSON(http.StatusBadRequest, &OAuth2ErrorResponse{ - Error: error, - ErrorDescription: description, - State: state, - }) -} - -func oauth2TokenError(c echo.Context, error, description string) error { - return c.JSON(http.StatusBadRequest, &OAuth2ErrorResponse{ - Error: error, - ErrorDescription: description, - }) -} - -func redirectError(c echo.Context, redirectURI, error, description, state string) error { - url := fmt.Sprintf("%s?error=%s&error_description=%s&state=%s", - redirectURI, error, description, state) - return c.Redirect(http.StatusFound, url) -} - -func buildAuthorizationRedirect(redirectURI, code, state string) string { - if strings.Contains(redirectURI, "?") { - return fmt.Sprintf("%s&code=%s&state=%s", redirectURI, code, state) - } - return fmt.Sprintf("%s?code=%s&state=%s", redirectURI, code, state) -} - -func renderOAuth2ConsentPage( - c echo.Context, - req *OAuth2AuthorizationRequest, - client *OAuth2Client, -) error { - // TODO: Render actual consent page - return c.JSON(http.StatusOK, map[string]any{ - "client": client, - "scopes": parseScopes(req.Scope), - "state": req.State, - "client_id": req.ClientID, - }) -} - -func getDefaultOAuth2Config() *OAuth2Config { - baseURL := "https://localhost:8080" - return &OAuth2Config{ - Issuer: baseURL, - AuthorizationEndpoint: baseURL + "/oauth2/authorize", - TokenEndpoint: baseURL + "/oauth2/token", - UserInfoEndpoint: baseURL + "/oauth2/userinfo", - JWKSEndpoint: baseURL + "/oauth2/jwks", - RegistrationEndpoint: baseURL + "/oauth2/register", - IntrospectionEndpoint: baseURL + "/oauth2/introspect", - RevocationEndpoint: baseURL + "/oauth2/revoke", - ScopesSupported: []string{ - "openid", "profile", "email", "offline_access", - "vault:read", "vault:write", "vault:sign", "vault:admin", - "service:manage", "did:read", "did:write", - }, - ResponseTypesSupported: []string{ - "code", "token", "id_token", - "code id_token", "code token", - "id_token token", "code id_token token", - }, - ResponseModesSupported: []string{ - "query", "fragment", "form_post", - }, - GrantTypesSupported: []string{ - "authorization_code", "implicit", "refresh_token", - "client_credentials", "urn:ietf:params:oauth:grant-type:device_code", - }, - SubjectTypesSupported: []string{ - "public", "pairwise", - }, - IDTokenSigningAlgValuesSupported: []string{ - "ES256", "RS256", "HS256", - }, - TokenEndpointAuthMethodsSupported: []string{ - "client_secret_basic", "client_secret_post", - "client_secret_jwt", "private_key_jwt", "none", - }, - ClaimsSupported: []string{ - "sub", "iss", "aud", "exp", "iat", "auth_time", "nonce", - "name", "given_name", "family_name", "middle_name", "nickname", - "preferred_username", "profile", "picture", "website", "email", - "email_verified", "did", "vault_id", "ucan_capabilities", - }, - CodeChallengeMethodsSupported: []string{ - PKCEMethodS256, PKCEMethodPlain, - }, - ServiceDocumentation: baseURL + "/docs/oauth2", - UILocalesSupported: []string{"en-US"}, - UCANSupported: true, - } -} diff --git a/bridge/handlers/oauth2_refresh.go b/bridge/handlers/oauth2_refresh.go deleted file mode 100644 index 11d2fd69e..000000000 --- a/bridge/handlers/oauth2_refresh.go +++ /dev/null @@ -1,563 +0,0 @@ -package handlers - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "github.com/sonr-io/sonr/crypto/ucan" -) - -// RefreshTokenHandler handles OAuth2 refresh token flows with UCAN chains -type RefreshTokenHandler struct { - delegator *UCANDelegator - signer *BlockchainUCANSigner - tokenStore TokenStore - clientStore ClientStore -} - -// RefreshTokenRequest represents an OAuth2 refresh token request -type RefreshTokenRequest struct { - GrantType string `json:"grant_type"` - RefreshToken string `json:"refresh_token"` - Scope string `json:"scope,omitempty"` - ClientID string `json:"client_id,omitempty"` - ClientSecret string `json:"client_secret,omitempty"` -} - -// RefreshTokenResponse represents an OAuth2 refresh token response -type RefreshTokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - RefreshToken string `json:"refresh_token,omitempty"` - Scope string `json:"scope,omitempty"` - UCANToken string `json:"ucan_token,omitempty"` -} - -// UCANRefreshMetadata stores metadata for UCAN refresh chains -type UCANRefreshMetadata struct { - OriginalIssuer string `json:"original_issuer"` - DelegationChain []string `json:"delegation_chain"` - RefreshCount int `json:"refresh_count"` - MaxRefreshCount int `json:"max_refresh_count"` - CreatedAt time.Time `json:"created_at"` - LastRefreshedAt time.Time `json:"last_refreshed_at"` - AttenuationPath []Attenuation `json:"attenuation_path"` -} - -// Attenuation represents scope reduction in the delegation chain -type Attenuation struct { - FromScopes []string `json:"from_scopes"` - ToScopes []string `json:"to_scopes"` - Timestamp time.Time `json:"timestamp"` - Reason string `json:"reason,omitempty"` -} - -// NewRefreshTokenHandler creates a new refresh token handler -func NewRefreshTokenHandler( - delegator *UCANDelegator, - signer *BlockchainUCANSigner, - tokenStore TokenStore, - clientStore ClientStore, -) *RefreshTokenHandler { - return &RefreshTokenHandler{ - delegator: delegator, - signer: signer, - tokenStore: tokenStore, - clientStore: clientStore, - } -} - -// HandleRefreshToken handles OAuth2 refresh token requests -func (h *RefreshTokenHandler) HandleRefreshToken(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - - // Parse request (handle both JSON and form-encoded) - var req RefreshTokenRequest - - contentType := r.Header.Get("Content-Type") - if strings.Contains(contentType, "application/json") { - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - h.sendError(w, "invalid_request", "Failed to parse JSON request body") - return - } - } else { - // Parse form data - if err := r.ParseForm(); err != nil { - h.sendError(w, "invalid_request", "Failed to parse form data") - return - } - - req.GrantType = r.FormValue("grant_type") - req.RefreshToken = r.FormValue("refresh_token") - req.Scope = r.FormValue("scope") - req.ClientID = r.FormValue("client_id") - req.ClientSecret = r.FormValue("client_secret") - } - - // Validate grant type - if req.GrantType != "refresh_token" { - h.sendError(w, "unsupported_grant_type", "Only refresh_token grant type is supported") - return - } - - // Validate refresh token - if req.RefreshToken == "" { - h.sendError(w, "invalid_request", "Missing refresh_token parameter") - return - } - - // Authenticate client - clientID, clientSecret := h.extractClientCredentials(r, &req) - ctx := r.Context() - - if err := h.clientStore.ValidateClientCredentials(ctx, clientID, clientSecret); err != nil { - h.sendError(w, "invalid_client", "Client authentication failed") - return - } - - // Get client information - client, err := h.clientStore.GetClient(ctx, clientID) - if err != nil { - h.sendError(w, "invalid_client", "Client not found") - return - } - - // Process refresh token - response, err := h.processRefreshToken(ctx, &req, client) - if err != nil { - h.sendError(w, "invalid_grant", err.Error()) - return - } - - // Send response - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Pragma", "no-cache") - json.NewEncoder(w).Encode(response) -} - -// processRefreshToken processes the refresh token and returns new tokens -func (h *RefreshTokenHandler) processRefreshToken( - ctx context.Context, - req *RefreshTokenRequest, - client *OAuth2Client, -) (*RefreshTokenResponse, error) { - // Retrieve stored refresh token - storedToken, err := h.tokenStore.GetToken(ctx, req.RefreshToken) - if err != nil { - return nil, fmt.Errorf("invalid refresh token") - } - - // Validate token type - if storedToken.TokenType != "refresh_token" { - return nil, fmt.Errorf("token is not a refresh token") - } - - // Validate client binding - if storedToken.ClientID != client.ClientID { - return nil, fmt.Errorf("refresh token was issued to a different client") - } - - // Check if refresh token has expired - if time.Now().After(storedToken.ExpiresAt) { - return nil, fmt.Errorf("refresh token has expired") - } - - // Get refresh metadata - metadata, err := h.getRefreshMetadata(ctx, req.RefreshToken) - if err != nil { - // Initialize metadata for first refresh - metadata = &UCANRefreshMetadata{ - OriginalIssuer: storedToken.UserDID, - DelegationChain: []string{}, - RefreshCount: 0, - MaxRefreshCount: 10, // Default max refresh count - CreatedAt: time.Now(), - AttenuationPath: []Attenuation{}, - } - } - - // Check refresh count limit - if metadata.RefreshCount >= metadata.MaxRefreshCount { - return nil, fmt.Errorf("refresh token has reached maximum refresh count") - } - - // Parse requested scopes - requestedScopes := storedToken.Scopes - if req.Scope != "" { - requestedScopes = strings.Split(req.Scope, " ") - - // Validate scope reduction (attenuate permissions) - if !h.validateScopeAttenuation(requestedScopes, storedToken.Scopes) { - return nil, fmt.Errorf("requested scopes exceed refresh token scopes") - } - - // Record attenuation - if !h.scopesEqual(requestedScopes, storedToken.Scopes) { - metadata.AttenuationPath = append(metadata.AttenuationPath, Attenuation{ - FromScopes: storedToken.Scopes, - ToScopes: requestedScopes, - Timestamp: time.Now(), - Reason: "Client requested scope reduction", - }) - } - } - - // Create new UCAN token with delegation chain - newUCANToken, err := h.createRefreshedUCANToken( - ctx, - metadata, - storedToken, - client, - requestedScopes, - ) - if err != nil { - return nil, fmt.Errorf("failed to create refreshed UCAN token: %w", err) - } - - // Generate new access token - accessTokenID := h.generateTokenID() - accessToken := &StoredToken{ - TokenID: accessTokenID, - TokenType: "access_token", - AccessToken: accessTokenID, - ExpiresAt: time.Now().Add(time.Hour), - Scopes: requestedScopes, - ClientID: client.ClientID, - UserDID: storedToken.UserDID, - UCANToken: newUCANToken, - } - - if err := h.tokenStore.StoreToken(ctx, accessToken); err != nil { - return nil, fmt.Errorf("failed to store new access token: %w", err) - } - - // Update refresh metadata - metadata.RefreshCount++ - metadata.LastRefreshedAt = time.Now() - metadata.DelegationChain = append(metadata.DelegationChain, newUCANToken) - - // Optionally rotate refresh token - newRefreshTokenID := "" - if h.shouldRotateRefreshToken(metadata) { - newRefreshTokenID = h.generateTokenID() - newRefreshToken := &StoredToken{ - TokenID: newRefreshTokenID, - TokenType: "refresh_token", - RefreshToken: newRefreshTokenID, - ExpiresAt: time.Now().Add(30 * 24 * time.Hour), // 30 days - Scopes: requestedScopes, - ClientID: client.ClientID, - UserDID: storedToken.UserDID, - } - - if err := h.tokenStore.StoreToken(ctx, newRefreshToken); err != nil { - // Non-fatal, continue with existing refresh token - newRefreshTokenID = "" - } else { - // Revoke old refresh token - h.tokenStore.RevokeToken(ctx, req.RefreshToken) - - // Store metadata for new refresh token - h.storeRefreshMetadata(ctx, newRefreshTokenID, metadata) - } - } else { - // Update metadata for existing refresh token - h.storeRefreshMetadata(ctx, req.RefreshToken, metadata) - } - - // Build response - response := &RefreshTokenResponse{ - AccessToken: accessTokenID, - TokenType: "Bearer", - ExpiresIn: 3600, - Scope: strings.Join(requestedScopes, " "), - UCANToken: newUCANToken, - } - - if newRefreshTokenID != "" { - response.RefreshToken = newRefreshTokenID - } - - return response, nil -} - -// createRefreshedUCANToken creates a new UCAN token with proper delegation chain -func (h *RefreshTokenHandler) createRefreshedUCANToken( - ctx context.Context, - metadata *UCANRefreshMetadata, - storedToken *StoredToken, - client *OAuth2Client, - scopes []string, -) (string, error) { - // Build proof chain from previous delegations - proofs := make([]ucan.Proof, 0, len(metadata.DelegationChain)) - for _, tokenStr := range metadata.DelegationChain { - proofs = append(proofs, ucan.Proof(tokenStr)) - } - - // Add original token as proof if exists - if storedToken.UCANToken != "" { - proofs = append([]ucan.Proof{ucan.Proof(storedToken.UCANToken)}, proofs...) - } - - // Determine issuer and audience - issuer := metadata.OriginalIssuer - if issuer == "" { - issuer = storedToken.UserDID - } - - audience := client.ClientID - if did, ok := client.Metadata["client_did"]; ok { - audience = did - } - - // Create resource context with refresh metadata - resourceContext := map[string]string{ - "refresh_count": fmt.Sprintf("%d", metadata.RefreshCount), - "original_issuer": metadata.OriginalIssuer, - "delegation_type": "refresh_token", - "client_id": client.ClientID, - } - - // Map OAuth scopes to UCAN attenuations - attenuations := h.delegator.scopeMapper.MapToUCAN(scopes, issuer, audience, resourceContext) - - // Create UCAN token with delegation chain - ucanToken := &ucan.Token{ - Issuer: issuer, - Audience: audience, - ExpiresAt: time.Now().Add(time.Hour).Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Proofs: proofs, - Facts: []ucan.Fact{ - { - Data: h.createRefreshFact(metadata, scopes), - }, - }, - } - - // Sign the token - signedToken, err := h.signer.Sign(ucanToken) - if err != nil { - return "", fmt.Errorf("failed to sign UCAN token: %w", err) - } - - // Validate the delegation chain - if len(metadata.DelegationChain) > 0 { - allTokens := append([]string{storedToken.UCANToken}, metadata.DelegationChain...) - allTokens = append(allTokens, signedToken) - - if err := h.signer.ValidateDelegationChain(allTokens); err != nil { - return "", fmt.Errorf("invalid delegation chain: %w", err) - } - } - - return signedToken, nil -} - -// validateScopeAttenuation validates that requested scopes are properly attenuated -func (h *RefreshTokenHandler) validateScopeAttenuation(requested, allowed []string) bool { - // Build allowed scope map - allowedMap := make(map[string]bool) - for _, scope := range allowed { - allowedMap[scope] = true - } - - // Check each requested scope - for _, scope := range requested { - if !allowedMap[scope] { - // Check if a parent scope allows this - found := false - for _, allowedScope := range allowed { - if h.delegator.scopeMapper.IsHierarchicalScope(allowedScope, scope) { - found = true - break - } - } - if !found { - return false - } - } - } - - return true -} - -// shouldRotateRefreshToken determines if refresh token should be rotated -func (h *RefreshTokenHandler) shouldRotateRefreshToken(metadata *UCANRefreshMetadata) bool { - // Rotate on every use for maximum security - // Could be configured based on policy - return true -} - -// extractClientCredentials extracts client credentials from request -func (h *RefreshTokenHandler) extractClientCredentials( - r *http.Request, - req *RefreshTokenRequest, -) (string, string) { - // Try Basic Auth first - if clientID, clientSecret, ok := r.BasicAuth(); ok { - return clientID, clientSecret - } - - // Fall back to request body - return req.ClientID, req.ClientSecret -} - -// getRefreshMetadata retrieves refresh metadata from storage -func (h *RefreshTokenHandler) getRefreshMetadata( - ctx context.Context, - refreshTokenID string, -) (*UCANRefreshMetadata, error) { - // In production, this would retrieve from persistent storage - // For now, return error to initialize new metadata - return nil, fmt.Errorf("metadata not found") -} - -// storeRefreshMetadata stores refresh metadata -func (h *RefreshTokenHandler) storeRefreshMetadata( - ctx context.Context, - refreshTokenID string, - metadata *UCANRefreshMetadata, -) error { - // In production, this would persist to storage - // For now, just return success - return nil -} - -// createRefreshFact creates a fact for refresh token -func (h *RefreshTokenHandler) createRefreshFact( - metadata *UCANRefreshMetadata, - scopes []string, -) json.RawMessage { - fact := map[string]any{ - "type": "refresh_token", - "refresh_count": metadata.RefreshCount, - "original_issuer": metadata.OriginalIssuer, - "scopes": scopes, - "refreshed_at": time.Now().Unix(), - "delegation_length": len(metadata.DelegationChain), - } - - // Add attenuation info if present - if len(metadata.AttenuationPath) > 0 { - fact["attenuations"] = len(metadata.AttenuationPath) - lastAttenuation := metadata.AttenuationPath[len(metadata.AttenuationPath)-1] - fact["last_attenuation"] = map[string]any{ - "from": strings.Join(lastAttenuation.FromScopes, " "), - "to": strings.Join(lastAttenuation.ToScopes, " "), - "at": lastAttenuation.Timestamp.Unix(), - } - } - - data, _ := json.Marshal(fact) - return json.RawMessage(data) -} - -// scopesEqual checks if two scope slices are equal -func (h *RefreshTokenHandler) scopesEqual(a, b []string) bool { - if len(a) != len(b) { - return false - } - - aMap := make(map[string]bool) - for _, scope := range a { - aMap[scope] = true - } - - for _, scope := range b { - if !aMap[scope] { - return false - } - } - - return true -} - -// generateTokenID generates a unique token identifier -func (h *RefreshTokenHandler) generateTokenID() string { - // In production, use a proper UUID or secure random generator - return fmt.Sprintf("tok_%d_%s", time.Now().UnixNano(), h.randomString(16)) -} - -// randomString generates a random string -func (h *RefreshTokenHandler) randomString(length int) string { - const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - result := make([]byte, length) - for i := range result { - result[i] = charset[time.Now().UnixNano()%int64(len(charset))] - } - return string(result) -} - -// sendError sends an OAuth error response -func (h *RefreshTokenHandler) sendError(w http.ResponseWriter, errorCode, errorDescription string) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Pragma", "no-cache") - w.WriteHeader(http.StatusBadRequest) - - response := map[string]string{ - "error": errorCode, - "error_description": errorDescription, - } - - json.NewEncoder(w).Encode(response) -} - -// HandleUCANRefresh handles UCAN-specific refresh requests -func (h *RefreshTokenHandler) HandleUCANRefresh(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - - // Parse UCAN token from Authorization header - authHeader := r.Header.Get("Authorization") - if !strings.HasPrefix(authHeader, "Bearer ") { - h.sendError(w, "invalid_request", "Missing or invalid Authorization header") - return - } - - tokenString := strings.TrimPrefix(authHeader, "Bearer ") - - // Verify the UCAN token - ucanToken, err := h.signer.VerifySignature(tokenString) - if err != nil { - h.sendError(w, "invalid_grant", "Invalid UCAN token") - return - } - - // Check if token can be refreshed (not expired beyond grace period) - gracePeriod := int64(300) // 5 minutes grace period - if time.Now().Unix() > ucanToken.ExpiresAt+gracePeriod { - h.sendError(w, "invalid_grant", "Token expired beyond grace period") - return - } - - // Create refreshed token with extended expiration - newToken, err := h.signer.RefreshToken(tokenString, time.Hour) - if err != nil { - h.sendError(w, "server_error", "Failed to refresh token") - return - } - - // Send response - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - json.NewEncoder(w).Encode(map[string]any{ - "ucan_token": newToken, - "token_type": "UCAN", - "expires_in": 3600, - }) -} diff --git a/bridge/handlers/oauth2_register.go b/bridge/handlers/oauth2_register.go deleted file mode 100644 index 78c2ea364..000000000 --- a/bridge/handlers/oauth2_register.go +++ /dev/null @@ -1,383 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "encoding/base64" - "encoding/json" - "net/http" - "strings" - "time" -) - -// DynamicClientRegistrationRequest represents a client registration request per RFC 7591 -type DynamicClientRegistrationRequest struct { - ClientName string `json:"client_name"` - RedirectURIs []string `json:"redirect_uris"` - GrantTypes []string `json:"grant_types,omitempty"` - ResponseTypes []string `json:"response_types,omitempty"` - Scope string `json:"scope,omitempty"` - TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"` - ApplicationType string `json:"application_type,omitempty"` - Contacts []string `json:"contacts,omitempty"` - LogoURI string `json:"logo_uri,omitempty"` - ClientURI string `json:"client_uri,omitempty"` - PolicyURI string `json:"policy_uri,omitempty"` - TosURI string `json:"tos_uri,omitempty"` - JwksURI string `json:"jwks_uri,omitempty"` - SoftwareID string `json:"software_id,omitempty"` - SoftwareVersion string `json:"software_version,omitempty"` -} - -// DynamicClientRegistrationResponse represents the response for client registration -type DynamicClientRegistrationResponse struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret,omitempty"` - ClientName string `json:"client_name"` - RedirectURIs []string `json:"redirect_uris"` - GrantTypes []string `json:"grant_types"` - ResponseTypes []string `json:"response_types"` - Scope string `json:"scope"` - TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` - ApplicationType string `json:"application_type"` - ClientIDIssuedAt int64 `json:"client_id_issued_at"` - ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"` - LogoURI string `json:"logo_uri,omitempty"` - ClientURI string `json:"client_uri,omitempty"` - PolicyURI string `json:"policy_uri,omitempty"` - TosURI string `json:"tos_uri,omitempty"` - JwksURI string `json:"jwks_uri,omitempty"` -} - -// HandleDynamicClientRegistration handles dynamic client registration per RFC 7591 -func (s *OAuth2Provider) HandleDynamicClientRegistration(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - - // Parse registration request - var req DynamicClientRegistrationRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, "Invalid registration request", http.StatusBadRequest) - return - } - - // Validate required fields - if req.ClientName == "" { - http.Error(w, "client_name is required", http.StatusBadRequest) - return - } - - if len(req.RedirectURIs) == 0 { - http.Error(w, "redirect_uris is required", http.StatusBadRequest) - return - } - - // Validate redirect URIs - for _, uri := range req.RedirectURIs { - if !isValidRedirectURI(uri) { - http.Error(w, "Invalid redirect URI: "+uri, http.StatusBadRequest) - return - } - } - - // Set defaults if not provided - if len(req.GrantTypes) == 0 { - req.GrantTypes = []string{"authorization_code"} - } - - if len(req.ResponseTypes) == 0 { - req.ResponseTypes = []string{"code"} - } - - if req.TokenEndpointAuthMethod == "" { - // Default based on application type - if req.ApplicationType == "native" || req.ApplicationType == "browser" { - req.TokenEndpointAuthMethod = "none" // Public client - } else { - req.TokenEndpointAuthMethod = "client_secret_basic" - } - } - - if req.ApplicationType == "" { - req.ApplicationType = "web" - } - - // Validate grant types and response types - if !validateGrantTypes(req.GrantTypes) { - http.Error(w, "Invalid grant types", http.StatusBadRequest) - return - } - - if !validateResponseTypes(req.ResponseTypes) { - http.Error(w, "Invalid response types", http.StatusBadRequest) - return - } - - // Validate scopes if scope mapper is available - if req.Scope != "" && s.scopeMapper != nil { - scopes := strings.Split(req.Scope, " ") - for _, scope := range scopes { - // Check if scope is valid using the scope mapper - if _, exists := s.scopeMapper.GetScope(scope); !exists { - http.Error(w, "Invalid scope: "+scope, http.StatusBadRequest) - return - } - } - } - - // Generate client credentials - clientID := generateDynamicClientID() - var clientSecret string - var clientSecretExpiresAt int64 - - // Only generate secret for confidential clients - if req.TokenEndpointAuthMethod != "none" { - clientSecret = generateDynamicClientSecret() - // Client secrets expire in 1 year by default - clientSecretExpiresAt = time.Now().Add(365 * 24 * time.Hour).Unix() - } - - // Create OAuth2 client - client := &OAuth2Client{ - ClientID: clientID, - ClientSecret: clientSecret, - RedirectURIs: req.RedirectURIs, - AllowedScopes: strings.Split(req.Scope, " "), - AllowedGrants: req.GrantTypes, - TokenLifetime: time.Hour, // Default 1 hour - RequirePKCE: false, - TrustedClient: false, - RequiresConsent: true, - Metadata: map[string]string{ - "client_name": req.ClientName, - "application_type": req.ApplicationType, - "logo_uri": req.LogoURI, - "client_uri": req.ClientURI, - "policy_uri": req.PolicyURI, - "tos_uri": req.TosURI, - "jwks_uri": req.JwksURI, - }, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - } - - // Set client type based on auth method - if req.TokenEndpointAuthMethod == "none" { - client.ClientType = "public" - } else { - client.ClientType = "confidential" - } - - // Determine if client requires PKCE - if req.ApplicationType == "native" || req.ApplicationType == "browser" { - client.RequirePKCE = true - } - - // Store client in the registry - if s.clientRegistry != nil { - if err := s.clientRegistry.RegisterClient(client); err != nil { - http.Error(w, "Failed to register client", http.StatusInternalServerError) - return - } - } - - // Build response - resp := DynamicClientRegistrationResponse{ - ClientID: clientID, - ClientSecret: clientSecret, - ClientName: req.ClientName, - RedirectURIs: req.RedirectURIs, - GrantTypes: req.GrantTypes, - ResponseTypes: req.ResponseTypes, - Scope: req.Scope, - TokenEndpointAuthMethod: req.TokenEndpointAuthMethod, - ApplicationType: req.ApplicationType, - ClientIDIssuedAt: time.Now().Unix(), - ClientSecretExpiresAt: clientSecretExpiresAt, - LogoURI: req.LogoURI, - ClientURI: req.ClientURI, - PolicyURI: req.PolicyURI, - TosURI: req.TosURI, - JwksURI: req.JwksURI, - } - - // Return registration response - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(resp) -} - -// HandleClientConfiguration handles client configuration retrieval -func (s *OAuth2Provider) HandleClientConfiguration(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - - // Extract client ID from path or query - clientID := r.URL.Query().Get("client_id") - if clientID == "" { - // Try to extract from path (e.g., /register/{client_id}) - parts := strings.Split(r.URL.Path, "/") - if len(parts) > 2 { - clientID = parts[len(parts)-1] - } - } - - if clientID == "" { - http.Error(w, "client_id is required", http.StatusBadRequest) - return - } - - // Validate access token for client management - authHeader := r.Header.Get("Authorization") - if !strings.HasPrefix(authHeader, "Bearer ") { - w.Header().Set("WWW-Authenticate", `Bearer realm="client_configuration"`) - http.Error(w, "Access token required", http.StatusUnauthorized) - return - } - - token := strings.TrimPrefix(authHeader, "Bearer ") - - // Validate token in the access token store - if s.accessTokenStore == nil { - http.Error(w, "Token store not available", http.StatusInternalServerError) - return - } - - // Check token validity (simplified for now) - // In production, this should validate the token properly - if token == "" { - http.Error(w, "Invalid or expired access token", http.StatusUnauthorized) - return - } - - // Get client from registry - if s.clientRegistry == nil { - http.Error(w, "Client registry not available", http.StatusInternalServerError) - return - } - - client, err := s.clientRegistry.GetClient(clientID) - if err != nil { - http.Error(w, "Client not found", http.StatusNotFound) - return - } - - // Build response - resp := DynamicClientRegistrationResponse{ - ClientID: client.ClientID, - ClientName: client.Metadata["client_name"], - RedirectURIs: client.RedirectURIs, - GrantTypes: client.AllowedGrants, - ResponseTypes: []string{"code", "token"}, // Default response types - Scope: strings.Join(client.AllowedScopes, " "), - TokenEndpointAuthMethod: getTokenEndpointAuthMethod(client), - ApplicationType: client.Metadata["application_type"], - ClientIDIssuedAt: client.CreatedAt.Unix(), - LogoURI: client.Metadata["logo_uri"], - ClientURI: client.Metadata["client_uri"], - PolicyURI: client.Metadata["policy_uri"], - TosURI: client.Metadata["tos_uri"], - JwksURI: client.Metadata["jwks_uri"], - } - - // Return client configuration - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - json.NewEncoder(w).Encode(resp) -} - -// getTokenEndpointAuthMethod determines the auth method from client type -func getTokenEndpointAuthMethod(client *OAuth2Client) string { - if client.ClientType == "public" { - return "none" - } - return "client_secret_basic" -} - -// Helper functions for dynamic registration - -func generateDynamicClientID() string { - // Generate a random client ID for dynamic registration - b := make([]byte, 16) - _, _ = rand.Read(b) - return "dyn_client_" + base64.RawURLEncoding.EncodeToString(b) -} - -func generateDynamicClientSecret() string { - // Generate a secure random secret for dynamic registration - b := make([]byte, 32) - _, _ = rand.Read(b) - return base64.RawURLEncoding.EncodeToString(b) -} - -func isValidRedirectURI(uri string) bool { - // Basic validation - in production, this should be more comprehensive - if uri == "" { - return false - } - - // Allow localhost for development - if strings.HasPrefix(uri, "http://localhost") || strings.HasPrefix(uri, "http://127.0.0.1") { - return true - } - - // Require HTTPS for production URIs - if !strings.HasPrefix(uri, "https://") { - // Allow custom schemes for native apps - if strings.Contains(uri, "://") { - return true - } - return false - } - - return true -} - -func validateGrantTypes(grantTypes []string) bool { - validGrants := map[string]bool{ - "authorization_code": true, - "implicit": true, - "refresh_token": true, - "client_credentials": true, - "password": true, - } - - for _, grant := range grantTypes { - if !validGrants[grant] { - return false - } - } - return true -} - -func validateResponseTypes(responseTypes []string) bool { - validTypes := map[string]bool{ - "code": true, - "token": true, - "id_token": true, - } - - for _, respType := range responseTypes { - // Handle composite types like "code id_token" - parts := strings.Split(respType, " ") - for _, part := range parts { - if !validTypes[part] { - return false - } - } - } - return true -} - -func hasScope(scopes []string, requiredScope string) bool { - for _, scope := range scopes { - if scope == requiredScope { - return true - } - } - return false -} diff --git a/bridge/handlers/oauth2_scopes.go b/bridge/handlers/oauth2_scopes.go deleted file mode 100644 index 52a72712f..000000000 --- a/bridge/handlers/oauth2_scopes.go +++ /dev/null @@ -1,412 +0,0 @@ -package handlers - -import ( - "fmt" - "strings" - - "github.com/sonr-io/sonr/crypto/ucan" -) - -// ScopeMapper manages OAuth scope to UCAN capability mapping -type ScopeMapper struct { - scopeDefinitions map[string]*OAuth2ScopeDefinition - ucanTemplates map[string]*ucan.Attenuation -} - -// NewScopeMapper creates a new scope mapper with standard scopes -func NewScopeMapper() *ScopeMapper { - mapper := &ScopeMapper{ - scopeDefinitions: make(map[string]*OAuth2ScopeDefinition), - ucanTemplates: make(map[string]*ucan.Attenuation), - } - - mapper.initializeStandardScopes() - return mapper -} - -// initializeStandardScopes defines the standard OAuth scopes and their UCAN mappings -func (m *ScopeMapper) initializeStandardScopes() { - // OpenID Connect scopes - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "openid", - Description: "OpenID Connect authentication", - UCANActions: []string{"authenticate"}, - ResourceType: "identity", - RequiresAuth: true, - Sensitive: false, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "profile", - Description: "Access to user profile information", - UCANActions: []string{"read"}, - ResourceType: "did", - RequiresAuth: true, - Sensitive: false, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "email", - Description: "Access to user email", - UCANActions: []string{"read"}, - ResourceType: "contact", - RequiresAuth: true, - Sensitive: true, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "offline_access", - Description: "Maintain access when user is not present", - UCANActions: []string{"refresh"}, - ResourceType: "session", - RequiresAuth: true, - Sensitive: true, - }) - - // Vault scopes - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "vault:read", - Description: "Read access to vault data", - UCANActions: []string{"read"}, - ResourceType: "vault", - RequiresAuth: true, - Sensitive: false, - ParentScope: "", - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "vault:write", - Description: "Write access to vault data", - UCANActions: []string{"read", "write"}, - ResourceType: "vault", - RequiresAuth: true, - Sensitive: true, - ParentScope: "vault:read", - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "vault:sign", - Description: "Signing operations with vault keys", - UCANActions: []string{"read", "sign"}, - ResourceType: "vault", - RequiresAuth: true, - Sensitive: true, - ParentScope: "vault:read", - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "vault:admin", - Description: "Full administrative access to vault", - UCANActions: []string{"read", "write", "sign", "export", "import", "delete", "admin"}, - ResourceType: "vault", - RequiresAuth: true, - Sensitive: true, - ParentScope: "vault:write", - ChildScopes: []string{"vault:read", "vault:write", "vault:sign"}, - }) - - // Service scopes - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "service:read", - Description: "Read service information", - UCANActions: []string{"read"}, - ResourceType: "service", - RequiresAuth: true, - Sensitive: false, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "service:write", - Description: "Create and update services", - UCANActions: []string{"read", "write"}, - ResourceType: "service", - RequiresAuth: true, - Sensitive: true, - ParentScope: "service:read", - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "service:manage", - Description: "Full service management capabilities", - UCANActions: []string{"read", "write", "delete", "admin"}, - ResourceType: "service", - RequiresAuth: true, - Sensitive: true, - ParentScope: "service:write", - ChildScopes: []string{"service:read", "service:write"}, - }) - - // DID scopes - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "did:read", - Description: "Read DID documents", - UCANActions: []string{"read"}, - ResourceType: "did", - RequiresAuth: false, - Sensitive: false, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "did:write", - Description: "Update DID documents", - UCANActions: []string{"read", "write"}, - ResourceType: "did", - RequiresAuth: true, - Sensitive: true, - ParentScope: "did:read", - }) - - // DWN (Decentralized Web Node) scopes - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "dwn:read", - Description: "Read data from DWN", - UCANActions: []string{"read"}, - ResourceType: "dwn", - RequiresAuth: true, - Sensitive: false, - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "dwn:write", - Description: "Write data to DWN", - UCANActions: []string{"read", "write"}, - ResourceType: "dwn", - RequiresAuth: true, - Sensitive: true, - ParentScope: "dwn:read", - }) - - _ = m.RegisterScope(&OAuth2ScopeDefinition{ - Name: "dwn:admin", - Description: "Full administrative access to DWN", - UCANActions: []string{"read", "write", "admin", "protocols-configure"}, - ResourceType: "dwn", - RequiresAuth: true, - Sensitive: true, - ParentScope: "dwn:write", - ChildScopes: []string{"dwn:read", "dwn:write"}, - }) -} - -// RegisterScope registers a new scope definition -func (m *ScopeMapper) RegisterScope(scope *OAuth2ScopeDefinition) error { - if scope.Name == "" { - return fmt.Errorf("scope name is required") - } - - m.scopeDefinitions[scope.Name] = scope - - // Create UCAN template for this scope - m.createUCANTemplate(scope) - - return nil -} - -// GetScope retrieves a scope definition -func (m *ScopeMapper) GetScope(name string) (*OAuth2ScopeDefinition, bool) { - scope, exists := m.scopeDefinitions[name] - return scope, exists -} - -// MapToUCAN maps OAuth scopes to UCAN attenuations -func (m *ScopeMapper) MapToUCAN( - scopes []string, - userDID string, - clientID string, - resourceContext map[string]string, -) []ucan.Attenuation { - attenuations := []ucan.Attenuation{} - - for _, scopeName := range scopes { - scope, exists := m.scopeDefinitions[scopeName] - if !exists { - continue - } - - // Create attenuation for this scope - attenuation := m.createAttenuation(scope, userDID, clientID, resourceContext) - attenuations = append(attenuations, attenuation) - - // Add child scope attenuations if this is a parent scope - for _, childScope := range scope.ChildScopes { - if childDef, exists := m.scopeDefinitions[childScope]; exists { - childAttenuation := m.createAttenuation( - childDef, - userDID, - clientID, - resourceContext, - ) - attenuations = append(attenuations, childAttenuation) - } - } - } - - return attenuations -} - -// ValidateScopes validates that the requested scopes are valid -func (m *ScopeMapper) ValidateScopes(scopes []string) error { - for _, scope := range scopes { - if _, exists := m.scopeDefinitions[scope]; !exists { - return fmt.Errorf("invalid scope: %s", scope) - } - } - return nil -} - -// GetScopeDescriptions returns human-readable descriptions for scopes -func (m *ScopeMapper) GetScopeDescriptions(scopes []string) map[string]string { - descriptions := make(map[string]string) - - for _, scope := range scopes { - if def, exists := m.scopeDefinitions[scope]; exists { - descriptions[scope] = def.Description - } - } - - return descriptions -} - -// GetSensitiveScopes returns only the sensitive scopes from a list -func (m *ScopeMapper) GetSensitiveScopes(scopes []string) []string { - sensitive := []string{} - - for _, scope := range scopes { - if def, exists := m.scopeDefinitions[scope]; exists && def.Sensitive { - sensitive = append(sensitive, scope) - } - } - - return sensitive -} - -// IsHierarchicalScope checks if one scope includes another -func (m *ScopeMapper) IsHierarchicalScope(parentScope, childScope string) bool { - parent, exists := m.scopeDefinitions[parentScope] - if !exists { - return false - } - - // Check direct children - for _, child := range parent.ChildScopes { - if child == childScope { - return true - } - // Recursive check - if m.IsHierarchicalScope(child, childScope) { - return true - } - } - - return false -} - -// Private helper methods - -func (m *ScopeMapper) createUCANTemplate(scope *OAuth2ScopeDefinition) { - // Create a template attenuation for this scope - capability := &ucan.SimpleCapability{ - Action: strings.Join(scope.UCANActions, ","), - } - - resource := &SimpleResource{ - Scheme: scope.ResourceType, - Value: "{resource_id}", - } - - m.ucanTemplates[scope.Name] = &ucan.Attenuation{ - Capability: capability, - Resource: resource, - } -} - -func (m *ScopeMapper) createAttenuation( - scope *OAuth2ScopeDefinition, - userDID string, - clientID string, - resourceContext map[string]string, -) ucan.Attenuation { - // Create capability based on scope actions - var capability ucan.Capability - if len(scope.UCANActions) == 1 { - capability = &ucan.SimpleCapability{ - Action: scope.UCANActions[0], - } - } else { - capability = &ucan.MultiCapability{ - Actions: scope.UCANActions, - } - } - - // Create resource based on scope type and context - resourceValue := m.resolveResourceValue(scope, userDID, resourceContext) - resource := &SimpleResource{ - Scheme: scope.ResourceType, - Value: resourceValue, - } - - return ucan.Attenuation{ - Capability: capability, - Resource: resource, - } -} - -func (m *ScopeMapper) resolveResourceValue( - scope *OAuth2ScopeDefinition, - userDID string, - context map[string]string, -) string { - switch scope.ResourceType { - case "did": - return fmt.Sprintf("did:sonr:%s", userDID) - case "vault": - if vaultAddr, exists := context["vault_address"]; exists { - return vaultAddr - } - return fmt.Sprintf("vault:%s", userDID) - case "service": - if serviceID, exists := context["service_id"]; exists { - return serviceID - } - return "service:*" - case "dwn": - if dwnID, exists := context["dwn_id"]; exists { - return dwnID - } - return fmt.Sprintf("dwn:%s", userDID) - default: - return "*" - } -} - -// SimpleResource implements the Resource interface for OAuth scopes -type SimpleResource struct { - Scheme string - Value string -} - -func (r *SimpleResource) GetScheme() string { - return r.Scheme -} - -func (r *SimpleResource) GetValue() string { - return r.Value -} - -func (r *SimpleResource) GetURI() string { - return fmt.Sprintf("%s://%s", r.Scheme, r.Value) -} - -func (r *SimpleResource) Matches(other ucan.Resource) bool { - if r.Scheme != other.GetScheme() { - return false - } - - // Wildcard matching - if r.Value == "*" || other.GetValue() == "*" { - return true - } - - // Exact match - return r.Value == other.GetValue() -} diff --git a/bridge/handlers/oauth2_security.go b/bridge/handlers/oauth2_security.go deleted file mode 100644 index 2a4009d1a..000000000 --- a/bridge/handlers/oauth2_security.go +++ /dev/null @@ -1,449 +0,0 @@ -package handlers - -import ( - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "encoding/hex" - "fmt" - "strings" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -const ( - // PKCE challenge methods - PKCEMethodS256 = "S256" - PKCEMethodPlain = "plain" -) - -// PKCEValidator handles PKCE validation -type PKCEValidator struct{} - -// NewPKCEValidator creates a new PKCE validator -func NewPKCEValidator() *PKCEValidator { - return &PKCEValidator{} -} - -// GeneratePKCEPair generates a PKCE verifier and challenge pair -func (p *PKCEValidator) GeneratePKCEPair() (verifier, challenge string, err error) { - // Generate cryptographically secure verifier (43-128 characters) - verifierBytes := make([]byte, 32) - if _, err := rand.Read(verifierBytes); err != nil { - return "", "", fmt.Errorf("failed to generate PKCE verifier: %w", err) - } - verifier = base64.RawURLEncoding.EncodeToString(verifierBytes) - - // Create S256 challenge - challenge = p.CreateChallenge(verifier, PKCEMethodS256) - - return verifier, challenge, nil -} - -// CreateChallenge creates a PKCE challenge from a verifier -func (p *PKCEValidator) CreateChallenge(verifier, method string) string { - switch method { - case PKCEMethodS256: - h := sha256.Sum256([]byte(verifier)) - return base64.RawURLEncoding.EncodeToString(h[:]) - case PKCEMethodPlain: - return verifier - default: - // Default to S256 for security - h := sha256.Sum256([]byte(verifier)) - return base64.RawURLEncoding.EncodeToString(h[:]) - } -} - -// Validate validates a PKCE verifier against a challenge -func (p *PKCEValidator) Validate(verifier, challenge, method string) bool { - if method == "" { - method = PKCEMethodPlain - } - - computed := p.CreateChallenge(verifier, method) - return subtle.ConstantTimeCompare([]byte(computed), []byte(challenge)) == 1 -} - -// computePKCEChallenge computes a PKCE challenge (helper function) -func computePKCEChallenge(verifier, method string) string { - validator := NewPKCEValidator() - return validator.CreateChallenge(verifier, method) -} - -// CSRFProtector handles CSRF protection -type CSRFProtector struct { - secret []byte -} - -// NewCSRFProtector creates a new CSRF protector -func NewCSRFProtector(secret string) *CSRFProtector { - return &CSRFProtector{ - secret: []byte(secret), - } -} - -// GenerateToken generates a CSRF token -func (c *CSRFProtector) GenerateToken(sessionID string) (string, error) { - // Create a unique token tied to the session - h := hmac.New(sha256.New, c.secret) - h.Write([]byte(sessionID)) - h.Write([]byte(time.Now().Format(time.RFC3339))) - - tokenBytes := h.Sum(nil) - return base64.RawURLEncoding.EncodeToString(tokenBytes), nil -} - -// ValidateToken validates a CSRF token -func (c *CSRFProtector) ValidateToken(token, sessionID string) bool { - // Decode the token - tokenBytes, err := base64.RawURLEncoding.DecodeString(token) - if err != nil { - return false - } - - // Recreate the expected token - h := hmac.New(sha256.New, c.secret) - h.Write([]byte(sessionID)) - - // Note: In production, you'd want to include time validation - // and possibly store tokens with expiration - expectedBytes := h.Sum(nil)[:len(tokenBytes)] - - return hmac.Equal(tokenBytes, expectedBytes) -} - -// StateValidator validates OAuth state parameters -type StateValidator struct { - states map[string]*StateEntry -} - -// StateEntry represents a stored state parameter -type StateEntry struct { - Value string - ClientID string - ExpiresAt time.Time - Used bool -} - -// NewStateValidator creates a new state validator -func NewStateValidator() *StateValidator { - validator := &StateValidator{ - states: make(map[string]*StateEntry), - } - - // Start cleanup routine - go validator.cleanup() - - return validator -} - -// GenerateState generates a secure state parameter -func (s *StateValidator) GenerateState() (string, error) { - stateBytes := make([]byte, 32) - if _, err := rand.Read(stateBytes); err != nil { - return "", fmt.Errorf("failed to generate state: %w", err) - } - - return base64.RawURLEncoding.EncodeToString(stateBytes), nil -} - -// StoreState stores a state parameter for validation -func (s *StateValidator) StoreState(state, clientID string) { - s.states[state] = &StateEntry{ - Value: state, - ClientID: clientID, - ExpiresAt: time.Now().Add(10 * time.Minute), - Used: false, - } -} - -// ValidateState validates and consumes a state parameter -func (s *StateValidator) ValidateState(state, clientID string) bool { - entry, exists := s.states[state] - if !exists { - return false - } - - // Check if expired - if time.Now().After(entry.ExpiresAt) { - delete(s.states, state) - return false - } - - // Check if already used - if entry.Used { - return false - } - - // Check client ID matches - if entry.ClientID != clientID { - return false - } - - // Mark as used - entry.Used = true - return true -} - -// cleanup removes expired states -func (s *StateValidator) cleanup() { - ticker := time.NewTicker(5 * time.Minute) - defer ticker.Stop() - - for range ticker.C { - now := time.Now() - for state, entry := range s.states { - if now.After(entry.ExpiresAt) { - delete(s.states, state) - } - } - } -} - -// JWTClientAuthenticator handles JWT client authentication -type JWTClientAuthenticator struct { - clientRegistry *ClientRegistry -} - -// NewJWTClientAuthenticator creates a new JWT client authenticator -func NewJWTClientAuthenticator(registry *ClientRegistry) *JWTClientAuthenticator { - return &JWTClientAuthenticator{ - clientRegistry: registry, - } -} - -// ValidateClientAssertion validates a JWT client assertion -func (j *JWTClientAuthenticator) ValidateClientAssertion( - assertion, expectedAudience string, -) (*OAuth2Client, error) { - // Parse the JWT without verification first to get the claims - token, _, err := jwt.NewParser().ParseUnverified(assertion, jwt.MapClaims{}) - if err != nil { - return nil, fmt.Errorf("failed to parse client assertion: %w", err) - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid claims format") - } - - // Extract client ID from issuer and subject - clientID, ok := claims["iss"].(string) - if !ok { - return nil, fmt.Errorf("missing issuer claim") - } - - subject, ok := claims["sub"].(string) - if !ok || subject != clientID { - return nil, fmt.Errorf("issuer and subject must match") - } - - // Validate audience - audience, ok := claims["aud"].(string) - if !ok || audience != expectedAudience { - return nil, fmt.Errorf("invalid audience") - } - - // Validate expiration - if exp, ok := claims["exp"].(float64); ok { - if time.Now().Unix() > int64(exp) { - return nil, fmt.Errorf("assertion expired") - } - } else { - return nil, fmt.Errorf("missing expiration") - } - - // Validate not before - if nbf, ok := claims["nbf"].(float64); ok { - if time.Now().Unix() < int64(nbf) { - return nil, fmt.Errorf("assertion not yet valid") - } - } - - // Validate issued at - if iat, ok := claims["iat"].(float64); ok { - // Check that the assertion is not too old (5 minutes max) - if time.Now().Unix()-int64(iat) > 300 { - return nil, fmt.Errorf("assertion too old") - } - } - - // Validate JTI for replay protection - if jti, ok := claims["jti"].(string); !ok || jti == "" { - return nil, fmt.Errorf("missing jti claim") - } - // TODO: Store and check JTI to prevent replay attacks - - // Get the client - client, err := j.clientRegistry.GetClient(clientID) - if err != nil { - return nil, fmt.Errorf("unknown client: %w", err) - } - - // TODO: Verify the JWT signature using the client's registered public key - // This requires storing client public keys in the registry - - return client, nil -} - -// SecureTokenGenerator generates cryptographically secure tokens -type SecureTokenGenerator struct { - entropy int // bits of entropy -} - -// NewSecureTokenGenerator creates a new secure token generator -func NewSecureTokenGenerator(entropyBits int) *SecureTokenGenerator { - if entropyBits < 128 { - entropyBits = 256 // Default to 256 bits for security - } - return &SecureTokenGenerator{ - entropy: entropyBits, - } -} - -// GenerateToken generates a secure random token -func (g *SecureTokenGenerator) GenerateToken() (string, error) { - bytes := make([]byte, g.entropy/8) - if _, err := rand.Read(bytes); err != nil { - return "", fmt.Errorf("failed to generate secure token: %w", err) - } - return base64.RawURLEncoding.EncodeToString(bytes), nil -} - -// GenerateHexToken generates a secure random token in hex format -func (g *SecureTokenGenerator) GenerateHexToken() (string, error) { - bytes := make([]byte, g.entropy/8) - if _, err := rand.Read(bytes); err != nil { - return "", fmt.Errorf("failed to generate secure token: %w", err) - } - return hex.EncodeToString(bytes), nil -} - -// RateLimiter implements rate limiting for OAuth endpoints -type RateLimiter struct { - attempts map[string][]time.Time - maxAttempts int - window time.Duration -} - -// NewRateLimiter creates a new rate limiter -func NewRateLimiter(maxAttempts int, window time.Duration) *RateLimiter { - limiter := &RateLimiter{ - attempts: make(map[string][]time.Time), - maxAttempts: maxAttempts, - window: window, - } - - // Start cleanup routine - go limiter.cleanup() - - return limiter -} - -// Allow checks if a request should be allowed -func (r *RateLimiter) Allow(key string) bool { - now := time.Now() - windowStart := now.Add(-r.window) - - // Get attempts for this key - attempts := r.attempts[key] - - // Filter out attempts outside the window - validAttempts := []time.Time{} - for _, attempt := range attempts { - if attempt.After(windowStart) { - validAttempts = append(validAttempts, attempt) - } - } - - // Check if under limit - if len(validAttempts) >= r.maxAttempts { - return false - } - - // Add this attempt - validAttempts = append(validAttempts, now) - r.attempts[key] = validAttempts - - return true -} - -// cleanup removes old entries -func (r *RateLimiter) cleanup() { - ticker := time.NewTicker(5 * time.Minute) - defer ticker.Stop() - - for range ticker.C { - now := time.Now() - windowStart := now.Add(-r.window) - - for key, attempts := range r.attempts { - validAttempts := []time.Time{} - for _, attempt := range attempts { - if attempt.After(windowStart) { - validAttempts = append(validAttempts, attempt) - } - } - - if len(validAttempts) == 0 { - delete(r.attempts, key) - } else { - r.attempts[key] = validAttempts - } - } - } -} - -// OriginValidator validates request origins for CORS -type OriginValidator struct { - allowedOrigins map[string]bool - allowSubdomains bool -} - -// NewOriginValidator creates a new origin validator -func NewOriginValidator(origins []string, allowSubdomains bool) *OriginValidator { - validator := &OriginValidator{ - allowedOrigins: make(map[string]bool), - allowSubdomains: allowSubdomains, - } - - for _, origin := range origins { - validator.allowedOrigins[origin] = true - } - - return validator -} - -// IsAllowed checks if an origin is allowed -func (o *OriginValidator) IsAllowed(origin string) bool { - // Direct match - if o.allowedOrigins[origin] { - return true - } - - // Check subdomain matching if enabled - if o.allowSubdomains { - for allowed := range o.allowedOrigins { - if o.isSubdomainOf(origin, allowed) { - return true - } - } - } - - return false -} - -// isSubdomainOf checks if origin is a subdomain of allowed -func (o *OriginValidator) isSubdomainOf(origin, allowed string) bool { - // Simple subdomain check - // In production, use proper URL parsing - if strings.HasPrefix(allowed, "*.") { - domain := strings.TrimPrefix(allowed, "*") - return strings.HasSuffix(origin, domain) - } - return false -} diff --git a/bridge/handlers/oauth2_token_exchange.go b/bridge/handlers/oauth2_token_exchange.go deleted file mode 100644 index e764def70..000000000 --- a/bridge/handlers/oauth2_token_exchange.go +++ /dev/null @@ -1,650 +0,0 @@ -package handlers - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "github.com/sonr-io/sonr/crypto/ucan" -) - -// TokenExchangeHandler implements RFC 8693 OAuth 2.0 Token Exchange -type TokenExchangeHandler struct { - delegator *UCANDelegator - signer *BlockchainUCANSigner - tokenStore TokenStore - clientStore ClientStore -} - -// TokenStore interface for token persistence -type TokenStore interface { - GetToken(ctx context.Context, tokenID string) (*StoredToken, error) - StoreToken(ctx context.Context, token *StoredToken) error - RevokeToken(ctx context.Context, tokenID string) error -} - -// ClientStore interface for OAuth client information -type ClientStore interface { - GetClient(ctx context.Context, clientID string) (*OAuth2Client, error) - ValidateClientCredentials(ctx context.Context, clientID, clientSecret string) error -} - -// StoredToken represents a stored OAuth token -type StoredToken struct { - TokenID string `json:"token_id"` - TokenType string `json:"token_type"` - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token,omitempty"` - ExpiresAt time.Time `json:"expires_at"` - Scopes []string `json:"scopes"` - ClientID string `json:"client_id"` - UserDID string `json:"user_did,omitempty"` - UCANToken string `json:"ucan_token"` -} - -// TokenExchangeRequest represents an RFC 8693 token exchange request -type TokenExchangeRequest struct { - GrantType string `json:"grant_type"` - Resource string `json:"resource,omitempty"` - Audience string `json:"audience,omitempty"` - Scope string `json:"scope,omitempty"` - RequestedTokenType string `json:"requested_token_type,omitempty"` - SubjectToken string `json:"subject_token"` - SubjectTokenType string `json:"subject_token_type"` - ActorToken string `json:"actor_token,omitempty"` - ActorTokenType string `json:"actor_token_type,omitempty"` -} - -// TokenExchangeResponse represents an RFC 8693 token exchange response -type TokenExchangeResponse struct { - AccessToken string `json:"access_token"` - IssuedTokenType string `json:"issued_token_type"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in,omitempty"` - Scope string `json:"scope,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` -} - -// Token type identifiers from RFC 8693 -const ( - TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" - TokenTypeRefreshToken = "urn:ietf:params:oauth:token-type:refresh_token" - TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token" - TokenTypeSAML1 = "urn:ietf:params:oauth:token-type:saml1" - TokenTypeSAML2 = "urn:ietf:params:oauth:token-type:saml2" - TokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" - TokenTypeUCAN = "urn:x-oath:params:oauth:token-type:ucan" -) - -// NewTokenExchangeHandler creates a new token exchange handler -func NewTokenExchangeHandler( - delegator *UCANDelegator, - signer *BlockchainUCANSigner, - tokenStore TokenStore, - clientStore ClientStore, -) *TokenExchangeHandler { - return &TokenExchangeHandler{ - delegator: delegator, - signer: signer, - tokenStore: tokenStore, - clientStore: clientStore, - } -} - -// HandleTokenExchange handles RFC 8693 token exchange requests -func (h *TokenExchangeHandler) HandleTokenExchange(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - return - } - - // Parse request - var req TokenExchangeRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - h.sendError(w, "invalid_request", "Failed to parse request body") - return - } - - // Validate grant type - if req.GrantType != "urn:ietf:params:oauth:grant-type:token-exchange" { - h.sendError(w, "unsupported_grant_type", "Only token-exchange grant type is supported") - return - } - - // Validate required parameters - if req.SubjectToken == "" || req.SubjectTokenType == "" { - h.sendError(w, "invalid_request", "Missing required parameters") - return - } - - // Authenticate client - clientID, clientSecret, ok := r.BasicAuth() - if !ok { - h.sendError(w, "invalid_client", "Client authentication required") - return - } - - ctx := r.Context() - if err := h.clientStore.ValidateClientCredentials(ctx, clientID, clientSecret); err != nil { - h.sendError(w, "invalid_client", "Client authentication failed") - return - } - - // Get client information - client, err := h.clientStore.GetClient(ctx, clientID) - if err != nil { - h.sendError(w, "invalid_client", "Client not found") - return - } - - // Process token exchange based on token types - response, err := h.processTokenExchange(ctx, &req, client) - if err != nil { - h.sendError(w, "invalid_request", err.Error()) - return - } - - // Send response - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Pragma", "no-cache") - json.NewEncoder(w).Encode(response) -} - -// processTokenExchange processes the token exchange based on token types -func (h *TokenExchangeHandler) processTokenExchange( - ctx context.Context, - req *TokenExchangeRequest, - client *OAuth2Client, -) (*TokenExchangeResponse, error) { - // Determine requested token type (default to access token) - requestedType := req.RequestedTokenType - if requestedType == "" { - requestedType = TokenTypeAccessToken - } - - // Handle different subject token types - switch req.SubjectTokenType { - case TokenTypeAccessToken: - return h.exchangeAccessToken(ctx, req, client, requestedType) - case TokenTypeRefreshToken: - return h.exchangeRefreshToken(ctx, req, client, requestedType) - case TokenTypeJWT: - return h.exchangeJWT(ctx, req, client, requestedType) - case TokenTypeUCAN: - return h.exchangeUCAN(ctx, req, client, requestedType) - default: - return nil, fmt.Errorf("unsupported subject token type: %s", req.SubjectTokenType) - } -} - -// exchangeAccessToken exchanges an access token for a new token -func (h *TokenExchangeHandler) exchangeAccessToken( - ctx context.Context, - req *TokenExchangeRequest, - client *OAuth2Client, - requestedType string, -) (*TokenExchangeResponse, error) { - // Retrieve the subject token - storedToken, err := h.tokenStore.GetToken(ctx, req.SubjectToken) - if err != nil { - return nil, fmt.Errorf("invalid subject token") - } - - // Validate token hasn't expired - if time.Now().After(storedToken.ExpiresAt) { - return nil, fmt.Errorf("subject token has expired") - } - - // Parse requested scopes (default to original scopes) - requestedScopes := storedToken.Scopes - if req.Scope != "" { - requestedScopes = strings.Split(req.Scope, " ") - // Validate requested scopes are subset of original - if !h.isScopeSubset(requestedScopes, storedToken.Scopes) { - return nil, fmt.Errorf("requested scopes exceed original token scopes") - } - } - - // Determine audience (default to requested audience or client ID) - audience := req.Audience - if audience == "" { - // Try to extract DID from client metadata - if clientDID, ok := client.Metadata["client_did"]; ok { - audience = clientDID - } else { - audience = client.ClientID - } - } - - // Create new UCAN delegation based on requested type - switch requestedType { - case TokenTypeUCAN: - return h.createUCANResponse( - ctx, - storedToken.UserDID, - audience, - requestedScopes, - storedToken.UCANToken, - ) - case TokenTypeAccessToken: - return h.createAccessTokenResponse(ctx, storedToken.UserDID, audience, requestedScopes) - default: - return nil, fmt.Errorf("unsupported requested token type: %s", requestedType) - } -} - -// exchangeRefreshToken exchanges a refresh token for new tokens -func (h *TokenExchangeHandler) exchangeRefreshToken( - ctx context.Context, - req *TokenExchangeRequest, - client *OAuth2Client, - requestedType string, -) (*TokenExchangeResponse, error) { - // Retrieve the refresh token - storedToken, err := h.tokenStore.GetToken(ctx, req.SubjectToken) - if err != nil { - return nil, fmt.Errorf("invalid refresh token") - } - - // Validate it's actually a refresh token - if storedToken.TokenType != "refresh_token" { - return nil, fmt.Errorf("token is not a refresh token") - } - - // Create new tokens with same scopes - clientDID := client.ClientID - if did, ok := client.Metadata["client_did"]; ok { - clientDID = did - } - return h.createAccessTokenResponse(ctx, storedToken.UserDID, clientDID, storedToken.Scopes) -} - -// exchangeJWT exchanges a JWT for a UCAN token -func (h *TokenExchangeHandler) exchangeJWT( - ctx context.Context, - req *TokenExchangeRequest, - client *OAuth2Client, - requestedType string, -) (*TokenExchangeResponse, error) { - // Verify the JWT - ucanToken, err := h.signer.VerifySignature(req.SubjectToken) - if err != nil { - return nil, fmt.Errorf("invalid JWT: %w", err) - } - - // Extract scopes from JWT claims - scopes := h.extractScopesFromUCAN(ucanToken) - - // Create response based on requested type - clientDID := client.ClientID - if did, ok := client.Metadata["client_did"]; ok { - clientDID = did - } - - switch requestedType { - case TokenTypeUCAN: - return h.createUCANResponse(ctx, ucanToken.Issuer, clientDID, scopes, req.SubjectToken) - case TokenTypeAccessToken: - return h.createAccessTokenResponse(ctx, ucanToken.Issuer, clientDID, scopes) - default: - return nil, fmt.Errorf("unsupported requested token type: %s", requestedType) - } -} - -// exchangeUCAN exchanges a UCAN token for another token type -func (h *TokenExchangeHandler) exchangeUCAN( - ctx context.Context, - req *TokenExchangeRequest, - client *OAuth2Client, - requestedType string, -) (*TokenExchangeResponse, error) { - // Verify the UCAN token - ucanToken, err := h.signer.VerifySignature(req.SubjectToken) - if err != nil { - return nil, fmt.Errorf("invalid UCAN token: %w", err) - } - - // Validate delegation chain if actor token is provided - if req.ActorToken != "" { - actorToken, err := h.signer.VerifySignature(req.ActorToken) - if err != nil { - return nil, fmt.Errorf("invalid actor token: %w", err) - } - - // Validate actor can act on behalf of subject - if actorToken.Audience != ucanToken.Issuer { - return nil, fmt.Errorf("actor token audience doesn't match subject issuer") - } - } - - // Extract scopes from UCAN - scopes := h.extractScopesFromUCAN(ucanToken) - - // Handle impersonation/delegation if actor token is present - issuer := ucanToken.Issuer - clientDID := client.ClientID - if did, ok := client.Metadata["client_did"]; ok { - clientDID = did - } - - if req.ActorToken != "" { - // Actor is performing action on behalf of subject - issuer = clientDID // Actor becomes the new issuer - } - - // Create response based on requested type - switch requestedType { - case TokenTypeAccessToken: - return h.createAccessTokenResponse(ctx, issuer, clientDID, scopes) - case TokenTypeUCAN: - // Create delegated UCAN with proof chain - proofs := []ucan.Proof{ucan.Proof(req.SubjectToken)} - if req.ActorToken != "" { - proofs = append(proofs, ucan.Proof(req.ActorToken)) - } - return h.createDelegatedUCANResponse(ctx, issuer, clientDID, scopes, proofs) - default: - return nil, fmt.Errorf("unsupported requested token type: %s", requestedType) - } -} - -// createUCANResponse creates a UCAN token response -func (h *TokenExchangeHandler) createUCANResponse( - ctx context.Context, - issuer, audience string, - scopes []string, - proof string, -) (*TokenExchangeResponse, error) { - // Create UCAN token with delegation - ucanToken, err := h.delegator.CreateDelegation( - issuer, - audience, - scopes, - time.Now().Add(time.Hour), - ) - if err != nil { - return nil, fmt.Errorf("failed to create UCAN token: %w", err) - } - - // Add proof if provided - if proof != "" { - ucanToken.Proofs = []ucan.Proof{ucan.Proof(proof)} - } - - // Sign the token - signedToken, err := h.signer.Sign(ucanToken) - if err != nil { - return nil, fmt.Errorf("failed to sign UCAN token: %w", err) - } - - return &TokenExchangeResponse{ - AccessToken: signedToken, - IssuedTokenType: TokenTypeUCAN, - TokenType: "Bearer", - ExpiresIn: 3600, - Scope: strings.Join(scopes, " "), - }, nil -} - -// createDelegatedUCANResponse creates a delegated UCAN token with proof chain -func (h *TokenExchangeHandler) createDelegatedUCANResponse( - ctx context.Context, - issuer, audience string, - scopes []string, - proofs []ucan.Proof, -) (*TokenExchangeResponse, error) { - // Build resource context - resourceContext := map[string]string{ - "delegation_type": "token_exchange", - "issued_at": fmt.Sprintf("%d", time.Now().Unix()), - } - - // Map scopes to attenuations - attenuations := h.delegator.scopeMapper.MapToUCAN(scopes, issuer, audience, resourceContext) - - // Create UCAN token with proof chain - ucanToken := &ucan.Token{ - Issuer: issuer, - Audience: audience, - ExpiresAt: time.Now().Add(time.Hour).Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Proofs: proofs, - Facts: []ucan.Fact{ - { - Data: h.createTokenExchangeFact(scopes), - }, - }, - } - - // Sign the token - signedToken, err := h.signer.Sign(ucanToken) - if err != nil { - return nil, fmt.Errorf("failed to sign delegated UCAN token: %w", err) - } - - return &TokenExchangeResponse{ - AccessToken: signedToken, - IssuedTokenType: TokenTypeUCAN, - TokenType: "Bearer", - ExpiresIn: 3600, - Scope: strings.Join(scopes, " "), - }, nil -} - -// createAccessTokenResponse creates a standard OAuth access token response -func (h *TokenExchangeHandler) createAccessTokenResponse( - ctx context.Context, - userDID, clientID string, - scopes []string, -) (*TokenExchangeResponse, error) { - // Create UCAN-backed access token - ucanToken, err := h.delegator.CreateDelegation( - userDID, - clientID, - scopes, - time.Now().Add(time.Hour), - ) - if err != nil { - return nil, fmt.Errorf("failed to create access token: %w", err) - } - - // Generate token ID - tokenID := h.generateTokenID() - - // Store token - storedToken := &StoredToken{ - TokenID: tokenID, - TokenType: "access_token", - AccessToken: tokenID, - ExpiresAt: time.Now().Add(time.Hour), - Scopes: scopes, - ClientID: clientID, - UserDID: userDID, - UCANToken: ucanToken.Raw, - } - - if err := h.tokenStore.StoreToken(ctx, storedToken); err != nil { - return nil, fmt.Errorf("failed to store token: %w", err) - } - - // Generate refresh token - refreshTokenID := h.generateTokenID() - refreshToken := &StoredToken{ - TokenID: refreshTokenID, - TokenType: "refresh_token", - RefreshToken: refreshTokenID, - ExpiresAt: time.Now().Add(30 * 24 * time.Hour), // 30 days - Scopes: scopes, - ClientID: clientID, - UserDID: userDID, - } - - if err := h.tokenStore.StoreToken(ctx, refreshToken); err != nil { - // Non-fatal, continue without refresh token - refreshTokenID = "" - } - - response := &TokenExchangeResponse{ - AccessToken: tokenID, - IssuedTokenType: TokenTypeAccessToken, - TokenType: "Bearer", - ExpiresIn: 3600, - Scope: strings.Join(scopes, " "), - } - - if refreshTokenID != "" { - response.RefreshToken = refreshTokenID - } - - return response, nil -} - -// extractScopesFromUCAN extracts OAuth scopes from UCAN attenuations -func (h *TokenExchangeHandler) extractScopesFromUCAN(token *ucan.Token) []string { - scopeMap := make(map[string]bool) - - for _, att := range token.Attenuations { - scheme := att.Resource.GetScheme() - actions := att.Capability.GetActions() - - // Map UCAN capabilities back to OAuth scopes - for _, action := range actions { - scope := h.mapUCANToScope(scheme, action) - if scope != "" { - scopeMap[scope] = true - } - } - } - - scopes := make([]string, 0, len(scopeMap)) - for scope := range scopeMap { - scopes = append(scopes, scope) - } - - return scopes -} - -// mapUCANToScope maps UCAN capability to OAuth scope -func (h *TokenExchangeHandler) mapUCANToScope(scheme, action string) string { - // Reverse mapping from UCAN to OAuth scopes - switch scheme { - case "vault": - switch action { - case "read": - return "vault:read" - case "write": - return "vault:write" - case "sign": - return "vault:sign" - case "*", "admin": - return "vault:admin" - } - case "service", "svc": - switch action { - case "read": - return "service:read" - case "write": - return "service:write" - case "*", "admin": - return "service:manage" - } - case "did": - switch action { - case "read": - return "did:read" - case "write", "update": - return "did:write" - } - case "dwn": - switch action { - case "read": - return "dwn:read" - case "write": - return "dwn:write" - } - } - - // Default mapping - return fmt.Sprintf("%s:%s", scheme, action) -} - -// isScopeSubset checks if requested scopes are subset of allowed scopes -func (h *TokenExchangeHandler) isScopeSubset(requested, allowed []string) bool { - allowedMap := make(map[string]bool) - for _, scope := range allowed { - allowedMap[scope] = true - } - - for _, scope := range requested { - if !allowedMap[scope] { - // Check if parent scope is allowed - if !h.isParentScopeAllowed(scope, allowed) { - return false - } - } - } - - return true -} - -// isParentScopeAllowed checks if a parent scope grants the requested scope -func (h *TokenExchangeHandler) isParentScopeAllowed(requested string, allowed []string) bool { - for _, scope := range allowed { - if h.delegator.scopeMapper.IsHierarchicalScope(scope, requested) { - return true - } - } - return false -} - -// createTokenExchangeFact creates a fact for token exchange -func (h *TokenExchangeHandler) createTokenExchangeFact(scopes []string) json.RawMessage { - fact := map[string]any{ - "type": "token_exchange", - "scopes": scopes, - "issued_at": time.Now().Unix(), - "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", - } - - data, _ := json.Marshal(fact) - return json.RawMessage(data) -} - -// generateTokenID generates a unique token identifier -func (h *TokenExchangeHandler) generateTokenID() string { - // In production, use a proper UUID or random generator - return fmt.Sprintf("tok_%d_%s", time.Now().UnixNano(), h.randomString(16)) -} - -// randomString generates a random string of specified length -func (h *TokenExchangeHandler) randomString(length int) string { - const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - result := make([]byte, length) - for i := range result { - result[i] = charset[time.Now().UnixNano()%int64(len(charset))] - } - return string(result) -} - -// sendError sends an OAuth error response -func (h *TokenExchangeHandler) sendError( - w http.ResponseWriter, - errorCode, errorDescription string, -) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Pragma", "no-cache") - w.WriteHeader(http.StatusBadRequest) - - response := map[string]string{ - "error": errorCode, - "error_description": errorDescription, - } - - json.NewEncoder(w).Encode(response) -} diff --git a/bridge/handlers/oauth2_types.go b/bridge/handlers/oauth2_types.go deleted file mode 100644 index c13b42616..000000000 --- a/bridge/handlers/oauth2_types.go +++ /dev/null @@ -1,269 +0,0 @@ -package handlers - -import ( - "encoding/json" - "time" - - "github.com/sonr-io/sonr/crypto/ucan" -) - -// OAuth2Client represents a registered OAuth2 client application -type OAuth2Client struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret,omitempty"` - ClientType string `json:"client_type"` // "confidential" or "public" - RedirectURIs []string `json:"redirect_uris"` - AllowedScopes []string `json:"allowed_scopes"` - AllowedGrants []string `json:"allowed_grants"` - TokenLifetime time.Duration `json:"token_lifetime"` - RequirePKCE bool `json:"require_pkce"` - TrustedClient bool `json:"trusted_client"` - RequiresConsent bool `json:"requires_consent"` - Metadata map[string]string `json:"metadata"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// OAuth2AuthorizationRequest represents an OAuth2 authorization request -type OAuth2AuthorizationRequest struct { - ResponseType string `json:"response_type" form:"response_type" query:"response_type"` - ClientID string `json:"client_id" form:"client_id" query:"client_id"` - RedirectURI string `json:"redirect_uri" form:"redirect_uri" query:"redirect_uri"` - Scope string `json:"scope" form:"scope" query:"scope"` - State string `json:"state" form:"state" query:"state"` - CodeChallenge string `json:"code_challenge" form:"code_challenge" query:"code_challenge"` - CodeChallengeMethod string `json:"code_challenge_method" form:"code_challenge_method" query:"code_challenge_method"` - Nonce string `json:"nonce" form:"nonce" query:"nonce"` - Prompt string `json:"prompt" form:"prompt" query:"prompt"` - MaxAge int `json:"max_age" form:"max_age" query:"max_age"` - LoginHint string `json:"login_hint" form:"login_hint" query:"login_hint"` -} - -// OAuth2TokenRequest represents an OAuth2 token exchange request -type OAuth2TokenRequest struct { - GrantType string `json:"grant_type" form:"grant_type"` - Code string `json:"code" form:"code"` - RedirectURI string `json:"redirect_uri" form:"redirect_uri"` - ClientID string `json:"client_id" form:"client_id"` - ClientSecret string `json:"client_secret" form:"client_secret"` - CodeVerifier string `json:"code_verifier" form:"code_verifier"` - RefreshToken string `json:"refresh_token" form:"refresh_token"` - Scope string `json:"scope" form:"scope"` - Username string `json:"username" form:"username"` - Password string `json:"password" form:"password"` - Assertion string `json:"assertion" form:"assertion"` - ClientAssertion string `json:"client_assertion" form:"client_assertion"` - ClientAssertionType string `json:"client_assertion_type" form:"client_assertion_type"` -} - -// OAuth2TokenResponse represents an OAuth2 token response -type OAuth2TokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - RefreshToken string `json:"refresh_token,omitempty"` - Scope string `json:"scope,omitempty"` - IDToken string `json:"id_token,omitempty"` - UCANToken string `json:"ucan_token,omitempty"` // UCAN delegation token -} - -// OAuth2ErrorResponse represents an OAuth2 error response -type OAuth2ErrorResponse struct { - Error string `json:"error"` - ErrorDescription string `json:"error_description,omitempty"` - ErrorURI string `json:"error_uri,omitempty"` - State string `json:"state,omitempty"` -} - -// OAuth2AuthorizationCode represents an authorization code with UCAN context -type OAuth2AuthorizationCode struct { - Code string `json:"code"` - ClientID string `json:"client_id"` - UserDID string `json:"user_did"` - RedirectURI string `json:"redirect_uri"` - Scopes []string `json:"scopes"` - State string `json:"state"` - Nonce string `json:"nonce"` - CodeChallenge string `json:"code_challenge"` - CodeChallengeMethod string `json:"code_challenge_method"` - ExpiresAt time.Time `json:"expires_at"` - Used bool `json:"used"` - UCANContext *UCANAuthContext `json:"ucan_context"` -} - -// UCANAuthContext holds UCAN-related data for authorization -type UCANAuthContext struct { - VaultAddress string `json:"vault_address"` - EnclaveDataCID string `json:"enclave_data_cid"` - DIDDocument json.RawMessage `json:"did_document"` - Capabilities []string `json:"capabilities"` -} - -// OAuth2AccessToken represents an access token with embedded UCAN -type OAuth2AccessToken struct { - Token string `json:"token"` - UserDID string `json:"user_did"` - ClientID string `json:"client_id"` - Scopes []string `json:"scopes"` - ExpiresAt time.Time `json:"expires_at"` - IssuedAt time.Time `json:"issued_at"` - UCANToken *ucan.Token `json:"ucan_token"` - SessionID string `json:"session_id"` - TokenType string `json:"token_type"` -} - -// OAuth2RefreshToken represents a refresh token -type OAuth2RefreshToken struct { - Token string `json:"token"` - AccessToken string `json:"access_token"` - ClientID string `json:"client_id"` - UserDID string `json:"user_did"` - Scopes []string `json:"scopes"` - ExpiresAt time.Time `json:"expires_at"` - IssuedAt time.Time `json:"issued_at"` - RotationCount int `json:"rotation_count"` -} - -// OAuth2Session extends OIDCSession with OAuth2-specific fields -type OAuth2Session struct { - SessionID string `json:"session_id"` - UserDID string `json:"user_did"` - ClientID string `json:"client_id"` - Scopes []string `json:"scopes"` - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - IDToken string `json:"id_token,omitempty"` - UCANToken *ucan.Token `json:"ucan_token"` - ConsentGiven bool `json:"consent_given"` - ConsentScopes []string `json:"consent_scopes"` - ExpiresAt time.Time `json:"expires_at"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// OAuth2ConsentRequest represents a consent request for a client -type OAuth2ConsentRequest struct { - UserDID string `json:"user_did"` - ClientID string `json:"client_id"` - RequestedScopes []string `json:"requested_scopes"` - ConsentID string `json:"consent_id"` - CreatedAt time.Time `json:"created_at"` -} - -// OAuth2ConsentResponse represents a user's consent response -type OAuth2ConsentResponse struct { - ConsentID string `json:"consent_id"` - Approved bool `json:"approved"` - ApprovedScopes []string `json:"approved_scopes"` - RememberChoice bool `json:"remember_choice"` -} - -// OAuth2ScopeDefinition defines an OAuth scope and its UCAN mapping -type OAuth2ScopeDefinition struct { - Name string `json:"name"` - Description string `json:"description"` - UCANActions []string `json:"ucan_actions"` - ResourceType string `json:"resource_type"` - RequiresAuth bool `json:"requires_auth"` - Sensitive bool `json:"sensitive"` - ParentScope string `json:"parent_scope,omitempty"` - ChildScopes []string `json:"child_scopes,omitempty"` - Metadata map[string]any `json:"metadata"` -} - -// OAuth2ClientRegistrationRequest represents a dynamic client registration request -type OAuth2ClientRegistrationRequest struct { - ClientName string `json:"client_name"` - ClientType string `json:"client_type"` // "confidential" or "public" - RedirectURIs []string `json:"redirect_uris"` - GrantTypes []string `json:"grant_types,omitempty"` - ResponseTypes []string `json:"response_types,omitempty"` - Scopes string `json:"scopes,omitempty"` - TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"` - LogoURI string `json:"logo_uri,omitempty"` - ClientURI string `json:"client_uri,omitempty"` - PolicyURI string `json:"policy_uri,omitempty"` - TOSUri string `json:"tos_uri,omitempty"` - Contacts []string `json:"contacts,omitempty"` -} - -// OAuth2ClientRegistrationResponse represents a successful client registration -type OAuth2ClientRegistrationResponse struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret,omitempty"` - ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"` - ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"` - RegistrationAccessToken string `json:"registration_access_token,omitempty"` - RegistrationClientURI string `json:"registration_client_uri,omitempty"` -} - -// OAuth2IntrospectionRequest represents a token introspection request -type OAuth2IntrospectionRequest struct { - Token string `json:"token" form:"token"` - TokenTypeHint string `json:"token_type_hint" form:"token_type_hint"` - ClientID string `json:"client_id" form:"client_id"` - ClientSecret string `json:"client_secret" form:"client_secret"` -} - -// OAuth2IntrospectionResponse represents a token introspection response -type OAuth2IntrospectionResponse struct { - Active bool `json:"active"` - Scope string `json:"scope,omitempty"` - ClientID string `json:"client_id,omitempty"` - Username string `json:"username,omitempty"` - TokenType string `json:"token_type,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` - Audience []string `json:"aud,omitempty"` - Issuer string `json:"iss,omitempty"` - JWTID string `json:"jti,omitempty"` - UCANToken string `json:"ucan_token,omitempty"` -} - -// OAuth2RevocationRequest represents a token revocation request -type OAuth2RevocationRequest struct { - Token string `json:"token" form:"token"` - TokenTypeHint string `json:"token_type_hint" form:"token_type_hint"` - ClientID string `json:"client_id" form:"client_id"` - ClientSecret string `json:"client_secret" form:"client_secret"` -} - -// OAuth2Config extends OIDCConfig with OAuth2-specific endpoints -type OAuth2Config struct { - Issuer string `json:"issuer"` - AuthorizationEndpoint string `json:"authorization_endpoint"` - TokenEndpoint string `json:"token_endpoint"` - UserInfoEndpoint string `json:"userinfo_endpoint"` - JWKSEndpoint string `json:"jwks_uri"` - RegistrationEndpoint string `json:"registration_endpoint"` - IntrospectionEndpoint string `json:"introspection_endpoint"` - RevocationEndpoint string `json:"revocation_endpoint"` - ScopesSupported []string `json:"scopes_supported"` - ResponseTypesSupported []string `json:"response_types_supported"` - ResponseModesSupported []string `json:"response_modes_supported,omitempty"` - GrantTypesSupported []string `json:"grant_types_supported"` - SubjectTypesSupported []string `json:"subject_types_supported"` - IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"` - TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"` - TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"` - ClaimsSupported []string `json:"claims_supported"` - CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"` - ServiceDocumentation string `json:"service_documentation,omitempty"` - UILocalesSupported []string `json:"ui_locales_supported,omitempty"` - OpPolicyURI string `json:"op_policy_uri,omitempty"` - OpTosURI string `json:"op_tos_uri,omitempty"` - UCANSupported bool `json:"ucan_supported"` // Custom field for UCAN support -} - -// TokenValidationResult represents the result of token validation -type TokenValidationResult struct { - Valid bool `json:"valid"` - UserDID string `json:"user_did"` - ClientID string `json:"client_id"` - Scopes []string `json:"scopes"` - UCANToken *ucan.Token `json:"ucan_token,omitempty"` - ExpiresAt time.Time `json:"expires_at"` - Error string `json:"error,omitempty"` -} diff --git a/bridge/handlers/oidc.go b/bridge/handlers/oidc.go deleted file mode 100644 index 508cdecc2..000000000 --- a/bridge/handlers/oidc.go +++ /dev/null @@ -1,466 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/labstack/echo/v4" -) - -// OIDCProvider manages OIDC operations -type OIDCProvider struct { - mu sync.RWMutex - codes map[string]*AuthorizationCode - sessions map[string]*OIDCSession - config any // TODO: Use bridge.OIDCProviderConfig -} - -var ( - oidcProvider = &OIDCProvider{ - codes: make(map[string]*AuthorizationCode), - sessions: make(map[string]*OIDCSession), - } - codeExpiration = 10 * time.Minute -) - -// SetOIDCConfig sets the OIDC provider configuration -func SetOIDCConfig(config any) { - oidcProvider.mu.Lock() - defer oidcProvider.mu.Unlock() - oidcProvider.config = config -} - -// GetOIDCDiscovery returns OIDC discovery configuration -func GetOIDCDiscovery(c echo.Context) error { - config := &OIDCConfig{ - Issuer: "https://localhost:8080", - AuthorizationEndpoint: "https://localhost:8080/oidc/authorize", - TokenEndpoint: "https://localhost:8080/oidc/token", - UserInfoEndpoint: "https://localhost:8080/oidc/userinfo", - JWKSEndpoint: "https://localhost:8080/oidc/jwks", - RevocationEndpoint: "https://localhost:8080/oidc/revoke", - IntrospectionEndpoint: "https://localhost:8080/oidc/introspect", - ScopesSupported: []string{ - "openid", "profile", "email", "did", "vault", "offline_access", - }, - ResponseTypesSupported: []string{ - "code", "id_token", "code id_token", - }, - GrantTypesSupported: []string{ - "authorization_code", "refresh_token", "client_credentials", - }, - SubjectTypesSupported: []string{ - "public", "pairwise", - }, - IDTokenSigningAlgValuesSupported: []string{ - "ES256", "RS256", - }, - TokenEndpointAuthMethodsSupported: []string{ - "client_secret_post", "client_secret_basic", "none", - }, - ClaimsSupported: []string{ - "sub", "name", "preferred_username", "email", "email_verified", - "did", "vault_id", "updated_at", - }, - CodeChallengeMethodsSupported: []string{ - "S256", "plain", - }, - } - - return c.JSON(http.StatusOK, config) -} - -// HandleOIDCAuthorization handles OIDC authorization requests -func HandleOIDCAuthorization(c echo.Context) error { - // Parse request parameters from query string for GET or form for POST - req := OIDCAuthorizationRequest{ - ResponseType: c.QueryParam("response_type"), - ClientID: c.QueryParam("client_id"), - RedirectURI: c.QueryParam("redirect_uri"), - Scope: c.QueryParam("scope"), - State: c.QueryParam("state"), - Nonce: c.QueryParam("nonce"), - CodeChallenge: c.QueryParam("code_challenge"), - CodeChallengeMethod: c.QueryParam("code_challenge_method"), - } - - // If no query params, try to bind from body (for POST requests) - if req.ResponseType == "" { - _ = c.Bind(&req) // Ignore bind errors and continue - } - - // Validate required parameters - if req.ResponseType == "" || req.ClientID == "" || req.RedirectURI == "" || req.Scope == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Missing required parameters", - }) - } - - // Validate response type - if req.ResponseType != "code" && req.ResponseType != "id_token" && - req.ResponseType != "code id_token" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "unsupported_response_type", - "error_description": "Response type not supported", - }) - } - - // Validate scope includes openid - if !strings.Contains(req.Scope, "openid") { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_scope", - "error_description": "Scope must include 'openid'", - }) - } - - // TODO: Validate client_id and redirect_uri against registered clients - - // For now, assume user is authenticated (in production, redirect to login) - userDID := c.Get("user_did") - if userDID == nil { - // Redirect to WebAuthn authentication - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "authentication_required", - "error_description": "User authentication required", - }) - } - - // Generate authorization code - code := generateAuthorizationCode() - - // Store authorization code - authCode := &AuthorizationCode{ - Code: code, - ClientID: req.ClientID, - RedirectURI: req.RedirectURI, - UserDID: userDID.(string), - Scope: req.Scope, - Nonce: req.Nonce, - CodeChallenge: req.CodeChallenge, - CodeChallengeMethod: req.CodeChallengeMethod, - ExpiresAt: time.Now().Add(codeExpiration), - Used: false, - } - - oidcProvider.mu.Lock() - oidcProvider.codes[code] = authCode - oidcProvider.mu.Unlock() - - // Build redirect URL - redirectURL := fmt.Sprintf("%s?code=%s&state=%s", req.RedirectURI, code, req.State) - - return c.Redirect(http.StatusFound, redirectURL) -} - -// HandleOIDCToken handles OIDC token requests -func HandleOIDCToken(c echo.Context) error { - var req OIDCTokenRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Invalid token request", - }) - } - - // Handle different grant types - switch req.GrantType { - case "authorization_code": - return handleAuthorizationCodeGrant(c, &req) - case "refresh_token": - return handleRefreshTokenGrant(c, &req) - case "client_credentials": - return handleClientCredentialsGrant(c, &req) - default: - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "unsupported_grant_type", - "error_description": "Grant type not supported", - }) - } -} - -// handleAuthorizationCodeGrant processes authorization code grant -func handleAuthorizationCodeGrant(c echo.Context, req *OIDCTokenRequest) error { - if req.Code == "" || req.RedirectURI == "" || req.ClientID == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Missing required parameters", - }) - } - - // Retrieve and validate authorization code - oidcProvider.mu.Lock() - authCode, exists := oidcProvider.codes[req.Code] - if exists { - delete(oidcProvider.codes, req.Code) // Single use - } - oidcProvider.mu.Unlock() - - if !exists { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Invalid authorization code", - }) - } - - // Validate code hasn't expired - if time.Now().After(authCode.ExpiresAt) { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Authorization code expired", - }) - } - - // Validate code hasn't been used - if authCode.Used { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Authorization code already used", - }) - } - - // Validate client and redirect URI - if authCode.ClientID != req.ClientID || authCode.RedirectURI != req.RedirectURI { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Invalid client or redirect URI", - }) - } - - // Validate PKCE if present - if authCode.CodeChallenge != "" { - if req.CodeVerifier == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Code verifier required", - }) - } - - if !verifyPKCE(req.CodeVerifier, authCode.CodeChallenge, authCode.CodeChallengeMethod) { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_grant", - "error_description": "Invalid code verifier", - }) - } - } - - // Mark code as used - authCode.Used = true - - // Generate tokens - accessToken := generateAccessToken(authCode.UserDID) - refreshToken := generateRefreshToken() - idToken, err := generateIDToken(authCode.UserDID, authCode.ClientID, authCode.Nonce) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "server_error", - "error_description": "Failed to generate ID token", - }) - } - - // Create session - session := &OIDCSession{ - SessionID: generateSessionID(), - UserDID: authCode.UserDID, - ClientID: authCode.ClientID, - Scope: authCode.Scope, - Nonce: authCode.Nonce, - AccessToken: accessToken, - RefreshToken: refreshToken, - IDToken: idToken, - ExpiresAt: time.Now().Add(time.Hour), - CreatedAt: time.Now(), - } - - oidcProvider.mu.Lock() - oidcProvider.sessions[accessToken] = session - oidcProvider.mu.Unlock() - - // Return tokens - response := &OIDCTokenResponse{ - AccessToken: accessToken, - TokenType: "Bearer", - ExpiresIn: 3600, - RefreshToken: refreshToken, - IDToken: idToken, - Scope: authCode.Scope, - } - - return c.JSON(http.StatusOK, response) -} - -// handleRefreshTokenGrant processes refresh token grant -func handleRefreshTokenGrant(c echo.Context, req *OIDCTokenRequest) error { - // TODO: Implement refresh token grant - return c.JSON(http.StatusNotImplemented, map[string]string{ - "error": "unsupported_grant_type", - "error_description": "Refresh token grant not yet implemented", - }) -} - -// handleClientCredentialsGrant processes client credentials grant -func handleClientCredentialsGrant(c echo.Context, req *OIDCTokenRequest) error { - // TODO: Implement client credentials grant - return c.JSON(http.StatusNotImplemented, map[string]string{ - "error": "unsupported_grant_type", - "error_description": "Client credentials grant not yet implemented", - }) -} - -// HandleOIDCUserInfo handles OIDC userinfo requests -func HandleOIDCUserInfo(c echo.Context) error { - // Extract access token from Authorization header - authHeader := c.Request().Header.Get("Authorization") - if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "invalid_token", - "error_description": "Invalid access token", - }) - } - - accessToken := strings.TrimPrefix(authHeader, "Bearer ") - - // Validate access token - oidcProvider.mu.RLock() - session, exists := oidcProvider.sessions[accessToken] - oidcProvider.mu.RUnlock() - - if !exists { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "invalid_token", - "error_description": "Invalid or expired access token", - }) - } - - // Check if token is expired - if time.Now().After(session.ExpiresAt) { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "invalid_token", - "error_description": "Access token expired", - }) - } - - // TODO: Fetch actual user info from DID document or database - userInfo := &OIDCUserInfo{ - Subject: session.UserDID, - PreferredUsername: "user", // TODO: Get from DID document - DID: session.UserDID, - UpdatedAt: time.Now().Unix(), - } - - // Add additional claims based on scope - if strings.Contains(session.Scope, "profile") { - userInfo.Name = "User Name" // TODO: Get from DID document - } - - if strings.Contains(session.Scope, "email") { - userInfo.Email = "user@example.com" // TODO: Get from DID document - userInfo.EmailVerified = true - } - - if strings.Contains(session.Scope, "vault") { - userInfo.VaultID = "vault_" + session.UserDID // TODO: Get actual vault ID - } - - return c.JSON(http.StatusOK, userInfo) -} - -// HandleOIDCJWKS handles JWKS endpoint -func HandleOIDCJWKS(c echo.Context) error { - // TODO: Return actual public keys used for signing - jwks := &JWKSet{ - Keys: []JWK{ - { - KeyType: "EC", - Use: "sig", - KeyID: "1", - Algorithm: "ES256", - Curve: "P-256", - // TODO: Add actual public key coordinates - }, - }, - } - - return c.JSON(http.StatusOK, jwks) -} - -// Helper functions - -func generateAuthorizationCode() string { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -func generateAccessToken(userDID string) string { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -func generateRefreshToken() string { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -func generateSessionID() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -func generateIDToken(userDID, clientID, nonce string) (string, error) { - claims := &DIDAuthClaims{ - RegisteredClaims: jwt.RegisteredClaims{ - Subject: userDID, - Issuer: "https://localhost:8080", - Audience: []string{clientID}, - ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)), - IssuedAt: jwt.NewNumericDate(time.Now()), - NotBefore: jwt.NewNumericDate(time.Now()), - }, - DID: userDID, - } - - if nonce != "" { - claims.Extra = map[string]any{ - "nonce": nonce, - } - } - - // TODO: Sign with actual signing key - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - return token.SignedString([]byte("temporary-secret-key")) -} - -func verifyPKCE(verifier, challenge, method string) bool { - var computed string - - switch method { - case "S256": - h := sha256.Sum256([]byte(verifier)) - computed = base64.RawURLEncoding.EncodeToString(h[:]) - case "plain": - computed = verifier - default: - return false - } - - return computed == challenge -} diff --git a/bridge/handlers/oidc_test.go b/bridge/handlers/oidc_test.go deleted file mode 100644 index ac37895d8..000000000 --- a/bridge/handlers/oidc_test.go +++ /dev/null @@ -1,360 +0,0 @@ -package handlers - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// TestOIDCDiscovery tests the OIDC discovery endpoint -func TestOIDCDiscovery(t *testing.T) { - e := echo.New() - req := httptest.NewRequest(http.MethodGet, "/.well-known/openid-configuration", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := GetOIDCDiscovery(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, rec.Code) - - var config OIDCConfig - err = json.Unmarshal(rec.Body.Bytes(), &config) - assert.NoError(t, err) - - // Verify required fields - assert.NotEmpty(t, config.Issuer) - assert.NotEmpty(t, config.AuthorizationEndpoint) - assert.NotEmpty(t, config.TokenEndpoint) - assert.NotEmpty(t, config.UserInfoEndpoint) - assert.NotEmpty(t, config.JWKSEndpoint) - assert.Contains(t, config.ScopesSupported, "openid") - assert.Contains(t, config.ResponseTypesSupported, "code") - assert.Contains(t, config.GrantTypesSupported, "authorization_code") -} - -// TestOIDCAuthorizationFlow tests the authorization code flow -func TestOIDCAuthorizationFlow(t *testing.T) { - e := echo.New() - - t.Run("ValidAuthorizationRequest", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "code") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid profile") - q.Set("state", "test-state") - q.Set("nonce", "test-nonce") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - // Set authenticated user context - c.Set("user_did", "did:sonr:testuser") - c.Set("authenticated", true) - - err := HandleOIDCAuthorization(c) - assert.NoError(t, err) - - // Should redirect with authorization code - assert.Equal(t, http.StatusFound, rec.Code) - location := rec.Header().Get("Location") - assert.Contains(t, location, "code=") - assert.Contains(t, location, "state=test-state") - }) - - t.Run("MissingRequiredParameters", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/authorize", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleOIDCAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "invalid_request", errorResp["error"]) - }) - - t.Run("InvalidResponseType", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "invalid") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleOIDCAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - }) -} - -// TestOIDCTokenExchange tests the token endpoint -func TestOIDCTokenExchange(t *testing.T) { - e := echo.New() - - // Setup: Create an authorization code - code := "test-auth-code" - authCode := &AuthorizationCode{ - Code: code, - ClientID: "test-client", - RedirectURI: "http://localhost:3000/callback", - UserDID: "did:sonr:testuser", - Scope: "openid profile", - ExpiresAt: time.Now().Add(10 * time.Minute), - CodeChallenge: "test-challenge", - CodeChallengeMethod: "S256", - } - - oidcProvider.mu.Lock() - oidcProvider.codes[code] = authCode - oidcProvider.mu.Unlock() - - t.Run("ValidTokenExchange", func(t *testing.T) { - body := strings.NewReader("grant_type=authorization_code&code=" + code + - "&redirect_uri=http://localhost:3000/callback&client_id=test-client" + - "&code_verifier=test-verifier") - - req := httptest.NewRequest(http.MethodPost, "/oidc/token", body) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - tokenReq := &OIDCTokenRequest{ - GrantType: "authorization_code", - Code: code, - RedirectURI: "http://localhost:3000/callback", - ClientID: "test-client", - CodeVerifier: "test-verifier", - } - - err := handleAuthorizationCodeGrant(c, tokenReq) - assert.NoError(t, err) - - if rec.Code == http.StatusOK { - var tokenResp OIDCTokenResponse - err = json.Unmarshal(rec.Body.Bytes(), &tokenResp) - assert.NoError(t, err) - assert.NotEmpty(t, tokenResp.AccessToken) - assert.NotEmpty(t, tokenResp.IDToken) - assert.Equal(t, "Bearer", tokenResp.TokenType) - } - }) - - t.Run("ExpiredAuthorizationCode", func(t *testing.T) { - expiredCode := "expired-code" - expiredAuthCode := &AuthorizationCode{ - Code: expiredCode, - ClientID: "test-client", - RedirectURI: "http://localhost:3000/callback", - UserDID: "did:sonr:testuser", - ExpiresAt: time.Now().Add(-1 * time.Hour), // Expired - } - - oidcProvider.mu.Lock() - oidcProvider.codes[expiredCode] = expiredAuthCode - oidcProvider.mu.Unlock() - - tokenReq := &OIDCTokenRequest{ - GrantType: "authorization_code", - Code: expiredCode, - RedirectURI: "http://localhost:3000/callback", - ClientID: "test-client", - } - - req := httptest.NewRequest(http.MethodPost, "/oidc/token", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := handleAuthorizationCodeGrant(c, tokenReq) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - }) -} - -// TestOIDCUserInfo tests the userinfo endpoint -func TestOIDCUserInfo(t *testing.T) { - e := echo.New() - - // Setup: Create a session - accessToken := "test-access-token" - session := &OIDCSession{ - SessionID: "test-session", - UserDID: "did:sonr:testuser", - ClientID: "test-client", - Scope: "openid profile email", - AccessToken: accessToken, - RefreshToken: "test-refresh-token", - ExpiresAt: time.Now().Add(1 * time.Hour), - CreatedAt: time.Now(), - } - - oidcProvider.mu.Lock() - oidcProvider.sessions[accessToken] = session - oidcProvider.mu.Unlock() - - t.Run("ValidUserInfoRequest", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/userinfo", nil) - req.Header.Set("Authorization", "Bearer "+accessToken) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleOIDCUserInfo(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, rec.Code) - - var userInfo map[string]any - err = json.Unmarshal(rec.Body.Bytes(), &userInfo) - assert.NoError(t, err) - assert.Equal(t, "did:sonr:testuser", userInfo["sub"]) - }) - - t.Run("InvalidAccessToken", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/userinfo", nil) - req.Header.Set("Authorization", "Bearer invalid-token") - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleOIDCUserInfo(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusUnauthorized, rec.Code) - }) - - t.Run("MissingAuthorizationHeader", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/userinfo", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleOIDCUserInfo(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusUnauthorized, rec.Code) - }) -} - -// TestPKCEFlow tests PKCE (Proof Key for Code Exchange) implementation -func TestPKCEFlow(t *testing.T) { - e := echo.New() - - // Generate PKCE parameters - codeVerifier := "test-code-verifier-string-that-is-long-enough" - codeChallenge := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" // SHA256 of verifier - - t.Run("AuthorizationWithPKCE", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/oidc/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "code") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid") - q.Set("code_challenge", codeChallenge) - q.Set("code_challenge_method", "S256") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - c.Set("user_did", "did:sonr:testuser") - c.Set("authenticated", true) - - err := HandleOIDCAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusFound, rec.Code) - }) - - t.Run("TokenExchangeWithPKCE", func(t *testing.T) { - // Create auth code with PKCE - code := "pkce-auth-code" - authCode := &AuthorizationCode{ - Code: code, - ClientID: "test-client", - RedirectURI: "http://localhost:3000/callback", - UserDID: "did:sonr:testuser", - CodeChallenge: codeChallenge, - CodeChallengeMethod: "S256", - ExpiresAt: time.Now().Add(10 * time.Minute), - } - - oidcProvider.mu.Lock() - oidcProvider.codes[code] = authCode - oidcProvider.mu.Unlock() - - tokenReq := &OIDCTokenRequest{ - GrantType: "authorization_code", - Code: code, - RedirectURI: "http://localhost:3000/callback", - ClientID: "test-client", - CodeVerifier: codeVerifier, - } - - req := httptest.NewRequest(http.MethodPost, "/oidc/token", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := handleAuthorizationCodeGrant(c, tokenReq) - require.NoError(t, err) - - // With correct verifier, should succeed - if rec.Code != http.StatusOK { - t.Logf("Response: %s", rec.Body.String()) - } - }) -} - -// TestRefreshTokenFlow tests refresh token functionality -func TestRefreshTokenFlow(t *testing.T) { - e := echo.New() - - // Create initial session with refresh token - refreshToken := "test-refresh-token" - session := &OIDCSession{ - SessionID: "test-session", - UserDID: "did:sonr:testuser", - ClientID: "test-client", - Scope: "openid profile offline_access", - AccessToken: "old-access-token", - RefreshToken: refreshToken, - ExpiresAt: time.Now().Add(-1 * time.Hour), // Expired access token - CreatedAt: time.Now().Add(-2 * time.Hour), - } - - oidcProvider.mu.Lock() - oidcProvider.sessions[refreshToken] = session - oidcProvider.mu.Unlock() - - t.Run("ValidRefreshToken", func(t *testing.T) { - tokenReq := &OIDCTokenRequest{ - GrantType: "refresh_token", - RefreshToken: refreshToken, - ClientID: "test-client", - } - - req := httptest.NewRequest(http.MethodPost, "/oidc/token", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := handleRefreshTokenGrant(c, tokenReq) - assert.NoError(t, err) - - if rec.Code == http.StatusOK { - var tokenResp OIDCTokenResponse - err = json.Unmarshal(rec.Body.Bytes(), &tokenResp) - assert.NoError(t, err) - assert.NotEmpty(t, tokenResp.AccessToken) - assert.NotEqual(t, "old-access-token", tokenResp.AccessToken) - } - }) -} diff --git a/bridge/handlers/siop.go b/bridge/handlers/siop.go deleted file mode 100644 index b8669546f..000000000 --- a/bridge/handlers/siop.go +++ /dev/null @@ -1,384 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/labstack/echo/v4" -) - -// SIOPProvider manages Self-Issued OpenID Provider operations -type SIOPProvider struct { - // No persistent state needed for SIOP as it's self-issued -} - -var siopProvider = &SIOPProvider{} - -// HandleSIOPAuthorization handles SIOP authorization requests -func HandleSIOPAuthorization(c echo.Context) error { - var req SIOPRequest - - // Check if request was already parsed by HandleSIOPRequest - if parsedReq := c.Get("siop_request"); parsedReq != nil { - req = *(parsedReq.(*SIOPRequest)) - } else { - // Parse request parameters from query string for GET or form for POST - req = SIOPRequest{ - ResponseType: c.QueryParam("response_type"), - ClientID: c.QueryParam("client_id"), - RedirectURI: c.QueryParam("redirect_uri"), - Scope: c.QueryParam("scope"), - Nonce: c.QueryParam("nonce"), - State: c.QueryParam("state"), - } - - // Parse claims if provided - if claimsStr := c.QueryParam("claims"); claimsStr != "" { - _ = json.Unmarshal([]byte(claimsStr), &req.Claims) // Ignore claims parsing errors - } - - // If no query params, try to bind from body (for POST requests) - if req.ResponseType == "" { - _ = c.Bind(&req) // Ignore bind errors and continue with empty request - } - } - - // Validate required parameters - if req.ResponseType == "" || req.ClientID == "" || req.RedirectURI == "" || - req.Scope == "" || req.Nonce == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Missing required parameters", - }) - } - - // Validate response type (SIOP v2 supports id_token) - if req.ResponseType != "id_token" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "unsupported_response_type", - "error_description": "SIOP only supports id_token response type", - }) - } - - // Validate scope includes openid - if !strings.Contains(req.Scope, "openid") { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_scope", - "error_description": "Scope must include 'openid'", - }) - } - - // Get user DID from context (assumes user is authenticated via WebAuthn) - userDID := c.Get("user_did") - if userDID == nil { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "authentication_required", - "error_description": "User authentication required for SIOP", - }) - } - - // Generate Self-Issued ID Token - idToken, err := generateSelfIssuedIDToken( - userDID.(string), - req.ClientID, - req.Nonce, - req.RedirectURI, - req.Claims, - ) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "server_error", - "error_description": "Failed to generate self-issued ID token", - }) - } - - // Build response - response := &SIOPResponse{ - IDToken: idToken, - State: req.State, - } - - // If VP token is requested, include it - if req.Claims.VPToken != nil { - vpToken, err := generateVPToken(userDID.(string), req.Claims.VPToken) - if err == nil { - response.VPToken = vpToken - } - } - - // Redirect back to client with response - redirectURL, err := buildSIOPRedirectURL(req.RedirectURI, response) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "server_error", - "error_description": "Failed to build redirect URL", - }) - } - - return c.Redirect(http.StatusFound, redirectURL) -} - -// HandleSIOPRegistration handles dynamic client registration for SIOP -func HandleSIOPRegistration(c echo.Context) error { - var registration SIOPRegistration - if err := c.Bind(®istration); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Invalid registration request", - }) - } - - // Validate registration parameters - if registration.ClientName == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Client name is required", - }) - } - - // Generate client ID for the registration - clientID := generateClientID() - - // Store registration (in production, persist this) - // For now, return the registration confirmation - response := map[string]any{ - "client_id": clientID, - "client_name": registration.ClientName, - "client_purpose": registration.ClientPurpose, - "logo_uri": registration.LogoURI, - "subject_syntax_types_supported": []string{"did"}, - "vp_formats": map[string]any{ - "jwt_vp": map[string]any{ - "alg": []string{"ES256", "EdDSA"}, - }, - "ldp_vp": map[string]any{ - "proof_type": []string{"Ed25519Signature2018"}, - }, - }, - } - - return c.JSON(http.StatusOK, response) -} - -// HandleSIOPMetadata returns SIOP provider metadata -func HandleSIOPMetadata(c echo.Context) error { - metadata := map[string]any{ - "issuer": "https://self-issued.me/v2", - "authorization_endpoint": "openid://", - "response_types_supported": []string{"id_token"}, - "scopes_supported": []string{ - "openid", - "profile", - "email", - "did", - }, - "subject_types_supported": []string{"pairwise"}, - "id_token_signing_alg_values_supported": []string{"ES256", "EdDSA"}, - "request_object_signing_alg_values_supported": []string{"ES256", "EdDSA"}, - "subject_syntax_types_supported": []string{ - "did:key", - "did:web", - "did:ion", - }, - "vp_formats_supported": map[string]any{ - "jwt_vp": map[string]any{ - "alg_values_supported": []string{"ES256", "EdDSA"}, - }, - "ldp_vp": map[string]any{ - "proof_type_values_supported": []string{"Ed25519Signature2018"}, - }, - }, - } - - return c.JSON(http.StatusOK, metadata) -} - -// generateSelfIssuedIDToken generates a self-issued ID token -func generateSelfIssuedIDToken( - userDID, clientID, nonce, redirectURI string, - requestedClaims SIOPClaims, -) (string, error) { - // Create base claims - claims := jwt.MapClaims{ - "iss": "https://self-issued.me/v2", - "sub": userDID, - "aud": clientID, - "exp": time.Now().Add(time.Hour).Unix(), - "iat": time.Now().Unix(), - "nonce": nonce, - "_sd_alg": "sha-256", // Selective disclosure algorithm - "sub_jwk": map[string]any{ - // TODO: Include actual public key from DID document - "kty": "EC", - "crv": "P-256", - "x": "placeholder_x", - "y": "placeholder_y", - }, - } - - // Add requested claims from ID token - if requestedClaims.IDToken != nil { - for claimName := range requestedClaims.IDToken { - // Add claim based on request - switch claimName { - case "email": - claims["email"] = "user@example.com" // TODO: Get from DID document - claims["email_verified"] = true - case "name": - claims["name"] = "User Name" // TODO: Get from DID document - case "did": - claims["did"] = userDID - } - } - } - - // Sign with user's DID key (simplified for now) - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - return token.SignedString([]byte("temporary-siop-key")) -} - -// generateVPToken generates a Verifiable Presentation token -func generateVPToken(userDID string, vpClaims map[string]ClaimRequest) (string, error) { - // Create VP structure - vp := map[string]any{ - "@context": []string{ - "https://www.w3.org/2018/credentials/v1", - }, - "type": []string{"VerifiablePresentation"}, - "holder": userDID, - "verifiableCredential": []any{ - // TODO: Include actual verifiable credentials - }, - } - - // Convert to JWT - vpJSON, err := json.Marshal(vp) - if err != nil { - return "", err - } - - // Sign VP (simplified for now) - claims := jwt.MapClaims{ - "vp": string(vpJSON), - "iss": userDID, - "aud": "verifier", - "exp": time.Now().Add(time.Hour).Unix(), - "iat": time.Now().Unix(), - "nonce": generateNonce(), - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - return token.SignedString([]byte("temporary-vp-key")) -} - -// buildSIOPRedirectURL builds the redirect URL with SIOP response -func buildSIOPRedirectURL(redirectURI string, response *SIOPResponse) (string, error) { - u, err := url.Parse(redirectURI) - if err != nil { - return "", err - } - - // Add response parameters - q := u.Query() - q.Set("id_token", response.IDToken) - if response.VPToken != "" { - q.Set("vp_token", response.VPToken) - } - if response.State != "" { - q.Set("state", response.State) - } - u.RawQuery = q.Encode() - - return u.String(), nil -} - -// generateClientID generates a unique client ID -func generateClientID() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return fmt.Sprintf("siop_client_%s", base64.RawURLEncoding.EncodeToString(bytes)) -} - -// generateNonce generates a nonce for tokens -func generateNonce() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - return "" - } - return base64.RawURLEncoding.EncodeToString(bytes) -} - -// ValidateSIOPRequest validates an incoming SIOP request -func ValidateSIOPRequest(requestURI string) (*SIOPRequest, error) { - // Parse the request URI - u, err := url.Parse(requestURI) - if err != nil { - return nil, fmt.Errorf("invalid request URI: %w", err) - } - - // Validate that it's a proper URI with scheme and host - if u.Scheme == "" && u.Host == "" { - return nil, fmt.Errorf("invalid request URI: missing scheme or host") - } - - // Extract parameters - q := u.Query() - req := &SIOPRequest{ - ResponseType: q.Get("response_type"), - ClientID: q.Get("client_id"), - RedirectURI: q.Get("redirect_uri"), - Scope: q.Get("scope"), - Nonce: q.Get("nonce"), - State: q.Get("state"), - } - - // Parse claims if present - if claimsStr := q.Get("claims"); claimsStr != "" { - if err := json.Unmarshal([]byte(claimsStr), &req.Claims); err != nil { - return nil, fmt.Errorf("invalid claims parameter: %w", err) - } - } - - // Parse registration if present - if regStr := q.Get("registration"); regStr != "" { - if err := json.Unmarshal([]byte(regStr), &req.Registration); err != nil { - return nil, fmt.Errorf("invalid registration parameter: %w", err) - } - } - - return req, nil -} - -// HandleSIOPRequest processes a complete SIOP request flow -func HandleSIOPRequest(c echo.Context) error { - // Get request URI from query parameter - requestURI := c.QueryParam("request_uri") - if requestURI == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": "Missing request_uri parameter", - }) - } - - // Validate and parse the request - req, err := ValidateSIOPRequest(requestURI) - if err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "invalid_request", - "error_description": err.Error(), - }) - } - - // Process as regular SIOP authorization - c.Set("siop_request", req) - return HandleSIOPAuthorization(c) -} diff --git a/bridge/handlers/siop_test.go b/bridge/handlers/siop_test.go deleted file mode 100644 index 5f2794f16..000000000 --- a/bridge/handlers/siop_test.go +++ /dev/null @@ -1,353 +0,0 @@ -package handlers - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" -) - -// TestSIOPAuthorization tests Self-Issued OpenID Provider authorization -func TestSIOPAuthorization(t *testing.T) { - e := echo.New() - - t.Run("ValidSIOPRequest", func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/siop/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "id_token") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid did") - q.Set("nonce", "test-nonce") - q.Set("state", "test-state") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - // Set authenticated user DID - c.Set("user_did", "did:sonr:testuser") - - err := HandleSIOPAuthorization(c) - assert.NoError(t, err) - - // Should redirect with ID token - assert.Equal(t, http.StatusFound, rec.Code) - location := rec.Header().Get("Location") - assert.Contains(t, location, "id_token=") - assert.Contains(t, location, "state=test-state") - }) - - t.Run("InvalidResponseType", func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/siop/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "code") // SIOP only supports id_token - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid") - q.Set("nonce", "test-nonce") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "unsupported_response_type", errorResp["error"]) - }) - - t.Run("MissingScopeOpenID", func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/siop/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "id_token") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "profile email") // Missing 'openid' - q.Set("nonce", "test-nonce") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "invalid_scope", errorResp["error"]) - }) - - t.Run("UnauthenticatedUser", func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/siop/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "id_token") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid") - q.Set("nonce", "test-nonce") - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - // No user_did set - user not authenticated - - err := HandleSIOPAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusUnauthorized, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "authentication_required", errorResp["error"]) - }) -} - -// TestSIOPRegistration tests dynamic client registration for SIOP -func TestSIOPRegistration(t *testing.T) { - e := echo.New() - - t.Run("ValidRegistration", func(t *testing.T) { - registration := map[string]any{ - "client_name": "Test SIOP Client", - "client_purpose": "Testing SIOP functionality", - "logo_uri": "https://example.com/logo.png", - } - body, _ := json.Marshal(registration) - - req := httptest.NewRequest(http.MethodPost, "/siop/register", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPRegistration(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, rec.Code) - - var response map[string]any - err = json.Unmarshal(rec.Body.Bytes(), &response) - assert.NoError(t, err) - assert.NotEmpty(t, response["client_id"]) - assert.Equal(t, "Test SIOP Client", response["client_name"]) - assert.Contains(t, response["subject_syntax_types_supported"], "did") - }) - - t.Run("MissingClientName", func(t *testing.T) { - registration := map[string]any{ - "client_purpose": "Testing", - } - body, _ := json.Marshal(registration) - - req := httptest.NewRequest(http.MethodPost, "/siop/register", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPRegistration(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "invalid_request", errorResp["error"]) - assert.Contains(t, errorResp["error_description"], "Client name is required") - }) -} - -// TestSIOPMetadata tests SIOP metadata endpoint -func TestSIOPMetadata(t *testing.T) { - e := echo.New() - - req := httptest.NewRequest(http.MethodGet, "/siop/metadata", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPMetadata(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, rec.Code) - - var metadata map[string]any - err = json.Unmarshal(rec.Body.Bytes(), &metadata) - assert.NoError(t, err) - - // Verify required SIOP metadata fields - assert.Equal(t, "https://self-issued.me/v2", metadata["issuer"]) - assert.Equal(t, "openid://", metadata["authorization_endpoint"]) - assert.Contains(t, metadata["response_types_supported"], "id_token") - assert.Contains(t, metadata["scopes_supported"], "openid") - assert.Contains(t, metadata["subject_types_supported"], "pairwise") - assert.NotNil(t, metadata["vp_formats_supported"]) -} - -// TestValidateSIOPRequest tests SIOP request validation -func TestValidateSIOPRequest(t *testing.T) { - t.Run("ValidRequest", func(t *testing.T) { - requestURI := "openid://?" + - "response_type=id_token" + - "&client_id=test-client" + - "&redirect_uri=" + url.QueryEscape("http://localhost:3000/callback") + - "&scope=openid+did" + - "&nonce=test-nonce" + - "&state=test-state" - - req, err := ValidateSIOPRequest(requestURI) - assert.NoError(t, err) - assert.NotNil(t, req) - assert.Equal(t, "id_token", req.ResponseType) - assert.Equal(t, "test-client", req.ClientID) - assert.Equal(t, "openid did", req.Scope) - assert.Equal(t, "test-nonce", req.Nonce) - }) - - t.Run("InvalidURI", func(t *testing.T) { - req, err := ValidateSIOPRequest("not-a-valid-uri") - assert.Error(t, err) - assert.Nil(t, req) - }) - - t.Run("WithClaims", func(t *testing.T) { - claims := map[string]any{ - "id_token": map[string]any{ - "email": map[string]any{ - "essential": true, - }, - "name": nil, - }, - } - claimsJSON, _ := json.Marshal(claims) - - requestURI := "openid://?" + - "response_type=id_token" + - "&client_id=test-client" + - "&redirect_uri=" + url.QueryEscape("http://localhost:3000/callback") + - "&scope=openid" + - "&nonce=test-nonce" + - "&claims=" + url.QueryEscape(string(claimsJSON)) - - req, err := ValidateSIOPRequest(requestURI) - assert.NoError(t, err) - assert.NotNil(t, req) - assert.NotNil(t, req.Claims.IDToken) - }) -} - -// TestSIOPWithVPToken tests SIOP with Verifiable Presentation -func TestSIOPWithVPToken(t *testing.T) { - e := echo.New() - - vpClaims := map[string]any{ - "vp_token": map[string]any{ - "presentation_definition": map[string]any{ - "id": "test-presentation", - "input_descriptors": []map[string]any{ - { - "id": "id_credential", - "constraints": map[string]any{ - "fields": []map[string]any{ - { - "path": []string{"$.type"}, - "filter": map[string]any{ - "type": "string", - "const": "IdentityCredential", - }, - }, - }, - }, - }, - }, - }, - }, - } - - claimsJSON, _ := json.Marshal(vpClaims) - - req := httptest.NewRequest(http.MethodPost, "/siop/authorize", nil) - q := req.URL.Query() - q.Set("response_type", "id_token") - q.Set("client_id", "test-client") - q.Set("redirect_uri", "http://localhost:3000/callback") - q.Set("scope", "openid") - q.Set("nonce", "test-nonce") - q.Set("claims", string(claimsJSON)) - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - c.Set("user_did", "did:sonr:testuser") - - // Parse request to set claims - siopReq := &SIOPRequest{ - ResponseType: "id_token", - ClientID: "test-client", - RedirectURI: "http://localhost:3000/callback", - Scope: "openid", - Nonce: "test-nonce", - } - err := json.Unmarshal(claimsJSON, &siopReq.Claims) - assert.NoError(t, err) - c.Set("siop_request", siopReq) - - err = HandleSIOPAuthorization(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusFound, rec.Code) - - location := rec.Header().Get("Location") - assert.Contains(t, location, "id_token=") - // VP token generation is optional, so we don't assert its presence -} - -// TestHandleSIOPRequest tests complete SIOP request flow -func TestHandleSIOPRequest(t *testing.T) { - e := echo.New() - - t.Run("ValidRequestURI", func(t *testing.T) { - requestURI := "openid://?" + - "response_type=id_token" + - "&client_id=test-client" + - "&redirect_uri=" + url.QueryEscape("http://localhost:3000/callback") + - "&scope=openid" + - "&nonce=test-nonce" - - req := httptest.NewRequest(http.MethodGet, "/siop/request", nil) - q := req.URL.Query() - q.Set("request_uri", requestURI) - req.URL.RawQuery = q.Encode() - - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - c.Set("user_did", "did:sonr:testuser") - - err := HandleSIOPRequest(c) - assert.NoError(t, err) - // Should process as authorization request - assert.Equal(t, http.StatusFound, rec.Code) - }) - - t.Run("MissingRequestURI", func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/siop/request", nil) - rec := httptest.NewRecorder() - c := e.NewContext(req, rec) - - err := HandleSIOPRequest(c) - assert.NoError(t, err) - assert.Equal(t, http.StatusBadRequest, rec.Code) - - var errorResp map[string]string - err = json.Unmarshal(rec.Body.Bytes(), &errorResp) - assert.NoError(t, err) - assert.Equal(t, "invalid_request", errorResp["error"]) - assert.Contains(t, errorResp["error_description"], "Missing request_uri") - }) -} diff --git a/bridge/handlers/types.go b/bridge/handlers/types.go deleted file mode 100644 index b27a54551..000000000 --- a/bridge/handlers/types.go +++ /dev/null @@ -1,265 +0,0 @@ -package handlers - -import ( - "time" - - "github.com/golang-jwt/jwt/v5" -) - -// WebAuthnCredential represents a WebAuthn credential -type WebAuthnCredential struct { - CredentialID string `json:"credential_id"` - RawID string `json:"raw_id"` - ClientDataJSON string `json:"client_data_json"` - AttestationObject string `json:"attestation_object"` - Username string `json:"username"` - Origin string `json:"origin"` - PublicKey []byte `json:"public_key"` - Algorithm int32 `json:"algorithm"` - CreatedAt time.Time `json:"created_at"` -} - -// WebAuthnRegistrationRequest represents a registration request -type WebAuthnRegistrationRequest struct { - Username string `json:"username"` - Challenge string `json:"challenge,omitempty"` - AutoCreateVault bool `json:"auto_create_vault"` - BroadcastToChain bool `json:"broadcast_to_chain"` -} - -// WebAuthnAuthenticationRequest represents an authentication request -type WebAuthnAuthenticationRequest struct { - Username string `json:"username"` - Challenge string `json:"challenge,omitempty"` -} - -// WebAuthnRegistrationResponse contains registration ceremony data -type WebAuthnRegistrationResponse struct { - Challenge string `json:"challenge"` - RP WebAuthnRPEntity `json:"rp"` - User WebAuthnUserEntity `json:"user"` - PubKeyCredParams []WebAuthnCredParam `json:"pubKeyCredParams"` - AuthenticatorSelection WebAuthnAuthenticatorSelection `json:"authenticatorSelection"` - Timeout int `json:"timeout"` - Attestation string `json:"attestation"` -} - -// WebAuthnAuthenticationResponse contains authentication ceremony data -type WebAuthnAuthenticationResponse struct { - Challenge string `json:"challenge"` - Timeout int `json:"timeout"` - RPID string `json:"rpId"` - AllowCredentials []WebAuthnAllowedCred `json:"allowCredentials"` - UserVerification string `json:"userVerification"` -} - -// WebAuthnRPEntity represents relying party info -type WebAuthnRPEntity struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// WebAuthnUserEntity represents user info -type WebAuthnUserEntity struct { - ID string `json:"id"` - Name string `json:"name"` - DisplayName string `json:"displayName"` -} - -// WebAuthnCredParam represents credential parameters -type WebAuthnCredParam struct { - Type string `json:"type"` - Alg int `json:"alg"` -} - -// WebAuthnAuthenticatorSelection represents authenticator requirements -type WebAuthnAuthenticatorSelection struct { - AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"` - UserVerification string `json:"userVerification"` - ResidentKey string `json:"residentKey,omitempty"` -} - -// WebAuthnAllowedCred represents allowed credentials for authentication -type WebAuthnAllowedCred struct { - Type string `json:"type"` - ID string `json:"id"` -} - -// OIDCConfig represents OpenID Connect configuration -type OIDCConfig struct { - Issuer string `json:"issuer"` - AuthorizationEndpoint string `json:"authorization_endpoint"` - TokenEndpoint string `json:"token_endpoint"` - UserInfoEndpoint string `json:"userinfo_endpoint"` - JWKSEndpoint string `json:"jwks_uri"` - RevocationEndpoint string `json:"revocation_endpoint,omitempty"` - IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"` - RegistrationEndpoint string `json:"registration_endpoint,omitempty"` - ScopesSupported []string `json:"scopes_supported"` - ResponseTypesSupported []string `json:"response_types_supported"` - GrantTypesSupported []string `json:"grant_types_supported"` - SubjectTypesSupported []string `json:"subject_types_supported"` - IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"` - TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"` - ClaimsSupported []string `json:"claims_supported"` - CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"` -} - -// OIDCAuthorizationRequest represents an authorization request -type OIDCAuthorizationRequest struct { - ResponseType string `json:"response_type"` - ClientID string `json:"client_id"` - RedirectURI string `json:"redirect_uri"` - Scope string `json:"scope"` - State string `json:"state"` - Nonce string `json:"nonce,omitempty"` - CodeChallenge string `json:"code_challenge,omitempty"` - CodeChallengeMethod string `json:"code_challenge_method,omitempty"` -} - -// OIDCTokenRequest represents a token request -type OIDCTokenRequest struct { - GrantType string `json:"grant_type"` - Code string `json:"code,omitempty"` - RedirectURI string `json:"redirect_uri,omitempty"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret,omitempty"` - CodeVerifier string `json:"code_verifier,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` -} - -// OIDCTokenResponse represents a token response -type OIDCTokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - RefreshToken string `json:"refresh_token,omitempty"` - IDToken string `json:"id_token,omitempty"` - Scope string `json:"scope,omitempty"` -} - -// OIDCUserInfo represents user information -type OIDCUserInfo struct { - Subject string `json:"sub"` - Name string `json:"name,omitempty"` - PreferredUsername string `json:"preferred_username,omitempty"` - Email string `json:"email,omitempty"` - EmailVerified bool `json:"email_verified,omitempty"` - DID string `json:"did,omitempty"` - VaultID string `json:"vault_id,omitempty"` - UpdatedAt int64 `json:"updated_at,omitempty"` - Claims map[string]any `json:"claims,omitempty"` -} - -// JWKSet represents a JSON Web Key Set -type JWKSet struct { - Keys []JWK `json:"keys"` -} - -// JWK represents a JSON Web Key -type JWK struct { - KeyType string `json:"kty"` - Use string `json:"use,omitempty"` - KeyID string `json:"kid"` - Algorithm string `json:"alg,omitempty"` - N string `json:"n,omitempty"` // RSA modulus - E string `json:"e,omitempty"` // RSA exponent - X string `json:"x,omitempty"` // EC x coordinate - Y string `json:"y,omitempty"` // EC y coordinate - Curve string `json:"crv,omitempty"` // EC curve -} - -// SIOPRequest represents a Self-Issued OpenID Provider request -type SIOPRequest struct { - ResponseType string `json:"response_type"` - ClientID string `json:"client_id"` - RedirectURI string `json:"redirect_uri"` - Scope string `json:"scope"` - Nonce string `json:"nonce"` - State string `json:"state,omitempty"` - Claims SIOPClaims `json:"claims,omitempty"` - Registration SIOPRegistration `json:"registration,omitempty"` -} - -// SIOPClaims represents claims requested in SIOP -type SIOPClaims struct { - IDToken map[string]ClaimRequest `json:"id_token,omitempty"` - VPToken map[string]ClaimRequest `json:"vp_token,omitempty"` -} - -// ClaimRequest represents a claim request -type ClaimRequest struct { - Essential bool `json:"essential,omitempty"` - Value string `json:"value,omitempty"` - Values []string `json:"values,omitempty"` -} - -// SIOPRegistration represents client registration in SIOP -type SIOPRegistration struct { - ClientName string `json:"client_name,omitempty"` - ClientPurpose string `json:"client_purpose,omitempty"` - LogoURI string `json:"logo_uri,omitempty"` - SubjectSyntaxTypesSupported []string `json:"subject_syntax_types_supported,omitempty"` - VPFormats map[string]any `json:"vp_formats,omitempty"` -} - -// SIOPResponse represents a Self-Issued OpenID Provider response -type SIOPResponse struct { - IDToken string `json:"id_token"` - VPToken string `json:"vp_token,omitempty"` - State string `json:"state,omitempty"` -} - -// DIDAuthClaims represents DID-based authentication claims -type DIDAuthClaims struct { - jwt.RegisteredClaims - DID string `json:"did"` - Challenge string `json:"challenge,omitempty"` - WebAuthn *WebAuthnCredential `json:"webauthn,omitempty"` - Extra map[string]any `json:"extra,omitempty"` -} - -// AuthorizationCode represents an OAuth2 authorization code -type AuthorizationCode struct { - Code string - ClientID string - RedirectURI string - UserDID string - Scope string - Nonce string - CodeChallenge string - CodeChallengeMethod string - ExpiresAt time.Time - Used bool -} - -// OIDCSession represents an active OIDC session -type OIDCSession struct { - SessionID string - UserDID string - ClientID string - Scope string - Nonce string - AccessToken string - RefreshToken string - IDToken string - ExpiresAt time.Time - CreatedAt time.Time -} - -// BroadcastRequest represents a blockchain broadcast request -type BroadcastRequest struct { - Message any `json:"message"` - Gasless bool `json:"gasless"` - AutoSign bool `json:"auto_sign"` - FromAddress string `json:"from_address,omitempty"` -} - -// BroadcastResponse represents a blockchain broadcast response -type BroadcastResponse struct { - TxHash string `json:"tx_hash"` - Height int64 `json:"height,omitempty"` - Code uint32 `json:"code,omitempty"` - RawLog string `json:"raw_log,omitempty"` - Success bool `json:"success"` -} diff --git a/bridge/handlers/ucan_signer.go b/bridge/handlers/ucan_signer.go deleted file mode 100644 index 42a4e2af9..000000000 --- a/bridge/handlers/ucan_signer.go +++ /dev/null @@ -1,602 +0,0 @@ -package handlers - -import ( - "context" - "crypto/ed25519" - "crypto/rand" - "encoding/base64" - "encoding/json" - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/golang-jwt/jwt/v5" - "github.com/sonr-io/sonr/crypto/ucan" - "github.com/sonr-io/sonr/x/did/types" -) - -// BlockchainUCANSigner implements UCAN signing with blockchain keys -type BlockchainUCANSigner struct { - didKeeper DIDKeeperInterface - issuerDID string - signingMethod jwt.SigningMethod - privateKey any -} - -// DIDKeeperInterface defines the minimal interface needed from DID keeper -type DIDKeeperInterface interface { - GetDIDDocument(ctx context.Context, did string) (*types.DIDDocument, error) - GetVerificationMethod( - ctx context.Context, - did string, - methodID string, - ) (*types.VerificationMethod, error) -} - -// NewBlockchainUCANSigner creates a new blockchain-integrated UCAN signer -func NewBlockchainUCANSigner( - didKeeper DIDKeeperInterface, - issuerDID string, -) (*BlockchainUCANSigner, error) { - return &BlockchainUCANSigner{ - didKeeper: didKeeper, - issuerDID: issuerDID, - signingMethod: jwt.SigningMethodES256, // Default to ES256 - }, nil -} - -// Sign signs a UCAN token with blockchain keys -func (s *BlockchainUCANSigner) Sign(token *ucan.Token) (string, error) { - // Build JWT claims from UCAN token - claims := s.buildClaims(token) - - // Get signing key - signingKey, method, err := s.getSigningKey(context.Background()) - if err != nil { - return "", fmt.Errorf("failed to get signing key: %w", err) - } - - // Create JWT token - jwtToken := jwt.NewWithClaims(method, claims) - - // Sign token - signedToken, err := jwtToken.SignedString(signingKey) - if err != nil { - return "", fmt.Errorf("failed to sign token: %w", err) - } - - return signedToken, nil -} - -// GetIssuerDID returns the issuer DID -func (s *BlockchainUCANSigner) GetIssuerDID() string { - if s.issuerDID == "" { - return "did:sonr:oauth-provider" - } - return s.issuerDID -} - -// buildClaims builds JWT claims from UCAN token -func (s *BlockchainUCANSigner) buildClaims(token *ucan.Token) jwt.MapClaims { - claims := jwt.MapClaims{ - "iss": token.Issuer, - "aud": token.Audience, - "exp": token.ExpiresAt, - "iat": time.Now().Unix(), - "nbf": token.NotBefore, - } - - // Add attenuations - if len(token.Attenuations) > 0 { - attClaims := make([]map[string]any, len(token.Attenuations)) - for i, att := range token.Attenuations { - attClaims[i] = s.serializeAttenuation(att) - } - claims["att"] = attClaims - } - - // Add proofs if present - if len(token.Proofs) > 0 { - proofClaims := make([]string, len(token.Proofs)) - for i, proof := range token.Proofs { - proofClaims[i] = string(proof) - } - claims["prf"] = proofClaims - } - - // Add facts if present - if len(token.Facts) > 0 { - factClaims := make([]json.RawMessage, len(token.Facts)) - for i, fact := range token.Facts { - factClaims[i] = fact.Data - } - claims["fct"] = factClaims - } - - // Add UCAN version - claims["ucv"] = "0.10.0" - - return claims -} - -// serializeAttenuation serializes an attenuation for JWT claims -func (s *BlockchainUCANSigner) serializeAttenuation(att ucan.Attenuation) map[string]any { - result := map[string]any{ - "with": att.Resource.GetURI(), - } - - // Handle capability serialization - actions := att.Capability.GetActions() - if len(actions) == 1 { - result["can"] = actions[0] - } else { - result["can"] = actions - } - - // Add resource-specific metadata - scheme := att.Resource.GetScheme() - switch scheme { - case "vault": - result["type"] = "vault_operation" - case "service", "svc": - result["type"] = "service_operation" - case "did": - result["type"] = "identity_operation" - case "dwn": - result["type"] = "data_operation" - case "dex", "pool": - result["type"] = "trading_operation" - } - - return result -} - -// getSigningKey retrieves the signing key from blockchain -func (s *BlockchainUCANSigner) getSigningKey(ctx context.Context) (any, jwt.SigningMethod, error) { - // If we have a cached private key, use it - if s.privateKey != nil { - return s.privateKey, s.signingMethod, nil - } - - // For OAuth provider, use a service key - if s.issuerDID == "did:sonr:oauth-provider" || s.issuerDID == "" { - // Generate or retrieve service key - privateKey, publicKey, err := s.generateServiceKey() - if err != nil { - return nil, nil, err - } - - s.privateKey = privateKey - s.signingMethod = jwt.SigningMethodEdDSA // Update to EdDSA for Ed25519 keys - _ = publicKey // Store public key if needed - - return privateKey, jwt.SigningMethodEdDSA, nil - } - - // For DID-based signing, retrieve from DID document - if s.didKeeper != nil { - didDoc, err := s.didKeeper.GetDIDDocument(ctx, s.issuerDID) - if err != nil { - return nil, nil, fmt.Errorf("failed to get DID document: %w", err) - } - - // Use the first verification method for signing - if len(didDoc.VerificationMethod) > 0 { - vm := didDoc.VerificationMethod[0] - - // Extract key based on verification method kind - switch vm.VerificationMethodKind { - case "Ed25519VerificationKey2020": - // Extract Ed25519 key - privateKey, err := s.extractEd25519Key(vm) - if err != nil { - return nil, nil, err - } - s.privateKey = privateKey - s.signingMethod = jwt.SigningMethodEdDSA - return privateKey, jwt.SigningMethodEdDSA, nil - - case "EcdsaSecp256k1VerificationKey2019": - // Extract Secp256k1 key - privateKey, err := s.extractSecp256k1Key(vm) - if err != nil { - return nil, nil, err - } - s.privateKey = privateKey - s.signingMethod = jwt.SigningMethodES256 - return privateKey, jwt.SigningMethodES256, nil - - default: - return nil, nil, fmt.Errorf( - "unsupported verification method type: %s", - vm.VerificationMethodKind, - ) - } - } - } - - return nil, nil, fmt.Errorf("no signing key available") -} - -// generateServiceKey generates a new service key pair -func (s *BlockchainUCANSigner) generateServiceKey() (ed25519.PrivateKey, ed25519.PublicKey, error) { - // In production, this should retrieve from secure storage - // For now, generate a new key pair - publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - return nil, nil, fmt.Errorf("failed to generate key pair: %w", err) - } - - return privateKey, publicKey, nil -} - -// extractEd25519Key extracts Ed25519 private key from verification method -func (s *BlockchainUCANSigner) extractEd25519Key( - vm *types.VerificationMethod, -) (ed25519.PrivateKey, error) { - // In production, this would retrieve the private key from secure storage - // based on the public key in the verification method - - // For now, return error as we don't have access to private keys - return nil, fmt.Errorf("private key retrieval not implemented") -} - -// extractSecp256k1Key extracts Secp256k1 private key from verification method -func (s *BlockchainUCANSigner) extractSecp256k1Key( - vm *types.VerificationMethod, -) (*secp256k1.PrivKey, error) { - // In production, this would retrieve the private key from secure storage - // based on the public key in the verification method - - // For now, return error as we don't have access to private keys - return nil, fmt.Errorf("private key retrieval not implemented") -} - -// VerifySignature verifies a UCAN token signature -func (s *BlockchainUCANSigner) VerifySignature(tokenString string) (*ucan.Token, error) { - // Parse token without verification first to get issuer - token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{}) - if err != nil { - return nil, fmt.Errorf("failed to parse token: %w", err) - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid claims format") - } - - issuer, ok := claims["iss"].(string) - if !ok { - return nil, fmt.Errorf("no issuer in token") - } - - // Get public key for issuer - publicKey, err := s.getPublicKey(context.Background(), issuer) - if err != nil { - return nil, fmt.Errorf("failed to get public key: %w", err) - } - - // Verify token with public key - parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { - return publicKey, nil - }) - if err != nil { - return nil, fmt.Errorf("token verification failed: %w", err) - } - - if !parsedToken.Valid { - return nil, fmt.Errorf("invalid token") - } - - // Convert JWT claims to UCAN token - return s.claimsToUCAN(claims, tokenString) -} - -// getPublicKey retrieves public key for a DID -func (s *BlockchainUCANSigner) getPublicKey(ctx context.Context, did string) (any, error) { - if did == "did:sonr:oauth-provider" { - // Return service public key - // In production, this would be retrieved from configuration - return []byte("oauth-provider-public-key"), nil - } - - if s.didKeeper != nil { - didDoc, err := s.didKeeper.GetDIDDocument(ctx, did) - if err != nil { - return nil, fmt.Errorf("failed to get DID document: %w", err) - } - - if len(didDoc.VerificationMethod) > 0 { - vm := didDoc.VerificationMethod[0] - - // Extract public key based on verification method kind - switch vm.VerificationMethodKind { - case "Ed25519VerificationKey2020": - // Decode base64 public key - publicKeyBytes, err := base64.StdEncoding.DecodeString(vm.PublicKeyMultibase) - if err != nil { - return nil, err - } - return ed25519.PublicKey(publicKeyBytes), nil - - case "EcdsaSecp256k1VerificationKey2019": - // Decode and return Secp256k1 public key - publicKeyBytes, err := base64.StdEncoding.DecodeString(vm.PublicKeyMultibase) - if err != nil { - return nil, err - } - return publicKeyBytes, nil - - default: - return nil, fmt.Errorf( - "unsupported verification method type: %s", - vm.VerificationMethodKind, - ) - } - } - } - - return nil, fmt.Errorf("no public key found for DID: %s", did) -} - -// claimsToUCAN converts JWT claims to UCAN token -func (s *BlockchainUCANSigner) claimsToUCAN( - claims jwt.MapClaims, - rawToken string, -) (*ucan.Token, error) { - token := &ucan.Token{ - Raw: rawToken, - } - - // Extract standard claims - if iss, ok := claims["iss"].(string); ok { - token.Issuer = iss - } - if aud, ok := claims["aud"].(string); ok { - token.Audience = aud - } - if exp, ok := claims["exp"].(float64); ok { - token.ExpiresAt = int64(exp) - } - if nbf, ok := claims["nbf"].(float64); ok { - token.NotBefore = int64(nbf) - } - - // Extract attenuations - if attClaims, ok := claims["att"].([]any); ok { - attenuations := make([]ucan.Attenuation, 0, len(attClaims)) - for _, attItem := range attClaims { - if attMap, ok := attItem.(map[string]any); ok { - att, err := s.parseAttenuation(attMap) - if err != nil { - return nil, fmt.Errorf("failed to parse attenuation: %w", err) - } - attenuations = append(attenuations, att) - } - } - token.Attenuations = attenuations - } - - // Extract proofs - if proofClaims, ok := claims["prf"].([]any); ok { - proofs := make([]ucan.Proof, 0, len(proofClaims)) - for _, proofItem := range proofClaims { - if proofStr, ok := proofItem.(string); ok { - proofs = append(proofs, ucan.Proof(proofStr)) - } - } - token.Proofs = proofs - } - - // Extract facts - if factClaims, ok := claims["fct"].([]any); ok { - facts := make([]ucan.Fact, 0, len(factClaims)) - for _, factItem := range factClaims { - factData, _ := json.Marshal(factItem) - facts = append(facts, ucan.Fact{ - Data: json.RawMessage(factData), - }) - } - token.Facts = facts - } - - return token, nil -} - -// parseAttenuation parses an attenuation from JWT claims -func (s *BlockchainUCANSigner) parseAttenuation(attMap map[string]any) (ucan.Attenuation, error) { - // Extract resource URI - resourceURI, ok := attMap["with"].(string) - if !ok { - return ucan.Attenuation{}, fmt.Errorf("missing resource URI") - } - - // Parse resource - resource := &SimpleResource{ - Scheme: "generic", - Value: resourceURI, - } - - // Extract scheme from URI if possible - if len(resourceURI) > 0 { - for _, scheme := range []string{"vault:", "service:", "did:", "dwn:", "dex:", "pool:"} { - if len(resourceURI) >= len(scheme) && resourceURI[:len(scheme)] == scheme { - resource.Scheme = scheme[:len(scheme)-1] - resource.Value = resourceURI[len(scheme):] - break - } - } - } - - // Extract capability - var capability ucan.Capability - switch can := attMap["can"].(type) { - case string: - capability = &ucan.SimpleCapability{Action: can} - case []any: - actions := make([]string, 0, len(can)) - for _, action := range can { - if actionStr, ok := action.(string); ok { - actions = append(actions, actionStr) - } - } - capability = &ucan.MultiCapability{Actions: actions} - default: - return ucan.Attenuation{}, fmt.Errorf("invalid capability format") - } - - return ucan.Attenuation{ - Capability: capability, - Resource: resource, - }, nil -} - -// SetPrivateKey sets a private key for signing (for testing) -func (s *BlockchainUCANSigner) SetPrivateKey(privateKey any, method jwt.SigningMethod) { - s.privateKey = privateKey - s.signingMethod = method -} - -// CreateDelegationToken creates a UCAN token for delegation -func (s *BlockchainUCANSigner) CreateDelegationToken( - issuer, audience string, - attenuations []ucan.Attenuation, - proofs []ucan.Proof, - expiresIn time.Duration, -) (string, error) { - token := &ucan.Token{ - Issuer: issuer, - Audience: audience, - ExpiresAt: time.Now().Add(expiresIn).Unix(), - NotBefore: time.Now().Unix(), - Attenuations: attenuations, - Proofs: proofs, - } - - return s.Sign(token) -} - -// ValidateDelegationChain validates a chain of UCAN delegations -func (s *BlockchainUCANSigner) ValidateDelegationChain(tokens []string) error { - if len(tokens) == 0 { - return fmt.Errorf("empty delegation chain") - } - - var previousToken *ucan.Token - for i, tokenString := range tokens { - // Verify current token - token, err := s.VerifySignature(tokenString) - if err != nil { - return fmt.Errorf("failed to verify token %d: %w", i, err) - } - - // Check expiration - if time.Now().Unix() > token.ExpiresAt { - return fmt.Errorf("token %d has expired", i) - } - - // Check not before - if token.NotBefore > 0 && time.Now().Unix() < token.NotBefore { - return fmt.Errorf("token %d not yet valid", i) - } - - // Validate delegation chain - if previousToken != nil { - // Check that previous token's audience matches current issuer - if previousToken.Audience != token.Issuer { - return fmt.Errorf("broken delegation chain at token %d", i) - } - - // Check that capabilities are properly attenuated - if !s.isProperlyAttenuated(previousToken.Attenuations, token.Attenuations) { - return fmt.Errorf("improper attenuation at token %d", i) - } - } - - previousToken = token - } - - return nil -} - -// isProperlyAttenuated checks if child attenuations are properly attenuated from parent -func (s *BlockchainUCANSigner) isProperlyAttenuated(parent, child []ucan.Attenuation) bool { - // Child cannot have more permissions than parent - for _, childAtt := range child { - found := false - for _, parentAtt := range parent { - // Check if child attenuation is covered by parent - if s.attenuationCovers(parentAtt, childAtt) { - found = true - break - } - } - if !found { - return false - } - } - return true -} - -// attenuationCovers checks if parent attenuation covers child -func (s *BlockchainUCANSigner) attenuationCovers(parent, child ucan.Attenuation) bool { - // Check resource match - if parent.Resource.GetScheme() != child.Resource.GetScheme() { - // Wildcard scheme matches all - if parent.Resource.GetScheme() != "*" { - return false - } - } - - // Check capability coverage - parentActions := parent.Capability.GetActions() - childActions := child.Capability.GetActions() - - // If parent has wildcard, it covers everything - for _, action := range parentActions { - if action == "*" { - return true - } - } - - // Check each child action is in parent - for _, childAction := range childActions { - found := false - for _, parentAction := range parentActions { - if parentAction == childAction { - found = true - break - } - } - if !found { - return false - } - } - - return true -} - -// RefreshToken creates a new token from an existing one with updated expiration -func (s *BlockchainUCANSigner) RefreshToken( - tokenString string, - newExpiration time.Duration, -) (string, error) { - // Verify existing token - token, err := s.VerifySignature(tokenString) - if err != nil { - return "", fmt.Errorf("failed to verify token: %w", err) - } - - // Create new token with same claims but new expiration - newToken := &ucan.Token{ - Issuer: token.Issuer, - Audience: token.Audience, - ExpiresAt: time.Now().Add(newExpiration).Unix(), - NotBefore: time.Now().Unix(), - Attenuations: token.Attenuations, - Proofs: append(token.Proofs, ucan.Proof(tokenString)), // Add original as proof - Facts: token.Facts, - } - - return s.Sign(newToken) -} diff --git a/bridge/handlers/vault.go b/bridge/handlers/vault.go deleted file mode 100644 index 3a355a8f7..000000000 --- a/bridge/handlers/vault.go +++ /dev/null @@ -1,535 +0,0 @@ -package handlers - -import ( - "fmt" - "net/http" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/hibiken/asynq" - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/bridge/tasks" - "github.com/sonr-io/sonr/crypto/mpc" - "github.com/sonr-io/sonr/types/ipfs" -) - -// VaultHandlers holds all vault-related handlers and their dependencies -type VaultHandlers struct { - IPFSClient ipfs.IPFSClient - ConnectionManager *ConnectionManager - SSEManager *SSEManager -} - -// NewVaultHandlers creates a new VaultHandlers instance -func NewVaultHandlers( - ipfsClient ipfs.IPFSClient, - connManager *ConnectionManager, - sseManager *SSEManager, -) *VaultHandlers { - return &VaultHandlers{ - IPFSClient: ipfsClient, - ConnectionManager: connManager, - SSEManager: sseManager, - } -} - -// GetQueueFromPriority determines the appropriate queue based on priority -func GetQueueFromPriority(priority string) string { - switch priority { - case "critical", "high": - return "critical" - case "low": - return "low" - default: - return "default" - } -} - -// GenerateHandler handles vault generation requests -func (vh *VaultHandlers) GenerateHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - // Extract user info from JWT token - user := c.Get("user").(*jwt.Token) - claims := user.Claims.(jwt.MapClaims) - userID := claims["user_id"].(string) - - var req struct { - UserID int `json:"user_id"` - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - task, err := tasks.NewUCANDIDTask(req.UserID) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - // Broadcast task status to WebSocket and SSE connections - go func() { - message := TaskStatusMessage{ - TaskID: info.ID, - Status: "enqueued", - Time: time.Now(), - } - vh.ConnectionManager.BroadcastToTask(info.ID, message) - vh.SSEManager.BroadcastToSSE(info.ID, message) - - // Simulate task progression for demonstration - // In a real implementation, this would be triggered by the actual task processors - time.Sleep(1 * time.Second) - processingMessage := TaskStatusMessage{ - TaskID: info.ID, - Status: "processing", - Progress: 50, - Time: time.Now(), - } - vh.ConnectionManager.BroadcastToTask(info.ID, processingMessage) - vh.SSEManager.BroadcastToSSE(info.ID, processingMessage) - - // Simulate completion - time.Sleep(2 * time.Second) - completedMessage := TaskStatusMessage{ - TaskID: info.ID, - Status: "completed", - Progress: 100, - Time: time.Now(), - } - vh.ConnectionManager.BroadcastToTask(info.ID, completedMessage) - vh.SSEManager.BroadcastToSSE(info.ID, completedMessage) - }() - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - "user_id": userID, - }) - } -} - -// SignHandler handles vault signing requests -func (vh *VaultHandlers) SignHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - var req struct { - Message []byte `json:"message"` - Enclave *mpc.EnclaveData `json:"enclave,omitempty"` // Direct enclave data (fallback) - EnclaveCID string `json:"enclave_cid,omitempty"` // IPFS CID reference - Password []byte `json:"password,omitempty"` // Decryption password for IPFS stored data - UCANToken string `json:"ucan_token,omitempty"` // UCAN token for authorization - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - if len(req.Message) == 0 { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Message is required"}) - } - - // Handle enclave data - either direct or via IPFS CID - var enclave *mpc.EnclaveData - if req.EnclaveCID != "" { - // Retrieve enclave from IPFS - if vh.IPFSClient == nil { - return c.JSON( - http.StatusServiceUnavailable, - map[string]string{"error": "IPFS client not available"}, - ) - } - - encryptedData, err := vh.IPFSClient.Get(req.EnclaveCID) - if err != nil { - return c.JSON( - http.StatusNotFound, - map[string]string{"error": "Failed to retrieve enclave from IPFS"}, - ) - } - - // Create temporary enclave for decryption - tempEnclave := &mpc.EnclaveData{} - decryptedData, err := tempEnclave.Decrypt(req.Password, encryptedData) - if err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to decrypt enclave data"}, - ) - } - - // Unmarshal decrypted data - enclave = &mpc.EnclaveData{} - if err := enclave.Unmarshal(decryptedData); err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to parse enclave data"}, - ) - } - } else if req.Enclave != nil { - // Use directly provided enclave data - enclave = req.Enclave - } else { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Either enclave or enclave_cid is required"}) - } - - task, err := tasks.NewUCANSignTask( - 0, - req.Message, - ) // TODO: Extract userID from JWT or context - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - }) - } -} - -// VerifyHandler handles vault verification requests -func (vh *VaultHandlers) VerifyHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - var req struct { - PublicKey []byte `json:"public_key"` - Message []byte `json:"message"` - Signature []byte `json:"signature"` - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - if len(req.PublicKey) == 0 || len(req.Message) == 0 || len(req.Signature) == 0 { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "PublicKey, message, and signature are required"}, - ) - } - - task, err := tasks.NewUCANVerifyTask( - 0, - req.Message, - req.Signature, - ) // TODO: Extract userID from JWT or context - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - }) - } -} - -// ExportHandler handles vault export requests -func (vh *VaultHandlers) ExportHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - var req struct { - Enclave *mpc.EnclaveData `json:"enclave,omitempty"` // Direct enclave data - EnclaveCID string `json:"enclave_cid,omitempty"` // IPFS CID reference - Password []byte `json:"password"` // For encryption/decryption - StoreIPFS bool `json:"store_ipfs,omitempty"` // Whether to store result in IPFS - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - if len(req.Password) == 0 { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Password is required"}) - } - - // Handle enclave data - either direct or via IPFS CID - var enclave *mpc.EnclaveData - if req.EnclaveCID != "" { - // Retrieve enclave from IPFS - if vh.IPFSClient == nil { - return c.JSON( - http.StatusServiceUnavailable, - map[string]string{"error": "IPFS client not available"}, - ) - } - - encryptedData, err := vh.IPFSClient.Get(req.EnclaveCID) - if err != nil { - return c.JSON( - http.StatusNotFound, - map[string]string{"error": "Failed to retrieve enclave from IPFS"}, - ) - } - - // Create temporary enclave for decryption - tempEnclave := &mpc.EnclaveData{} - decryptedData, err := tempEnclave.Decrypt(req.Password, encryptedData) - if err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to decrypt enclave data"}, - ) - } - - // Unmarshal decrypted data - enclave = &mpc.EnclaveData{} - if err := enclave.Unmarshal(decryptedData); err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to parse enclave data"}, - ) - } - } else if req.Enclave != nil { - // Use directly provided enclave data - enclave = req.Enclave - } else { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Either enclave or enclave_cid is required"}) - } - - // If store_ipfs is true, encrypt and store the enclave in IPFS first - if req.StoreIPFS && vh.IPFSClient != nil { - encryptedData, err := enclave.Encrypt(req.Password) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to encrypt enclave data"}, - ) - } - - cid, err := vh.IPFSClient.Add(encryptedData) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to store enclave in IPFS"}, - ) - } - - // Return the CID for future reference - return c.JSON(http.StatusOK, map[string]any{ - "cid": cid, - "status": "stored", - "message": "Enclave data encrypted and stored in IPFS", - }) - } - - // Export functionality replaced with UCAN token creation for data access - // Convert export operation to UCAN token generation with export permissions - attenuations := []map[string]any{ - { - "can": []string{"export", "read"}, - "with": "vault://exported-data", - }, - } - task, err := tasks.NewUCANTokenTask( - 0, - "did:sonr:export-recipient", - attenuations, - time.Now().Add(24*time.Hour).Unix(), - ) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - }) - } -} - -// ImportHandler handles vault import requests -func (vh *VaultHandlers) ImportHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - var req struct { - CID string `json:"cid"` - Password []byte `json:"password"` - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - if req.CID == "" || len(req.Password) == 0 { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "CID and password are required"}, - ) - } - - // Import functionality replaced with UCAN token creation for data import - // Convert import operation to UCAN token generation with import permissions - attenuations := []map[string]any{ - { - "can": []string{"import", "write"}, - "with": fmt.Sprintf("ipfs://%s", req.CID), - }, - } - task, err := tasks.NewUCANTokenTask( - 0, - "did:sonr:import-recipient", - attenuations, - time.Now().Add(1*time.Hour).Unix(), - ) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - }) - } -} - -// RefreshHandler handles vault refresh requests -func (vh *VaultHandlers) RefreshHandler(client *asynq.Client) echo.HandlerFunc { - return func(c echo.Context) error { - var req struct { - Enclave *mpc.EnclaveData `json:"enclave,omitempty"` // Direct enclave data - EnclaveCID string `json:"enclave_cid,omitempty"` // IPFS CID reference - Password []byte `json:"password,omitempty"` // Decryption password for IPFS stored data - Priority string `json:"priority,omitempty"` - } - - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid JSON payload"}) - } - - // Handle enclave data - either direct or via IPFS CID - var enclave *mpc.EnclaveData - if req.EnclaveCID != "" { - // Retrieve enclave from IPFS - if vh.IPFSClient == nil { - return c.JSON( - http.StatusServiceUnavailable, - map[string]string{"error": "IPFS client not available"}, - ) - } - - encryptedData, err := vh.IPFSClient.Get(req.EnclaveCID) - if err != nil { - return c.JSON( - http.StatusNotFound, - map[string]string{"error": "Failed to retrieve enclave from IPFS"}, - ) - } - - // Create temporary enclave for decryption - tempEnclave := &mpc.EnclaveData{} - decryptedData, err := tempEnclave.Decrypt(req.Password, encryptedData) - if err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to decrypt enclave data"}, - ) - } - - // Unmarshal decrypted data - enclave = &mpc.EnclaveData{} - if err := enclave.Unmarshal(decryptedData); err != nil { - return c.JSON( - http.StatusBadRequest, - map[string]string{"error": "Failed to parse enclave data"}, - ) - } - } else if req.Enclave != nil { - // Use directly provided enclave data - enclave = req.Enclave - } else { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Either enclave or enclave_cid is required"}) - } - - // Refresh functionality replaced with UCAN DID generation for new identity - // Convert refresh operation to DID generation which includes key refresh - task, err := tasks.NewUCANDIDTask(0) // TODO: Extract userID from JWT or context - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to create task"}, - ) - } - - queue := GetQueueFromPriority(req.Priority) - info, err := client.Enqueue(task, asynq.Queue(queue)) - if err != nil { - return c.JSON( - http.StatusInternalServerError, - map[string]string{"error": "Failed to enqueue task"}, - ) - } - - return c.JSON(http.StatusOK, map[string]any{ - "task_id": info.ID, - "queue": queue, - "status": "enqueued", - }) - } -} diff --git a/bridge/handlers/webauthn.go b/bridge/handlers/webauthn.go deleted file mode 100644 index dea39c937..000000000 --- a/bridge/handlers/webauthn.go +++ /dev/null @@ -1,558 +0,0 @@ -package handlers - -import ( - "crypto/rand" - "encoding/base64" - "fmt" - "net/http" - "sync" - "time" - - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/types/webauthn" - "github.com/sonr-io/sonr/types/webauthn/webauthncbor" -) - -// WebAuthnStore manages WebAuthn sessions and credentials -type WebAuthnStore struct { - mu sync.RWMutex - sessions map[string]*WebAuthnSession - credentials map[string][]*WebAuthnCredential -} - -// WebAuthnSession holds session data for WebAuthn ceremonies -type WebAuthnSession struct { - Challenge string - Username string - CreatedAt time.Time - SessionType string // "registration" or "authentication" -} - -var ( - webAuthnStore = &WebAuthnStore{ - sessions: make(map[string]*WebAuthnSession), - credentials: make(map[string][]*WebAuthnCredential), - } - sessionTimeout = 5 * time.Minute -) - -// BeginWebAuthnRegistration starts WebAuthn registration ceremony -func BeginWebAuthnRegistration(c echo.Context) error { - var req WebAuthnRegistrationRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid request format", - }) - } - - if req.Username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Username is required", - }) - } - - // Store the request in context for later use in FinishWebAuthnRegistration - c.Set("webauthn_registration_request", &req) - - // Generate challenge - challenge, err := generateChallenge() - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "Failed to generate challenge", - }) - } - - // Store session - session := &WebAuthnSession{ - Challenge: challenge, - Username: req.Username, - CreatedAt: time.Now(), - SessionType: "registration", - } - - webAuthnStore.mu.Lock() - webAuthnStore.sessions[req.Username] = session - webAuthnStore.mu.Unlock() - - // Create registration response - response := WebAuthnRegistrationResponse{ - Challenge: challenge, - RP: WebAuthnRPEntity{ - ID: "localhost", // TODO: Get from config - Name: "Sonr Identity Platform", - }, - User: WebAuthnUserEntity{ - ID: base64.URLEncoding.EncodeToString([]byte(req.Username)), - Name: req.Username, - DisplayName: req.Username, - }, - PubKeyCredParams: []WebAuthnCredParam{ - {Type: "public-key", Alg: -7}, // ES256 - {Type: "public-key", Alg: -257}, // RS256 - }, - AuthenticatorSelection: WebAuthnAuthenticatorSelection{ - AuthenticatorAttachment: "platform", - UserVerification: "required", - ResidentKey: "preferred", - }, - Timeout: 60000, - Attestation: "direct", - } - - return c.JSON(http.StatusOK, response) -} - -// FinishWebAuthnRegistration completes WebAuthn registration ceremony -func FinishWebAuthnRegistration(c echo.Context) error { - username := c.QueryParam("username") - if username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Username is required", - }) - } - - // Parse registration response - var regResponse map[string]any - if err := c.Bind(®Response); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid registration response", - }) - } - - // Get stored session - webAuthnStore.mu.RLock() - session, exists := webAuthnStore.sessions[username] - webAuthnStore.mu.RUnlock() - - if !exists || session.SessionType != "registration" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "No registration session found", - }) - } - - // Check session timeout - if time.Since(session.CreatedAt) > sessionTimeout { - webAuthnStore.mu.Lock() - delete(webAuthnStore.sessions, username) - webAuthnStore.mu.Unlock() - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Registration session expired", - }) - } - - // Extract credential data - credentialID, _ := regResponse["id"].(string) - rawID, _ := regResponse["rawId"].(string) - response, _ := regResponse["response"].(map[string]any) - clientDataJSON, _ := response["clientDataJSON"].(string) - attestationObject, _ := response["attestationObject"].(string) - - // Verify client data - if err := verifyClientData(clientDataJSON, session.Challenge, "webauthn.create"); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": fmt.Sprintf("Client data verification failed: %v", err), - }) - } - - // Extract public key from attestation - publicKey, algorithm, err := extractPublicKeyFromAttestation(attestationObject) - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": fmt.Sprintf("Failed to extract public key: %v", err), - }) - } - - // Create credential - credential := &WebAuthnCredential{ - CredentialID: credentialID, - RawID: rawID, - ClientDataJSON: clientDataJSON, - AttestationObject: attestationObject, - Username: username, - Origin: "localhost", // TODO: Extract from client data - PublicKey: publicKey, - Algorithm: algorithm, - CreatedAt: time.Now(), - } - - // Store credential - webAuthnStore.mu.Lock() - webAuthnStore.credentials[username] = append(webAuthnStore.credentials[username], credential) - delete(webAuthnStore.sessions, username) - webAuthnStore.mu.Unlock() - - // Check if we should broadcast to blockchain - broadcastReq, ok := c.Get("broadcast_to_chain").(bool) - if !ok { - // Check from original request stored in context - if origReq, exists := c.Get("webauthn_registration_request").(*WebAuthnRegistrationRequest); exists { - broadcastReq = origReq.BroadcastToChain - } - } - - var broadcastResult *BroadcastResponse - if broadcastReq { - // Broadcast WebAuthn credential to blockchain as gasless transaction - result, err := BroadcastWebAuthnRegistration(credential, true) - if err != nil { - // Log error but don't fail registration - c.Logger().Error("Failed to broadcast WebAuthn credential:", err) - } else { - broadcastResult = result - } - } - - // Check if we should create a vault - autoCreateVault, ok := c.Get("auto_create_vault").(bool) - if !ok { - // Check from original request - if origReq, exists := c.Get("webauthn_registration_request").(*WebAuthnRegistrationRequest); exists { - autoCreateVault = origReq.AutoCreateVault - } - } - - var vaultResult *BroadcastResponse - if autoCreateVault { - // Create vault for the user - vaultConfig := map[string]any{ - "type": "standard", - "encryption": "AES256", - "owner": username, - } - - userDID := fmt.Sprintf("did:sonr:%s", username) - result, err := BroadcastVaultCreation(userDID, vaultConfig) - if err != nil { - // Log error but don't fail registration - c.Logger().Error("Failed to create vault:", err) - } else { - vaultResult = result - } - } - - finalResponse := map[string]any{ - "success": true, - "message": "Registration completed successfully", - "credentialId": credentialID, - } - - if broadcastResult != nil { - finalResponse["broadcast"] = broadcastResult - } - - if vaultResult != nil { - finalResponse["vault"] = vaultResult - } - - return c.JSON(http.StatusOK, finalResponse) -} - -// BeginWebAuthnAuthentication starts WebAuthn authentication ceremony -func BeginWebAuthnAuthentication(c echo.Context) error { - var req WebAuthnAuthenticationRequest - if err := c.Bind(&req); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid request format", - }) - } - - if req.Username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Username is required", - }) - } - - // Check if user has credentials - webAuthnStore.mu.RLock() - credentials, exists := webAuthnStore.credentials[req.Username] - webAuthnStore.mu.RUnlock() - - if !exists || len(credentials) == 0 { - return c.JSON(http.StatusNotFound, map[string]string{ - "error": "No credentials found for user", - }) - } - - // Generate challenge - challenge, err := generateChallenge() - if err != nil { - return c.JSON(http.StatusInternalServerError, map[string]string{ - "error": "Failed to generate challenge", - }) - } - - // Store session - session := &WebAuthnSession{ - Challenge: challenge, - Username: req.Username, - CreatedAt: time.Now(), - SessionType: "authentication", - } - - webAuthnStore.mu.Lock() - webAuthnStore.sessions[req.Username] = session - webAuthnStore.mu.Unlock() - - // Build allowed credentials - allowCredentials := make([]WebAuthnAllowedCred, len(credentials)) - for i, cred := range credentials { - allowCredentials[i] = WebAuthnAllowedCred{ - Type: "public-key", - ID: cred.CredentialID, - } - } - - // Create authentication response - response := WebAuthnAuthenticationResponse{ - Challenge: challenge, - Timeout: 60000, - RPID: "localhost", // TODO: Get from config - AllowCredentials: allowCredentials, - UserVerification: "required", - } - - return c.JSON(http.StatusOK, response) -} - -// FinishWebAuthnAuthentication completes WebAuthn authentication ceremony -func FinishWebAuthnAuthentication(c echo.Context) error { - username := c.QueryParam("username") - if username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Username is required", - }) - } - - // Parse authentication response - var authResponse map[string]any - if err := c.Bind(&authResponse); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Invalid authentication response", - }) - } - - // Get stored session - webAuthnStore.mu.RLock() - session, exists := webAuthnStore.sessions[username] - webAuthnStore.mu.RUnlock() - - if !exists || session.SessionType != "authentication" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "No authentication session found", - }) - } - - // Check session timeout - if time.Since(session.CreatedAt) > sessionTimeout { - webAuthnStore.mu.Lock() - delete(webAuthnStore.sessions, username) - webAuthnStore.mu.Unlock() - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Authentication session expired", - }) - } - - // Extract response data - credentialID, _ := authResponse["id"].(string) - response, _ := authResponse["response"].(map[string]any) - clientDataJSON, _ := response["clientDataJSON"].(string) - authenticatorData, _ := response["authenticatorData"].(string) - signature, _ := response["signature"].(string) - userHandle, _ := response["userHandle"].(string) - - // Verify client data - if err := verifyClientData(clientDataJSON, session.Challenge, "webauthn.get"); err != nil { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": fmt.Sprintf("Client data verification failed: %v", err), - }) - } - - // Find matching credential - webAuthnStore.mu.RLock() - credentials := webAuthnStore.credentials[username] - webAuthnStore.mu.RUnlock() - - var matchedCredential *WebAuthnCredential - for _, cred := range credentials { - if cred.CredentialID == credentialID { - matchedCredential = cred - break - } - } - - if matchedCredential == nil { - return c.JSON(http.StatusUnauthorized, map[string]string{ - "error": "Invalid credential", - }) - } - - // TODO: Verify signature using the stored public key - // This would require implementing proper WebAuthn signature verification - - // Clean up session - webAuthnStore.mu.Lock() - delete(webAuthnStore.sessions, username) - webAuthnStore.mu.Unlock() - - // Create authenticated session - userDID := fmt.Sprintf("did:sonr:%s", username) - authSession := &OIDCSession{ - SessionID: generateSessionID(), - UserDID: userDID, - ClientID: "webauthn-client", - Scope: "openid profile did vault", - AccessToken: generateAccessToken(userDID), - RefreshToken: generateRefreshToken(), - ExpiresAt: time.Now().Add(time.Hour), - CreatedAt: time.Now(), - } - - // Store session for OIDC compatibility - oidcProvider.mu.Lock() - oidcProvider.sessions[authSession.AccessToken] = authSession - oidcProvider.mu.Unlock() - - // Set user context for downstream handlers - c.Set("user_did", userDID) - c.Set("authenticated", true) - c.Set("auth_method", "webauthn") - c.Set("credential_id", credentialID) - - return c.JSON(http.StatusOK, map[string]any{ - "success": true, - "message": "Authentication successful", - "credentialId": credentialID, - "accessToken": authSession.AccessToken, - "expiresIn": 3600, - "userDID": userDID, - "sessionId": authSession.SessionID, - "authenticatorData": authenticatorData, - "signature": signature, - "userHandle": userHandle, - }) -} - -// generateChallenge creates a cryptographically secure challenge -func generateChallenge() (string, error) { - bytes := make([]byte, 32) - if _, err := rand.Read(bytes); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(bytes), nil -} - -// verifyClientData verifies client data JSON -func verifyClientData(clientDataJSON, expectedChallenge, expectedType string) error { - clientData, err := webauthn.ValidateClientDataJSONFormat(clientDataJSON) - if err != nil { - return fmt.Errorf("failed to parse client data: %w", err) - } - - if clientData.Challenge != expectedChallenge { - return fmt.Errorf("challenge mismatch") - } - - if clientData.Type != expectedType { - return fmt.Errorf( - "invalid client data type: expected %s, got %s", - expectedType, - clientData.Type, - ) - } - - // TODO: Verify origin from config - expectedOrigins := []string{ - "http://localhost", - "http://localhost:8080", - "http://localhost:8081", - "http://localhost:8082", - "http://localhost:8083", - "http://localhost:8084", - } - - validOrigin := false - for _, origin := range expectedOrigins { - if clientData.Origin == origin { - validOrigin = true - break - } - } - - if !validOrigin { - return fmt.Errorf("invalid origin: %s", clientData.Origin) - } - - return nil -} - -// extractPublicKeyFromAttestation extracts public key from attestation object -func extractPublicKeyFromAttestation(attestationObjectB64 string) ([]byte, int32, error) { - // Validate format - if err := webauthn.ValidateAttestationObjectFormat(attestationObjectB64); err != nil { - return nil, 0, fmt.Errorf("invalid attestation format: %w", err) - } - - // Decode attestation object - attestationBytes, err := base64.RawURLEncoding.DecodeString(attestationObjectB64) - if err != nil { - return nil, 0, fmt.Errorf("failed to decode attestation: %w", err) - } - - // Parse CBOR - var attestationObj webauthn.AttestationObject - if err := webauthncbor.Unmarshal(attestationBytes, &attestationObj); err != nil { - return nil, 0, fmt.Errorf("failed to unmarshal attestation: %w", err) - } - - // Unmarshal authenticator data - if err := attestationObj.AuthData.Unmarshal(attestationObj.RawAuthData); err != nil { - return nil, 0, fmt.Errorf("failed to unmarshal auth data: %w", err) - } - - // Check for attested credential data - if !attestationObj.AuthData.Flags.HasAttestedCredentialData() { - return nil, 0, fmt.Errorf("no attested credential data") - } - - publicKey := attestationObj.AuthData.AttData.CredentialPublicKey - if len(publicKey) == 0 { - return nil, 0, fmt.Errorf("no public key found") - } - - // Default to ES256 algorithm - algorithm := int32(-7) - - return publicKey, algorithm, nil -} - -// GetWebAuthnCredentials retrieves credentials for a user -func GetWebAuthnCredentials(c echo.Context) error { - username := c.Param("username") - if username == "" { - return c.JSON(http.StatusBadRequest, map[string]string{ - "error": "Username is required", - }) - } - - webAuthnStore.mu.RLock() - credentials, exists := webAuthnStore.credentials[username] - webAuthnStore.mu.RUnlock() - - if !exists { - return c.JSON(http.StatusNotFound, map[string]string{ - "error": "No credentials found for user", - }) - } - - // Return sanitized credentials (without sensitive data) - sanitized := make([]map[string]any, len(credentials)) - for i, cred := range credentials { - sanitized[i] = map[string]any{ - "credentialId": cred.CredentialID, - "createdAt": cred.CreatedAt, - "algorithm": cred.Algorithm, - } - } - - return c.JSON(http.StatusOK, sanitized) -} diff --git a/bridge/handlers/websocket.go b/bridge/handlers/websocket.go deleted file mode 100644 index d1ec531ed..000000000 --- a/bridge/handlers/websocket.go +++ /dev/null @@ -1,284 +0,0 @@ -package handlers - -import ( - "fmt" - "log" - "net/http" - "sync" - "time" - - "github.com/gorilla/websocket" - "github.com/labstack/echo/v4" -) - -// TaskStatusMessage represents a WebSocket message for task status updates -type TaskStatusMessage struct { - TaskID string `json:"task_id"` - Status string `json:"status"` - Progress int `json:"progress,omitempty"` - Data any `json:"data,omitempty"` - Error string `json:"error,omitempty"` - Time time.Time `json:"timestamp"` -} - -// ConnectionManager manages WebSocket connections for task status broadcasting -type ConnectionManager struct { - connections map[string]map[*websocket.Conn]bool // taskID -> connections - mutex sync.RWMutex -} - -// NewConnectionManager creates a new connection manager -func NewConnectionManager() *ConnectionManager { - return &ConnectionManager{ - connections: make(map[string]map[*websocket.Conn]bool), - mutex: sync.RWMutex{}, - } -} - -// AddConnection adds a WebSocket connection for a specific task ID -func (cm *ConnectionManager) AddConnection(taskID string, conn *websocket.Conn) { - cm.mutex.Lock() - defer cm.mutex.Unlock() - - if cm.connections[taskID] == nil { - cm.connections[taskID] = make(map[*websocket.Conn]bool) - } - cm.connections[taskID][conn] = true - log.Printf("WebSocket connection added for task: %s", taskID) -} - -// RemoveConnection removes a WebSocket connection -func (cm *ConnectionManager) RemoveConnection(taskID string, conn *websocket.Conn) { - cm.mutex.Lock() - defer cm.mutex.Unlock() - - if connections, exists := cm.connections[taskID]; exists { - delete(connections, conn) - if len(connections) == 0 { - delete(cm.connections, taskID) - } - } - log.Printf("WebSocket connection removed for task: %s", taskID) -} - -// BroadcastToTask broadcasts a message to all connections listening to a specific task -func (cm *ConnectionManager) BroadcastToTask(taskID string, message TaskStatusMessage) { - cm.mutex.RLock() - connections, exists := cm.connections[taskID] - cm.mutex.RUnlock() - - if !exists { - return - } - - for conn := range connections { - if err := conn.WriteJSON(message); err != nil { - log.Printf("Error broadcasting to WebSocket: %v", err) - cm.RemoveConnection(taskID, conn) - conn.Close() - } - } -} - -// SSEManager manages Server-Sent Event connections for task status streaming -type SSEManager struct { - connections map[string]map[chan TaskStatusMessage]bool // taskID -> channels - mutex sync.RWMutex -} - -// NewSSEManager creates a new SSE manager -func NewSSEManager() *SSEManager { - return &SSEManager{ - connections: make(map[string]map[chan TaskStatusMessage]bool), - mutex: sync.RWMutex{}, - } -} - -// AddSSEConnection adds an SSE channel for a specific task ID -func (sm *SSEManager) AddSSEConnection(taskID string, ch chan TaskStatusMessage) { - sm.mutex.Lock() - defer sm.mutex.Unlock() - - if sm.connections[taskID] == nil { - sm.connections[taskID] = make(map[chan TaskStatusMessage]bool) - } - sm.connections[taskID][ch] = true - log.Printf("SSE connection added for task: %s", taskID) -} - -// RemoveSSEConnection removes an SSE channel -func (sm *SSEManager) RemoveSSEConnection(taskID string, ch chan TaskStatusMessage) { - sm.mutex.Lock() - defer sm.mutex.Unlock() - - if channels, exists := sm.connections[taskID]; exists { - delete(channels, ch) - if len(channels) == 0 { - delete(sm.connections, taskID) - } - } - close(ch) - log.Printf("SSE connection removed for task: %s", taskID) -} - -// BroadcastToSSE broadcasts a message to all SSE connections listening to a specific task -func (sm *SSEManager) BroadcastToSSE(taskID string, message TaskStatusMessage) { - sm.mutex.RLock() - channels, exists := sm.connections[taskID] - sm.mutex.RUnlock() - - if !exists { - return - } - - for ch := range channels { - select { - case ch <- message: - // Message sent successfully - default: - // Channel is blocked, remove it - log.Printf("SSE channel blocked, removing for task: %s", taskID) - sm.RemoveSSEConnection(taskID, ch) - } - } -} - -// WebSocketHandler handles WebSocket connections for real-time task status updates -func WebSocketHandler( - upgrader *websocket.Upgrader, - connectionManager *ConnectionManager, -) echo.HandlerFunc { - return func(c echo.Context) error { - taskID := c.Param("task_id") - if taskID == "" { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Task ID is required"}) - } - - // Upgrade HTTP connection to WebSocket - ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil) - if err != nil { - log.Printf("WebSocket upgrade failed: %v", err) - return err - } - defer ws.Close() - - // Add connection to manager - connectionManager.AddConnection(taskID, ws) - defer connectionManager.RemoveConnection(taskID, ws) - - // Send initial connection confirmation - initialMessage := TaskStatusMessage{ - TaskID: taskID, - Status: "connected", - Time: time.Now(), - } - if err := ws.WriteJSON(initialMessage); err != nil { - log.Printf("Error sending initial message: %v", err) - return err - } - - // Keep connection alive and handle incoming messages - for { - // Read message from client (ping/pong for keepalive) - _, _, err := ws.ReadMessage() - if err != nil { - log.Printf("WebSocket read error: %v", err) - break - } - // Echo back a pong message to keep connection alive - pongMessage := TaskStatusMessage{ - TaskID: taskID, - Status: "pong", - Time: time.Now(), - } - if err := ws.WriteJSON(pongMessage); err != nil { - log.Printf("Error sending pong: %v", err) - break - } - } - - return nil - } -} - -// SSEHandler handles Server-Sent Events for streaming task status updates -func SSEHandler(sseManager *SSEManager) echo.HandlerFunc { - return func(c echo.Context) error { - taskID := c.Param("task_id") - if taskID == "" { - return c.JSON(http.StatusBadRequest, map[string]string{"error": "Task ID is required"}) - } - - // Set SSE headers - c.Response().Header().Set("Content-Type", "text/event-stream") - c.Response().Header().Set("Cache-Control", "no-cache") - c.Response().Header().Set("Connection", "keep-alive") - c.Response().Header().Set("Access-Control-Allow-Origin", "*") - c.Response().Header().Set("Access-Control-Allow-Headers", "Cache-Control") - - // Create a channel for this SSE connection - messageCh := make(chan TaskStatusMessage, 10) - sseManager.AddSSEConnection(taskID, messageCh) - defer sseManager.RemoveSSEConnection(taskID, messageCh) - - // Send initial connection message - initialMessage := TaskStatusMessage{ - TaskID: taskID, - Status: "connected", - Time: time.Now(), - } - fmt.Fprintf( - c.Response().Writer, - "data: {\"task_id\":\"%s\",\"status\":\"connected\",\"timestamp\":\"%s\"}\n\n", - taskID, - initialMessage.Time.Format(time.RFC3339), - ) - c.Response().Flush() - - // Keep connection alive and send messages - for { - select { - case message, ok := <-messageCh: - if !ok { - return nil - } - - // Format message as SSE data - sseData := fmt.Sprintf( - "data: {\"task_id\":\"%s\",\"status\":\"%s\",\"progress\":%d,\"timestamp\":\"%s\"}", - message.TaskID, - message.Status, - message.Progress, - message.Time.Format(time.RFC3339), - ) - - if message.Error != "" { - sseData = fmt.Sprintf( - "data: {\"task_id\":\"%s\",\"status\":\"%s\",\"error\":\"%s\",\"timestamp\":\"%s\"}", - message.TaskID, - message.Status, - message.Error, - message.Time.Format(time.RFC3339), - ) - } - - fmt.Fprintf(c.Response().Writer, "%s\n\n", sseData) - c.Response().Flush() - - case <-c.Request().Context().Done(): - // Client disconnected - return nil - - case <-time.After(30 * time.Second): - // Send keepalive message every 30 seconds - fmt.Fprintf( - c.Response().Writer, - "data: {\"task_id\":\"%s\",\"status\":\"keepalive\",\"timestamp\":\"%s\"}\n\n", - taskID, - time.Now().Format(time.RFC3339), - ) - c.Response().Flush() - } - } - } -} diff --git a/bridge/queue.go b/bridge/queue.go deleted file mode 100644 index ab6f82e03..000000000 --- a/bridge/queue.go +++ /dev/null @@ -1,62 +0,0 @@ -package bridge - -import ( - "log" - - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/bridge/tasks" -) - -// QueueManager handles Asynq server setup and task registration -type QueueManager struct { - server *asynq.Server - mux *asynq.ServeMux - config *Config -} - -// NewQueueManager creates a new queue manager with the given configuration -func NewQueueManager(config *Config) *QueueManager { - // Initialize UCAN task processing server with optimized queue configuration - srv := asynq.NewServer( - asynq.RedisClientOpt{Addr: config.RedisAddr}, - config.AsynqConfig, - ) - - // Register UCAN-based task handlers - mux := asynq.NewServeMux() - registerTaskHandlers(mux) - - return &QueueManager{ - server: srv, - mux: mux, - config: config, - } -} - -// registerTaskHandlers registers all UCAN-based task handlers -func registerTaskHandlers(mux *asynq.ServeMux) { - // Core UCAN token operations - mux.Handle(tasks.TypeUCANToken, tasks.NewUCANProcessor()) - mux.Handle(tasks.TypeUCANAttenuation, tasks.NewUCANAttenuationProcessor()) - - // MPC-based cryptographic operations - mux.Handle(tasks.TypeUCANSign, tasks.NewUCANSignProcessor()) - mux.Handle(tasks.TypeUCANVerify, tasks.NewUCANVerifyProcessor()) - - // DID operations (replaces both TypeVaultGenerate and TypeVaultRefresh) - // Serves as proxy for future x/did module integration - mux.Handle(tasks.TypeUCANDIDGeneration, tasks.NewUCANDIDProcessor()) - - log.Printf("UCAN task handlers registered successfully") -} - -// Run starts the Asynq server with the registered task handlers -func (qm *QueueManager) Run() error { - log.Printf("Starting Asynq task server with Redis at %s", qm.config.RedisAddr) - return qm.server.Run(qm.mux) -} - -// Shutdown gracefully shuts down the Asynq server -func (qm *QueueManager) Shutdown() { - qm.server.Shutdown() -} diff --git a/bridge/server/benchmark_test.go b/bridge/server/benchmark_test.go deleted file mode 100644 index a491c9c5a..000000000 --- a/bridge/server/benchmark_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package server - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "runtime" - "testing" - "time" - - "github.com/hibiken/asynq" - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/crypto/mpc" -) - -// MockAsynqClient provides a test double for asynq.Client -type MockAsynqClient struct { - enqueuedTasks []MockTask -} - -type MockTask struct { - Type string - Payload []byte - Queue string -} - -func (m *MockAsynqClient) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) { - mockTask := MockTask{ - Type: task.Type(), - Payload: task.Payload(), - Queue: "default", - } - m.enqueuedTasks = append(m.enqueuedTasks, mockTask) - - return &asynq.TaskInfo{ - ID: "test-task-id", - Type: task.Type(), - Queue: mockTask.Queue, - }, nil -} - -func (m *MockAsynqClient) Close() error { - return nil -} - -// setupTestEcho creates a test Echo server and mock client for benchmarking -func setupTestEcho() (*echo.Echo, *MockAsynqClient) { - mockClient := &MockAsynqClient{} - config := &Config{ - JWTSecret: []byte("test-secret"), - IPFSClient: &MockIPFSClient{}, - } - s := NewServer(config) - return s.Echo(), mockClient -} - -// BenchmarkHealthCheckHandler measures the performance of the health check endpoint -func BenchmarkHealthCheckHandler(b *testing.B) { - e, _ := setupTestEcho() - - b.ResetTimer() - b.ReportAllocs() - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - req := httptest.NewRequest("GET", "/health", nil) - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - - if rr.Code != http.StatusOK { - b.Errorf("Expected status 200, got %d", rr.Code) - } - } - }) -} - -// BenchmarkGenerateHandler measures the performance of the generate endpoint -func BenchmarkGenerateHandler(b *testing.B) { - e, client := setupTestEcho() - - payload := map[string]any{ - "user_id": 123, - "priority": "default", - } - - var buf bytes.Buffer - json.NewEncoder(&buf).Encode(payload) - requestBody := buf.Bytes() - - b.ResetTimer() - b.ReportAllocs() - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - req := httptest.NewRequest("POST", "/vault/generate", bytes.NewReader(requestBody)) - req.Header.Set("Content-Type", "application/json") - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - - if rr.Code != http.StatusOK { - b.Errorf("Expected status 200, got %d", rr.Code) - } - } - }) - - b.StopTimer() - b.Logf("Tasks enqueued: %d", len(client.enqueuedTasks)) -} - -// BenchmarkSignHandler measures the performance of the sign endpoint -func BenchmarkSignHandler(b *testing.B) { - e, client := setupTestEcho() - - payload := map[string]any{ - "message": []byte("benchmark test message"), - "enclave": &mpc.EnclaveData{}, - "priority": "default", - } - - var buf bytes.Buffer - json.NewEncoder(&buf).Encode(payload) - requestBody := buf.Bytes() - - b.ResetTimer() - b.ReportAllocs() - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - req := httptest.NewRequest("POST", "/vault/sign", bytes.NewReader(requestBody)) - req.Header.Set("Content-Type", "application/json") - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - - if rr.Code != http.StatusOK { - b.Errorf("Expected status 200, got %d", rr.Code) - } - } - }) - - b.StopTimer() - b.Logf("Tasks enqueued: %d", len(client.enqueuedTasks)) -} - -// BenchmarkMemoryAllocation measures memory allocation patterns -func BenchmarkMemoryAllocation(b *testing.B) { - e, _ := setupTestEcho() - - payload := map[string]any{ - "user_id": 123, - } - - var buf bytes.Buffer - json.NewEncoder(&buf).Encode(payload) - requestBody := buf.Bytes() - - var m1, m2 runtime.MemStats - runtime.GC() - runtime.ReadMemStats(&m1) - - b.ReportAllocs() - - for b.Loop() { - req := httptest.NewRequest("POST", "/vault/generate", bytes.NewReader(requestBody)) - req.Header.Set("Content-Type", "application/json") - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - } - - b.StopTimer() - runtime.GC() - runtime.ReadMemStats(&m2) - - b.Logf("Memory allocated per operation: %d bytes", (m2.TotalAlloc-m1.TotalAlloc)/uint64(b.N)) - b.Logf("Total allocations: %d", m2.Mallocs-m1.Mallocs) -} - -// BenchmarkLatencyMeasurement measures end-to-end latency -func BenchmarkLatencyMeasurement(b *testing.B) { - e, _ := setupTestEcho() - - payload := map[string]any{ - "user_id": 123, - } - - var buf bytes.Buffer - json.NewEncoder(&buf).Encode(payload) - requestBody := buf.Bytes() - - var totalLatency time.Duration - minLatency := time.Hour - var maxLatency time.Duration - - for b.Loop() { - start := time.Now() - - req := httptest.NewRequest("POST", "/vault/generate", bytes.NewReader(requestBody)) - req.Header.Set("Content-Type", "application/json") - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - - latency := time.Since(start) - totalLatency += latency - - if latency < minLatency { - minLatency = latency - } - if latency > maxLatency { - maxLatency = latency - } - - if rr.Code != http.StatusOK { - b.Errorf("Expected status 200, got %d", rr.Code) - } - } - - b.StopTimer() - - avgLatency := totalLatency / time.Duration(b.N) - b.Logf("Average latency: %v", avgLatency) - b.Logf("Min latency: %v", minLatency) - b.Logf("Max latency: %v", maxLatency) -} diff --git a/bridge/server/server.go b/bridge/server/server.go deleted file mode 100644 index 4da020287..000000000 --- a/bridge/server/server.go +++ /dev/null @@ -1,118 +0,0 @@ -// Package server provides the HTTP server for the highway server -package server - -import ( - "net/http" - - "github.com/gorilla/websocket" - "github.com/hibiken/asynq" - echojwt "github.com/labstack/echo-jwt/v4" - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" - "github.com/sonr-io/sonr/bridge/handlers" - "github.com/sonr-io/sonr/types/ipfs" -) - -const ( - DefaultHTTPAddr = ":8080" -) - -// Config holds server configuration -type Config struct { - HTTPAddr string - JWTSecret []byte - IPFSClient ipfs.IPFSClient -} - -// Server represents the HTTP server -type Server struct { - config *Config - echo *echo.Echo - upgrader *websocket.Upgrader - connectionManager *handlers.ConnectionManager - sseManager *handlers.SSEManager - vaultHandlers *handlers.VaultHandlers -} - -// NewServer creates a new server instance -func NewServer(config *Config) *Server { - // WebSocket upgrader with CORS settings - upgrader := &websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { - return true // Allow all origins in development - }, - } - - // Create connection managers - connectionManager := handlers.NewConnectionManager() - sseManager := handlers.NewSSEManager() - - // Create vault handlers - vaultHandlers := handlers.NewVaultHandlers(config.IPFSClient, connectionManager, sseManager) - - return &Server{ - config: config, - echo: echo.New(), - upgrader: upgrader, - connectionManager: connectionManager, - sseManager: sseManager, - vaultHandlers: vaultHandlers, - } -} - -// Echo returns the underlying Echo instance for testing -func (s *Server) Echo() *echo.Echo { - return s.echo -} - -// Start starts the HTTP server -func (s *Server) Start(client *asynq.Client) error { - s.setupMiddleware() - s.setupRoutes(client) - - addr := s.config.HTTPAddr - if addr == "" { - addr = DefaultHTTPAddr - } - return s.echo.Start(addr) -} - -// setupMiddleware configures Echo middleware -func (s *Server) setupMiddleware() { - s.echo.Use(middleware.Logger()) - s.echo.Use(middleware.Recover()) - s.echo.Use(middleware.CORS()) -} - -// setupRoutes configures all routes -func (s *Server) setupRoutes(client *asynq.Client) { - // Initialize health checker - handlers.InitHealthChecker(client, s.config.IPFSClient) - - // Public endpoints (no authentication required) - s.echo.GET("/health", handlers.HealthCheckHandler) // Liveness probe - s.echo.GET("/ready", handlers.ReadinessHandler) // Readiness probe - s.echo.POST("/auth/login", handlers.LoginHandler(s.config.JWTSecret)) - - // JWT middleware configuration - jwtConfig := echojwt.Config{ - SigningKey: s.config.JWTSecret, - SigningMethod: "HS256", - } - - // Protected vault endpoints group with JWT middleware - vault := s.echo.Group("/vault") - vault.Use(echojwt.WithConfig(jwtConfig)) - vault.POST("/generate", s.vaultHandlers.GenerateHandler(client)) - vault.POST("/sign", s.vaultHandlers.SignHandler(client)) - vault.POST("/verify", s.vaultHandlers.VerifyHandler(client)) - vault.POST("/export", s.vaultHandlers.ExportHandler(client)) - vault.POST("/import", s.vaultHandlers.ImportHandler(client)) - vault.POST("/refresh", s.vaultHandlers.RefreshHandler(client)) - - // WebSocket endpoint for real-time task status updates - vault.GET("/ws/:task_id", handlers.WebSocketHandler(s.upgrader, s.connectionManager)) - - // Server-Sent Events endpoint for task progress streaming - vault.GET("/events/:task_id", handlers.SSEHandler(s.sseManager)) -} diff --git a/bridge/server/server_test.go b/bridge/server/server_test.go deleted file mode 100644 index ed7a9f93e..000000000 --- a/bridge/server/server_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package server - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/labstack/echo/v4" - "github.com/sonr-io/sonr/bridge/handlers" - "github.com/sonr-io/sonr/types/ipfs" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// MockIPFSClient provides a test implementation of IPFSClient for server tests -type MockIPFSClient struct{} - -func (m *MockIPFSClient) Add(data []byte) (string, error) { return "mock-cid", nil } - -func (m *MockIPFSClient) AddFile( - file ipfs.File, -) (string, error) { - return "mock-file-cid", nil -} - -func (m *MockIPFSClient) AddFolder( - folder ipfs.Folder, -) (string, error) { - return "mock-folder-cid", nil -} - -func (m *MockIPFSClient) Get( - cid string, -) ([]byte, error) { - return []byte("mock-ipfs-data"), nil -} -func (m *MockIPFSClient) GetFile(cid string) (ipfs.File, error) { return nil, nil } -func (m *MockIPFSClient) GetFolder(cid string) (ipfs.Folder, error) { return nil, nil } -func (m *MockIPFSClient) Pin(cid string, name string) error { return nil } -func (m *MockIPFSClient) Unpin(cid string) error { return nil } -func (m *MockIPFSClient) Exists(cid string) (bool, error) { return true, nil } -func (m *MockIPFSClient) IsPinned(ipns string) (bool, error) { return true, nil } -func (m *MockIPFSClient) Ls(cid string) ([]string, error) { - return []string{"mock-file1", "mock-file2"}, nil -} - -func (m *MockIPFSClient) NodeStatus() (*ipfs.NodeStatus, error) { - return &ipfs.NodeStatus{ - PeerID: "mock-peer-id", - Version: "mock-version", - PeerType: "kubo", - ConnectedPeers: 3, - }, nil -} - -func setupTestServer() *Server { - config := &Config{ - JWTSecret: []byte("test-secret"), - IPFSClient: &MockIPFSClient{}, - } - s := NewServer(config) - - // Setup routes manually for testing since we can't call Start() which would block - e := s.Echo() - - // Setup middleware - e.Use(func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - return next(c) - } - }) - - // Setup routes manually (mimicking server.setupRoutes) - e.GET("/health", handlers.HealthCheckHandler) - e.POST("/auth/login", handlers.LoginHandler(config.JWTSecret)) - - return s -} - -func TestHealthCheckHandler(t *testing.T) { - s := setupTestServer() - e := s.Echo() - - req, err := http.NewRequest("GET", "/health", nil) - require.NoError(t, err) - - rr := httptest.NewRecorder() - e.ServeHTTP(rr, req) - - assert.Equal(t, http.StatusOK, rr.Code) - assert.Equal(t, "application/json", rr.Header().Get("Content-Type")) - - var response map[string]string - err = json.Unmarshal(rr.Body.Bytes(), &response) - require.NoError(t, err) - // When health checker is not initialized, it returns "starting" status - // This is expected behavior in test environment - assert.Equal(t, "starting", response["status"]) -} - -func TestVaultHandlersCreation(t *testing.T) { - // Test the vault handlers creation - vaultHandlers := handlers.NewVaultHandlers( - &MockIPFSClient{}, - handlers.NewConnectionManager(), - handlers.NewSSEManager(), - ) - assert.NotNil(t, vaultHandlers) -} diff --git a/bridge/tasks/attenuation.go b/bridge/tasks/attenuation.go deleted file mode 100644 index 796413342..000000000 --- a/bridge/tasks/attenuation.go +++ /dev/null @@ -1,156 +0,0 @@ -// Package tasks provides UCAN-based task processing for token attenuation operations. -package tasks - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/asynkron/protoactor-go/actor" - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/x/dwn/client/plugin" -) - -// ╭─────────────────────────────────────────────────────────╮ -// │ Processor │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANAttenuationProcessor implements asynq.Handler interface for UCAN attenuation operations. -type UCANAttenuationProcessor struct { - asynq.Handler - pid *actor.PID -} - -// NewUCANAttenuationProcessor creates a new UCANAttenuationProcessor for the specified actor system. -func NewUCANAttenuationProcessor() *UCANAttenuationProcessor { - pid := system.Root.SpawnPrefix(plugin.Props(), TypeUCANAttenuation) - return &UCANAttenuationProcessor{ - pid: pid, - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Payload │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANAttenuationPayload contains parameters for UCAN token attenuation task. -type UCANAttenuationPayload struct { - UserID int `json:"user_id"` - ParentToken string `json:"parent_token"` - AudienceDID string `json:"audience_did"` - Attenuations []map[string]any `json:"attenuations,omitempty"` - ExpiresAt int64 `json:"expires_at,omitempty"` -} - -// NewUCANAttenuationTask creates a new UCAN token attenuation task. -func NewUCANAttenuationTask( - userID int, - parentToken string, - audienceDID string, - attenuations []map[string]any, - expiresAt int64, -) (*asynq.Task, error) { - payload, err := json.Marshal(UCANAttenuationPayload{ - UserID: userID, - ParentToken: parentToken, - AudienceDID: audienceDID, - Attenuations: attenuations, - ExpiresAt: expiresAt, - }) - if err != nil { - return nil, err - } - return asynq.NewTask(TypeUCANAttenuation, payload), nil -} - -// ╭───────────────────────────────────────────────────────╮ -// │ Handler │ -// ╰───────────────────────────────────────────────────────╯ - -// ProcessTask processes the UCAN token attenuation task. -func (processor *UCANAttenuationProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error { - var p UCANAttenuationPayload - if err := json.Unmarshal(t.Payload(), &p); err != nil { - return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry) - } - - // Create attenuated token request for the actor - request := &plugin.NewAttenuatedTokenRequest{ - ParentToken: p.ParentToken, - AudienceDID: p.AudienceDID, - Attenuations: p.Attenuations, - ExpiresAt: p.ExpiresAt, - } - - resp, err := system.Root.RequestFuture(processor.pid, request, KRequestTimeout).Result() - if err != nil { - return err - } - switch resp := resp.(type) { - case *plugin.UCANTokenResponse: - if resp.Error != "" { - return fmt.Errorf("UCAN token attenuation failed: %s", resp.Error) - } - return nil - default: - return fmt.Errorf("invalid response type: %T", resp) - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ DID Generation Processor │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANDIDProcessor implements asynq.Handler interface for DID generation operations. -type UCANDIDProcessor struct { - asynq.Handler - pid *actor.PID -} - -// NewUCANDIDProcessor creates a new UCANDIDProcessor for the specified actor system. -func NewUCANDIDProcessor() *UCANDIDProcessor { - pid := system.Root.SpawnPrefix(plugin.Props(), TypeUCANDIDGeneration) - return &UCANDIDProcessor{ - pid: pid, - } -} - -// UCANDIDPayload contains parameters for DID generation task. -type UCANDIDPayload struct { - UserID int `json:"user_id"` -} - -// NewUCANDIDTask creates a new DID generation task. -func NewUCANDIDTask(userID int) (*asynq.Task, error) { - payload, err := json.Marshal(UCANDIDPayload{ - UserID: userID, - }) - if err != nil { - return nil, err - } - return asynq.NewTask(TypeUCANDIDGeneration, payload), nil -} - -// ProcessTask processes the DID generation task. -func (processor *UCANDIDProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error { - var p UCANDIDPayload - if err := json.Unmarshal(t.Payload(), &p); err != nil { - return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry) - } - - // Request DID generation from the actor - resp, err := system.Root.RequestFuture(processor.pid, &plugin.GetIssuerDIDResponse{}, KRequestTimeout). - Result() - if err != nil { - return err - } - switch resp := resp.(type) { - case *plugin.GetIssuerDIDResponse: - if resp.Error != "" { - return fmt.Errorf("DID generation failed: %s", resp.Error) - } - return nil - default: - return fmt.Errorf("invalid response type: %T", resp) - } -} diff --git a/bridge/tasks/generate.go b/bridge/tasks/generate.go deleted file mode 100644 index 3e3791e04..000000000 --- a/bridge/tasks/generate.go +++ /dev/null @@ -1,96 +0,0 @@ -// Package tasks provides UCAN-based task processing for the refactored Motor plugin. -// This package handles asynchronous UCAN token creation, signing operations, -// and DID management tasks using the MPC-based plugin architecture. -package tasks - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/asynkron/protoactor-go/actor" - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/x/dwn/client/plugin" -) - -// ╭─────────────────────────────────────────────────────────╮ -// │ Processor │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANProcessor implements asynq.Handler interface for UCAN operations. -type UCANProcessor struct { - asynq.Handler - pid *actor.PID -} - -// NewUCANProcessor creates a new UCANProcessor for the specified actor system. -func NewUCANProcessor() *UCANProcessor { - pid := system.Root.SpawnPrefix(plugin.Props(), TypeUCANToken) - return &UCANProcessor{ - pid: pid, - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Payload │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANTokenPayload contains parameters for UCAN token creation task. -type UCANTokenPayload struct { - UserID int `json:"user_id"` - AudienceDID string `json:"audience_did"` - Attenuations []map[string]any `json:"attenuations,omitempty"` - ExpiresAt int64 `json:"expires_at,omitempty"` -} - -// NewUCANTokenTask creates a new UCAN token creation task. -func NewUCANTokenTask( - userID int, - audienceDID string, - attenuations []map[string]any, - expiresAt int64, -) (*asynq.Task, error) { - payload, err := json.Marshal(UCANTokenPayload{ - UserID: userID, - AudienceDID: audienceDID, - Attenuations: attenuations, - ExpiresAt: expiresAt, - }) - if err != nil { - return nil, err - } - return asynq.NewTask(TypeUCANToken, payload), nil -} - -// ╭───────────────────────────────────────────────────────╮ -// │ Handler │ -// ╰───────────────────────────────────────────────────────╯ - -// ProcessTask processes the UCAN token creation task. -func (processor *UCANProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error { - var p UCANTokenPayload - if err := json.Unmarshal(t.Payload(), &p); err != nil { - return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry) - } - - // Create UCAN token request for the actor - request := &plugin.NewOriginTokenRequest{ - AudienceDID: p.AudienceDID, - Attenuations: p.Attenuations, - ExpiresAt: p.ExpiresAt, - } - - resp, err := system.Root.RequestFuture(processor.pid, request, KRequestTimeout).Result() - if err != nil { - return err - } - switch resp := resp.(type) { - case *plugin.UCANTokenResponse: - if resp.Error != "" { - return fmt.Errorf("UCAN token creation failed: %s", resp.Error) - } - return nil - default: - return fmt.Errorf("invalid response type: %T", resp) - } -} diff --git a/bridge/tasks/signing.go b/bridge/tasks/signing.go deleted file mode 100644 index de0794783..000000000 --- a/bridge/tasks/signing.go +++ /dev/null @@ -1,149 +0,0 @@ -// Package tasks provides UCAN-based task processing for MPC signing operations. -package tasks - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/asynkron/protoactor-go/actor" - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/x/dwn/client/plugin" -) - -// ╭─────────────────────────────────────────────────────────╮ -// │ Processor │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANSignProcessor implements asynq.Handler interface for UCAN signing operations. -type UCANSignProcessor struct { - asynq.Handler - pid *actor.PID -} - -// NewUCANSignProcessor creates a new UCANSignProcessor for the specified actor system. -func NewUCANSignProcessor() *UCANSignProcessor { - pid := system.Root.SpawnPrefix(plugin.Props(), TypeUCANSign) - return &UCANSignProcessor{ - pid: pid, - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Payload │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANSignPayload contains parameters for UCAN signing task. -type UCANSignPayload struct { - UserID int `json:"user_id"` - Data []byte `json:"data"` -} - -// NewUCANSignTask creates a new UCAN signing task. -func NewUCANSignTask(userID int, data []byte) (*asynq.Task, error) { - payload, err := json.Marshal(UCANSignPayload{ - UserID: userID, - Data: data, - }) - if err != nil { - return nil, err - } - return asynq.NewTask(TypeUCANSign, payload), nil -} - -// ╭───────────────────────────────────────────────────────╮ -// │ Handler │ -// ╰───────────────────────────────────────────────────────╯ - -// ProcessTask processes the UCAN signing task. -func (processor *UCANSignProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error { - var p UCANSignPayload - if err := json.Unmarshal(t.Payload(), &p); err != nil { - return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry) - } - - // Create signing request for the actor - request := &plugin.SignDataRequest{ - Data: p.Data, - } - - resp, err := system.Root.RequestFuture(processor.pid, request, KRequestTimeout).Result() - if err != nil { - return err - } - switch resp := resp.(type) { - case *plugin.SignDataResponse: - if resp.Error != "" { - return fmt.Errorf("UCAN signing failed: %s", resp.Error) - } - return nil - default: - return fmt.Errorf("invalid response type: %T", resp) - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Verification Processor │ -// ╰─────────────────────────────────────────────────────────╯ - -// UCANVerifyProcessor implements asynq.Handler interface for UCAN verification operations. -type UCANVerifyProcessor struct { - asynq.Handler - pid *actor.PID -} - -// NewUCANVerifyProcessor creates a new UCANVerifyProcessor for the specified actor system. -func NewUCANVerifyProcessor() *UCANVerifyProcessor { - pid := system.Root.SpawnPrefix(plugin.Props(), TypeUCANVerify) - return &UCANVerifyProcessor{ - pid: pid, - } -} - -// UCANVerifyPayload contains parameters for UCAN verification task. -type UCANVerifyPayload struct { - UserID int `json:"user_id"` - Data []byte `json:"data"` - Signature []byte `json:"signature"` -} - -// NewUCANVerifyTask creates a new UCAN verification task. -func NewUCANVerifyTask(userID int, data, signature []byte) (*asynq.Task, error) { - payload, err := json.Marshal(UCANVerifyPayload{ - UserID: userID, - Data: data, - Signature: signature, - }) - if err != nil { - return nil, err - } - return asynq.NewTask(TypeUCANVerify, payload), nil -} - -// ProcessTask processes the UCAN verification task. -func (processor *UCANVerifyProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error { - var p UCANVerifyPayload - if err := json.Unmarshal(t.Payload(), &p); err != nil { - return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry) - } - - // Create verification request for the actor - request := &plugin.VerifyDataRequest{ - Data: p.Data, - Signature: p.Signature, - } - - resp, err := system.Root.RequestFuture(processor.pid, request, KRequestTimeout).Result() - if err != nil { - return err - } - switch resp := resp.(type) { - case *plugin.VerifyDataResponse: - if resp.Error != "" { - return fmt.Errorf("UCAN verification failed: %s", resp.Error) - } - return nil - default: - return fmt.Errorf("invalid response type: %T", resp) - } -} diff --git a/bridge/tasks/tasks_test.go b/bridge/tasks/tasks_test.go deleted file mode 100644 index 433e99740..000000000 --- a/bridge/tasks/tasks_test.go +++ /dev/null @@ -1,425 +0,0 @@ -package tasks - -import ( - "context" - "encoding/json" - "fmt" - "os" - "strings" - "testing" - "time" - - "github.com/asynkron/protoactor-go/actor" - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/crypto/mpc" - "github.com/sonr-io/sonr/x/dwn/client/plugin" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// generateTestEnclaveData creates a test enclave data for testing purposes -func generateTestEnclaveData(t *testing.T) *mpc.EnclaveData { - t.Helper() - - // Generate a new enclave for testing - enclave, err := mpc.NewEnclave() - require.NoError(t, err, "failed to generate test enclave") - - return enclave.GetData() -} - -// MockUCANActor for testing UCAN task processors -type MockUCANActor struct { - responses map[string]any -} - -func NewMockUCANActor() *MockUCANActor { - return &MockUCANActor{ - responses: make(map[string]any), - } -} - -// SlowMockUCANActor simulates timeout scenarios -type SlowMockUCANActor struct{} - -func (s *SlowMockUCANActor) Receive(c actor.Context) { - switch c.Message().(type) { - case *plugin.NewOriginTokenRequest: - // Simulate slow response (longer than KRequestTimeout) - time.Sleep(KRequestTimeout + time.Second) - c.Respond(&plugin.UCANTokenResponse{}) - } -} - -func (m *MockUCANActor) Receive(c actor.Context) { - switch c.Message().(type) { - case *actor.Started: - // Actor started - case *plugin.NewOriginTokenRequest: - c.Respond(&plugin.UCANTokenResponse{ - Token: "mock-ucan-token", - Issuer: "did:sonr:mock-issuer", - Address: "mock-address", - }) - case *plugin.SignDataRequest: - c.Respond(&plugin.SignDataResponse{ - Signature: []byte("mock-signature"), - }) - case *plugin.VerifyDataRequest: - c.Respond(&plugin.VerifyDataResponse{ - Valid: true, - }) - case *plugin.NewAttenuatedTokenRequest: - c.Respond(&plugin.UCANTokenResponse{ - Token: "mock-attenuated-token", - Issuer: "did:sonr:mock-issuer", - Address: "mock-address", - }) - case *plugin.GetIssuerDIDResponse: - c.Respond(&plugin.GetIssuerDIDResponse{ - IssuerDID: "did:sonr:mock-issuer", - Address: "mock-address", - ChainCode: "mock-chain-code", - }) - default: - c.Respond(&actor.DeadLetterResponse{}) - } -} - -func TestUCANTokenTask(t *testing.T) { - tests := []struct { - name string - userID int - audienceDID string - attenuations []map[string]any - expiresAt int64 - }{ - { - name: "valid UCAN token request", - userID: 123, - audienceDID: "did:sonr:audience", - attenuations: []map[string]any{ - {"can": []string{"sign"}, "with": "vault://example"}, - }, - expiresAt: time.Now().Add(24 * time.Hour).Unix(), - }, - { - name: "zero user ID", - userID: 0, - audienceDID: "did:sonr:audience", - attenuations: []map[string]any{}, - expiresAt: 0, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - task, err := NewUCANTokenTask(tt.userID, tt.audienceDID, tt.attenuations, tt.expiresAt) - require.NoError(t, err) - assert.Equal(t, TypeUCANToken, task.Type()) - - var payload UCANTokenPayload - err = json.Unmarshal(task.Payload(), &payload) - require.NoError(t, err) - assert.Equal(t, tt.userID, payload.UserID) - assert.Equal(t, tt.audienceDID, payload.AudienceDID) - // Handle JSON unmarshaling type conversion ([]string becomes []any) - assert.Equal(t, len(tt.attenuations), len(payload.Attenuations)) - for i, expectedAtt := range tt.attenuations { - actualAtt := payload.Attenuations[i] - for key, expectedVal := range expectedAtt { - actualVal, exists := actualAtt[key] - assert.True(t, exists, "key %s should exist", key) - - // Handle []string to []any conversion - if expectedSlice, ok := expectedVal.([]string); ok { - actualSlice, ok := actualVal.([]any) - assert.True(t, ok, "expected []any for key %s", key) - assert.Equal(t, len(expectedSlice), len(actualSlice)) - for j, expectedItem := range expectedSlice { - assert.Equal(t, expectedItem, actualSlice[j]) - } - } else { - assert.Equal(t, expectedVal, actualVal) - } - } - } - assert.Equal(t, tt.expiresAt, payload.ExpiresAt) - }) - } -} - -func TestUCANSignTask(t *testing.T) { - tests := []struct { - name string - userID int - data []byte - }{ - { - name: "valid sign request", - userID: 123, - data: []byte("test data to sign"), - }, - { - name: "empty data", - userID: 456, - data: []byte{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - task, err := NewUCANSignTask(tt.userID, tt.data) - require.NoError(t, err) - assert.Equal(t, TypeUCANSign, task.Type()) - - var payload UCANSignPayload - err = json.Unmarshal(task.Payload(), &payload) - require.NoError(t, err) - assert.Equal(t, tt.userID, payload.UserID) - assert.Equal(t, tt.data, payload.Data) - }) - } -} - -func TestUCANVerifyTask(t *testing.T) { - tests := []struct { - name string - userID int - data []byte - signature []byte - }{ - { - name: "valid verify request", - userID: 123, - data: []byte("test data to verify"), - signature: []byte("test-signature"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - task, err := NewUCANVerifyTask(tt.userID, tt.data, tt.signature) - require.NoError(t, err) - assert.Equal(t, TypeUCANVerify, task.Type()) - - var payload UCANVerifyPayload - err = json.Unmarshal(task.Payload(), &payload) - require.NoError(t, err) - assert.Equal(t, tt.userID, payload.UserID) - assert.Equal(t, tt.data, payload.Data) - assert.Equal(t, tt.signature, payload.Signature) - }) - } -} - -func TestUCANAttenuationTask(t *testing.T) { - tests := []struct { - name string - userID int - parentToken string - audienceDID string - attenuations []map[string]any - expiresAt int64 - }{ - { - name: "valid attenuation request", - userID: 123, - parentToken: "parent-ucan-token", - audienceDID: "did:sonr:delegated", - attenuations: []map[string]any{ - {"can": []string{"read"}, "with": "vault://example"}, - }, - expiresAt: time.Now().Add(1 * time.Hour).Unix(), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - task, err := NewUCANAttenuationTask( - tt.userID, - tt.parentToken, - tt.audienceDID, - tt.attenuations, - tt.expiresAt, - ) - require.NoError(t, err) - assert.Equal(t, TypeUCANAttenuation, task.Type()) - - var payload UCANAttenuationPayload - err = json.Unmarshal(task.Payload(), &payload) - require.NoError(t, err) - assert.Equal(t, tt.userID, payload.UserID) - assert.Equal(t, tt.parentToken, payload.ParentToken) - assert.Equal(t, tt.audienceDID, payload.AudienceDID) - // Handle JSON unmarshaling type conversion ([]string becomes []any) - assert.Equal(t, len(tt.attenuations), len(payload.Attenuations)) - for i, expectedAtt := range tt.attenuations { - actualAtt := payload.Attenuations[i] - for key, expectedVal := range expectedAtt { - actualVal, exists := actualAtt[key] - assert.True(t, exists, "key %s should exist", key) - - // Handle []string to []any conversion - if expectedSlice, ok := expectedVal.([]string); ok { - actualSlice, ok := actualVal.([]any) - assert.True(t, ok, "expected []any for key %s", key) - assert.Equal(t, len(expectedSlice), len(actualSlice)) - for j, expectedItem := range expectedSlice { - assert.Equal(t, expectedItem, actualSlice[j]) - } - } else { - assert.Equal(t, expectedVal, actualVal) - } - } - } - assert.Equal(t, tt.expiresAt, payload.ExpiresAt) - }) - } -} - -func TestUCANDIDTask(t *testing.T) { - tests := []struct { - name string - userID int - }{ - {"valid DID request", 123}, - {"zero user ID", 0}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - task, err := NewUCANDIDTask(tt.userID) - require.NoError(t, err) - assert.Equal(t, TypeUCANDIDGeneration, task.Type()) - - var payload UCANDIDPayload - err = json.Unmarshal(task.Payload(), &payload) - require.NoError(t, err) - assert.Equal(t, tt.userID, payload.UserID) - }) - } -} - -// Test processor functionality with mock actors -func TestUCANTokenProcessor(t *testing.T) { - // Create actor system - system := actor.NewActorSystem() - defer system.Shutdown() - - // Create mock actor - use the mock instead of real plugin - mockActor := system.Root.Spawn(actor.PropsFromProducer(func() actor.Actor { - return NewMockUCANActor() - })) - - // Create processor with mock actor - processor := &UCANProcessor{pid: mockActor} - - // Create test task - task, err := NewUCANTokenTask(123, "did:sonr:audience", []map[string]any{ - {"can": []string{"sign"}, "with": "vault://example"}, - }, time.Now().Add(24*time.Hour).Unix()) - require.NoError(t, err) - - // Process the task - the error is expected because the mock actor returns a dead letter - // The processor should handle this gracefully - err = processor.ProcessTask(context.Background(), task) - - // For now, we expect this to fail with the dead letter error - // In a real scenario, the actor would be properly initialized with enclave data - assert.Error(t, err, "expected error due to mock actor limitations") - assert.Contains(t, err.Error(), "dead letter", "should get dead letter error from mock") -} - -// TestUCANActorWithRealEnclave tests the real UCAN actor with generated enclave data -func TestUCANActorWithRealEnclave(t *testing.T) { - // Skip this test if we're not in integration test mode - if testing.Short() { - t.Skip("skipping integration test") - } - - // Skip this test in CI environments where WASM plugin is not available - if os.Getenv("CI") == "true" || os.Getenv("GITHUB_ACTIONS") == "true" { - t.Skip("skipping WASM enclave test in CI environment") - } - - // Generate test enclave data - enclaveData := generateTestEnclaveData(t) - - // Create enclave config with test data - config := plugin.DefaultEnclaveConfig() - config.EnclaveData = enclaveData - - // Create actor system - system := actor.NewActorSystem() - defer system.Shutdown() - - // Create real UCAN actor with the enclave configuration - realActor := system.Root.Spawn(plugin.PropsWithConfig(config)) - - // Wait for actor to initialize (longer wait for CI environments) - time.Sleep(500 * time.Millisecond) - - // Test creating a UCAN token through the actor - req := &plugin.NewOriginTokenRequest{ - AudienceDID: "did:sonr:test-audience", - Attenuations: []map[string]any{ - {"can": []string{"read"}, "with": "vault://test"}, - }, - ExpiresAt: time.Now().Add(1 * time.Hour).Unix(), - } - - // Send request to actor with enhanced error handling and longer timeout for CI - result := system.Root.RequestFuture(realActor, req, 10*time.Second) - response, err := result.Result() - if err != nil { - t.Logf("Actor request failed: %v", err) - - // If it's a timeout or WASM-related error, that's expected in test environments - if err.Error() == "future: timeout" || strings.Contains(err.Error(), "wasm") { - t.Skip("skipping test due to WASM enclave not available in test environment") - } - } - - // The response could be an error if the actor didn't initialize properly - // For now, just verify we got some response (could be error or success) - but only if not a timeout - if err == nil || err.Error() != "future: timeout" { - assert.NotNil(t, response, "should receive some response from actor") - } - - // Check if this is a WASM-related error (expected when WASM plugin is not available) - if err == nil && response != nil { - // The response could be a string or an error - responseStr := "" - if errResponse, ok := response.(error); ok { - responseStr = errResponse.Error() - } else if strResponse, ok := response.(string); ok { - responseStr = strResponse - } else { - responseStr = fmt.Sprintf("%+v", response) - } - - if responseStr != "" && (strings.Contains(responseStr, "wasm error: unreachable") || - strings.Contains(responseStr, "wasm not available") || - strings.Contains(responseStr, "runtime.notInitialized")) { - t.Log("WASM plugin not available (expected in test environment)") - } else { - t.Logf("Actor successfully processed request: %+v", response) - } - } else { - t.Logf("Actor response: %+v, error: %v", response, err) - } -} - -func TestInvalidJSONPayload(t *testing.T) { - // Create processor - processor := NewUCANProcessor() - - // Create task with invalid JSON - task := asynq.NewTask(TypeUCANToken, []byte("invalid json")) - - // Process the task - should fail with skip retry - err := processor.ProcessTask(context.Background(), task) - assert.Error(t, err) - assert.Contains(t, err.Error(), "json.Unmarshal failed") -} diff --git a/bridge/tasks/types.go b/bridge/tasks/types.go deleted file mode 100644 index a3786fac2..000000000 --- a/bridge/tasks/types.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package tasks provides UCAN-based tasks for the MPC enclave service. -package tasks - -import ( - "time" - - "github.com/asynkron/protoactor-go/actor" -) - -var system = actor.NewActorSystem() - -const KRequestTimeout = 20 * time.Second - -// A list of UCAN-based task types. -const ( - TypeUCANToken = "ucan:token" // Create UCAN origin tokens - TypeUCANAttenuation = "ucan:attenuation" // Create attenuated UCAN tokens - TypeUCANSign = "ucan:sign" // MPC-based data signing - TypeUCANVerify = "ucan:verify" // MPC-based signature verification - TypeUCANDIDGeneration = "ucan:did:generation" // DID generation from MPC enclave - TypeUCANTokenValidation = "ucan:token:validation" // UCAN token validation -) diff --git a/bridge/testutils_test.go b/bridge/testutils_test.go deleted file mode 100644 index 64bd26a12..000000000 --- a/bridge/testutils_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package bridge - -import ( - "github.com/hibiken/asynq" - "github.com/sonr-io/sonr/types/ipfs" -) - -// MockIPFSClient provides a test implementation of IPFSClient -type MockIPFSClient struct{} - -func (m *MockIPFSClient) Add(data []byte) (string, error) { - return "mock-cid", nil -} - -func (m *MockIPFSClient) AddFile(file ipfs.File) (string, error) { - return "mock-file-cid", nil -} - -func (m *MockIPFSClient) AddFolder(folder ipfs.Folder) (string, error) { - return "mock-folder-cid", nil -} - -func (m *MockIPFSClient) Get(cid string) ([]byte, error) { - return []byte("mock-ipfs-data"), nil -} - -func (m *MockIPFSClient) GetFile(cid string) (ipfs.File, error) { - return nil, nil -} - -func (m *MockIPFSClient) GetFolder(cid string) (ipfs.Folder, error) { - return nil, nil -} - -func (m *MockIPFSClient) Pin(cid string, name string) error { - return nil -} - -func (m *MockIPFSClient) Unpin(cid string) error { - return nil -} - -func (m *MockIPFSClient) Exists(cid string) (bool, error) { - return true, nil -} - -func (m *MockIPFSClient) IsPinned(ipns string) (bool, error) { - return true, nil -} - -func (m *MockIPFSClient) Ls(cid string) ([]string, error) { - return []string{"mock-file1", "mock-file2"}, nil -} - -func (m *MockIPFSClient) NodeStatus() (*ipfs.NodeStatus, error) { - return &ipfs.NodeStatus{ - PeerID: "mock-peer-id", - Version: "mock-version", - PeerType: "kubo", - ConnectedPeers: 5, - }, nil -} - -// AsynqClientInterface defines the interface we need for testing -type AsynqClientInterface interface { - Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) - Close() error -} - -// MockAsynqClient provides a test double for asynq.Client -type MockAsynqClient struct { - enqueuedTasks []MockTask -} - -type MockTask struct { - Type string - Payload []byte - Queue string -} - -func (m *MockAsynqClient) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) { - mockTask := MockTask{ - Type: task.Type(), - Payload: task.Payload(), - Queue: "default", // Default queue - } - - // For testing purposes, we'll just use the default queue - // In real implementation, options would be parsed properly - m.enqueuedTasks = append(m.enqueuedTasks, mockTask) - - return &asynq.TaskInfo{ - ID: "test-task-id", - Type: task.Type(), - Queue: mockTask.Queue, - }, nil -} - -func (m *MockAsynqClient) Close() error { - return nil -} diff --git a/client/auth/webauthn.go b/client/auth/webauthn.go index 05d272bfa..4a4613e62 100644 --- a/client/auth/webauthn.go +++ b/client/auth/webauthn.go @@ -13,9 +13,9 @@ import ( "github.com/sonr-io/sonr/client/errors" "github.com/sonr-io/sonr/client/keys" - "github.com/sonr-io/sonr/types/webauthn" - "github.com/sonr-io/sonr/types/webauthn/webauthncbor" - "github.com/sonr-io/sonr/types/webauthn/webauthncose" + "github.com/sonr-io/common/webauthn" + "github.com/sonr-io/common/webauthn/webauthncbor" + "github.com/sonr-io/common/webauthn/webauthncose" ) // WebAuthnClient provides an interface for WebAuthn operations with Sonr's Decentralized Abstracted Smart Wallets. diff --git a/client/go.mod b/client/go.mod index 05a350f1e..3b00b1735 100644 --- a/client/go.mod +++ b/client/go.mod @@ -11,7 +11,7 @@ replace ( cosmossdk.io/store => github.com/evmos/cosmos-sdk/store v0.0.0-20240718141609-414cbd051fbe github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 github.com/cosmos/cosmos-sdk => github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 - github.com/sonr-io/sonr/crypto => ../crypto + github.com/sonr-io/crypto => ../crypto github.com/spf13/viper => github.com/spf13/viper v1.17.0 nhooyr.io/websocket => nhooyr.io/websocket v1.8.17 ) @@ -172,7 +172,7 @@ require ( github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sasha-s/go-deadlock v0.3.5 // indirect - github.com/sonr-io/sonr/crypto v0.0.0-00010101000000-000000000000 // indirect + github.com/sonr-io/crypto v0.0.0-00010101000000-000000000000 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spf13/afero v1.11.0 // indirect diff --git a/cmd/hway/.cz.toml b/cmd/hway/.cz.toml deleted file mode 100644 index 412f4fb20..000000000 --- a/cmd/hway/.cz.toml +++ /dev/null @@ -1,18 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "hway/v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "scm" -update_changelog_on_bump = true -changelog_file = "CHANGELOG.md" -major_version_zero = true -annotated_tag = true -pre_bump_hooks = ["bash scripts/hook-bump-pre.sh"] -post_bump_hooks = ["goreleaser release --clean -f cmd/hway/.goreleaser.yml"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(hway\\)(!)?:" diff --git a/cmd/hway/.goreleaser.yml b/cmd/hway/.goreleaser.yml deleted file mode 100644 index a4591d962..000000000 --- a/cmd/hway/.goreleaser.yml +++ /dev/null @@ -1,293 +0,0 @@ -# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json ---- -version: 2 -dist: dist/hway -monorepo: - tag_prefix: hway/ - dir: cmd/hway - -project_name: hway - -before: - hooks: - - go mod download - -builds: - # Hway Darwin AMD64 - - id: hway-darwin-amd64 - main: . - binary: hway - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=o64-clang - - CXX=o64-clang++ - goos: - - darwin - goarch: - - amd64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X main.Version={{.Version}} - - -X main.Commit={{.Commit}} - - -s -w # Strip debug info - - # Hway Darwin ARM64 - - id: hway-darwin-arm64 - main: . - binary: hway - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=oa64-clang - - CXX=oa64-clang++ - goos: - - darwin - goarch: - - arm64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X main.Version={{.Version}} - - -X main.Commit={{.Commit}} - - -s -w # Strip debug info - - # Hway Linux AMD64 - - id: hway-linux-amd64 - main: . - binary: hway - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=x86_64-linux-gnu-gcc - - CXX=x86_64-linux-gnu-g++ - goos: - - linux - goarch: - - amd64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X main.Version={{.Version}} - - -X main.Commit={{.Commit}} - - -s -w - - # Hway Linux ARM64 - - id: hway-linux-arm64 - main: . - binary: hway - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=aarch64-linux-gnu-gcc - - CXX=aarch64-linux-gnu-g++ - goos: - - linux - goarch: - - arm64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X main.Version={{.Version}} - - -X main.Commit={{.Commit}} - - -s -w - -aur_sources: - - name: hway - disable: true - homepage: "https://sonr.io" - description: "Highway service - bridge between the Public Internet and Sonr blockchain" - maintainers: - - "Sonr " - license: "GPL-3.0" - private_key: "{{ .Env.AUR_KEY }}" - git_url: "ssh://[email protected]/hway.git" - skip_upload: auto - provides: - - hway - conflicts: - - hway-bin - depends: - - glibc - - redis - optdepends: - - "docker: for container-based vault operations" - makedepends: - - go - - git - - make - commit_msg_template: "Update to {{ .Tag }}" - commit_author: - name: goreleaserbot - email: "prad@sonr.io" - prepare: |- - cd "${pkgname}_${pkgver}" - go mod download - build: |- - cd "${pkgname}_${pkgver}" - export CGO_ENABLED=1 - export CGO_CPPFLAGS="${CPPFLAGS}" - export CGO_CFLAGS="${CFLAGS}" - export CGO_CXXFLAGS="${CXXFLAGS}" - export CGO_LDFLAGS="${LDFLAGS}" - export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw" - go build \ - -ldflags="-w -s -buildid='' -linkmode=external \ - -X main.Version=${pkgver}" \ - -o hway ./cmd/hway - chmod +x ./hway - package: |- - cd "${pkgname}_${pkgver}" - - # bin - install -Dm755 "./hway" "${pkgdir}/usr/bin/hway" - - # license - if [ -f "./LICENSE" ]; then - install -Dm644 "./LICENSE" "${pkgdir}/usr/share/licenses/hway/LICENSE" - fi - - # readme - if [ -f "./README.md" ]; then - install -Dm644 "./README.md" "${pkgdir}/usr/share/doc/hway/README.md" - fi - -nix: - - name: hway - ids: - - hway - homepage: "https://sonr.io" - description: "Highway network component for Sonr" - license: "gpl3" - path: pkgs/hway/default.nix - commit_msg_template: "hway: {{ .Tag }}" - dependencies: - - stdenv - - glibc - extra_install: |- - wrapProgram $out/bin/hway --prefix PATH : ${lib.makeBinPath [ glibc stdenv.cc.cc.lib ]} - repository: - owner: sonr-io - name: nur - branch: main - token: "{{ .Env.GITHUB_TOKEN }}" - -archives: - - id: hway - ids: - - hway-linux-amd64 - - hway-linux-arm64 - - hway-darwin-amd64 - - hway-darwin-arm64 - name_template: >- - hway_{{ .Os }}_{{- if eq .Arch "amd64" }}x86_64 {{- else if eq .Arch "386" }}i386 {{- else }}{{ .Arch }}{{ end }} - formats: ["tar.gz"] - files: - - src: README* - wrap_in_directory: false - -homebrew_casks: - - name: hway - ids: - - hway - homepage: "https://sonr.io" - description: "Highway service - bridge between the Public Internet and Sonr blockchain" - commit_msg_template: "Brew cask update for {{ .ProjectName }} version {{ .Tag }}" - directory: Casks - repository: - owner: sonr-io - name: homebrew-tap - branch: main - token: "{{ .Env.GITHUB_TOKEN }}" - commit_author: - name: goreleaserbot - email: "prad@sonr.io" - hooks: - post: - install: | - if OS.mac? - system_command "/usr/bin/xattr", args: ["-dr", "com.apple.quarantine", "#{staged_path}/hway"] - end - -nfpms: - - id: hway - package_name: hway - ids: - - hway-linux-amd64 - - hway-linux-arm64 - file_name_template: "hway_{{ .Os }}_{{ .Arch }}{{ .ConventionalExtension }}" - vendor: Sonr - homepage: "https://sonr.io" - maintainer: "Sonr " - description: "Hway is the bridge between the Public Internet and the Sonr blockchain." - license: "GPL-3.0" - formats: - - rpm - - deb - - apk - - archlinux - contents: - - src: README* - dst: /usr/share/doc/hway - bindir: /usr/bin - section: net - priority: optional - -blobs: - - provider: s3 - endpoint: https://eb37925850388bca807b7fab964c12bb.r2.cloudflarestorage.com - bucket: releases - region: auto - directory: "hway/{{ .Tag }}" - ids: - - hway - -release: - disable: false - github: - owner: sonr-io - name: sonr - name_template: "{{.ProjectName}}/{{ .Tag }}" - draft: false - replace_existing_draft: false # Don't replace drafts - replace_existing_artifacts: false # Append, don't replace - mode: append # Explicitly set to append mode - -checksum: - name_template: 'hway_checksums.txt' - -npms: - - name: "@sonr.io/hway" - ids: - - hway - description: "Highway service - bridge between the Public Internet and Sonr blockchain" - homepage: "https://sonr.io" - license: "GPL-3.0" - author: "Sonr " - repository: "https://github.com/sonr-io/sonr" - bugs: "https://github.com/sonr-io/sonr/issues" - keywords: - - highway - - bridge - - blockchain - - sonr - - service - access: public - format: tar.gz - -snapshot: - version_template: "{{ incpatch .Version }}-dev" - -# Changelog configuration -changelog: - sort: asc - filters: - exclude: - - '^docs:' - - '^test:' - - '^chore:' diff --git a/cmd/hway/CHANGELOG.md b/cmd/hway/CHANGELOG.md deleted file mode 100644 index 290dca19b..000000000 --- a/cmd/hway/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -## hway/v0.0.3 (2025-10-04) - -## hway/v0.0.2 (2025-10-04) - -## hway/v0.0.1 (2025-10-03) diff --git a/cmd/hway/Dockerfile b/cmd/hway/Dockerfile deleted file mode 100644 index 741fd6117..000000000 --- a/cmd/hway/Dockerfile +++ /dev/null @@ -1,77 +0,0 @@ -# Use build argument for base image to allow using pre-cached base -ARG BASE_IMAGE=golang:1.24.7-alpine3.22 - -# -------------------------------------------------------- -# Highway service build stage -FROM ${BASE_IMAGE} AS builder -SHELL ["/bin/sh", "-ecuxo", "pipefail"] - -# Install build dependencies -RUN apk add --no-cache \ - ca-certificates \ - build-base \ - git \ - linux-headers \ - bash - -WORKDIR /code - -# Copy entire source code -COPY . . - -# Fix git ownership issue -RUN git config --global --add safe.directory /code - -# Download Go modules -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - go mod download - -# Build Highway binary -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - set -eux; \ - VERSION=$(git describe --tags --always 2>/dev/null || echo "dev"); \ - COMMIT=$(git log -1 --format='%H' 2>/dev/null || echo "unknown"); \ - CGO_ENABLED=1 GOOS=linux \ - go build \ - -mod=readonly \ - -ldflags "-X main.Version=${VERSION} \ - -X main.Commit=${COMMIT} \ - -w -s" \ - -buildvcs=false \ - -trimpath \ - -o /code/build/hway \ - ./cmd/hway - -# -------------------------------------------------------- -# Highway runtime image -FROM alpine:3.17 - -LABEL org.opencontainers.image.title="Sonr Highway Service" -LABEL org.opencontainers.image.source="https://github.com/sonr-io/sonr" - -# Copy binary from builder -COPY --from=builder /code/build/hway /usr/bin/hway - -# Install runtime dependencies -RUN apk add --no-cache ca-certificates wget - -# Create non-root user -RUN adduser -D -u 1000 highway - -# Set working directory -WORKDIR /home/highway - -# Switch to non-root user -USER highway - -# Health check endpoint -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD wget --spider -q http://localhost:8090/health || exit 1 - -# Expose Highway port -EXPOSE 8090 - -# Set default command -ENTRYPOINT ["/usr/bin/hway"] diff --git a/cmd/hway/Makefile b/cmd/hway/Makefile deleted file mode 100644 index b3df9e265..000000000 --- a/cmd/hway/Makefile +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/make -f - -# Version and build information -GIT_ROOT := $(shell git rev-parse --show-toplevel) -VERSION := $(shell echo $(shell git describe --tags 2>/dev/null || echo "dev") | sed 's/^v//') -COMMIT := $(shell git log -1 --format='%H') - -BUMP_LEVEL := PATCH - -# Build configuration -BUILD_FLAGS := -trimpath - -# Linker flags for version info -ldflags = -X main.Version=$(VERSION) \ - -X main.Commit=$(COMMIT) \ - -s -w - -BUILD_FLAGS += -ldflags '$(ldflags)' -HWAY_OUT := $(GIT_ROOT)/build/hway - -.PHONY: all build install clean test version help docker - -all: build - -build: -ifeq ($(OS),Windows_NT) - $(error hway server not supported on Windows) -else - @echo "Building Highway service..." - @go build -mod=readonly $(BUILD_FLAGS) -o $(HWAY_OUT) . - @echo "Binary built: ../../build/hway" -endif - -install: -ifeq ($(OS),Windows_NT) - $(error hway server not supported on Windows) -else - @echo "Installing Highway service..." - @go install -mod=readonly $(BUILD_FLAGS) . - @echo "Binary installed to $(GOPATH)/bin/hway" -endif - -tidy: - @echo "Tidying Go module..." - @go mod tidy - -clean: - @echo "Cleaning build artifacts..." - @rm -f $(HWAY_OUT) - @echo "Clean complete" - -test: - @echo "Running Highway service tests..." - @go test -v -race ./... - -release: - @echo "Creating hway release..." - @cd $(GIT_ROOT) && cz --config cmd/hway/.cz.toml --no-raise 6,21 bump --yes --increment PATCH - -snapshot: - @echo "Dry-Run Bumping Highway version..." - @cd $(GIT_ROOT) && cz --config cmd/hway/.cz.toml bump --yes --no-verify --dry-run --increment PATCH - @echo "Creating hway snapshots for all platforms..." - @cd $(GIT_ROOT) && goreleaser release --snapshot --clean -f cmd/hway/.goreleaser.yml - -# Docker build targets -docker: - @echo "Building Highway Docker image..." - @docker build -f Dockerfile -t onsonr/hway:latest -t ghcr.io/sonr-io/hway:latest ../.. - @echo "Docker image built and tagged:" - @echo " - onsonr/hway:latest" - @echo " - ghcr.io/sonr-io/hway:latest" - -docker-local: - @echo "Building Highway Docker image with local context..." - @docker build -f Dockerfile -t onsonr/hway:local -t ghcr.io/sonr-io/hway:local ../.. - @echo "Docker image built and tagged:" - @echo " - onsonr/hway:local" - @echo " - ghcr.io/sonr-io/hway:local" - -version: - @echo "Highway Service" - @echo "===============" - @echo "Version: $(VERSION)" - @echo "Commit: $(COMMIT)" - -help: - @echo "Highway Service Makefile" - @echo "========================" - @echo "" - @echo "Highway is an Asynq-based task processing service for vault operations," - @echo "using Redis-backed job queues and Proto.Actor framework for concurrency." - @echo "" - @echo "Available targets:" - @echo " build - Build Highway binary (default)" - @echo " install - Install Highway to GOPATH/bin" - @echo " docker - Build Docker image (onsonr/hway:latest)" - @echo " clean - Remove build artifacts" - @echo " test - Run Highway tests" - @echo " version - Display version information" - @echo " help - Show this help message" - @echo "" - @echo "Requirements:" - @echo " - Redis server running on 127.0.0.1:6379" - @echo " - IPFS nodes for vault operations" - @echo "" - @echo "Examples:" - @echo " make build # Build the Highway service" - @echo " make test # Run tests" - @echo " make install # Install to GOPATH/bin" diff --git a/cmd/hway/README.md b/cmd/hway/README.md deleted file mode 100644 index f65d1d3f0374294efc1ea0017deeb66cee548bfa..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8814 zcmbVSOLHSd5+>%@u?G%&;8<(N?#c>F!X6f4P0Yb#d%(e%G4>1`CJ5AOm88P0uBNKn z9zo1M+aI@IW>&SjB^emR!&W`>onK{oUwv)ni-&ZjZne8NnN~gec90}-+<29$1r`lT z?Pk_3(*moi)ZeMn*-U$Hin;P(Hx{T{TeyFFHPx9eDwpQwS3OntX`NTfuY9GKLv>lv z=6f^MINh&`Y~gHSYk#PwwM!?tR{EXJ>dM$c*_q1Rs;unXrRBn8%7T!Tro5{8@*ni% z)O)?0{V+-P_tmR=qFFzzSxvKw$N|6D zRyi}NE9`5t3ht^!TB!w2&vA(dkxoBOABm${Xcmc@FzG z8K{2$6cYKR-&eHT>D;hD8uAr1fW=D)S3Q_&AzbptYiBDvJk2WW!gjD^9VFnvNM;LA z>mZ>OuihoLuUnMQDI0~66|9$NNs zWRT->IwB`Y<~Ga@tYRM;(uG3DO`x8&FV4{>ho!KSgrS_x2fc>rM9+FKc}^-UK!>Vq zkQG_^M9*PTEoT&8BfIrtAw zcjPuum$A-NMtdwtlp3gUM&GkEAD^htn;kqe)id&VOg!yQfCvm8g+UUQI(69sCXiL| zrL{MjWtp>;lS3|XmKo&f3Kj!3wl=Vr1bc0}DmVpiB*wpewE6j1;j=yb(Iev@Cr_~c zHHAEp1in3?Gcg=3D2C5C{yoP#c161E2_Mm813#bveCSaAUymI=4#)9c%bRKLN%Hqi zK0f+{j@TZ4Z2S{w?XP{F{NVkQSGi56q<=&BO0peO%DY;*Ah&aqag@ES z%hEbRG_M)}wT`x4W zK!9^IH^3t5*365PavN*`lOhKiq`U_FO!$Zyrm>yOUdgIQDF~+oieuD!j5z>6g2*j# z$;G=w)zBXA4m|tFQU0lUObN{LcZ8?<(% zvnDa`n)J{P} zy*_HSL9vH+2{g4VE3!ut%ysHL;{PWiL40m%$!|r3rHq+3Mf+ZC&<|p$)6EKym^-(qHg}c=l)16 zBq{kstK2CdF{>LrLrht8%qNWP6whCwF&aU0?k?tE-JyQKo)D?0pMe95$zX>ZVIPwa zh1`yK-bb(`$a}+y)S1%=E{Ok>@eo=02VMsB8pjOMoD>J>?IUQZA^^{m1att6a(>Ln zD*@pN4-PWBJw)wAJsDF{%=8%GHVWl;5CSd)0}Q2*Vb@0ja}{_H zqiixq35OqxlNB@!bS>Zu216Fn?4Z{$@FxU^H}rUyibqT<0Y-wvjoGCoP*w^21xQc^ zJVrnpF4=}0oc4iH5j^BIOD5Y;5P+I>1QKro&2fbknH&=q;XfleJl59_c)?qO<2NQ6 zl}Ob9*e;e0)~>OJdf~+mP+5^*k#+>Fu!O)Dieh9m>e-gntS#aPt{UKB)1gq#5i^u2 z0de>}R-~xraLCz;pVwHgfBL5ul-coEdUYZHz7E`HcO2M8pL`0 zsp_i=Ux#>S*kT&bL`@drG1W?4*{ROgK88s3SZRbSA+&|R(P(?Q^nP@!!G(!TMA%#VLTs7I8-kqo;A-*$b>j+Us2*f2Mt{F+V zA8Em2>!Nb+@_?dfwnYrZN8+Wqpn0CQA6+2lh0*!+Xak+icrYM@xagR8 z!$l~CrxrEeK34GKGrMDJ6l%3UTE`3@oj)?qEZDV9M`)i7wM2WJ0O z9(=itq`IP=Evw-L-9GE>b)Z}`4qW*c0{~q>O1BU@z-QJn z8|C#5m=!h(s^Gjv$pt~Gm2^-xsHtHGU|c%A(1kbm2vl5}si}oSVHJUDAVIBMmocRX zg{mcWqe2r9u~G_vSl_DXaZn2#CCmt}5v1EhDu6$>CjT2Q|N?Wl0hALR|Po$9xdxqL^}5|g1o z*|0z`5iJec$JR$4B5+nZm*_TGGzCE!rDxDUz0O$1LKI%p#VtUO6`a&4;uG*i^n@~& zDMLACcxG~B3veRc&+Aq*7hdVniVaOw=|N&FLNgehI-UMpqXZYK$eFEiffRP}lsdb9 z1Ny;HQ)#B^Bv|YB8O(J%N9uW+w|mI3sie{jhj3y9PMr`$rGf#aTQuJ&c}g=%OyWu} zty`%#R6QdCgL;F(EM=CYQKJw-?>&}Np1OGe|MxbpQ5j+?+5TD*p#wKH2Ii<@fBj}a zX_syPOH{Fb)v>*`rXOuWYHPhlg%qu9zpz$3iQEb$|0Sro^d2?MBq5*yTupe98hb?O z3%0v{pW$}`QKN5J*oyk0q2Pal{xrRMvQl-QZzp6%bWZaN9q9B7wi8e#>V0LRC6D`5{D#BU5(S_;q)O+Zp-3ylu0?2HQp_>fB#x+43CG?;t#tfn~sk}B3+ z<|M+>vxJ}J==z6-&BA){5UTN9>gEg~&OA_|ir5YtFmL*!0ocA+A^q6`SDXw~(2yQZ zL_+~?3VZG_fmJt}{vrVNIqLh6NC=g8O%N)RFm_3m{HFT8!5MHZ)mT9TMZ7hifWGK{ zbC7LrYq3dz2CfB~<2H8xBYKcWN^~I)L2XUg5IPnGwg~B}-em Q(apu_`PId6IXy`J55<)Fz5oCK diff --git a/cmd/hway/go.mod b/cmd/hway/go.mod deleted file mode 100644 index 44f8d7bf7..000000000 --- a/cmd/hway/go.mod +++ /dev/null @@ -1,312 +0,0 @@ -module hway - -go 1.24.7 - -// overrides -replace ( - cosmossdk.io/core => cosmossdk.io/core v0.11.0 - cosmossdk.io/store => github.com/evmos/cosmos-sdk/store v0.0.0-20240718141609-414cbd051fbe - github.com/CosmWasm/wasmd => github.com/rollchains/wasmd v0.50.0-evm - - github.com/cosmos/cosmos-sdk => github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 - github.com/cosmos/evm => github.com/strangelove-ventures/cosmos-evm v0.2.0 - github.com/ethereum/go-ethereum => github.com/evmos/go-ethereum v1.10.26-evmos-rc2 - github.com/sonr-io/sonr => ../../ - github.com/sonr-io/sonr/crypto => ../../crypto - github.com/spf13/viper => github.com/spf13/viper v1.17.0 // v1.18+ breaks app overrides - nhooyr.io/websocket => nhooyr.io/websocket v1.8.17 -) - -replace ( - github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 - // Fix btcec version for evmos compatibility - github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.2 - // dgrijalva/jwt-go is deprecated and doesn't receive security updates. - // See: https://github.com/cosmos/cosmos-sdk/issues/13134 - github.com/dgrijalva/jwt-go => github.com/golang-jwt/jwt/v4 v4.4.2 - // Fix upstream GHSA-h395-qcrw-5vmq vulnerability. - // See: https://github.com/cosmos/cosmos-sdk/issues/10409 - github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.8.1 - - // pin version! 126854af5e6d has issues with the store so that queries fail - github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 -) - -require github.com/sonr-io/sonr v0.0.0-00010101000000-000000000000 - -require ( - cosmossdk.io/api v0.7.6 // indirect - cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/core v0.12.0 // indirect - cosmossdk.io/depinject v1.1.0 // indirect - cosmossdk.io/errors v1.0.1 // indirect - cosmossdk.io/math v1.5.0 // indirect - cosmossdk.io/orm v1.0.0-beta.3 // indirect - cosmossdk.io/store v1.1.1 // indirect - cosmossdk.io/x/tx v0.13.7 // indirect - github.com/Oudwins/zog v0.21.6 // indirect - github.com/asynkron/protoactor-go v0.0.0-20240822202345-3c0e61ca19c9 // indirect - github.com/biter777/countries v1.7.5 // indirect - github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/gogoproto v1.7.0 // indirect - github.com/extism/go-sdk v1.7.1 // indirect - github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/golang-jwt/jwt/v5 v5.3.0 // indirect - github.com/golang/protobuf v1.5.4 // indirect - github.com/google/go-tpm v0.9.5 // indirect - github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect - github.com/ipfs/boxo v0.32.0 // indirect - github.com/ipfs/kubo v0.35.0 // indirect - github.com/labstack/echo/v4 v4.13.4 // indirect - github.com/labstack/gommon v0.4.2 // indirect - github.com/sonr-io/sonr/crypto v0.0.0-00010101000000-000000000000 // indirect - github.com/stretchr/testify v1.10.0 // indirect - github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/x448/float16 v0.8.4 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect - google.golang.org/grpc v1.71.0 // indirect - google.golang.org/protobuf v1.36.6 // indirect -) - -require ( - cosmossdk.io/log v1.5.0 // indirect - filippo.io/edwards25519 v1.1.0 // indirect - github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect - github.com/Workiva/go-datastructures v1.1.3 // indirect - github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // 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.0 // indirect - github.com/blang/semver/v4 v4.0.0 // indirect - github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect - github.com/bwesterb/go-ristretto v1.2.3 // indirect - github.com/bytedance/sonic v1.14.0 // indirect - github.com/bytedance/sonic/loader v0.3.0 // indirect - github.com/caddyserver/certmagic v0.21.6 // indirect - github.com/caddyserver/zerossl v0.1.3 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/cloudwego/base64x v0.1.5 // indirect - github.com/cockroachdb/apd/v3 v3.2.1 // indirect - github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect - github.com/cockroachdb/errors v1.11.3 // indirect - github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v1.1.2 // indirect - github.com/cockroachdb/pebble/v2 v2.0.3 // indirect - github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect - github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/cometbft/cometbft v0.38.17 // indirect - github.com/cometbft/cometbft-db v0.14.1 // indirect - github.com/consensys/gnark-crypto v0.19.0 // indirect - github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/cosmos-db v1.1.1 // indirect - github.com/cosmos/cosmos-sdk v0.53.4 // indirect - github.com/cosmos/ics23/go v0.11.0 // indirect - github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect - github.com/dgraph-io/badger/v4 v4.2.0 // indirect - github.com/dgraph-io/ristretto v0.1.1 // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/dustin/go-humanize v1.0.1 // indirect - github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 // indirect - github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect - github.com/emirpasic/gods v1.18.1 // indirect - github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 // indirect - github.com/flynn/noise v1.1.0 // indirect - github.com/francoispqt/gojay v1.2.13 // indirect - github.com/gammazero/deque v1.0.0 // indirect - github.com/getsentry/sentry-go v0.27.0 // indirect - github.com/go-kit/kit v0.13.0 // indirect - github.com/go-kit/log v0.2.1 // indirect - github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/gobwas/glob v0.2.3 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/glog v1.2.4 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/snappy v0.0.5-0.20231225225746-43d5d4cd4e0e // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/flatbuffers v23.5.26+incompatible // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/google/gopacket v1.1.19 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/gopherjs/gopherjs v1.17.2 // indirect - github.com/gorilla/websocket v1.5.3 // indirect - github.com/gtank/merlin v0.1.1 // indirect - github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-metrics v0.5.3 // indirect - github.com/hashicorp/go-uuid v1.0.3 // indirect - github.com/hashicorp/golang-lru v1.0.2 // indirect - github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect - github.com/hdevalence/ed25519consensus v0.1.0 // indirect - github.com/hibiken/asynq v0.25.1 // indirect - github.com/huin/goupnp v1.3.0 // indirect - github.com/iancoleman/strcase v0.3.0 // indirect - github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/ipfs/bbloom v0.0.4 // indirect - github.com/ipfs/go-bitfield v1.1.0 // indirect - github.com/ipfs/go-block-format v0.2.1 // indirect - github.com/ipfs/go-cid v0.5.0 // indirect - github.com/ipfs/go-datastore v0.8.2 // indirect - github.com/ipfs/go-ds-measure v0.2.2 // indirect - github.com/ipfs/go-fs-lock v0.1.1 // indirect - github.com/ipfs/go-ipfs-cmds v0.14.1 // indirect - github.com/ipfs/go-ipld-cbor v0.2.0 // indirect - github.com/ipfs/go-ipld-format v0.6.1 // indirect - github.com/ipfs/go-ipld-legacy v0.2.1 // indirect - github.com/ipfs/go-log v1.0.5 // indirect - github.com/ipfs/go-log/v2 v2.6.0 // indirect - github.com/ipfs/go-metrics-interface v0.3.0 // indirect - github.com/ipfs/go-unixfsnode v1.10.1 // indirect - github.com/ipld/go-car/v2 v2.14.3 // indirect - github.com/ipld/go-codec-dagpb v1.7.0 // indirect - github.com/ipld/go-ipld-prime v0.21.0 // indirect - github.com/ipshipyard/p2p-forge v0.5.1 // indirect - github.com/jackpal/go-nat-pmp v1.0.2 // indirect - github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect - github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.18.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/koron/go-ssdp v0.0.6 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/kr/text v0.2.0 // indirect - github.com/labstack/echo-jwt/v4 v4.3.1 // indirect - github.com/libdns/libdns v0.2.2 // 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.2.0 // indirect - github.com/libp2p/go-libp2p v0.43.0 // indirect - github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect - github.com/libp2p/go-libp2p-kad-dht v0.33.1 // indirect - github.com/libp2p/go-libp2p-kbucket v0.7.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.2.2 // indirect - github.com/libp2p/go-reuseport v0.4.0 // indirect - github.com/linxGnu/grocksdb v1.9.8 // indirect - github.com/lithammer/shortuuid/v4 v4.0.0 // indirect - github.com/lmittmann/tint v1.0.3 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mholt/acmez/v3 v3.0.0 // indirect - github.com/miekg/dns v1.1.66 // indirect - github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect - github.com/minio/sha256-simd v1.0.1 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/mr-tron/base58 v1.2.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 v0.16.0 // indirect - github.com/multiformats/go-multiaddr-dns v0.4.1 // indirect - github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect - github.com/multiformats/go-multibase v0.2.0 // indirect - github.com/multiformats/go-multicodec v0.9.1 // 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/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect - github.com/onsi/gomega v1.36.2 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect - github.com/orcaman/concurrent-map v1.0.0 // indirect - github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect - github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 // indirect - github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect - github.com/pion/datachannel v1.5.10 // indirect - github.com/pion/dtls/v2 v2.2.12 // indirect - github.com/pion/dtls/v3 v3.0.6 // indirect - github.com/pion/ice/v4 v4.0.10 // indirect - github.com/pion/interceptor v0.1.40 // indirect - github.com/pion/logging v0.2.3 // indirect - github.com/pion/mdns/v2 v2.0.7 // indirect - github.com/pion/randutil v0.1.0 // indirect - github.com/pion/rtcp v1.2.15 // indirect - github.com/pion/rtp v1.8.19 // indirect - github.com/pion/sctp v1.8.39 // indirect - github.com/pion/sdp/v3 v3.0.13 // indirect - github.com/pion/srtp/v3 v3.0.6 // indirect - github.com/pion/stun v0.6.1 // indirect - github.com/pion/stun/v3 v3.0.0 // indirect - github.com/pion/transport/v2 v2.2.10 // indirect - github.com/pion/transport/v3 v3.0.7 // indirect - github.com/pion/turn/v4 v4.0.2 // indirect - github.com/pion/webrtc/v4 v4.1.2 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/polydawn/refmt v0.89.0 // indirect - github.com/prometheus/client_golang v1.22.0 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.64.0 // indirect - github.com/prometheus/procfs v0.16.1 // indirect - github.com/quic-go/qpack v0.5.1 // indirect - github.com/quic-go/quic-go v0.54.0 // indirect - github.com/quic-go/webtransport-go v0.9.0 // indirect - github.com/redis/go-redis/v9 v9.11.0 // indirect - github.com/robfig/cron/v3 v3.0.1 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/rs/cors v1.11.1 // indirect - github.com/rs/zerolog v1.33.0 // indirect - github.com/samber/lo v1.47.0 // indirect - github.com/sasha-s/go-deadlock v0.3.5 // indirect - github.com/smarty/assertions v1.15.0 // indirect - github.com/spaolacci/murmur3 v1.1.0 // indirect - github.com/spf13/cast v1.9.2 // indirect - github.com/spf13/cobra v1.8.1 // indirect - github.com/spf13/pflag v1.0.6 // indirect - github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - github.com/tendermint/go-amino v0.16.0 // indirect - github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect - github.com/tetratelabs/wazero v1.9.0 // indirect - github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/twmb/murmur3 v1.1.8 // indirect - github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc // indirect - github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 // indirect - github.com/whyrusleeping/cbor-gen v0.1.2 // indirect - github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f // indirect - github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect - github.com/wlynxg/anet v0.0.5 // indirect - github.com/zeebo/assert v1.3.0 // indirect - github.com/zeebo/blake3 v0.2.4 // indirect - go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect - go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/otel v1.35.0 // indirect - go.opentelemetry.io/otel/exporters/prometheus v0.44.0 // indirect - go.opentelemetry.io/otel/metric v1.35.0 // indirect - go.opentelemetry.io/otel/sdk v1.34.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.35.0 // indirect - go.opentelemetry.io/proto/otlp v1.3.1 // indirect - go.uber.org/dig v1.19.0 // indirect - go.uber.org/fx v1.24.0 // indirect - go.uber.org/mock v0.5.2 // indirect - go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.0 // indirect - go.uber.org/zap/exp v0.3.0 // indirect - go.yaml.in/yaml/v2 v2.4.2 // indirect - go4.org v0.0.0-20230225012048-214862532bf5 // indirect - golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.42.0 // indirect - golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect - golang.org/x/mod v0.27.0 // indirect - golang.org/x/net v0.43.0 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/sys v0.36.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.36.0 // indirect - golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect - gonum.org/v1/gonum v0.16.0 // indirect - google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - lukechampine.com/blake3 v1.4.1 // indirect - sigs.k8s.io/yaml v1.5.0 // indirect -) diff --git a/cmd/hway/go.sum b/cmd/hway/go.sum deleted file mode 100644 index 68b2999ba..000000000 --- a/cmd/hway/go.sum +++ /dev/null @@ -1,1382 +0,0 @@ -bazil.org/fuse v0.0.0-20200117225306-7b5117fecadc h1:utDghgcjE8u+EBjHOgYT+dJPcnDF05KqWMBcjuJy510= -bazil.org/fuse v0.0.0-20200117225306-7b5117fecadc/go.mod h1:FbcW6z/2VytnFDhZfumh8Ss8zxHE6qpMP5sHTRe0EaM= -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.31.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.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= -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.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -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/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -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/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cosmossdk.io/api v0.7.6 h1:PC20PcXy1xYKH2KU4RMurVoFjjKkCgYRbVAD4PdqUuY= -cosmossdk.io/api v0.7.6/go.mod h1:IcxpYS5fMemZGqyYtErK7OqvdM0C8kdW3dq8Q/XIG38= -cosmossdk.io/collections v0.4.0 h1:PFmwj2W8szgpD5nOd8GWH6AbYNi1f2J6akWXJ7P5t9s= -cosmossdk.io/collections v0.4.0/go.mod h1:oa5lUING2dP+gdDquow+QjlF45eL1t4TJDypgGd+tv0= -cosmossdk.io/core v0.11.0 h1:vtIafqUi+1ZNAE/oxLOQQ7Oek2n4S48SWLG8h/+wdbo= -cosmossdk.io/core v0.11.0/go.mod h1:LaTtayWBSoacF5xNzoF8tmLhehqlA9z1SWiPuNC6X1w= -cosmossdk.io/depinject v1.1.0 h1:wLan7LG35VM7Yo6ov0jId3RHWCGRhe8E8bsuARorl5E= -cosmossdk.io/depinject v1.1.0/go.mod h1:kkI5H9jCGHeKeYWXTqYdruogYrEeWvBQCw1Pj4/eCFI= -cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= -cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U= -cosmossdk.io/log v1.5.0 h1:dVdzPJW9kMrnAYyMf1duqacoidB9uZIl+7c6z0mnq0g= -cosmossdk.io/log v1.5.0/go.mod h1:Tr46PUJjiUthlwQ+hxYtUtPn4D/oCZXAkYevBeh5+FI= -cosmossdk.io/math v1.5.0 h1:sbOASxee9Zxdjd6OkzogvBZ25/hP929vdcYcBJQbkLc= -cosmossdk.io/math v1.5.0/go.mod h1:AAwwBmUhqtk2nlku174JwSll+/DepUXW3rWIXN5q+Nw= -cosmossdk.io/orm v1.0.0-beta.3 h1:XmffCwsIZE+y0sS4kEfRUfIgvJfGGn3HFKntZ91sWcU= -cosmossdk.io/orm v1.0.0-beta.3/go.mod h1:KSH9lKA+0K++2OKECWwPAasKbUIEtZ7xYG+0ikChiyU= -cosmossdk.io/x/tx v0.13.7 h1:8WSk6B/OHJLYjiZeMKhq7DK7lHDMyK0UfDbBMxVmeOI= -cosmossdk.io/x/tx v0.13.7/go.mod h1:V6DImnwJMTq5qFjeGWpXNiT/fjgE4HtmclRmTqRVM3w= -dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= -dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= -dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= -github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 h1:cTp8I5+VIoKjsnZuH8vjyaysT/ses3EvZeaV/1UkF2M= -github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= -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/DataDog/datadog-go v3.2.0+incompatible h1:qSG2N4FghB1He/r2mFrWKCaL7dXCilEuNEeAn20fdD4= -github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e h1:ZIWapoIRN1VqT8GR8jAwb1Ie9GyehWjVcGh32Y2MznE= -github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= -github.com/Jorropo/jsync v1.0.1 h1:6HgRolFZnsdfzRUj+ImB9og1JYOxQoReSywkHOGSaUU= -github.com/Jorropo/jsync v1.0.1/go.mod h1:jCOZj3vrBCri3bSU3ErUYvevKlnbssrXeCivybS5ABQ= -github.com/Oudwins/zog v0.21.6 h1:3JVJA66fr59k2x72RojCB7v5XkVmtVsnp1YO/np595k= -github.com/Oudwins/zog v0.21.6/go.mod h1:c4ADJ2zNkJp37ZViNy1o3ZZoeMvO7UQVO7BaPtRoocg= -github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= -github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= -github.com/Workiva/go-datastructures v1.1.3 h1:LRdRrug9tEuKk7TGfz/sct5gjVj44G9pfqDt4qm7ghw= -github.com/Workiva/go-datastructures v1.1.3/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= -github.com/aclements/go-perfevent v0.0.0-20240301234650-f7843625020f h1:JjxwchlOepwsUWcQwD2mLUAGE9aCp0/ehy6yCHFBOvo= -github.com/aclements/go-perfevent v0.0.0-20240301234650-f7843625020f/go.mod h1:tMDTce/yLLN/SK8gMOxQfnyeMeCg8KGzp0D1cbECEeo= -github.com/alecthomas/participle/v2 v2.0.0-alpha7 h1:cK4vjj0VSgb3lN1nuKA5F7dw+1s1pWBe5bx7nNCnN+c= -github.com/alecthomas/participle/v2 v2.0.0-alpha7/go.mod h1:NumScqsC42o9x+dGj8/YqsIfhrIQjFEOFovxotbBirA= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b h1:mimo19zliBX/vSQ6PWWSL9lK8qwHozUj03+zLoEB8O0= -github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b/go.mod h1:fvzegU4vN3H1qMT+8wDmzjAcDONcgo2/SZ/TyfdUOFs= -github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5 h1:iW0a5ljuFxkLGPNem5Ui+KBjFJzKg4Fv2fnxe4dvzpM= -github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5/go.mod h1:Y2QMoi1vgtOIfc+6DhrMOGkLoGzqSV2rKp4Sm+opsyA= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/asynkron/protoactor-go v0.0.0-20240822202345-3c0e61ca19c9 h1:mFWX0/oYqQ4Z+er0U56vA+ZPisr3kaYs1QsQetAVs6E= -github.com/asynkron/protoactor-go v0.0.0-20240822202345-3c0e61ca19c9/go.mod h1:HTx47MGokOrouz8nrUmjyLLOVu+/kRNN6KKVG0XjQ3E= -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 v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -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.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= -github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/biter777/countries v1.7.5 h1:MJ+n3+rSxWQdqVJU8eBy9RqcdH6ePPn4PJHocVWUa+Q= -github.com/biter777/countries v1.7.5/go.mod h1:1HSpZ526mYqKJcpT5Ti1kcGQ0L0SrXWIaptUWjFfv2E= -github.com/bits-and-blooms/bitset v1.24.0 h1:H4x4TuulnokZKvHLfzVRTHJfFfnHEeSYJizujEZvmAM= -github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= -github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= -github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/btcsuite/btcd v0.24.2 h1:aLmxPguqxza+4ag8R1I2nnJjSu2iFn/kqtHTIImswcY= -github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= -github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= -github.com/btcsuite/btcd/btcutil v1.1.6 h1:zFL2+c3Lb9gEgqKNzowKUPQNb8jV7v5Oaodi/AYFd6c= -github.com/btcsuite/btcd/btcutil v1.1.6/go.mod h1:9dFymx8HpuLqBnsPELrImQeTQfKBQqzqGbbV3jK55aE= -github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= -github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw= -github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= -github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= -github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= -github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= -github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= -github.com/caddyserver/certmagic v0.21.6 h1:1th6GfprVfsAtFNOu4StNMF5IxK5XiaI0yZhAHlZFPE= -github.com/caddyserver/certmagic v0.21.6/go.mod h1:n1sCo7zV1Ez2j+89wrzDxo4N/T1Ws/Vx8u5NvuBFabw= -github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA= -github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= -github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= -github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= -github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/ceramicnetwork/go-dag-jose v0.1.1 h1:7pObs22egc14vSS3AfCFfS1VmaL4lQUsAK7OGC3PlKk= -github.com/ceramicnetwork/go-dag-jose v0.1.1/go.mod h1:8ptnYwY2Z2y/s5oJnNBn/UCxLg6CpramNJ2ZXF/5aNY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -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/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= -github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4= -github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= -github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cockroachdb/apd/v3 v3.2.1 h1:U+8j7t0axsIgvQUqthuNm82HIrYXodOV2iWLWtEaIwg= -github.com/cockroachdb/apd/v3 v3.2.1/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc= -github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 h1:bvJv505UUfjzbaIPdNS4AEkHreDqQk6yuNpsdRHpwFA= -github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= -github.com/cockroachdb/datadriven v1.0.3-0.20240530155848-7682d40af056 h1:slXychO2uDM6hYRu4c0pD0udNI8uObfeKN6UInWViS8= -github.com/cockroachdb/datadriven v1.0.3-0.20240530155848-7682d40af056/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= -github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= -github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= -github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= -github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= -github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/metamorphic v0.0.0-20231108215700-4ba948b56895 h1:XANOgPYtvELQ/h4IrmPAohXqe2pWA8Bwhejr3VQoZsA= -github.com/cockroachdb/metamorphic v0.0.0-20231108215700-4ba948b56895/go.mod h1:aPd7gM9ov9M8v32Yy5NJrDyOcD8z642dqs+F0CeNXfA= -github.com/cockroachdb/pebble v1.1.2 h1:CUh2IPtR4swHlEj48Rhfzw6l/d0qA31fItcIszQVIsA= -github.com/cockroachdb/pebble v1.1.2/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= -github.com/cockroachdb/pebble/v2 v2.0.3 h1:YJ3Sc9jRN/q6OOCNyRHPbcpenbxL1DdgdpUqPlPus6o= -github.com/cockroachdb/pebble/v2 v2.0.3/go.mod h1:NgxgNcWwyG/uxkLUZGM2aelshaLIZvc0hCX7SCfaO8s= -github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= -github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= -github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLHLZd4AwKNzClZgL1co3pUPGv3o8FlcA= -github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961/go.mod h1:yBRu/cnL4ks9bgy4vAASdjIW+/xMlFwuHKqtmh3GZQg= -github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= -github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= -github.com/cometbft/cometbft v0.38.17 h1:FkrQNbAjiFqXydeAO81FUzriL4Bz0abYxN/eOHrQGOk= -github.com/cometbft/cometbft v0.38.17/go.mod h1:5l0SkgeLRXi6bBfQuevXjKqML1jjfJJlvI1Ulp02/o4= -github.com/cometbft/cometbft-db v0.14.1 h1:SxoamPghqICBAIcGpleHbmoPqy+crij/++eZz3DlerQ= -github.com/cometbft/cometbft-db v0.14.1/go.mod h1:KHP1YghilyGV/xjD5DP3+2hyigWx0WTp9X+0Gnx0RxQ= -github.com/consensys/gnark-crypto v0.19.0 h1:zXCqeY2txSaMl6G5wFpZzMWJU9HPNh8qxPnYJ1BL9vA= -github.com/consensys/gnark-crypto v0.19.0/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0= -github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= -github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= -github.com/cosmos/cosmos-db v1.1.1 h1:FezFSU37AlBC8S98NlSagL76oqBRWq/prTPvFcEJNCM= -github.com/cosmos/cosmos-db v1.1.1/go.mod h1:AghjcIPqdhSLP/2Z0yha5xPH3nLnskz81pBx3tcVSAw= -github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= -github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= -github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= -github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= -github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= -github.com/cosmos/gogoproto v1.7.0 h1:79USr0oyXAbxg3rspGh/m4SWNyoz/GLaAh0QlCe2fro= -github.com/cosmos/gogoproto v1.7.0/go.mod h1:yWChEv5IUEYURQasfyBW5ffkMHR/90hiHgbNgrtp4j0= -github.com/cosmos/iavl v1.2.2 h1:qHhKW3I70w+04g5KdsdVSHRbFLgt3yY3qTMd4Xa4rC8= -github.com/cosmos/iavl v1.2.2/go.mod h1:GiM43q0pB+uG53mLxLDzimxM9l/5N9UuSY3/D0huuVw= -github.com/cosmos/ics23/go v0.11.0 h1:jk5skjT0TqX5e5QJbEnwXIS2yI2vnmLOgpQPeM5RtnU= -github.com/cosmos/ics23/go v0.11.0/go.mod h1:A8OjxPE67hHST4Icw94hOxxFEJMBG031xIGF/JHNIY0= -github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= -github.com/cosmos/keyring v1.2.0/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/cosmos/ledger-cosmos-go v0.14.0 h1:WfCHricT3rPbkPSVKRH+L4fQGKYHuGOK9Edpel8TYpE= -github.com/cosmos/ledger-cosmos-go v0.14.0/go.mod h1:E07xCWSBl3mTGofZ2QnL4cIUzMbbGVyik84QYKbX3RA= -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.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf h1:dwGgBWn84wUS1pVikGiruW+x5XM4amhjaZO20vCjay4= -github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf/go.mod h1:p1d6YEZWvFzEh4KLyvBcVSnrfNDDvK2zfK/4x2v/4pE= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cskr/pubsub v1.0.2 h1:vlOzMhl6PFn60gRlTQQsIfVwaPB/B/8MziK8FhEPt/0= -github.com/cskr/pubsub v1.0.2/go.mod h1:/8MzYXk/NJAz782G8RPkFzXTZVu63VotefPnR9TIRis= -github.com/cucumber/common/gherkin/go/v22 v22.0.0 h1:4K8NqptbvdOrjL9DEea6HFjSpbdT9+Q5kgLpmmsHYl0= -github.com/cucumber/common/gherkin/go/v22 v22.0.0/go.mod h1:3mJT10B2GGn3MvVPd3FwR7m2u4tLhSRhWUqJU4KN4Fg= -github.com/cucumber/common/messages/go/v17 v17.1.1 h1:RNqopvIFyLWnKv0LfATh34SWBhXeoFTJnSrgm9cT/Ts= -github.com/cucumber/common/messages/go/v17 v17.1.1/go.mod h1:bpGxb57tDE385Rb2EohgUadLkAbhoC4IyCFi89u/JQI= -github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= -github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/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.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= -github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= -github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= -github.com/dgraph-io/badger v1.6.2 h1:mNw0qs90GVgGGWylh0umH5iag1j6n/PeJtNvL6KY/x8= -github.com/dgraph-io/badger v1.6.2/go.mod h1:JW2yswe3V058sS0kZ2h/AXeDSqFjxnZcRrVH//y2UQE= -github.com/dgraph-io/badger/v4 v4.2.0 h1:kJrlajbXXL9DFTNuhhu9yCx7JJa4qpYWxtE8BzuWsEs= -github.com/dgraph-io/badger/v4 v4.2.0/go.mod h1:qfCqhPoWDFJRx1gp5QwwyGo8xk1lbHUxvK9nK0OGAak= -github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= -github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= -github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -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/dustinxie/ecc v0.0.0-20210511000915-959544187564 h1:I6KUy4CI6hHjqnyJLNCEi7YHVMkwwtfSr2k9splgdSM= -github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564/go.mod h1:yekO+3ZShy19S+bsmnERmznGy9Rfg6dWWWpiGJjNAz8= -github.com/dvsekhvalnov/jose2go v1.6.0 h1:Y9gnSnP4qEI0+/uQkHvFXeD2PLPJeXEL+ySMEA2EjTY= -github.com/dvsekhvalnov/jose2go v1.6.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= -github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a h1:UwSIFv5g5lIvbGgtf3tVwC7Ky9rmMFBp0RMs+6f6YqE= -github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q= -github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A= -github.com/emicklei/dot v1.6.2/go.mod h1:DeV7GvQtIw4h2u73RKBkkFdvVAz0D9fzeJrgPW6gy/s= -github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= -github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= -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/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evmos/cosmos-sdk/store v0.0.0-20240718141609-414cbd051fbe h1:CKvjP3CcWckOiwffAARb9qe+t0+VWoVDiicYkQMvZfQ= -github.com/evmos/cosmos-sdk/store v0.0.0-20240718141609-414cbd051fbe/go.mod h1:Bm6h8ZkYgVTytHK5vhHOMKw9OHyiumm3b1UbkYIJ/Ug= -github.com/evmos/go-ethereum v1.10.26-evmos-rc2 h1:tYghk1ZZ8X4/OQ4YI9hvtm8aSN8OSqO0g9vo/sCMdBo= -github.com/evmos/go-ethereum v1.10.26-evmos-rc2/go.mod h1:/6CsT5Ceen2WPLI/oCA3xMcZ5sWMF/D46SjM/ayY0Oo= -github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw= -github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA= -github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 h1:BBso6MBKW8ncyZLv37o+KNyy0HrrHgfnOaGQC2qvN+A= -github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5/go.mod h1:JpoxHjuQauoxiFMl1ie8Xc/7TfLuMZ5eOCONd1sUBHg= -github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= -github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= -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/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= -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/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= -github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= -github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk= -github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY= -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.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= -github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= -github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= -github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/gabriel-vasile/mimetype v1.4.6 h1:3+PzJTKLkvgjeTbts6msPJt4DixhT4YtFNf1gtGe3zc= -github.com/gabriel-vasile/mimetype v1.4.6/go.mod h1:JX1qVKqZd40hUPpAfiNTe0Sne7hdfKSbOqqmkq8GCXc= -github.com/gammazero/chanqueue v1.1.0 h1:yiwtloc1azhgGLFo2gMloJtQvkYD936Ai7tBfa+rYJw= -github.com/gammazero/chanqueue v1.1.0/go.mod h1:fMwpwEiuUgpab0sH4VHiVcEoji1pSi+EIzeG4TPeKPc= -github.com/gammazero/deque v1.0.0 h1:LTmimT8H7bXkkCy6gZX7zNLtkbz4NdS2z8LZuor3j34= -github.com/gammazero/deque v1.0.0/go.mod h1:iflpYvtGfM3U8S8j+sZEKIak3SAKYpA5/SQewgfXDKo= -github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= -github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9 h1:r5GgOLGbza2wVHRzK7aAj6lWZjfbAwiu/RDCVOKjRyM= -github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9/go.mod h1:106OIgooyS7OzLDOpUGgm9fA3bQENb/cFSyyBmMoJDs= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= -github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= -github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -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-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= -github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU= -github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg= -github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= -github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= -github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/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-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0= -github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= -github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= -github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= -github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v1.4.1 h1:1Yx4Myt7BxzvUr5ldGSbwYiZG6t9wGBZ+8/fX3Wvtq0= -github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= -github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.2.4 h1:CNNw5U8lSiiBk7druxtSHHTsRWcxKoac6kZKm2peBBc= -github.com/golang/glog v1.2.4/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= -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/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= -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.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= -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.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.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 v0.0.5-0.20231225225746-43d5d4cd4e0e h1:4bw4WeyTYPp0smaXiJZCNnLrvVBqirQVreixayXezGc= -github.com/golang/snappy v0.0.5-0.20231225225746-43d5d4cd4e0e/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/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/flatbuffers v23.5.26+incompatible h1:M9dgRyhJemaM4Sw8+66GHBu8ioaQmyPLg1b8VwK5WJg= -github.com/google/flatbuffers v23.5.26+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= -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.5.0/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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= -github.com/google/go-tpm v0.9.5 h1:ocUmnDebX54dnW+MQWGQRbdaAcJELsa6PqZhJ48KwVU= -github.com/google/go-tpm v0.9.5/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= -github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= -github.com/google/gofuzz v1.2.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/orderedcode v0.0.1 h1:UzfcAexk9Vhv8+9pNOgRu41f16lHq725vPwnSeiG/Us= -github.com/google/orderedcode v0.0.1/go.mod h1:iVyU4/qPKHY5h/wSd6rZZCDcLJNxiWO6dvsYES2Sb20= -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-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0/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.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= -github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= -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/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -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.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= -github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= -github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= -github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= -github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= -github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= -github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= -github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= -github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-metrics v0.5.3 h1:M5uADWMOGCTUNU1YuC4hfknOeHNaX54LDm4oYSucoNE= -github.com/hashicorp/go-metrics v0.5.3/go.mod h1:KEjodfebIOuBYSAe/bHTm+HChmKSxAOXPBieMLYozDE= -github.com/hashicorp/go-plugin v1.5.2 h1:aWv8eimFqWlsEiMrYZdPYl+FdHaBJSN4AWwGWfT1G2Y= -github.com/hashicorp/go-plugin v1.5.2/go.mod h1:w1sAEES3g3PuV/RzUrgow20W2uErMly84hhD3um1WL4= -github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= -github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -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 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= -github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= -github.com/hdevalence/ed25519consensus v0.1.0 h1:jtBwzzcHuTmFrQN6xQZn6CQEO/V9f7HsjsjeEZ6auqU= -github.com/hdevalence/ed25519consensus v0.1.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= -github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw= -github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw= -github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= -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-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw= -github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= -github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= -github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= -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-shipyard/nopfs v0.0.14 h1:HFepJt/MxhZ3/GsLZkkAPzIPdNYKaLO1Qb7YmPbWIKk= -github.com/ipfs-shipyard/nopfs v0.0.14/go.mod h1:mQyd0BElYI2gB/kq/Oue97obP4B3os4eBmgfPZ+hnrE= -github.com/ipfs-shipyard/nopfs/ipfs v0.25.0 h1:OqNqsGZPX8zh3eFMO8Lf8EHRRnSGBMqcdHUd7SDsUOY= -github.com/ipfs-shipyard/nopfs/ipfs v0.25.0/go.mod h1:BxhUdtBgOXg1B+gAPEplkg/GpyTZY+kCMSfsJvvydqU= -github.com/ipfs/bbloom v0.0.4 h1:Gi+8EGJ2y5qiD5FbsbpX/TMNcJw8gSqr7eyjHa4Fhvs= -github.com/ipfs/bbloom v0.0.4/go.mod h1:cS9YprKXpoZ9lT0n/Mw/a6/aFV6DTjTLYHeA+gyqMG0= -github.com/ipfs/boxo v0.32.0 h1:rBs3P53Wt9bFW9WJwVdkzLtzYCXAj2bMjM7+1nrazZw= -github.com/ipfs/boxo v0.32.0/go.mod h1:VEtO3gOmr+sXGodalaTV9Vvsp3qVYegc4Rcu08Iw+wM= -github.com/ipfs/go-bitfield v1.1.0 h1:fh7FIo8bSwaJEh6DdTWbCeZ1eqOaOkKFI74SCnsWbGA= -github.com/ipfs/go-bitfield v1.1.0/go.mod h1:paqf1wjq/D2BBmzfTVFlJQ9IlFOZpg422HL0HqsGWHU= -github.com/ipfs/go-block-format v0.2.1 h1:96kW71XGNNa+mZw/MTzJrCpMhBWCrd9kBLoKm9Iip/Q= -github.com/ipfs/go-block-format v0.2.1/go.mod h1:frtvXHMQhM6zn7HvEQu+Qz5wSTj+04oEH/I+NjDgEjk= -github.com/ipfs/go-cid v0.5.0 h1:goEKKhaGm0ul11IHA7I6p1GmKz8kEYniqFopaB5Otwg= -github.com/ipfs/go-cid v0.5.0/go.mod h1:0L7vmeNXpQpUS9vt+yEARkJ8rOg43DF3iPgn4GIN0mk= -github.com/ipfs/go-cidutil v0.1.0 h1:RW5hO7Vcf16dplUU60Hs0AKDkQAVPVplr7lk97CFL+Q= -github.com/ipfs/go-cidutil v0.1.0/go.mod h1:e7OEVBMIv9JaOxt9zaGEmAoSlXW9jdFZ5lP/0PwcfpA= -github.com/ipfs/go-datastore v0.8.2 h1:Jy3wjqQR6sg/LhyY0NIePZC3Vux19nLtg7dx0TVqr6U= -github.com/ipfs/go-datastore v0.8.2/go.mod h1:W+pI1NsUsz3tcsAACMtfC+IZdnQTnC/7VfPoJBQuts0= -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-ds-badger v0.3.4 h1:MmqFicftE0KrwMC77WjXTrPuoUxhwyFsjKONSeWrlOo= -github.com/ipfs/go-ds-badger v0.3.4/go.mod h1:HfqsKJcNnIr9ZhZ+rkwS1J5PpaWjJjg6Ipmxd7KPfZ8= -github.com/ipfs/go-ds-flatfs v0.5.5 h1:lkx5C99pFBMI7T1sYF7y3v7xIYekNVNMp/95Gm9Y3tY= -github.com/ipfs/go-ds-flatfs v0.5.5/go.mod h1:bM7+m7KFUyv5dp3RBKTr3+OHgZ6h8ydCQkO7tjeO9Z4= -github.com/ipfs/go-ds-leveldb v0.5.2 h1:6nmxlQ2zbp4LCNdJVsmHfs9GP0eylfBNxpmY1csp0x0= -github.com/ipfs/go-ds-leveldb v0.5.2/go.mod h1:2fAwmcvD3WoRT72PzEekHBkQmBDhc39DJGoREiuGmYo= -github.com/ipfs/go-ds-measure v0.2.2 h1:4kwvBGbbSXNYe4ANlg7qTIYoZU6mNlqzQHdVqICkqGI= -github.com/ipfs/go-ds-measure v0.2.2/go.mod h1:b/87ak0jMgH9Ylt7oH0+XGy4P8jHx9KG09Qz+pOeTIs= -github.com/ipfs/go-ds-pebble v0.5.0 h1:lXffYCAKVD7nLLPqwJ9D8IxgO7Kz8woiX021tezdsIM= -github.com/ipfs/go-ds-pebble v0.5.0/go.mod h1:aiCRVcj3K60sxc6k5C+HO9C6rouqiSkjR/WKnbTcMfQ= -github.com/ipfs/go-fs-lock v0.1.1 h1:TecsP/Uc7WqYYatasreZQiP9EGRy4ZnKoG4yXxR33nw= -github.com/ipfs/go-fs-lock v0.1.1/go.mod h1:2goSXMCw7QfscHmSe09oXiR34DQeUdm+ei+dhonqly0= -github.com/ipfs/go-ipfs-blockstore v1.3.1 h1:cEI9ci7V0sRNivqaOr0elDsamxXFxJMMMy7PTTDQNsQ= -github.com/ipfs/go-ipfs-blockstore v1.3.1/go.mod h1:KgtZyc9fq+P2xJUiCAzbRdhhqJHvsw8u2Dlqy2MyRTE= -github.com/ipfs/go-ipfs-cmds v0.14.1 h1:TA8vBixPwXL3k7VtcbX3r4FQgw2m+jMOWlslUOlM9Rs= -github.com/ipfs/go-ipfs-cmds v0.14.1/go.mod h1:SCYxNUVPeVR05cE8DJ6wyH2+aQ8vPgjxxkxQWOXobzo= -github.com/ipfs/go-ipfs-delay v0.0.1 h1:r/UXYyRcddO6thwOnhiznIAiSvxMECGgtv35Xs1IeRQ= -github.com/ipfs/go-ipfs-delay v0.0.1/go.mod h1:8SP1YXK1M1kXuc4KJZINY3TQQ03J2rwBG9QfXmbRPrw= -github.com/ipfs/go-ipfs-ds-help v1.1.1 h1:B5UJOH52IbcfS56+Ul+sv8jnIV10lbjLF5eOO0C66Nw= -github.com/ipfs/go-ipfs-ds-help v1.1.1/go.mod h1:75vrVCkSdSFidJscs8n4W+77AtTpCIAdDGAwjitJMIo= -github.com/ipfs/go-ipfs-pq v0.0.3 h1:YpoHVJB+jzK15mr/xsWC574tyDLkezVrDNeaalQBsTE= -github.com/ipfs/go-ipfs-pq v0.0.3/go.mod h1:btNw5hsHBpRcSSgZtiNm/SLj5gYIZ18AKtv3kERkRb4= -github.com/ipfs/go-ipfs-redirects-file v0.1.2 h1:QCK7VtL91FH17KROVVy5KrzDx2hu68QvB2FTWk08ZQk= -github.com/ipfs/go-ipfs-redirects-file v0.1.2/go.mod h1:yIiTlLcDEM/8lS6T3FlCEXZktPPqSOyuY6dEzVqw7Fw= -github.com/ipfs/go-ipfs-util v0.0.3 h1:2RFdGez6bu2ZlZdI+rWfIdbQb1KudQp3VGwPtdNCmE0= -github.com/ipfs/go-ipfs-util v0.0.3/go.mod h1:LHzG1a0Ig4G+iZ26UUOMjHd+lfM84LZCrn17xAKWBvs= -github.com/ipfs/go-ipld-cbor v0.2.0 h1:VHIW3HVIjcMd8m4ZLZbrYpwjzqlVUfjLM7oK4T5/YF0= -github.com/ipfs/go-ipld-cbor v0.2.0/go.mod h1:Cp8T7w1NKcu4AQJLqK0tWpd1nkgTxEVB5C6kVpLW6/0= -github.com/ipfs/go-ipld-format v0.6.1 h1:lQLmBM/HHbrXvjIkrydRXkn+gc0DE5xO5fqelsCKYOQ= -github.com/ipfs/go-ipld-format v0.6.1/go.mod h1:8TOH1Hj+LFyqM2PjSqI2/ZnyO0KlfhHbJLkbxFa61hs= -github.com/ipfs/go-ipld-git v0.1.1 h1:TWGnZjS0htmEmlMFEkA3ogrNCqWjIxwr16x1OsdhG+Y= -github.com/ipfs/go-ipld-git v0.1.1/go.mod h1:+VyMqF5lMcJh4rwEppV0e6g4nCCHXThLYYDpKUkJubI= -github.com/ipfs/go-ipld-legacy v0.2.1 h1:mDFtrBpmU7b//LzLSypVrXsD8QxkEWxu5qVxN99/+tk= -github.com/ipfs/go-ipld-legacy v0.2.1/go.mod h1:782MOUghNzMO2DER0FlBR94mllfdCJCkTtDtPM51otM= -github.com/ipfs/go-log v1.0.5 h1:2dOuUCB1Z7uoczMWgAyDck5JLb72zHzrMnGnCNNbvY8= -github.com/ipfs/go-log v1.0.5/go.mod h1:j0b8ZoR+7+R99LD9jZ6+AJsrzkPbSXbZfGakb5JPtIo= -github.com/ipfs/go-log/v2 v2.1.3/go.mod h1:/8d0SH3Su5Ooc31QlL1WysJhvyOTDCjcCZ9Axpmri6g= -github.com/ipfs/go-log/v2 v2.6.0 h1:2Nu1KKQQ2ayonKp4MPo6pXCjqw1ULc9iohRqWV5EYqg= -github.com/ipfs/go-log/v2 v2.6.0/go.mod h1:p+Efr3qaY5YXpx9TX7MoLCSEZX5boSWj9wh86P5HJa8= -github.com/ipfs/go-metrics-interface v0.3.0 h1:YwG7/Cy4R94mYDUuwsBfeziJCVm9pBMJ6q/JR9V40TU= -github.com/ipfs/go-metrics-interface v0.3.0/go.mod h1:OxxQjZDGocXVdyTPocns6cOLwHieqej/jos7H4POwoY= -github.com/ipfs/go-peertaskqueue v0.8.2 h1:PaHFRaVFdxQk1Qo3OKiHPYjmmusQy7gKQUaL8JDszAU= -github.com/ipfs/go-peertaskqueue v0.8.2/go.mod h1:L6QPvou0346c2qPJNiJa6BvOibxDfaiPlqHInmzg0FA= -github.com/ipfs/go-test v0.2.2 h1:1yjYyfbdt1w93lVzde6JZ2einh3DIV40at4rVoyEcE8= -github.com/ipfs/go-test v0.2.2/go.mod h1:cmLisgVwkdRCnKu/CFZOk2DdhOcwghr5GsHeqwexoRA= -github.com/ipfs/go-unixfsnode v1.10.1 h1:hGKhzuH6NSzZ4y621wGuDspkjXRNG3B+HqhlyTjSwSM= -github.com/ipfs/go-unixfsnode v1.10.1/go.mod h1:eguv/otvacjmfSbYvmamc9ssNAzLvRk0+YN30EYeOOY= -github.com/ipfs/kubo v0.35.0 h1:gSL9deP/W5Vmyz/lZ37KeX4mIaXoPQ/97xxZpqlUr00= -github.com/ipfs/kubo v0.35.0/go.mod h1:wAZKTT0wbblEWvysWo7MBC3/NlzK2jkNrX/JcjqR6q8= -github.com/ipld/go-car/v2 v2.14.3 h1:1Mhl82/ny8MVP+w1M4LXbj4j99oK3gnuZG2GmG1IhC8= -github.com/ipld/go-car/v2 v2.14.3/go.mod h1:/vpSvPngOX8UnvmdFJ3o/mDgXa9LuyXsn7wxOzHDYQE= -github.com/ipld/go-codec-dagpb v1.7.0 h1:hpuvQjCSVSLnTnHXn+QAMR0mLmb1gA6wl10LExo2Ts0= -github.com/ipld/go-codec-dagpb v1.7.0/go.mod h1:rD3Zg+zub9ZnxcLwfol/OTQRVjaLzXypgy4UqHQvilM= -github.com/ipld/go-ipld-prime v0.21.0 h1:n4JmcpOlPDIxBcY037SVfpd1G+Sj1nKZah0m6QH9C2E= -github.com/ipld/go-ipld-prime v0.21.0/go.mod h1:3RLqy//ERg/y5oShXXdx5YIp50cFGOanyMctpPjsvxQ= -github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20230102063945-1a409dc236dd h1:gMlw/MhNr2Wtp5RwGdsW23cs+yCuj9k2ON7i9MiJlRo= -github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20230102063945-1a409dc236dd/go.mod h1:wZ8hH8UxeryOs4kJEJaiui/s00hDSbE37OKsL47g+Sw= -github.com/ipshipyard/p2p-forge v0.5.1 h1:9MCpAlk+wNhy7W/yOYKgi9KlXPnyb0abmDpsRPHUDxQ= -github.com/ipshipyard/p2p-forge v0.5.1/go.mod h1:GNDXM2CR8KRS8mJGw7ARIRVlrG9NH8MdewgNVfIIByA= -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/jbenet/goprocess v0.1.4 h1:DRGOFReOMqqDNXwW70QkacFW0YN9QnwLV0Vqk+3oU0o= -github.com/jbenet/goprocess v0.1.4/go.mod h1:5yspPrukOVuOLORacaBi858NqyClJPQxYZlqdZVfqY4= -github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= -github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= -github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.9/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/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -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.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= -github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -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.0.6 h1:Jb0h04599eq/CY7rB5YEqPS83HmRfHP2azkxMN2rFtU= -github.com/koron/go-ssdp v0.0.6/go.mod h1:0R9LfRJGek1zWTjN3JUNlm5INCDYGpRDfAptnct63fI= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -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/pty v1.1.3/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/labstack/echo-jwt/v4 v4.3.1 h1:d8+/qf8nx7RxeL46LtoIwHJsH2PNN8xXCQ/jDianycE= -github.com/labstack/echo-jwt/v4 v4.3.1/go.mod h1:yJi83kN8S/5vePVPd+7ID75P4PqPNVRs2HVeuvYJH00= -github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA= -github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ= -github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0= -github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU= -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/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/libdns/libdns v0.2.2 h1:O6ws7bAfRPaBsgAYt8MDe2HcNBGC29hkZ9MX2eUSX3s= -github.com/libdns/libdns v0.2.2/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= -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-doh-resolver v0.5.0 h1:4h7plVVW+XTS+oUBw2+8KfoM1jF6w8XmO7+skhePFdE= -github.com/libp2p/go-doh-resolver v0.5.0/go.mod h1:aPDxfiD2hNURgd13+hfo29z9IC22fv30ee5iM31RzxU= -github.com/libp2p/go-flow-metrics v0.2.0 h1:EIZzjmeOE6c8Dav0sNv35vhZxATIXWZg6j/C08XmmDw= -github.com/libp2p/go-flow-metrics v0.2.0/go.mod h1:st3qqfu8+pMfh+9Mzqb2GTiwrAGjIPszEjZmtksN8Jc= -github.com/libp2p/go-libp2p v0.43.0 h1:b2bg2cRNmY4HpLK8VHYQXLX2d3iND95OjodLFymvqXU= -github.com/libp2p/go-libp2p v0.43.0/go.mod h1:IiSqAXDyP2sWH+J2gs43pNmB/y4FOi2XQPbsb+8qvzc= -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.33.1 h1:hKFhHMf7WH69LDjaxsJUWOU6qZm71uO47M/a5ijkiP0= -github.com/libp2p/go-libp2p-kad-dht v0.33.1/go.mod h1:CdmNk4VeGJa9EXM9SLNyNVySEvduKvb+5rSC/H4pLAo= -github.com/libp2p/go-libp2p-kbucket v0.7.0 h1:vYDvRjkyJPeWunQXqcW2Z6E93Ywx7fX0jgzb/dGOKCs= -github.com/libp2p/go-libp2p-kbucket v0.7.0/go.mod h1:blOINGIj1yiPYlVEX0Rj9QwEkmVnz3EP8LK1dRKBC6g= -github.com/libp2p/go-libp2p-pubsub v0.13.1 h1:tV3ttzzZSCk0EtEXnxVmWIXgjVxXx+20Jwjbs/Ctzjo= -github.com/libp2p/go-libp2p-pubsub v0.13.1/go.mod h1:MKPU5vMI8RRFyTP0HfdsF9cLmL1nHAeJm44AxJGJx44= -github.com/libp2p/go-libp2p-pubsub-router v0.6.0 h1:D30iKdlqDt5ZmLEYhHELCMRj8b4sFAqrUcshIUvVP/s= -github.com/libp2p/go-libp2p-pubsub-router v0.6.0/go.mod h1:FY/q0/RBTKsLA7l4vqC2cbRbOvyDotg8PJQ7j8FDudE= -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-libp2p-xor v0.1.0 h1:hhQwT4uGrBcuAkUGXADuPltalOdpf9aag9kaYNT2tLA= -github.com/libp2p/go-libp2p-xor v0.1.0/go.mod h1:LSTM5yRnjGZbWNTA/hRwq2gGFrvRIbQJscoIL/u6InY= -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.2.2 h1:Dejd8cQ47Qx2kRABg6lPwknU7+nBnFRpko45/fFPuZ8= -github.com/libp2p/go-netroute v0.2.2/go.mod h1:Rntq6jUAH0l9Gg17w5bFGhcC9a+vk4KNXs6s7IljKYE= -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.0.1 h1:f0WoX/bEF2E8SbE4c/k1Mo+/9z0O4oC/hWEA+nfYRSg= -github.com/libp2p/go-yamux/v5 v5.0.1/go.mod h1:en+3cdX51U0ZslwRdRLrvQsdayFt3TSUKvBGErzpWbU= -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/linxGnu/grocksdb v1.9.8 h1:vOIKv9/+HKiqJAElJIEYv3ZLcihRxyP7Suu/Mu8Dxjs= -github.com/linxGnu/grocksdb v1.9.8/go.mod h1:C3CNe9UYc9hlEM2pC82AqiGS3LRW537u9LFV4wIZuHk= -github.com/lithammer/shortuuid/v4 v4.0.0 h1:QRbbVkfgNippHOS8PXDkti4NaWeyYfcBTHtw7k08o4c= -github.com/lithammer/shortuuid/v4 v4.0.0/go.mod h1:Zs8puNcrvf2rV9rTH51ZLLcj7ZXqQI3lv67aw4KiB1Y= -github.com/lmittmann/tint v1.0.3 h1:W5PHeA2D8bBJVvabNfQD/XW9HPLZK1XoPZH0cq8NouQ= -github.com/lmittmann/tint v1.0.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE= -github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= -github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= -github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -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.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -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.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/mholt/acmez/v3 v3.0.0 h1:r1NcjuWR0VaKP2BTjDK9LRFBw/WvURx3jlaEUl9Ht8E= -github.com/mholt/acmez/v3 v3.0.0/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= -github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= -github.com/miekg/dns v1.1.66 h1:FeZXOS3VCVsKnEAd+wBkjMC3D2K+ww66Cq3VnCINuJE= -github.com/miekg/dns v1.1.66/go.mod h1:jGFzBsSNbJw6z1HYut1RKBKHA9PBdxeHrZG8J+gC2WE= -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/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= -github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= -github.com/minio/highwayhash v1.0.3 h1:kbnuUMoHYyVl7szWjSxJnxw11k2U709jqFPPmIUyD6Q= -github.com/minio/highwayhash v1.0.3/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= -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/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= -github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= -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/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/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.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= -github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= -github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= -github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= -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.0 h1:oGWEVKioVQcdIOBlYM8BH1rZDWOGJSqr9/BKl6zQ4qc= -github.com/multiformats/go-multiaddr v0.16.0/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0= -github.com/multiformats/go-multiaddr-dns v0.4.1 h1:whi/uCLbDS3mSEUMb1MsoT4uzUeZB0N32yzufqS0i5M= -github.com/multiformats/go-multiaddr-dns v0.4.1/go.mod h1:7hfthtB4E4pQwirrz+J0CcDUfbWzTqEzVyYKKIKpgkc= -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.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g= -github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk= -github.com/multiformats/go-multicodec v0.9.1 h1:x/Fuxr7ZuR4jJV4Os5g444F7xC4XmyUaT/FWtE+9Zjo= -github.com/multiformats/go-multicodec v0.9.1/go.mod h1:LLWNMtyV5ithSBUo3vFIMaeDy+h3EbkMTek1m+Fybbo= -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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= -github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= -github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc= -github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a h1:dlRvE5fWabOchtH7znfiFCcOvmIYgOeAS5ifBXBlh9Q= -github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a/go.mod h1:hVoHR2EVESiICEMbg137etN/Lx+lSrHPTD39Z/uE+2s= -github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= -github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= -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.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -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/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.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= -github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= -github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= -github.com/openzipkin/zipkin-go v0.4.3 h1:9EGwpqkgnwdEIJ+Od7QVSEIH+ocmm5nPat0G7sjsSdg= -github.com/openzipkin/zipkin-go v0.4.3/go.mod h1:M9wCJZFWCo2RiY+o1eBCEMe0Dp2S5LDHcMZmk3RmK7c= -github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY= -github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI= -github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= -github.com/pascaldekloe/goe v0.1.0/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/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= -github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= -github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 h1:1/WtZae0yGtPq+TI6+Tv1WTxkukpXeMlviSxvL7SRgk= -github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9/go.mod h1:x3N5drFsm2uilKKuuYo6LdyD8vZAW55sH/9w+pbo1sw= -github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= -github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= -github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= -github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= -github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= -github.com/pion/datachannel v1.5.10 h1:ly0Q26K1i6ZkGf42W7D4hQYR90pZwzFOjTq5AuCKk4o= -github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oLo8Rs4Py/M= -github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= -github.com/pion/dtls/v2 v2.2.12 h1:KP7H5/c1EiVAAKUmXyCzPiQe5+bCJrpOeKg/L05dunk= -github.com/pion/dtls/v2 v2.2.12/go.mod h1:d9SYc9fch0CqK90mRk1dC7AkzzpwJj6u2GU3u+9pqFE= -github.com/pion/dtls/v3 v3.0.6 h1:7Hkd8WhAJNbRgq9RgdNh1aaWlZlGpYTzdqjy9x9sK2E= -github.com/pion/dtls/v3 v3.0.6/go.mod h1:iJxNQ3Uhn1NZWOMWlLxEEHAN5yX7GyPvvKw04v9bzYU= -github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4= -github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw= -github.com/pion/interceptor v0.1.40 h1:e0BjnPcGpr2CFQgKhrQisBU7V3GXK6wrfYrGYaU6Jq4= -github.com/pion/interceptor v0.1.40/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic= -github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= -github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI= -github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90= -github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM= -github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA= -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.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo= -github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0= -github.com/pion/rtp v1.8.19 h1:jhdO/3XhL/aKm/wARFVmvTfq0lC/CvN1xwYKmduly3c= -github.com/pion/rtp v1.8.19/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk= -github.com/pion/sctp v1.8.39 h1:PJma40vRHa3UTO3C4MyeJDQ+KIobVYRZQZ0Nt7SjQnE= -github.com/pion/sctp v1.8.39/go.mod h1:cNiLdchXra8fHQwmIoqw0MbLLMs+f7uQ+dGMG2gWebE= -github.com/pion/sdp/v3 v3.0.13 h1:uN3SS2b+QDZnWXgdr69SM8KB4EbcnPnPf2Laxhty/l4= -github.com/pion/sdp/v3 v3.0.13/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E= -github.com/pion/srtp/v3 v3.0.6 h1:E2gyj1f5X10sB/qILUGIkL4C2CqK269Xq167PbGCc/4= -github.com/pion/srtp/v3 v3.0.6/go.mod h1:BxvziG3v/armJHAaJ87euvkhHqWe9I7iiOy50K2QkhY= -github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4= -github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8= -github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw= -github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU= -github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= -github.com/pion/transport/v2 v2.2.4/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= -github.com/pion/transport/v2 v2.2.10 h1:ucLBLE8nuxiHfvkFKnkDQRYWYfp8ejf4YBOPfaQpw6Q= -github.com/pion/transport/v2 v2.2.10/go.mod h1:sq1kSLWs+cHW9E+2fJP95QudkzbK7wscs8yYgQToO5E= -github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0= -github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo= -github.com/pion/turn/v4 v4.0.2 h1:ZqgQ3+MjP32ug30xAbD6Mn+/K4Sxi3SdNOTFf+7mpps= -github.com/pion/turn/v4 v4.0.2/go.mod h1:pMMKP/ieNAG/fN5cZiN4SDuyKsXtNTr0ccN7IToA1zs= -github.com/pion/webrtc/v4 v4.1.2 h1:mpuUo/EJ1zMNKGE79fAdYNFZBX790KE7kQQpLMjjR54= -github.com/pion/webrtc/v4 v4.1.2/go.mod h1:xsCXiNAmMEjIdFxAYU0MbB3RwRieJsegSB2JZsGN+8U= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/polydawn/refmt v0.89.0 h1:ADJTApkvkeBZsN0tBTx8QjpD9JkmxbKp0cxfr9qszm4= -github.com/polydawn/refmt v0.89.0/go.mod h1:/zvteZs/GwLtCgZ4BL6CBsk9IKIlexP43ObX9AxTqTw= -github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0/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.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= -github.com/prometheus/common v0.64.0 h1:pdZeA+g617P7oGv1CzdTzyeShxAGrTBsolKNOLQPGO4= -github.com/prometheus/common v0.64.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= -github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= -github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= -github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= -github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= -github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= -github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg= -github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY= -github.com/quic-go/webtransport-go v0.9.0 h1:jgys+7/wm6JarGDrW+lD/r9BGqBAmqY/ssklE09bA70= -github.com/quic-go/webtransport-go v0.9.0/go.mod h1:4FUYIiUc75XSsF6HShcLeXXYZJ9AGwo/xh3L8M/P1ao= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= -github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= -github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M= -github.com/regen-network/gocuke v0.6.2/go.mod h1:zYaqIHZobHyd0xOrHGPQjbhGJsuZ1oElx150u2o1xuk= -github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= -github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -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.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -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/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= -github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -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/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= -github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= -github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= -github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= -github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= -github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= -github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= -github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= -github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= -github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= -github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= -github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= -github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= -github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= -github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= -github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= -github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= -github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= -github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= -github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= -github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= -github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= -github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= -github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= -github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= -github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= -github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= -github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -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 v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= -github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= -github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= -github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= -github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= -github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= -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.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= -github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= -github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= -github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= -github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= -github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.17.0 h1:I5txKw7MJasPL/BrfkbA0Jyo/oELqVmux4pR/UxOMfI= -github.com/spf13/viper v1.17.0/go.mod h1:BmMMMLQXSbcHK6KAOiFLz0l5JHrU89OdIRHvsk0+yVI= -github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 h1:5v7j5P2QTOiV3Uftja+1bwwuyaGe/lpnsC7dZNgoo/U= -github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5/go.mod h1:PHUr2nW1WC6isM2ar72DLQ/Cd/ibvUntm/YU6ML/eG0= -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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= -github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= -github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= -github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= -github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= -github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= -github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q= -github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk= -github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= -github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM= -github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= -github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= -github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= -github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= -github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= -github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= -github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -github.com/twmb/murmur3 v1.1.8 h1:8Yt9taO/WN3l08xErzjeschgZU2QSrwm1kclYq+0aRg= -github.com/twmb/murmur3 v1.1.8/go.mod h1:Qq/R7NUyOfr65zD+6Q5IHKsJLwP7exErjN6lyyq3OSQ= -github.com/ucarion/urlpath v0.0.0-20200424170820-7ccc79b76bbb h1:Ywfo8sUltxogBpFuMOFRrrSifO788kAFxmvVw31PtQQ= -github.com/ucarion/urlpath v0.0.0-20200424170820-7ccc79b76bbb/go.mod h1:ikPs9bRWicNw3S7XpJ8sK/smGwU9WcSVU3dy9qahYBM= -github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= -github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= -github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= -github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= -github.com/warpfork/go-testmark v0.12.1 h1:rMgCpJfwy1sJ50x0M0NgyphxYYPMOODIJHhsXyEHU0s= -github.com/warpfork/go-testmark v0.12.1/go.mod h1:kHwy7wfvGSPh1rQJYKayD4AbtNaeyZdcGi9tNJTaa5Y= -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/base32 v0.0.0-20170828182744-c30ac30633cc h1:BCPnHtcboadS0DvysUuJXZ4lWVv5Bh5i7+tbIyi+ck4= -github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc/go.mod h1:r45hJU7yEoA81k6MWNhpMj/kms0n14dkzkxYHoB96UM= -github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 h1:5HZfQkwe0mIfyDmc1Em5GqlNRzcdtlv4HTNmdpt7XH0= -github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11/go.mod h1:Wlo/SzPmxVp6vXpGt/zaXhHH0fn4IxgqZc82aKg6bpQ= -github.com/whyrusleeping/cbor-gen v0.1.2 h1:WQFlrPhpcQl+M2/3dP5cvlTLWPVsL6LGBb9jJt6l/cA= -github.com/whyrusleeping/cbor-gen v0.1.2/go.mod h1:pM99HXyEbSQHcosHc0iW7YFmwnscr+t9Te4ibko05so= -github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f h1:jQa4QT2UP9WYv2nzyawpKMOCl+Z/jW7djv2/J50lj9E= -github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f/go.mod h1:p9UJB6dDgdPgMJZs7UjUOdulKyRr9fqkS+6JKAInPy8= -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/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7 h1:E9S12nwJwEOXe2d6gT6qxdvqMnNq+VnSsKPgm2ZZNds= -github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= -github.com/wlynxg/anet v0.0.3/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= -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.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= -github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= -github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= -github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= -github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= -github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= -github.com/zondax/hid v0.9.2 h1:WCJFnEDMiqGF64nlZz28E9qLVZ0KSJ7xpc5DLEyma2U= -github.com/zondax/hid v0.9.2/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= -github.com/zondax/ledger-go v0.14.3 h1:wEpJt2CEcBJ428md/5MgSLsXLBos98sBOyxNmCjfUCw= -github.com/zondax/ledger-go v0.14.3/go.mod h1:IKKaoxupuB43g4NxeQmbLXv7T9AlQyie1UpHb342ycI= -go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 h1:qxen9oVGzDdIRP6ejyAJc760RwW4SnVDiTYTzwnXuxo= -go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5/go.mod h1:eW0HG9/oHQhvRCvb1/pIXW4cOvtDqeQK+XSi3TnwaXY= -go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= -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.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= -go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 h1:UP6IpuHFkUgOQL9FFQFrZ+5LiwhhYRbi7VZSIx6Nj5s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0/go.mod h1:qxuZLtbq5QDtdeSHsS7bcf6EH6uO6jUAgk764zd3rhM= -go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= -go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 h1:FFeLy03iVTXP6ffeN2iXrxfGsZGCjVx0/4KlizjyBwU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0/go.mod h1:TMu73/k1CP8nBUpDLc71Wj/Kf7ZS9FK5b53VapRsP9o= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0 h1:lUsI2TYsQw2r1IASwoROaCnjdj2cvC2+Jbxvk6nHnWU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0/go.mod h1:2HpZxxQurfGxJlJDblybejHB6RX6pmExPNe517hREw4= -go.opentelemetry.io/otel/exporters/prometheus v0.44.0 h1:08qeJgaPC0YEBu2PQMbqU3rogTlyzpjhCI2b58Yn00w= -go.opentelemetry.io/otel/exporters/prometheus v0.44.0/go.mod h1:ERL2uIeBtg4TxZdojHUwzZfIFlUIjZtxubT5p4h1Gjg= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0 h1:UGZ1QwZWY67Z6BmckTU+9Rxn04m2bD3gD6Mk0OIOCPk= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0/go.mod h1:fcwWuDuaObkkChiDlhEpSq9+X1C0omv+s5mBtToAQ64= -go.opentelemetry.io/otel/exporters/zipkin v1.31.0 h1:CgucL0tj3717DJnni7HVVB2wExzi8c2zJNEA2BhLMvI= -go.opentelemetry.io/otel/exporters/zipkin v1.31.0/go.mod h1:rfzOVNiSwIcWtEC2J8epwG26fiaXlYvLySJ7bwsrtAE= -go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= -go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= -go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= -go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= -go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= -go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= -go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -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.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= -go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= -go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= -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/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= -go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= -go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= -go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= -go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= -go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE= -go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI= -go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= -go4.org v0.0.0-20230225012048-214862532bf5 h1:nifaUDeh+rPaBCMPMQHZmvJf+QdpLFnuQPwx+LxVmtc= -go4.org v0.0.0-20230225012048-214862532bf5/go.mod h1:F57wTi5Lrj6WLyswp5EYV1ncrEbFGHD4hhz6S1ZYeaU= -golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= -golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/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-20190313024323-a1f597ede03a/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-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-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= -golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= -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-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= -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-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -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/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.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/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.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= -golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= -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-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/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-20190313220215-9f648a60d977/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-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/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-20200202094626-16171245cfb2/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-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/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-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -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.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= -golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= -golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/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/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= -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-20201020160332-67f06af15bc9/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.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/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-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/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-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/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-20191005200804-aed5e4c7ecf9/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-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/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-20210615035016-665e8c7367d1/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.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20221010170243-090e33056c14/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.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -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.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= -golang.org/x/term v0.35.0 h1:bZBVKBudEyhRcajGcNc3jIfWPqV4y/Kt2XcoigOWtDQ= -golang.org/x/term v0.35.0/go.mod h1:TPGtkTLesOwf2DE8CgVYiZinHAOuy5AYUYT1lENIZnA= -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.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.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -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.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/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-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/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-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-20200130002326-2f3ba24bd6e7/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-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -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.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= -golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= -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-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.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= -gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= -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/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -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/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= -google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -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-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094 h1:6whtk83KtD3FkGrVb2hFXuQ+ZMbCNdakARIn/aHMmG8= -google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094/go.mod h1:Zs4wYw8z1zr6RNF4cwYb31mvN/EGaKAdQjNCF3DW6K4= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 h1:e0AIkUUhxyBKh6ssZNrAMeqhA7RKUj42346d1y02i2g= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -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.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= -google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= -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.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -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-20190902080502-41f04d3bba15/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/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -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.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -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.5/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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= -gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= -gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= -grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -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= -lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= -lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= -nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y= -nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= -nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= -pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= -pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -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= -sigs.k8s.io/yaml v1.5.0 h1:M10b2U7aEUY6hRtU870n2VTPgR5RZiL/I6Lcc2F4NUQ= -sigs.k8s.io/yaml v1.5.0/go.mod h1:wZs27Rbxoai4C0f8/9urLZtZtF3avA3gKvGyPdDqTO4= -sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= -sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/cmd/hway/main.go b/cmd/hway/main.go deleted file mode 100644 index d4204df9f..000000000 --- a/cmd/hway/main.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package main provides the Highway service, a UCAN-based task processing service -// that acts as a bridge proxy for MPC operations and decentralized identity management. -// -// The service processes asynchronous UCAN (User-Controlled Authorization Networks) tasks -// including token creation, delegation, signing, verification, and DID generation. -// It serves as a proxy between the bridge handlers and the underlying blockchain operations. -package main - -import ( - "github.com/sonr-io/sonr/bridge" -) - -func main() { - // Create and configure the Highway service - service := bridge.NewHighwayService() - defer service.Shutdown() - - // Start the service and block until shutdown - service.Start() -} diff --git a/cmd/hway/version.go b/cmd/hway/version.go deleted file mode 100644 index a5a16c0a9..000000000 --- a/cmd/hway/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package main - -// Version is set by commitizen during release process -var Version = "dev" diff --git a/cmd/motr/.cz.toml b/cmd/motr/.cz.toml deleted file mode 100644 index d273f539b..000000000 --- a/cmd/motr/.cz.toml +++ /dev/null @@ -1,18 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "motr/v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "scm" -update_changelog_on_bump = true -changelog_file = "CHANGELOG.md" -major_version_zero = true -annotated_tag = true -pre_bump_hooks = ["bash scripts/hook-bump-pre.sh"] -post_bump_hooks = ["goreleaser release --clean -f cmd/motr/.goreleaser.yml"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(motr\\)(!)?:" diff --git a/cmd/motr/.goreleaser.yml b/cmd/motr/.goreleaser.yml deleted file mode 100644 index db34abc3b..000000000 --- a/cmd/motr/.goreleaser.yml +++ /dev/null @@ -1,75 +0,0 @@ -# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json ---- -version: 2 -dist: dist/motr -monorepo: - tag_prefix: motr/ - dir: cmd/motr - -project_name: motr - -before: - hooks: - - go mod download - -builds: - - id: motr-wasm - main: . - binary: motr - no_unique_dist_dir: true - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=0 - goos: - - js - goarch: - - wasm - flags: - - -mod=readonly - - -trimpath - ldflags: - - -s -w - - -X main.version={{.Version}} - - -X main.commit={{.Commit}} - - -X main.date={{.Date}} - hooks: - post: - - cp dist/motr/motr.wasm packages/es/src/worker/app.wasm -archives: - - id: motr-wasm-archive - name_template: "motr_wasm_{{ .Version }}" - formats: ["binary"] - wrap_in_directory: true - -blobs: - - provider: s3 - endpoint: https://eb37925850388bca807b7fab964c12bb.r2.cloudflarestorage.com - bucket: releases - region: auto - directory: "motr/{{ .Tag }}" - -release: - disable: false - github: - owner: sonr-io - name: sonr - name_template: "{{.ProjectName}}/{{ .Tag }}" - draft: false - replace_existing_draft: false # Don't replace drafts - replace_existing_artifacts: false # Append, don't replace - mode: append # Explicitly set to append mode - -checksum: - name_template: "motr_checksums.txt" - -snapshot: - version_template: "{{ incpatch .Version }}-dev" - -# Changelog configuration -changelog: - sort: asc - filters: - exclude: - - "^docs:" - - "^test:" - - "^chore:" diff --git a/cmd/motr/CHANGELOG.md b/cmd/motr/CHANGELOG.md deleted file mode 100644 index 1ee0cc481..000000000 --- a/cmd/motr/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -## motr/v0.0.3 (2025-10-04) - -## motr/v0.0.2 (2025-10-04) - -## motr/v0.0.1 (2025-10-03) diff --git a/cmd/motr/Makefile b/cmd/motr/Makefile deleted file mode 100644 index 6cdf368a8..000000000 --- a/cmd/motr/Makefile +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/make -f - -# Output configuration - outputs to ES package for bundling -GIT_ROOT := $(shell git rev-parse --show-toplevel) -ES_PACKAGE_DIR := $(GIT_ROOT)/packages/es/src/worker -WASM_FILE := app.wasm -JS_FILE := wasm_exec.js -OUTPUT_PATH := $(ES_PACKAGE_DIR)/$(WASM_FILE) -JS_PATH := $(ES_PACKAGE_DIR)/$(JS_FILE) - -# Build configuration for WASM -GOOS := js -GOARCH := wasm -CGO_ENABLED := 0 - -# Version information -VERSION := $(shell echo $(shell git describe --tags 2>/dev/null || echo "dev") | sed 's/^v//') -COMMIT := $(shell git log -1 --format='%H') - -# Go installation paths -GOROOT := $(shell go env GOROOT) -WASM_EXEC_SOURCE := $(GOROOT)/misc/wasm/wasm_exec.js - -# Build flags -LDFLAGS := -s -w -BUILD_FLAGS := -ldflags="$(LDFLAGS)" -trimpath - -.PHONY: all build clean test verify help version runtime tidy - -all: build - -build: clean-output runtime - @echo "Building Motor WASM module for ES package..." - @echo "Target: $(OUTPUT_PATH)" - @mkdir -p $(ES_PACKAGE_DIR) - @GOOS=$(GOOS) GOARCH=$(GOARCH) CGO_ENABLED=$(CGO_ENABLED) go build $(BUILD_FLAGS) -o $(OUTPUT_PATH) . - @echo "✅ Motor WASM module built successfully" - @echo "Output: $(OUTPUT_PATH)" - @ls -lh $(OUTPUT_PATH) | awk '{print "Size: " $$5}' - @$(MAKE) runtime - -runtime: - @echo "Copying WASM runtime..." - @if [ -f "$(WASM_EXEC_SOURCE)" ]; then \ - cp "$(WASM_EXEC_SOURCE)" "$(JS_PATH)"; \ - echo "✅ WASM runtime copied to $(JS_PATH)"; \ - else \ - echo "⚠️ WASM runtime not found at $(WASM_EXEC_SOURCE)"; \ - echo "You may need to manually copy wasm_exec.js"; \ - fi - -clean-output: - @echo "Cleaning previous builds..." - @rm -f $(OUTPUT_PATH) - @rm -f $(JS_PATH) - @mkdir -p $(ES_PACKAGE_DIR) - -clean: - @echo "Cleaning build artifacts..." - @rm -f $(OUTPUT_PATH) - @rm -f $(JS_PATH) - @echo "✅ Clean complete" - -release: - @echo "Creating motr release..." - @cd $(GIT_ROOT) && cz --config cmd/motr/.cz.toml --no-raise 6,21 bump --yes --increment PATCH - -snapshot: - @echo "Dry-Run Bumping Motor version..." - @cd $(GIT_ROOT) && cz --config cmd/motr/.cz.toml bump --yes --no-verify --dry-run --increment PATCH - @echo "Creating motr snapshots for all platforms..." - @cd $(GIT_ROOT) && goreleaser release --snapshot --clean -f cmd/motr/.goreleaser.yml - -tidy: - @echo "Tidying Motor module..." - @go mod tidy - @echo "✅ Tidy complete" - -test: - @echo "Running Motor tests..." - @go test -v ./... - -verify: build - @echo "Verifying WASM module..." - @if [ -f "$(OUTPUT_PATH)" ]; then \ - file "$(OUTPUT_PATH)"; \ - echo "✅ WASM file exists"; \ - else \ - echo "❌ WASM file not found"; \ - exit 1; \ - fi - @if [ -f "$(JS_PATH)" ]; then \ - echo "✅ Runtime file exists"; \ - else \ - echo "⚠️ Runtime file not found"; \ - fi - @if command -v wasm-validate >/dev/null 2>&1; then \ - if wasm-validate "$(OUTPUT_PATH)"; then \ - echo "✅ WASM module is valid"; \ - else \ - echo "❌ WASM module validation failed"; \ - exit 1; \ - fi \ - else \ - echo "⚠️ wasm-validate not available, skipping validation"; \ - fi - @echo "✅ Verification complete" - @echo "" - @echo "The WASM module has been built in the ES package at:" - @echo " $(OUTPUT_PATH)" - @echo "" - @echo "The ES package will bundle and distribute this via jsDelivr" - -version: - @echo "Motor WASM Service Worker" - @echo "=========================" - @echo "Version: $(VERSION)" - @echo "Commit: $(COMMIT)" - @echo "Target OS: $(GOOS)" - @echo "Target Arch: $(GOARCH)" - @echo "Output: $(OUTPUT_PATH)" - -help: - @echo "Motor WASM Module Makefile" - @echo "==========================" - @echo "" - @echo "Motor provides WebAssembly-based DWN and Wallet operations" - @echo "for the @sonr.io/es package to distribute via jsDelivr." - @echo "" - @echo "Available targets:" - @echo " build - Build Motor WASM module (default)" - @echo " clean - Remove all build artifacts" - @echo " test - Run Motor tests" - @echo " tidy - Tidy Go module dependencies" - @echo " verify - Build and validate WASM module" - @echo " version - Display version information" - @echo " help - Show this help message" - @echo "" - @echo "Build components (called by build):" - @echo " runtime - Copy WASM runtime (wasm_exec.js)" - @echo "" - @echo "Output location:" - @echo " ES Package: $(ES_PACKAGE_DIR)/" - @echo " WASM File: $(OUTPUT_PATH)" - @echo "" - @echo "Integration:" - @echo " The WASM module is built directly into the ES package plugins" - @echo " directory for bundling and CDN distribution. The TypeScript" - @echo " client in @sonr.io/es/plugins/motor handles service worker management." - @echo "" - @echo "Examples:" - @echo " make build # Build WASM module into ES package" - @echo " make verify # Build and validate the module" - @echo " make clean # Remove artifacts" diff --git a/cmd/motr/README.md b/cmd/motr/README.md deleted file mode 100644 index 8e6f99f48..000000000 --- a/cmd/motr/README.md +++ /dev/null @@ -1,385 +0,0 @@ -# Motor WASM Service Worker - Payment Gateway & OIDC Authorization - -Motor is a WebAssembly-based HTTP server that runs as a Service Worker in the browser, providing secure payment processing and OpenID Connect (OIDC) authorization without requiring backend infrastructure. - -## Overview - -Motor implements a comprehensive payment gateway and identity provider that runs entirely in the browser: - -1. **Payment Gateway**: W3C Payment Handler API compliant payment processing with PCI DSS compliance -2. **OIDC Authorization**: Complete OpenID Connect provider with JWT token management -3. **Service Worker**: Runs as a browser service worker using go-wasm-http-server - -## Features - -### Payment Gateway (W3C Payment Handler API) -- ✅ Process payment transactions securely -- ✅ PCI DSS compliant card tokenization -- ✅ Card validation (Luhn algorithm, CVV, expiry) -- ✅ Transaction signing with HMAC-SHA256 -- ✅ AES-256-GCM encryption for sensitive data -- ✅ Payment method validation -- ✅ Refund processing -- ✅ Comprehensive audit logging - -### OIDC Authorization -- ✅ Discovery endpoint (`.well-known/openid-configuration`) -- ✅ Authorization endpoint with PKCE support -- ✅ Token endpoint with JWT generation -- ✅ UserInfo endpoint -- ✅ JWKS endpoint for key rotation -- ✅ RS256 JWT signing -- ✅ Refresh token support - -### Security Features -- ✅ Rate limiting (100 requests/minute per client) -- ✅ Origin validation -- ✅ Security headers (CSP, X-Frame-Options, etc.) -- ✅ CORS configuration -- ✅ Secure token generation -- ✅ Card number masking -- ✅ Sensitive data sanitization - -## API Endpoints - -### Payment Gateway Endpoints - -#### Process Payment -```http -POST /api/payment/process -Content-Type: application/json - -{ - "method": "card", - "amount": 100.00, - "currency": "USD", - "card_number": "4111111111111111", - "cvv": "123", - "expiry_month": 12, - "expiry_year": 2025, - "billing_address": { - "line1": "123 Main St", - "city": "San Francisco", - "state": "CA", - "postal_code": "94105", - "country": "US" - } -} -``` - -#### Validate Payment Method -```http -POST /api/payment/validate -Content-Type: application/json - -{ - "method": "card", - "card_number": "4111111111111111", - "cvv": "123", - "expiry_month": 12, - "expiry_year": 2025 -} -``` - -#### Get Payment Status -```http -GET /api/payment/status/:id -``` - -#### Process Refund -```http -POST /api/payment/refund -Content-Type: application/json - -{ - "payment_id": "pay_abc123", - "amount": 50.00, - "reason": "Customer request" -} -``` - -#### W3C Payment Handler API -```http -GET /payment/instruments -POST /payment/canmakepayment -POST /payment/paymentrequest -``` - -### OIDC Endpoints - -#### Discovery -```http -GET /.well-known/openid-configuration -``` - -#### Authorization -```http -GET /authorize?client_id=CLIENT_ID&redirect_uri=URI&response_type=code&scope=openid%20profile -``` - -#### Token Exchange -```http -POST /token -Content-Type: application/x-www-form-urlencoded - -grant_type=authorization_code&code=AUTH_CODE&client_id=CLIENT_ID -``` - -#### UserInfo -```http -GET /userinfo -Authorization: Bearer ACCESS_TOKEN -``` - -#### JWKS -```http -GET /.well-known/jwks.json -``` - -### Health & Monitoring - -```http -GET /health -GET /status -``` - -## Building - -### Using Make -```bash -# Build Motor WASM module -make motr-wasm - -# Or build directly -cd cmd/motr -GOOS=js GOARCH=wasm go build -o ../../packages/es/src/plugins/motor/motor.wasm . -``` - -### Build Output -The WASM module is built to: `packages/es/src/plugins/motor/motor.wasm` - -## Integration - -### Service Worker Registration - -```javascript -// motor-worker.js -importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.4/misc/wasm/wasm_exec.js'); -importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v2.2.1/sw.js'); - -// Register Motor WASM as HTTP listener -registerWasmHTTPListener('motor.wasm', { - base: '/api' -}); -``` - -### TypeScript Client Usage - -```typescript -import { PaymentGatewayClient, OIDCClient } from '@sonr.io/es/plugins/motor'; - -// Initialize clients -const payment = new PaymentGatewayClient('https://localhost:3000'); -const oidc = new OIDCClient('https://localhost:3000'); - -// Process a payment -const result = await payment.processPayment({ - method: 'card', - amount: 100.00, - currency: 'USD', - card_number: '4111111111111111', - cvv: '123', - expiry_month: 12, - expiry_year: 2025 -}); - -// OIDC authorization flow -const authUrl = await oidc.buildAuthorizationUrl({ - client_id: 'my-app', - redirect_uri: 'https://myapp.com/callback', - scope: 'openid profile email' -}); - -// Exchange authorization code for tokens -const tokens = await oidc.exchangeCode('auth_code_here', 'code_verifier'); -``` - -## Security Implementation - -### PCI DSS Compliance -- **Tokenization**: Cards are immediately tokenized, raw data never stored -- **Encryption**: AES-256-GCM for all sensitive data at rest -- **Masking**: Card numbers always masked except last 4 digits -- **Audit Logging**: Complete audit trail for compliance -- **CVV Handling**: CVV never stored, only validated - -### Transaction Security -- **Signing**: HMAC-SHA256 signatures on all transactions -- **Verification**: Signature verification before processing -- **Tamper Detection**: Any modification invalidates transaction -- **Idempotency**: Duplicate transaction prevention - -### Authentication Security -- **JWT Signing**: RS256 with 2048-bit RSA keys -- **PKCE**: Proof Key for Code Exchange for authorization flow -- **Token Expiration**: Configurable expiration (default 1 hour) -- **Refresh Tokens**: Secure refresh token rotation - -## Testing - -### Unit Tests -```bash -# Run unit tests (without WASM constraints) -go test ./cmd/motr/... -``` - -### Integration Tests -```bash -# Build WASM first -make motr-wasm - -# Run integration tests -cd cmd/motr -GOOS=js GOARCH=wasm go test -v -``` - -### Test Coverage -- ✅ Payment processing flows -- ✅ Card validation (Luhn, CVV, expiry) -- ✅ Tokenization and encryption -- ✅ Transaction signing/verification -- ✅ OIDC discovery and flows -- ✅ JWT generation/validation -- ✅ Rate limiting -- ✅ Security headers -- ✅ PCI compliance features - -## Performance - -### Bundle Size -- WASM module: ~3-4MB (production build) -- Service Worker: ~10KB -- TypeScript client: ~25KB (minified) - -### Optimization -- Built with `-ldflags="-s -w"` for size reduction -- Gzip compression reduces transfer to ~1MB -- Lazy loading recommended for optimal performance - -### Benchmarks -- Payment processing: <100ms average -- Token generation: <50ms -- Card validation: <10ms -- Encryption/decryption: <20ms - -## Browser Compatibility - -| Feature | Chrome | Firefox | Safari | Edge | -|---------|--------|---------|--------|------| -| Service Workers | 45+ | 44+ | 11.1+ | 17+ | -| WebAssembly | 57+ | 52+ | 11+ | 16+ | -| Payment Handler | 68+ | - | - | 79+ | -| Full Support | 68+ | 52+* | 11.1+* | 79+ | - -*Payment Handler API has limited support - -## Configuration - -### Environment Variables -```javascript -// Configure in service worker -const config = { - issuer: 'https://motor.sonr.io', - rateLimit: 100, // requests per minute - rateWindow: 60000, // milliseconds - tokenExpiry: 3600, // seconds - allowedOrigins: ['https://localhost:3000'] -}; -``` - -### Security Settings -- Rate limiting: Configurable per-client limits -- CORS: Configurable allowed origins -- CSP: Customizable content security policy -- Token expiry: Adjustable for different use cases - -## Development - -### Prerequisites -- Go 1.21+ (1.23+ recommended) -- Modern browser with Service Worker support -- HTTPS or localhost (Service Workers requirement) - -### Local Development -```bash -# Build WASM module -make motr-wasm - -# Start local server (example) -cd packages/es/src/plugins/motor -python3 -m http.server 8080 --bind localhost - -# Access at https://localhost:8080 -``` - -### Debugging -- Browser DevTools: Network tab for API inspection -- Service Worker: Application tab for SW debugging -- Console: WASM logs and errors -- Payment Handler: chrome://settings/content/paymentHandler - -## Production Deployment - -### Best Practices -1. **HTTPS Required**: Service Workers only work over HTTPS -2. **Cache Strategy**: Implement proper cache headers -3. **Error Handling**: Comprehensive error logging -4. **Monitoring**: Track payment success rates -5. **Compliance**: Regular PCI DSS audits - -### Deployment Checklist -- [ ] Configure production issuer URL -- [ ] Set appropriate rate limits -- [ ] Configure allowed origins -- [ ] Enable production encryption keys -- [ ] Set up monitoring and alerting -- [ ] Configure backup payment processors -- [ ] Implement fraud detection rules -- [ ] Schedule security audits - -## Troubleshooting - -### Common Issues - -#### Service Worker Not Registering -- Ensure HTTPS or localhost -- Check browser compatibility -- Verify WASM file path - -#### Payment Processing Errors -- Validate card details format -- Check rate limiting -- Verify origin is allowed - -#### OIDC Flow Issues -- Ensure redirect URI matches -- Check PKCE implementation -- Verify token expiration - -### Debug Mode -Enable debug logging in the service worker: -```javascript -// motor-worker.js -const DEBUG = true; -``` - -## License - -This implementation is part of the Sonr project and follows the same license terms. - -## Support - -For issues, questions, or contributions: -- GitHub Issues: https://github.com/sonr-io/sonr/issues -- Documentation: https://docs.sonr.io -- Security: security@sonr.io (for security vulnerabilities) \ No newline at end of file diff --git a/cmd/motr/go.mod b/cmd/motr/go.mod deleted file mode 100644 index ebddbc323..000000000 --- a/cmd/motr/go.mod +++ /dev/null @@ -1,10 +0,0 @@ -module motr - -go 1.24.7 - -require github.com/go-sonr/wasm-http-server/v3 v3.0.0 - -require ( - github.com/hack-pad/safejs v0.1.1 // indirect - github.com/nlepage/go-js-promise v1.0.0 // indirect -) diff --git a/cmd/motr/go.sum b/cmd/motr/go.sum deleted file mode 100644 index 366bd0e80..000000000 --- a/cmd/motr/go.sum +++ /dev/null @@ -1,6 +0,0 @@ -github.com/go-sonr/wasm-http-server/v3 v3.0.0 h1:DY/XaJD0jfKlvpVlOTqyU5b+SRVOulR5+zOye0LK0o0= -github.com/go-sonr/wasm-http-server/v3 v3.0.0/go.mod h1:97QCYR5OlAEWeKeeIKCMZqCOIHqJakyTIFu0sbwDSJ8= -github.com/hack-pad/safejs v0.1.1 h1:d5qPO0iQ7h2oVtpzGnLExE+Wn9AtytxIfltcS2b9KD8= -github.com/hack-pad/safejs v0.1.1/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio= -github.com/nlepage/go-js-promise v1.0.0 h1:K7OmJ3+0BgWJ2LfXchg2sI6RDr7AW/KWR8182epFwGQ= -github.com/nlepage/go-js-promise v1.0.0/go.mod h1:bdOP0wObXu34euibyK39K1hoBCtlgTKXGc56AGflaRo= diff --git a/cmd/motr/handlers.go b/cmd/motr/handlers.go deleted file mode 100644 index 30c99b90a..000000000 --- a/cmd/motr/handlers.go +++ /dev/null @@ -1,446 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "encoding/json" - "net/http" - "strings" - "time" -) - -// Health & Status Handlers - -// handleHealth returns service health status -func handleHealth(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - writeJSON(w, http.StatusOK, map[string]interface{}{ - "status": "healthy", - "service": "motor-gateway", - "timestamp": time.Now().Unix(), - }) -} - -// handleStatus returns detailed service status -func handleStatus(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - writeJSON(w, http.StatusOK, map[string]interface{}{ - "status": "operational", - "version": "1.0.0", - "services": map[string]string{ - "payment_gateway": "active", - "oidc_provider": "active", - }, - "uptime": time.Now().Unix(), - }) -} - -// W3C Payment Handler API Handlers - -// handlePaymentInstruments returns available payment instruments -func handlePaymentInstruments(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "GET" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - instruments := paymentHandler.GetInstruments() - writeJSON(w, http.StatusOK, map[string]interface{}{ - "instruments": instruments, - }) -} - -// handleCanMakePayment checks if payment can be made -func handleCanMakePayment(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - var req struct { - MethodData []PaymentMethod `json:"methodData"` - } - - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeError(w, http.StatusBadRequest, "Invalid request body") - return - } - - canMakePayment := paymentHandler.CanMakePayment(req.MethodData) - writeJSON(w, http.StatusOK, map[string]interface{}{ - "canMakePayment": canMakePayment, - }) -} - -// handlePaymentRequest handles W3C PaymentRequestEvent -func handlePaymentRequest(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Parse payment request event - var reqData json.RawMessage - if err := json.NewDecoder(r.Body).Decode(&reqData); err != nil { - writeError(w, http.StatusBadRequest, "Invalid request body") - return - } - - paymentReq, err := SerializePaymentRequest(reqData) - if err != nil { - writeError(w, http.StatusBadRequest, "Invalid payment request") - return - } - - // Process payment request - tx, err := paymentHandler.ProcessPayment(paymentReq) - if err != nil { - writeError(w, http.StatusInternalServerError, "Payment processing failed") - return - } - - // Return payment response - if tx.Response != nil { - writeJSON(w, http.StatusOK, tx.Response) - } else { - writeJSON(w, http.StatusAccepted, map[string]interface{}{ - "transactionId": tx.ID, - "status": tx.Status, - }) - } -} - -// Payment Gateway Handlers - -// handlePaymentProcess processes a payment transaction using W3C Payment Handler API -func handlePaymentProcess(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Parse payment request - var reqData json.RawMessage - if err := json.NewDecoder(r.Body).Decode(&reqData); err != nil { - writeError(w, http.StatusBadRequest, "Invalid request body") - return - } - - paymentReq, err := SerializePaymentRequest(reqData) - if err != nil { - writeError(w, http.StatusBadRequest, "Invalid payment request") - return - } - - // Process payment - tx, err := paymentHandler.ProcessPayment(paymentReq) - if err != nil { - writeError(w, http.StatusInternalServerError, "Payment processing failed") - return - } - - writeJSON(w, http.StatusOK, tx) -} - -// handlePaymentValidate validates a payment method -func handlePaymentValidate(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Parse validation request - var req struct { - Method string `json:"method"` - Data map[string]interface{} `json:"data"` - } - - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeError(w, http.StatusBadRequest, "Invalid request body") - return - } - - // Validate payment method - valid, err := paymentHandler.ValidatePaymentMethod(req.Method, req.Data) - if err != nil { - writeError(w, http.StatusInternalServerError, "Validation failed") - return - } - - writeJSON(w, http.StatusOK, map[string]interface{}{ - "valid": valid, - "method": req.Method, - "message": "Payment method validation complete", - }) -} - -// handlePaymentStatus returns payment transaction status -func handlePaymentStatus(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "GET" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Extract transaction ID from path - txID := strings.TrimPrefix(r.URL.Path, "/api/payment/status/") - if txID == "" { - writeError(w, http.StatusBadRequest, "Transaction ID required") - return - } - - // Get transaction from handler - tx, exists := paymentHandler.GetTransaction(txID) - if !exists { - writeError(w, http.StatusNotFound, "Transaction not found") - return - } - - writeJSON(w, http.StatusOK, tx) -} - -// handlePaymentRefund processes a refund -func handlePaymentRefund(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // TODO: Implement refund processing - writeJSON(w, http.StatusOK, map[string]interface{}{ - "refund_id": "ref_" + generateID(), - "status": "processing", - "message": "Refund initiated", - }) -} - -// OIDC Handlers - -// handleOIDCDiscovery returns OIDC discovery document -func handleOIDCDiscovery(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - discovery := oidcProvider.GetDiscovery() - writeJSON(w, http.StatusOK, discovery) -} - -// handleJWKS returns JSON Web Key Set -func handleJWKS(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - jwk := jwtManager.GetPublicKeyJWK() - writeJSON(w, http.StatusOK, map[string]interface{}{ - "keys": []map[string]interface{}{jwk}, - }) -} - -// handleAuthorize handles authorization requests -func handleAuthorize(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "GET" && r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Parse authorization request - clientID := r.FormValue("client_id") - redirectURI := r.FormValue("redirect_uri") - responseType := r.FormValue("response_type") - scope := r.FormValue("scope") - state := r.FormValue("state") - nonce := r.FormValue("nonce") - codeChallenge := r.FormValue("code_challenge") - codeChallengeMethod := r.FormValue("code_challenge_method") - - // Validate request - if clientID == "" || redirectURI == "" || responseType == "" { - writeError(w, http.StatusBadRequest, "Missing required parameters") - return - } - - // For demo, auto-approve with test user - userID := "test-user" - - // Generate authorization code - authCode, err := oidcProvider.GenerateAuthorizationCode( - clientID, redirectURI, scope, state, nonce, userID, - codeChallenge, codeChallengeMethod, - ) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - - // Return authorization code - writeJSON(w, http.StatusOK, map[string]interface{}{ - "code": authCode.Code, - "state": state, - "redirect_uri": redirectURI, - }) -} - -// handleToken handles token requests -func handleToken(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Parse token request - var req TokenRequest - req.GrantType = r.FormValue("grant_type") - req.Code = r.FormValue("code") - req.RedirectURI = r.FormValue("redirect_uri") - req.ClientID = r.FormValue("client_id") - req.ClientSecret = r.FormValue("client_secret") - req.RefreshToken = r.FormValue("refresh_token") - req.Scope = r.FormValue("scope") - req.CodeVerifier = r.FormValue("code_verifier") - - // Handle based on grant type - var resp *TokenResponse - var err error - - switch req.GrantType { - case "authorization_code": - resp, err = oidcProvider.ExchangeCode(&req) - case "refresh_token": - // TODO: Implement refresh token flow - writeError(w, http.StatusNotImplemented, "Refresh token not yet implemented") - return - default: - writeError(w, http.StatusBadRequest, "Unsupported grant type") - return - } - - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - - writeJSON(w, http.StatusOK, resp) -} - -// handleUserInfo returns user information -func handleUserInfo(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - handleCORS(w) - return - } - - if r.Method != "GET" && r.Method != "POST" { - writeError(w, http.StatusMethodNotAllowed, "Method not allowed") - return - } - - // Get bearer token from Authorization header - authHeader := r.Header.Get("Authorization") - if authHeader == "" { - writeError(w, http.StatusUnauthorized, "Missing authorization header") - return - } - - // Extract token - parts := strings.Split(authHeader, " ") - if len(parts) != 2 || parts[0] != "Bearer" { - writeError(w, http.StatusUnauthorized, "Invalid authorization header") - return - } - - accessToken := parts[1] - - // Get user info - userInfo, err := oidcProvider.GetUserInfo(accessToken) - if err != nil { - writeError(w, http.StatusUnauthorized, err.Error()) - return - } - - writeJSON(w, http.StatusOK, userInfo) -} - -// Helper Functions - -// handleCORS handles CORS preflight requests -func handleCORS(w http.ResponseWriter) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") - w.WriteHeader(http.StatusOK) -} - -// writeJSON writes JSON response -func writeJSON(w http.ResponseWriter, status int, data interface{}) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Access-Control-Allow-Origin", "*") - w.WriteHeader(status) - json.NewEncoder(w).Encode(data) -} - -// writeError writes error response -func writeError(w http.ResponseWriter, status int, message string) { - writeJSON(w, status, map[string]string{"error": message}) -} - -// generateID generates a simple ID -func generateID() string { - return time.Now().Format("20060102150405") -} diff --git a/cmd/motr/integration_test.go b/cmd/motr/integration_test.go deleted file mode 100644 index 0d4d6ffbf..000000000 --- a/cmd/motr/integration_test.go +++ /dev/null @@ -1,405 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - "time" -) - -// TestHealthEndpoint tests the health check endpoint -func TestHealthEndpoint(t *testing.T) { - req := httptest.NewRequest("GET", "/health", nil) - w := httptest.NewRecorder() - - handleHealth(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var response map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&response); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - if response["status"] != "healthy" { - t.Errorf("Expected status healthy, got %v", response["status"]) - } -} - -// TestPaymentInstruments tests getting payment instruments -func TestPaymentInstruments(t *testing.T) { - req := httptest.NewRequest("GET", "/payment/instruments", nil) - w := httptest.NewRecorder() - - handlePaymentInstruments(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var instruments []map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&instruments); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - if len(instruments) == 0 { - t.Error("Expected at least one payment instrument") - } -} - -// TestCanMakePayment tests payment capability check -func TestCanMakePayment(t *testing.T) { - payload := map[string]interface{}{ - "origin": "https://localhost:3000", - "methodData": []map[string]interface{}{ - { - "supportedMethods": "https://motor.sonr.io/pay", - }, - }, - } - - body, _ := json.Marshal(payload) - req := httptest.NewRequest("POST", "/payment/canmakepayment", bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - - handleCanMakePayment(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var response map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&response); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - if response["canMakePayment"] != true { - t.Errorf("Expected canMakePayment to be true") - } -} - -// TestProcessPayment tests payment processing with security -func TestProcessPayment(t *testing.T) { - // Initialize payment security - InitializePaymentSecurity() - - payload := map[string]interface{}{ - "origin": "https://localhost:3000", - "topOrigin": "https://localhost:3000", - "paymentRequestId": "test-request-123", - "methodData": []map[string]interface{}{ - { - "supportedMethods": "https://motor.sonr.io/pay", - }, - }, - "details": map[string]interface{}{ - "total": map[string]interface{}{ - "label": "Test Payment", - "amount": map[string]interface{}{ - "currency": "USD", - "value": "100.00", - }, - }, - }, - } - - body, _ := json.Marshal(payload) - req := httptest.NewRequest("POST", "/api/payment/process", bytes.NewBuffer(body)) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Origin", "https://localhost:3000") - w := httptest.NewRecorder() - - handleProcessPayment(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var response map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&response); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - if response["paymentId"] == "" { - t.Error("Expected payment ID in response") - } - - if response["status"] != "pending" { - t.Errorf("Expected status pending, got %v", response["status"]) - } -} - -// TestCardTokenization tests PCI-compliant card tokenization -func TestCardTokenization(t *testing.T) { - // Initialize payment security - InitializePaymentSecurity() - - // Test valid card - token, err := TokenizeCard("4111111111111111", "123", 12, 2025) - if err != nil { - t.Fatalf("Failed to tokenize valid card: %v", err) - } - - if token == "" { - t.Error("Expected token to be generated") - } - - // Test invalid card number - _, err = TokenizeCard("1234567890123456", "123", 12, 2025) - if err == nil { - t.Error("Expected error for invalid card number") - } - - // Test expired card - _, err = TokenizeCard("4111111111111111", "123", 1, 2020) - if err == nil { - t.Error("Expected error for expired card") - } -} - -// TestTransactionSigning tests transaction signature verification -func TestTransactionSigning(t *testing.T) { - // Initialize payment security - InitializePaymentSecurity() - - txData := map[string]interface{}{ - "id": "test-tx-123", - "amount": "100.00", - "currency": "USD", - "method": "card", - "timestamp": time.Now().Unix(), - } - - // Sign transaction - signature, err := SignTransaction(txData) - if err != nil { - t.Fatalf("Failed to sign transaction: %v", err) - } - - if signature == "" { - t.Error("Expected signature to be generated") - } - - // Verify signature - valid := VerifyTransactionSignature(txData, signature) - if !valid { - t.Error("Expected signature to be valid") - } - - // Test invalid signature - invalid := VerifyTransactionSignature(txData, "invalid-signature") - if invalid { - t.Error("Expected invalid signature to fail verification") - } -} - -// TestOIDCDiscovery tests OIDC discovery endpoint -func TestOIDCDiscovery(t *testing.T) { - req := httptest.NewRequest("GET", "/.well-known/openid-configuration", nil) - w := httptest.NewRecorder() - - handleOIDCDiscovery(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var config map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&config); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - // Check required OIDC fields - requiredFields := []string{ - "issuer", - "authorization_endpoint", - "token_endpoint", - "userinfo_endpoint", - "jwks_uri", - } - - for _, field := range requiredFields { - if _, exists := config[field]; !exists { - t.Errorf("Missing required OIDC field: %s", field) - } - } -} - -// TestJWKS tests JWKS endpoint -func TestJWKS(t *testing.T) { - req := httptest.NewRequest("GET", "/.well-known/jwks.json", nil) - w := httptest.NewRecorder() - - handleJWKS(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Expected status 200, got %d", w.Code) - } - - var jwks map[string]interface{} - if err := json.NewDecoder(w.Body).Decode(&jwks); err != nil { - t.Fatalf("Failed to decode response: %v", err) - } - - keys, ok := jwks["keys"].([]interface{}) - if !ok || len(keys) == 0 { - t.Error("Expected at least one key in JWKS") - } -} - -// TestRateLimiting tests rate limiting functionality -func TestRateLimiting(t *testing.T) { - // Initialize with low rate limit for testing - securityConfig.RateLimit = 5 - securityConfig.RateWindow = time.Second - rateLimiter = NewRateLimiter(5, time.Second) - - // Make requests up to the limit - for i := 0; i < 5; i++ { - req := httptest.NewRequest("GET", "/health", nil) - req.Header.Set("Origin", "test-client") - w := httptest.NewRecorder() - - SecurityMiddleware(handleHealth)(w, req) - - if w.Code != http.StatusOK { - t.Errorf("Request %d: Expected status 200, got %d", i+1, w.Code) - } - } - - // Next request should be rate limited - req := httptest.NewRequest("GET", "/health", nil) - req.Header.Set("Origin", "test-client") - w := httptest.NewRecorder() - - SecurityMiddleware(handleHealth)(w, req) - - if w.Code != http.StatusTooManyRequests { - t.Errorf("Expected rate limit (429), got %d", w.Code) - } - - // Wait for rate limit window to reset - time.Sleep(time.Second + 100*time.Millisecond) - - // Should work again - req = httptest.NewRequest("GET", "/health", nil) - req.Header.Set("Origin", "test-client") - w = httptest.NewRecorder() - - SecurityMiddleware(handleHealth)(w, req) - - if w.Code != http.StatusOK { - t.Errorf("After reset: Expected status 200, got %d", w.Code) - } -} - -// TestSecurityHeaders tests security headers are properly set -func TestSecurityHeaders(t *testing.T) { - req := httptest.NewRequest("GET", "/health", nil) - w := httptest.NewRecorder() - - SecurityMiddleware(handleHealth)(w, req) - - // Check security headers - headers := map[string]string{ - "X-Content-Type-Options": "nosniff", - "X-Frame-Options": "DENY", - "X-XSS-Protection": "1; mode=block", - "Referrer-Policy": "strict-origin-when-cross-origin", - } - - for header, expected := range headers { - actual := w.Header().Get(header) - if actual != expected { - t.Errorf("Header %s: expected %s, got %s", header, expected, actual) - } - } - - // Check CSP is present - csp := w.Header().Get("Content-Security-Policy") - if csp == "" { - t.Error("Expected Content-Security-Policy header") - } -} - -// TestPCICompliance tests PCI compliance audit logging -func TestPCICompliance(t *testing.T) { - // Initialize payment security - InitializePaymentSecurity() - - // Log some actions - pciCompliance.LogAction("TEST_ACTION", "user123", "resource456", "SUCCESS", "127.0.0.1") - - // Get audit log - logs := pciCompliance.GetAuditLog(10) - - if len(logs) == 0 { - t.Error("Expected audit log entries") - } - - // Check last entry - lastLog := logs[len(logs)-1] - if lastLog.Action != "TEST_ACTION" { - t.Errorf("Expected action TEST_ACTION, got %s", lastLog.Action) - } - - if lastLog.UserID != "user123" { - t.Errorf("Expected user ID user123, got %s", lastLog.UserID) - } -} - -// TestDataEncryption tests sensitive data encryption -func TestDataEncryption(t *testing.T) { - // Initialize payment security - InitializePaymentSecurity() - - sensitiveData := "4111-1111-1111-1111" - - // Encrypt data - encrypted, err := EncryptSensitiveData(sensitiveData) - if err != nil { - t.Fatalf("Failed to encrypt data: %v", err) - } - - if encrypted == sensitiveData { - t.Error("Encrypted data should not match plaintext") - } - - // Decrypt data - decrypted, err := DecryptSensitiveData(encrypted) - if err != nil { - t.Fatalf("Failed to decrypt data: %v", err) - } - - if decrypted != sensitiveData { - t.Errorf("Decrypted data doesn't match original: got %s, want %s", decrypted, sensitiveData) - } -} - -// TestCardMasking tests card number masking -func TestCardMasking(t *testing.T) { - testCases := []struct { - input string - expected string - }{ - {"4111111111111111", "**** **** **** 1111"}, - {"5500000000000004", "**** **** **** 0004"}, - {"340000000000009", "********** 00009"}, - {"123", "123"}, // Too short to mask - } - - for _, tc := range testCases { - masked := MaskCardNumber(tc.input) - if masked != tc.expected { - t.Errorf("MaskCardNumber(%s): got %s, want %s", tc.input, masked, tc.expected) - } - } -} diff --git a/cmd/motr/jwt.go b/cmd/motr/jwt.go deleted file mode 100644 index bda2c13d7..000000000 --- a/cmd/motr/jwt.go +++ /dev/null @@ -1,273 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "strings" - "time" -) - -// JWTManager handles JWT token operations -type JWTManager struct { - privateKey *rsa.PrivateKey - publicKey *rsa.PublicKey - kid string - issuer string -} - -// JWTHeader represents JWT header -type JWTHeader struct { - Alg string `json:"alg"` - Typ string `json:"typ"` - Kid string `json:"kid,omitempty"` -} - -// JWTClaims represents standard JWT claims -type JWTClaims struct { - Issuer string `json:"iss,omitempty"` - Subject string `json:"sub,omitempty"` - Audience interface{} `json:"aud,omitempty"` // Can be string or []string - Expiration int64 `json:"exp,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - JWTID string `json:"jti,omitempty"` - Nonce string `json:"nonce,omitempty"` - Extra map[string]interface{} `json:"-"` -} - -// IDToken represents an OpenID Connect ID token -type IDToken struct { - JWTClaims - AuthTime int64 `json:"auth_time,omitempty"` - Nonce string `json:"nonce,omitempty"` - ACR string `json:"acr,omitempty"` - AMR []string `json:"amr,omitempty"` - AZP string `json:"azp,omitempty"` - Name string `json:"name,omitempty"` - GivenName string `json:"given_name,omitempty"` - FamilyName string `json:"family_name,omitempty"` - Email string `json:"email,omitempty"` - EmailVerified bool `json:"email_verified,omitempty"` -} - -// Global JWT manager instance -var jwtManager *JWTManager - -// InitJWTManager initializes the JWT manager -func InitJWTManager() error { - // Generate RSA key pair - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return fmt.Errorf("failed to generate RSA key: %w", err) - } - - jwtManager = &JWTManager{ - privateKey: privateKey, - publicKey: &privateKey.PublicKey, - kid: "motor-key-1", - issuer: "https://motor.sonr.io", - } - - return nil -} - -// GenerateToken generates a JWT token -func (m *JWTManager) GenerateToken(claims JWTClaims) (string, error) { - // Set standard claims - if claims.Issuer == "" { - claims.Issuer = m.issuer - } - if claims.IssuedAt == 0 { - claims.IssuedAt = time.Now().Unix() - } - if claims.Expiration == 0 { - claims.Expiration = time.Now().Add(1 * time.Hour).Unix() - } - - // Create header - header := JWTHeader{ - Alg: "RS256", - Typ: "JWT", - Kid: m.kid, - } - - // Encode header - headerJSON, _ := json.Marshal(header) - headerEncoded := base64.RawURLEncoding.EncodeToString(headerJSON) - - // Encode claims - claimsJSON, _ := json.Marshal(claims) - claimsEncoded := base64.RawURLEncoding.EncodeToString(claimsJSON) - - // Create signature - message := headerEncoded + "." + claimsEncoded - hash := sha256.Sum256([]byte(message)) - signature, err := rsa.SignPKCS1v15(rand.Reader, m.privateKey, crypto.SHA256, hash[:]) - if err != nil { - return "", err - } - signatureEncoded := base64.RawURLEncoding.EncodeToString(signature) - - // Combine parts - token := message + "." + signatureEncoded - return token, nil -} - -// GenerateIDToken generates an OpenID Connect ID token -func (m *JWTManager) GenerateIDToken(subject, audience, nonce string, extra map[string]interface{}) (string, error) { - idToken := IDToken{ - JWTClaims: JWTClaims{ - Issuer: m.issuer, - Subject: subject, - Audience: audience, - IssuedAt: time.Now().Unix(), - Expiration: time.Now().Add(1 * time.Hour).Unix(), - Nonce: nonce, - }, - AuthTime: time.Now().Unix(), - Email: fmt.Sprintf("%s@motor.sonr.io", subject), - EmailVerified: true, - } - - // Convert to claims - claims := JWTClaims{ - Issuer: idToken.Issuer, - Subject: idToken.Subject, - Audience: idToken.Audience, - IssuedAt: idToken.IssuedAt, - Expiration: idToken.Expiration, - Nonce: idToken.Nonce, - Extra: map[string]interface{}{ - "auth_time": idToken.AuthTime, - "email": idToken.Email, - "email_verified": idToken.EmailVerified, - }, - } - - // Add extra claims - for k, v := range extra { - claims.Extra[k] = v - } - - return m.GenerateToken(claims) -} - -// ValidateToken validates a JWT token -func (m *JWTManager) ValidateToken(tokenString string) (*JWTClaims, error) { - // Split token - parts := strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, fmt.Errorf("invalid token format") - } - - // Decode header - headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0]) - if err != nil { - return nil, fmt.Errorf("failed to decode header: %w", err) - } - - var header JWTHeader - if err := json.Unmarshal(headerJSON, &header); err != nil { - return nil, fmt.Errorf("failed to parse header: %w", err) - } - - // Verify algorithm - if header.Alg != "RS256" { - return nil, fmt.Errorf("unsupported algorithm: %s", header.Alg) - } - - // Decode claims - claimsJSON, err := base64.RawURLEncoding.DecodeString(parts[1]) - if err != nil { - return nil, fmt.Errorf("failed to decode claims: %w", err) - } - - var claims JWTClaims - if err := json.Unmarshal(claimsJSON, &claims); err != nil { - return nil, fmt.Errorf("failed to parse claims: %w", err) - } - - // Verify signature - message := parts[0] + "." + parts[1] - signature, err := base64.RawURLEncoding.DecodeString(parts[2]) - if err != nil { - return nil, fmt.Errorf("failed to decode signature: %w", err) - } - - hash := sha256.Sum256([]byte(message)) - if err := rsa.VerifyPKCS1v15(m.publicKey, crypto.SHA256, hash[:], signature); err != nil { - return nil, fmt.Errorf("invalid signature: %w", err) - } - - // Verify expiration - if claims.Expiration > 0 && time.Now().Unix() > claims.Expiration { - return nil, fmt.Errorf("token expired") - } - - // Verify not before - if claims.NotBefore > 0 && time.Now().Unix() < claims.NotBefore { - return nil, fmt.Errorf("token not yet valid") - } - - return &claims, nil -} - -// GetPublicKeyJWK returns the public key in JWK format -func (m *JWTManager) GetPublicKeyJWK() map[string]interface{} { - // Get modulus and exponent - n := base64.RawURLEncoding.EncodeToString(m.publicKey.N.Bytes()) - e := base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}) // 65537 - - return map[string]interface{}{ - "kty": "RSA", - "use": "sig", - "kid": m.kid, - "alg": "RS256", - "n": n, - "e": e, - } -} - -// GetPublicKeyPEM returns the public key in PEM format -func (m *JWTManager) GetPublicKeyPEM() string { - pubKeyBytes, _ := x509.MarshalPKIXPublicKey(m.publicKey) - pubKeyPEM := pem.EncodeToMemory(&pem.Block{ - Type: "PUBLIC KEY", - Bytes: pubKeyBytes, - }) - return string(pubKeyPEM) -} - -// GenerateAccessToken generates an access token -func (m *JWTManager) GenerateAccessToken(subject, scope string) (string, error) { - claims := JWTClaims{ - Subject: subject, - Extra: map[string]interface{}{ - "scope": scope, - "token_type": "Bearer", - }, - } - return m.GenerateToken(claims) -} - -// GenerateRefreshToken generates a refresh token -func (m *JWTManager) GenerateRefreshToken(subject string) (string, error) { - claims := JWTClaims{ - Subject: subject, - Expiration: time.Now().Add(30 * 24 * time.Hour).Unix(), // 30 days - Extra: map[string]interface{}{ - "token_type": "refresh", - }, - } - return m.GenerateToken(claims) -} diff --git a/cmd/motr/main.go b/cmd/motr/main.go deleted file mode 100644 index 4ed616d23..000000000 --- a/cmd/motr/main.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "log" - "net/http" - - wasmhttp "github.com/go-sonr/wasm-http-server/v3" -) - -func main() { - // Set up HTTP routes - setupRoutes() - - // Start the WASM HTTP server - log.Println("Motor Payment Gateway & OIDC Server starting...") - log.Println("Available endpoints:") - log.Println(" Health: /health, /status") - log.Println(" Payment API: /api/payment/*") - log.Println(" OIDC: /.well-known/*, /authorize, /token, /userinfo") - - wasmhttp.Serve(nil) -} - -// setupRoutes configures all HTTP routes with security middleware -func setupRoutes() { - // Health and status endpoints (no rate limiting) - http.HandleFunc("/health", handleHealth) - http.HandleFunc("/status", handleStatus) - - // W3C Payment Handler API endpoints with security - http.HandleFunc("/payment/instruments", SecurityMiddleware(handlePaymentInstruments)) - http.HandleFunc("/payment/canmakepayment", SecurityMiddleware(handleCanMakePayment)) - http.HandleFunc("/payment/paymentrequest", SecurityMiddleware(handlePaymentRequest)) - - // Payment Gateway endpoints with security - http.HandleFunc("/api/payment/process", SecurityMiddleware(handlePaymentProcess)) - http.HandleFunc("/api/payment/validate", SecurityMiddleware(handlePaymentValidate)) - http.HandleFunc("/api/payment/status/", SecurityMiddleware(handlePaymentStatus)) - http.HandleFunc("/api/payment/refund", SecurityMiddleware(handlePaymentRefund)) - - // OIDC endpoints with security - http.HandleFunc("/.well-known/openid-configuration", handleOIDCDiscovery) // No rate limit for discovery - http.HandleFunc("/.well-known/jwks.json", handleJWKS) // No rate limit for JWKS - http.HandleFunc("/authorize", SecurityMiddleware(handleAuthorize)) - http.HandleFunc("/token", SecurityMiddleware(handleToken)) - http.HandleFunc("/userinfo", SecurityMiddleware(handleUserInfo)) -} diff --git a/cmd/motr/oidc.go b/cmd/motr/oidc.go deleted file mode 100644 index f4839f0e9..000000000 --- a/cmd/motr/oidc.go +++ /dev/null @@ -1,364 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "crypto/rand" - "encoding/base64" - "fmt" - "strings" - "sync" - "time" -) - -// OIDCProvider manages OpenID Connect operations -type OIDCProvider struct { - mu sync.RWMutex - issuer string - authCodes map[string]*AuthorizationCode - accessTokens map[string]*AccessToken - refreshTokens map[string]*RefreshToken - clients map[string]*OIDCClient - users map[string]*User -} - -// AuthorizationCode represents an authorization code -type AuthorizationCode struct { - Code string - ClientID string - RedirectURI string - Scope string - State string - Nonce string - UserID string - ExpiresAt time.Time - CodeChallenge string - CodeChallengeMethod string -} - -// AccessToken represents an access token -type AccessToken struct { - Token string - ClientID string - UserID string - Scope string - ExpiresAt time.Time -} - -// RefreshToken represents a refresh token -type RefreshToken struct { - Token string - ClientID string - UserID string - Scope string - ExpiresAt time.Time -} - -// OIDCClient represents an OIDC client application -type OIDCClient struct { - ClientID string - ClientSecret string - RedirectURIs []string - GrantTypes []string - ResponseTypes []string - Scopes []string - Name string -} - -// User represents a user -type User struct { - ID string - Username string - Email string - EmailVerified bool - Name string - GivenName string - FamilyName string -} - -// OIDCDiscovery represents OIDC discovery document -type OIDCDiscovery struct { - Issuer string `json:"issuer"` - AuthorizationEndpoint string `json:"authorization_endpoint"` - TokenEndpoint string `json:"token_endpoint"` - UserInfoEndpoint string `json:"userinfo_endpoint"` - JWKSUri string `json:"jwks_uri"` - RegistrationEndpoint string `json:"registration_endpoint,omitempty"` - ScopesSupported []string `json:"scopes_supported"` - ResponseTypesSupported []string `json:"response_types_supported"` - ResponseModesSupported []string `json:"response_modes_supported,omitempty"` - GrantTypesSupported []string `json:"grant_types_supported"` - ACRValuesSupported []string `json:"acr_values_supported,omitempty"` - SubjectTypesSupported []string `json:"subject_types_supported"` - IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"` - TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"` - ClaimsSupported []string `json:"claims_supported"` - CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"` -} - -// TokenRequest represents a token request -type TokenRequest struct { - GrantType string `json:"grant_type"` - Code string `json:"code,omitempty"` - RedirectURI string `json:"redirect_uri,omitempty"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` - Scope string `json:"scope,omitempty"` - CodeVerifier string `json:"code_verifier,omitempty"` -} - -// TokenResponse represents a token response -type TokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - RefreshToken string `json:"refresh_token,omitempty"` - IDToken string `json:"id_token,omitempty"` - Scope string `json:"scope,omitempty"` -} - -// Global OIDC provider instance -var oidcProvider = &OIDCProvider{ - issuer: "https://motor.sonr.io", - authCodes: make(map[string]*AuthorizationCode), - accessTokens: make(map[string]*AccessToken), - refreshTokens: make(map[string]*RefreshToken), - clients: make(map[string]*OIDCClient), - users: make(map[string]*User), -} - -// Initialize OIDC provider -func init() { - // Initialize JWT manager - InitJWTManager() - - // Add default client for testing - oidcProvider.clients["motor-client"] = &OIDCClient{ - ClientID: "motor-client", - ClientSecret: "motor-secret", - RedirectURIs: []string{"https://localhost:3000/callback", "http://localhost:3000/callback"}, - GrantTypes: []string{"authorization_code", "refresh_token"}, - ResponseTypes: []string{"code", "token", "id_token"}, - Scopes: []string{"openid", "profile", "email"}, - Name: "Motor Test Client", - } - - // Add default user for testing - oidcProvider.users["test-user"] = &User{ - ID: "test-user", - Username: "testuser", - Email: "test@motor.sonr.io", - EmailVerified: true, - Name: "Test User", - GivenName: "Test", - FamilyName: "User", - } -} - -// GetDiscovery returns OIDC discovery document -func (p *OIDCProvider) GetDiscovery() *OIDCDiscovery { - return &OIDCDiscovery{ - Issuer: p.issuer, - AuthorizationEndpoint: "/authorize", - TokenEndpoint: "/token", - UserInfoEndpoint: "/userinfo", - JWKSUri: "/.well-known/jwks.json", - ScopesSupported: []string{ - "openid", "profile", "email", "offline_access", - }, - ResponseTypesSupported: []string{ - "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", - }, - GrantTypesSupported: []string{ - "authorization_code", "implicit", "refresh_token", - }, - SubjectTypesSupported: []string{"public"}, - IDTokenSigningAlgValuesSupported: []string{"RS256"}, - TokenEndpointAuthMethodsSupported: []string{ - "client_secret_basic", "client_secret_post", - }, - ClaimsSupported: []string{ - "sub", "name", "given_name", "family_name", "email", "email_verified", - }, - CodeChallengeMethodsSupported: []string{"plain", "S256"}, - } -} - -// GenerateAuthorizationCode generates an authorization code -func (p *OIDCProvider) GenerateAuthorizationCode(clientID, redirectURI, scope, state, nonce, userID string, codeChallenge, codeChallengeMethod string) (*AuthorizationCode, error) { - p.mu.Lock() - defer p.mu.Unlock() - - // Validate client - client, exists := p.clients[clientID] - if !exists { - return nil, fmt.Errorf("invalid client_id") - } - - // Validate redirect URI - validRedirect := false - for _, uri := range client.RedirectURIs { - if uri == redirectURI { - validRedirect = true - break - } - } - if !validRedirect { - return nil, fmt.Errorf("invalid redirect_uri") - } - - // Generate code - code := generateRandomString(32) - - authCode := &AuthorizationCode{ - Code: code, - ClientID: clientID, - RedirectURI: redirectURI, - Scope: scope, - State: state, - Nonce: nonce, - UserID: userID, - ExpiresAt: time.Now().Add(10 * time.Minute), - CodeChallenge: codeChallenge, - CodeChallengeMethod: codeChallengeMethod, - } - - p.authCodes[code] = authCode - - return authCode, nil -} - -// ExchangeCode exchanges authorization code for tokens -func (p *OIDCProvider) ExchangeCode(req *TokenRequest) (*TokenResponse, error) { - p.mu.Lock() - defer p.mu.Unlock() - - // Get authorization code - authCode, exists := p.authCodes[req.Code] - if !exists { - return nil, fmt.Errorf("invalid authorization code") - } - - // Validate code hasn't expired - if time.Now().After(authCode.ExpiresAt) { - delete(p.authCodes, req.Code) - return nil, fmt.Errorf("authorization code expired") - } - - // Validate client - if authCode.ClientID != req.ClientID { - return nil, fmt.Errorf("client_id mismatch") - } - - // Validate redirect URI - if authCode.RedirectURI != req.RedirectURI { - return nil, fmt.Errorf("redirect_uri mismatch") - } - - // Validate PKCE if present - if authCode.CodeChallenge != "" { - if !validatePKCE(authCode.CodeChallenge, authCode.CodeChallengeMethod, req.CodeVerifier) { - return nil, fmt.Errorf("invalid code_verifier") - } - } - - // Delete used code - delete(p.authCodes, req.Code) - - // Generate tokens - accessToken, _ := jwtManager.GenerateAccessToken(authCode.UserID, authCode.Scope) - refreshToken, _ := jwtManager.GenerateRefreshToken(authCode.UserID) - idToken, _ := jwtManager.GenerateIDToken(authCode.UserID, authCode.ClientID, authCode.Nonce, nil) - - // Store tokens - p.accessTokens[accessToken] = &AccessToken{ - Token: accessToken, - ClientID: authCode.ClientID, - UserID: authCode.UserID, - Scope: authCode.Scope, - ExpiresAt: time.Now().Add(1 * time.Hour), - } - - p.refreshTokens[refreshToken] = &RefreshToken{ - Token: refreshToken, - ClientID: authCode.ClientID, - UserID: authCode.UserID, - Scope: authCode.Scope, - ExpiresAt: time.Now().Add(30 * 24 * time.Hour), - } - - return &TokenResponse{ - AccessToken: accessToken, - TokenType: "Bearer", - ExpiresIn: 3600, - RefreshToken: refreshToken, - IDToken: idToken, - Scope: authCode.Scope, - }, nil -} - -// GetUserInfo returns user information -func (p *OIDCProvider) GetUserInfo(accessToken string) (map[string]interface{}, error) { - p.mu.RLock() - defer p.mu.RUnlock() - - // Validate access token - token, exists := p.accessTokens[accessToken] - if !exists { - return nil, fmt.Errorf("invalid access token") - } - - // Check expiration - if time.Now().After(token.ExpiresAt) { - return nil, fmt.Errorf("access token expired") - } - - // Get user - user, exists := p.users[token.UserID] - if !exists { - return nil, fmt.Errorf("user not found") - } - - // Return user info based on scope - userInfo := map[string]interface{}{ - "sub": user.ID, - } - - // Add claims based on scope - scopes := strings.Split(token.Scope, " ") - for _, scope := range scopes { - switch scope { - case "profile": - userInfo["name"] = user.Name - userInfo["given_name"] = user.GivenName - userInfo["family_name"] = user.FamilyName - userInfo["preferred_username"] = user.Username - case "email": - userInfo["email"] = user.Email - userInfo["email_verified"] = user.EmailVerified - } - } - - return userInfo, nil -} - -// Helper functions - -// generateRandomString generates a random string -func generateRandomString(length int) string { - bytes := make([]byte, length) - rand.Read(bytes) - return base64.RawURLEncoding.EncodeToString(bytes)[:length] -} - -// validatePKCE validates PKCE code challenge -func validatePKCE(codeChallenge, method, verifier string) bool { - if method == "plain" { - return codeChallenge == verifier - } - // For S256, would need to implement SHA256 hashing - // For simplicity, returning true for now - return true -} diff --git a/cmd/motr/payment.go b/cmd/motr/payment.go deleted file mode 100644 index 14a90370a..000000000 --- a/cmd/motr/payment.go +++ /dev/null @@ -1,354 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "crypto/rand" - "encoding/hex" - "encoding/json" - "fmt" - "sync" - "time" -) - -// PaymentMethod represents a payment method according to W3C Payment Handler API -type PaymentMethod struct { - SupportedMethods string `json:"supportedMethods"` - Data interface{} `json:"data,omitempty"` -} - -// PaymentDetails contains payment details -type PaymentDetails struct { - Total PaymentItem `json:"total"` - DisplayItems []PaymentItem `json:"displayItems,omitempty"` - Modifiers []interface{} `json:"modifiers,omitempty"` - ShippingOptions []interface{} `json:"shippingOptions,omitempty"` -} - -// PaymentItem represents an item in payment -type PaymentItem struct { - Label string `json:"label"` - Amount PaymentCurrency `json:"amount"` -} - -// PaymentCurrency represents currency amount -type PaymentCurrency struct { - Currency string `json:"currency"` - Value string `json:"value"` -} - -// PaymentRequest represents a W3C Payment Request -type PaymentRequest struct { - ID string `json:"id"` - MethodData []PaymentMethod `json:"methodData"` - Details PaymentDetails `json:"details"` - Options PaymentOptions `json:"options,omitempty"` - Origin string `json:"origin"` - TopOrigin string `json:"topOrigin"` - PaymentRequestID string `json:"paymentRequestId"` - Total PaymentItem `json:"total"` -} - -// PaymentOptions contains payment options -type PaymentOptions struct { - RequestPayerName bool `json:"requestPayerName,omitempty"` - RequestPayerEmail bool `json:"requestPayerEmail,omitempty"` - RequestPayerPhone bool `json:"requestPayerPhone,omitempty"` - RequestShipping bool `json:"requestShipping,omitempty"` - ShippingType string `json:"shippingType,omitempty"` -} - -// PaymentResponse represents response to payment request -type PaymentResponse struct { - RequestID string `json:"requestId"` - MethodName string `json:"methodName"` - Details map[string]interface{} `json:"details"` - PayerName string `json:"payerName,omitempty"` - PayerEmail string `json:"payerEmail,omitempty"` - PayerPhone string `json:"payerPhone,omitempty"` - ShippingAddress interface{} `json:"shippingAddress,omitempty"` -} - -// PaymentTransaction represents a payment transaction -type PaymentTransaction struct { - ID string `json:"id"` - Status string `json:"status"` - Amount PaymentCurrency `json:"amount"` - Method string `json:"method"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - Request *PaymentRequest `json:"request,omitempty"` - Response *PaymentResponse `json:"response,omitempty"` - Metadata map[string]interface{} `json:"metadata,omitempty"` -} - -// PaymentHandler manages payment processing -type PaymentHandler struct { - mu sync.RWMutex - transactions map[string]*PaymentTransaction - instruments []PaymentInstrument -} - -// PaymentInstrument represents a payment instrument -type PaymentInstrument struct { - Name string `json:"name"` - Icons []Icon `json:"icons,omitempty"` - Method string `json:"method"` - Capabilities []string `json:"capabilities,omitempty"` -} - -// Icon represents a payment instrument icon -type Icon struct { - Src string `json:"src"` - Sizes string `json:"sizes,omitempty"` - Type string `json:"type,omitempty"` -} - -// Global payment handler instance -var paymentHandler = &PaymentHandler{ - transactions: make(map[string]*PaymentTransaction), - instruments: []PaymentInstrument{ - { - Name: "Motor Payment", - Method: "https://motor.sonr.io/pay", - Capabilities: []string{"basic-card", "tokenized-card"}, - }, - }, -} - -// ProcessPayment processes a payment request with enhanced security -func (h *PaymentHandler) ProcessPayment(req *PaymentRequest) (*PaymentTransaction, error) { - h.mu.Lock() - defer h.mu.Unlock() - - // Initialize payment security if not already done - InitializePaymentSecurity() - - // Validate origin for security - if !ValidateOrigin(req.Origin) { - return nil, fmt.Errorf("invalid origin: %s", req.Origin) - } - - // Generate transaction ID - txID := generateTransactionID() - - // Create transaction data for signing - txData := map[string]interface{}{ - "id": txID, - "amount": req.Details.Total.Amount.Value, - "currency": req.Details.Total.Amount.Currency, - "method": req.MethodData[0].SupportedMethods, - "timestamp": time.Now().Unix(), - } - - // Sign transaction for integrity - signature, err := SignTransaction(txData) - if err != nil { - return nil, fmt.Errorf("failed to sign transaction: %v", err) - } - - // Create transaction - tx := &PaymentTransaction{ - ID: txID, - Status: "pending", - Amount: req.Details.Total.Amount, - Method: req.MethodData[0].SupportedMethods, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - Request: req, - Metadata: map[string]interface{}{ - "origin": req.Origin, - "topOrigin": req.TopOrigin, - "signature": signature, - }, - } - - // Log for PCI compliance - pciCompliance.LogAction("PROCESS_PAYMENT", "", txID, "INITIATED", req.Origin) - - // Store transaction - h.transactions[txID] = tx - - // Process payment asynchronously with security checks - go h.processPaymentSecurely(txID) - - return tx, nil -} - -// ValidatePaymentMethod validates a payment method -func (h *PaymentHandler) ValidatePaymentMethod(method string, data interface{}) (bool, error) { - // Check if method is supported - for _, instrument := range h.instruments { - if instrument.Method == method { - // Perform validation based on method type - switch method { - case "basic-card", "https://motor.sonr.io/pay": - return h.validateCardData(data) - default: - return true, nil - } - } - } - return false, nil -} - -// GetTransaction retrieves a transaction by ID -func (h *PaymentHandler) GetTransaction(id string) (*PaymentTransaction, bool) { - h.mu.RLock() - defer h.mu.RUnlock() - - tx, exists := h.transactions[id] - return tx, exists -} - -// UpdateTransactionStatus updates transaction status -func (h *PaymentHandler) UpdateTransactionStatus(id, status string) error { - h.mu.Lock() - defer h.mu.Unlock() - - if tx, exists := h.transactions[id]; exists { - tx.Status = status - tx.UpdatedAt = time.Now() - return nil - } - return nil -} - -// CanMakePayment checks if payment can be made -func (h *PaymentHandler) CanMakePayment(methods []PaymentMethod) bool { - for _, method := range methods { - for _, instrument := range h.instruments { - if instrument.Method == method.SupportedMethods { - return true - } - } - } - return false -} - -// GetInstruments returns available payment instruments -func (h *PaymentHandler) GetInstruments() []PaymentInstrument { - return h.instruments -} - -// Helper functions - -// generateTransactionID generates a unique transaction ID -func generateTransactionID() string { - bytes := make([]byte, 16) - rand.Read(bytes) - return "txn_" + hex.EncodeToString(bytes) -} - -// validateCardData validates and tokenizes card payment data -func (h *PaymentHandler) validateCardData(data interface{}) (bool, error) { - // Initialize payment security - InitializePaymentSecurity() - - if data == nil { - return false, fmt.Errorf("no payment data provided") - } - - // Parse card data - cardData, ok := data.(map[string]interface{}) - if !ok { - return false, fmt.Errorf("invalid payment data format") - } - - // Extract card details - cardNumber, hasNumber := cardData["cardNumber"].(string) - cvv, hasCVV := cardData["cvv"].(string) - expiryMonth, hasMonth := cardData["expiryMonth"].(float64) - expiryYear, hasYear := cardData["expiryYear"].(float64) - - if !hasNumber || !hasCVV || !hasMonth || !hasYear { - return false, fmt.Errorf("missing required card fields") - } - - // Tokenize the card for PCI compliance - token, err := TokenizeCard(cardNumber, cvv, int(expiryMonth), int(expiryYear)) - if err != nil { - return false, fmt.Errorf("card validation failed: %v", err) - } - - // Replace sensitive data with token - cardData["token"] = token - cardData["cardNumber"] = MaskCardNumber(cardNumber) - delete(cardData, "cvv") // Never store CVV - - return true, nil -} - -// processPaymentSecurely processes payment with enhanced security -func (h *PaymentHandler) processPaymentSecurely(txID string) { - // Initialize payment security - InitializePaymentSecurity() - - // Simulate processing delay - time.Sleep(2 * time.Second) - - // Verify transaction exists - h.mu.RLock() - tx, exists := h.transactions[txID] - h.mu.RUnlock() - - if !exists { - pciCompliance.LogAction("PROCESS_PAYMENT", "", txID, "FAILED", "Transaction not found") - return - } - - // Verify transaction signature - txData := map[string]interface{}{ - "id": txID, - "amount": tx.Amount.Value, - "currency": tx.Amount.Currency, - "method": tx.Method, - "timestamp": tx.CreatedAt.Unix(), - } - - if signature, ok := tx.Metadata["signature"].(string); ok { - if !VerifyTransactionSignature(txData, signature) { - h.UpdateTransactionStatus(txID, "failed") - pciCompliance.LogAction("PROCESS_PAYMENT", "", txID, "FAILED", "Invalid signature") - return - } - } - - // Update status to completed - h.UpdateTransactionStatus(txID, "completed") - - // Create secure payment response - h.mu.Lock() - if tx, exists := h.transactions[txID]; exists { - // Generate response token - responseToken := generateSecureToken() - - tx.Response = &PaymentResponse{ - RequestID: tx.Request.PaymentRequestID, - MethodName: tx.Method, - Details: map[string]interface{}{ - "transactionId": txID, - "status": "success", - "token": responseToken, - "timestamp": time.Now().Unix(), - }, - } - - // Log successful payment - pciCompliance.LogAction("PROCESS_PAYMENT", "", txID, "SUCCESS", tx.Request.Origin) - } - h.mu.Unlock() -} - -// SerializePaymentRequest serializes a payment request from JSON -func SerializePaymentRequest(data []byte) (*PaymentRequest, error) { - var req PaymentRequest - err := json.Unmarshal(data, &req) - return &req, err -} - -// SerializePaymentResponse serializes a payment response to JSON -func SerializePaymentResponse(resp *PaymentResponse) ([]byte, error) { - return json.Marshal(resp) -} diff --git a/cmd/motr/payment_security.go b/cmd/motr/payment_security.go deleted file mode 100644 index 910ab767e..000000000 --- a/cmd/motr/payment_security.go +++ /dev/null @@ -1,454 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "regexp" - "strings" - "sync" - "time" -) - -// PaymentTokenizer handles secure payment method tokenization -type PaymentTokenizer struct { - mu sync.RWMutex - tokens map[string]*TokenData - encryptKey []byte -} - -// TokenData stores tokenized payment data -type TokenData struct { - Token string `json:"token"` - LastFour string `json:"last_four"` - Brand string `json:"brand"` - ExpiryMonth int `json:"expiry_month"` - ExpiryYear int `json:"expiry_year"` - CreatedAt time.Time `json:"created_at"` - UsedCount int `json:"used_count"` -} - -// TransactionSigner handles transaction signing and verification -type TransactionSigner struct { - signKey []byte -} - -// PCICompliance handles PCI DSS compliance requirements -type PCICompliance struct { - auditLog []AuditEntry - mu sync.RWMutex -} - -// AuditEntry for PCI compliance logging -type AuditEntry struct { - Timestamp time.Time `json:"timestamp"` - Action string `json:"action"` - UserID string `json:"user_id"` - ResourceID string `json:"resource_id"` - Result string `json:"result"` - IPAddress string `json:"ip_address"` -} - -var ( - paymentTokenizer *PaymentTokenizer - transactionSigner *TransactionSigner - pciCompliance *PCICompliance - initOnce sync.Once -) - -// InitializePaymentSecurity initializes payment security components -func InitializePaymentSecurity() { - initOnce.Do(func() { - // Generate encryption key (in production, use KMS) - encKey := make([]byte, 32) - io.ReadFull(rand.Reader, encKey) - - // Generate signing key - signKey := make([]byte, 32) - io.ReadFull(rand.Reader, signKey) - - paymentTokenizer = &PaymentTokenizer{ - tokens: make(map[string]*TokenData), - encryptKey: encKey, - } - - transactionSigner = &TransactionSigner{ - signKey: signKey, - } - - pciCompliance = &PCICompliance{ - auditLog: make([]AuditEntry, 0), - } - }) -} - -// TokenizeCard tokenizes credit card data (PCI DSS compliant) -func TokenizeCard(cardNumber, cvv string, expiryMonth, expiryYear int) (string, error) { - // Validate card number using Luhn algorithm - if !validateLuhn(cardNumber) { - return "", fmt.Errorf("invalid card number") - } - - // Validate CVV - if !validateCVV(cvv) { - return "", fmt.Errorf("invalid CVV") - } - - // Validate expiry - if !validateExpiry(expiryMonth, expiryYear) { - return "", fmt.Errorf("card expired or invalid expiry date") - } - - // Extract card info - lastFour := cardNumber[len(cardNumber)-4:] - brand := detectCardBrand(cardNumber) - - // Generate secure token - token := generateSecureToken() - - // Store tokenized data (never store raw card data) - tokenData := &TokenData{ - Token: token, - LastFour: lastFour, - Brand: brand, - ExpiryMonth: expiryMonth, - ExpiryYear: expiryYear, - CreatedAt: time.Now(), - UsedCount: 0, - } - - paymentTokenizer.mu.Lock() - paymentTokenizer.tokens[token] = tokenData - paymentTokenizer.mu.Unlock() - - // Log tokenization for PCI compliance - pciCompliance.LogAction("TOKENIZE_CARD", "", token, "SUCCESS", "") - - return token, nil -} - -// validateLuhn validates credit card number using Luhn algorithm -func validateLuhn(cardNumber string) bool { - // Remove spaces and dashes - cardNumber = strings.ReplaceAll(cardNumber, " ", "") - cardNumber = strings.ReplaceAll(cardNumber, "-", "") - - // Check if all digits - if !regexp.MustCompile(`^\d+$`).MatchString(cardNumber) { - return false - } - - // Luhn algorithm - sum := 0 - isEven := false - - for i := len(cardNumber) - 1; i >= 0; i-- { - digit := int(cardNumber[i] - '0') - - if isEven { - digit *= 2 - if digit > 9 { - digit -= 9 - } - } - - sum += digit - isEven = !isEven - } - - return sum%10 == 0 -} - -// validateCVV validates CVV format -func validateCVV(cvv string) bool { - // CVV should be 3 or 4 digits - return regexp.MustCompile(`^\d{3,4}$`).MatchString(cvv) -} - -// validateExpiry validates card expiry date -func validateExpiry(month, year int) bool { - now := time.Now() - currentYear := now.Year() - currentMonth := int(now.Month()) - - // Check valid month - if month < 1 || month > 12 { - return false - } - - // Check if expired - if year < currentYear || (year == currentYear && month < currentMonth) { - return false - } - - // Check reasonable future date (max 20 years) - if year > currentYear+20 { - return false - } - - return true -} - -// detectCardBrand detects card brand from number -func detectCardBrand(cardNumber string) string { - // Remove spaces and dashes - cardNumber = strings.ReplaceAll(cardNumber, " ", "") - cardNumber = strings.ReplaceAll(cardNumber, "-", "") - - // Visa - if strings.HasPrefix(cardNumber, "4") { - return "visa" - } - - // Mastercard - if regexp.MustCompile(`^5[1-5]`).MatchString(cardNumber) || - regexp.MustCompile(`^2[2-7]`).MatchString(cardNumber) { - return "mastercard" - } - - // American Express - if strings.HasPrefix(cardNumber, "34") || strings.HasPrefix(cardNumber, "37") { - return "amex" - } - - // Discover - if strings.HasPrefix(cardNumber, "6011") || strings.HasPrefix(cardNumber, "65") { - return "discover" - } - - return "unknown" -} - -// generateSecureToken generates a cryptographically secure token -func generateSecureToken() string { - b := make([]byte, 32) - rand.Read(b) - return "tok_" + base64.URLEncoding.EncodeToString(b) -} - -// SignTransaction signs a transaction for integrity -func SignTransaction(transactionData map[string]interface{}) (string, error) { - // Serialize transaction data - data, err := json.Marshal(transactionData) - if err != nil { - return "", err - } - - // Create HMAC signature - h := hmac.New(sha256.New, transactionSigner.signKey) - h.Write(data) - signature := hex.EncodeToString(h.Sum(nil)) - - // Log signing for audit - txID := "" - if id, ok := transactionData["id"].(string); ok { - txID = id - } - pciCompliance.LogAction("SIGN_TRANSACTION", "", txID, "SUCCESS", "") - - return signature, nil -} - -// VerifyTransactionSignature verifies a transaction signature -func VerifyTransactionSignature(transactionData map[string]interface{}, signature string) bool { - // Serialize transaction data - data, err := json.Marshal(transactionData) - if err != nil { - return false - } - - // Create HMAC signature - h := hmac.New(sha256.New, transactionSigner.signKey) - h.Write(data) - expectedSignature := hex.EncodeToString(h.Sum(nil)) - - // Compare signatures - return hmac.Equal([]byte(signature), []byte(expectedSignature)) -} - -// EncryptSensitiveData encrypts sensitive payment data -func EncryptSensitiveData(plaintext string) (string, error) { - // Create cipher - block, err := aes.NewCipher(paymentTokenizer.encryptKey) - if err != nil { - return "", err - } - - // Generate nonce - nonce := make([]byte, 12) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return "", err - } - - // Encrypt - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return "", err - } - - ciphertext := aesgcm.Seal(nil, nonce, []byte(plaintext), nil) - - // Combine nonce and ciphertext - combined := append(nonce, ciphertext...) - - return base64.StdEncoding.EncodeToString(combined), nil -} - -// DecryptSensitiveData decrypts sensitive payment data -func DecryptSensitiveData(encrypted string) (string, error) { - // Decode from base64 - combined, err := base64.StdEncoding.DecodeString(encrypted) - if err != nil { - return "", err - } - - // Extract nonce and ciphertext - if len(combined) < 12 { - return "", fmt.Errorf("invalid encrypted data") - } - - nonce := combined[:12] - ciphertext := combined[12:] - - // Create cipher - block, err := aes.NewCipher(paymentTokenizer.encryptKey) - if err != nil { - return "", err - } - - // Decrypt - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return "", err - } - - plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) - if err != nil { - return "", err - } - - return string(plaintext), nil -} - -// LogAction logs an action for PCI compliance audit -func (p *PCICompliance) LogAction(action, userID, resourceID, result, ipAddress string) { - p.mu.Lock() - defer p.mu.Unlock() - - entry := AuditEntry{ - Timestamp: time.Now(), - Action: action, - UserID: userID, - ResourceID: resourceID, - Result: result, - IPAddress: ipAddress, - } - - p.auditLog = append(p.auditLog, entry) - - // In production, persist to secure audit log storage - // For now, just keep in memory (limited to last 10000 entries) - if len(p.auditLog) > 10000 { - p.auditLog = p.auditLog[1:] - } -} - -// GetAuditLog returns recent audit log entries -func (p *PCICompliance) GetAuditLog(limit int) []AuditEntry { - p.mu.RLock() - defer p.mu.RUnlock() - - if limit > len(p.auditLog) { - limit = len(p.auditLog) - } - - // Return most recent entries - start := len(p.auditLog) - limit - if start < 0 { - start = 0 - } - - return p.auditLog[start:] -} - -// ValidateToken validates a payment token -func ValidateToken(token string) (*TokenData, error) { - paymentTokenizer.mu.RLock() - defer paymentTokenizer.mu.RUnlock() - - tokenData, exists := paymentTokenizer.tokens[token] - if !exists { - return nil, fmt.Errorf("invalid token") - } - - // Check if token is expired (tokens valid for 1 hour) - if time.Since(tokenData.CreatedAt) > time.Hour { - return nil, fmt.Errorf("token expired") - } - - // Increment usage count - tokenData.UsedCount++ - - return tokenData, nil -} - -// MaskCardNumber masks all but last 4 digits of card number -func MaskCardNumber(cardNumber string) string { - // Remove spaces and dashes - cardNumber = strings.ReplaceAll(cardNumber, " ", "") - cardNumber = strings.ReplaceAll(cardNumber, "-", "") - - if len(cardNumber) < 4 { - return strings.Repeat("*", len(cardNumber)) - } - - lastFour := cardNumber[len(cardNumber)-4:] - masked := strings.Repeat("*", len(cardNumber)-4) + lastFour - - // Format based on card type - if len(masked) == 16 { - // Format as XXXX XXXX XXXX 1234 - return masked[:4] + " " + masked[4:8] + " " + masked[8:12] + " " + masked[12:] - } - - return masked -} - -// SanitizePaymentData removes sensitive data from payment objects -func SanitizePaymentData(data map[string]interface{}) map[string]interface{} { - sanitized := make(map[string]interface{}) - - // List of sensitive fields to exclude - sensitiveFields := []string{ - "card_number", "cvv", "cvc", "card_code", - "account_number", "routing_number", "pin", - } - - for key, value := range data { - // Check if field is sensitive - isSensitive := false - keyLower := strings.ToLower(key) - for _, sensitive := range sensitiveFields { - if strings.Contains(keyLower, sensitive) { - isSensitive = true - break - } - } - - if !isSensitive { - sanitized[key] = value - } - } - - return sanitized -} diff --git a/cmd/motr/security.go b/cmd/motr/security.go deleted file mode 100644 index 34a985526..000000000 --- a/cmd/motr/security.go +++ /dev/null @@ -1,242 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "fmt" - "net/http" - "strings" - "sync" - "time" -) - -// RateLimiter implements rate limiting -type RateLimiter struct { - mu sync.RWMutex - requests map[string]*RequestCounter - limit int - window time.Duration -} - -// RequestCounter tracks requests -type RequestCounter struct { - Count int - ResetTime time.Time -} - -// SecurityConfig holds security configuration -type SecurityConfig struct { - EnableRateLimit bool - RateLimit int - RateWindow time.Duration - EnableCSP bool - CSPPolicy string -} - -// Global security configuration -var securityConfig = &SecurityConfig{ - EnableRateLimit: true, - RateLimit: 100, // 100 requests - RateWindow: time.Minute, - EnableCSP: true, - CSPPolicy: "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' https:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline';", -} - -// Global rate limiter -var rateLimiter = NewRateLimiter(securityConfig.RateLimit, securityConfig.RateWindow) - -// NewRateLimiter creates a new rate limiter -func NewRateLimiter(limit int, window time.Duration) *RateLimiter { - return &RateLimiter{ - requests: make(map[string]*RequestCounter), - limit: limit, - window: window, - } -} - -// Allow checks if request is allowed -func (rl *RateLimiter) Allow(identifier string) bool { - rl.mu.Lock() - defer rl.mu.Unlock() - - now := time.Now() - counter, exists := rl.requests[identifier] - - if !exists || now.After(counter.ResetTime) { - // Create new counter or reset existing one - rl.requests[identifier] = &RequestCounter{ - Count: 1, - ResetTime: now.Add(rl.window), - } - return true - } - - if counter.Count >= rl.limit { - return false - } - - counter.Count++ - return true -} - -// SecurityMiddleware wraps handlers with security features -func SecurityMiddleware(next http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // Apply security headers - applySecurityHeaders(w) - - // Rate limiting - if securityConfig.EnableRateLimit { - // Use client IP or a default identifier for WASM environment - identifier := getClientIdentifier(r) - if !rateLimiter.Allow(identifier) { - writeError(w, http.StatusTooManyRequests, "Rate limit exceeded") - return - } - } - - // Call the next handler - next(w, r) - } -} - -// applySecurityHeaders applies security headers to response -func applySecurityHeaders(w http.ResponseWriter) { - // CORS headers (already handled by handleCORS, but adding for completeness) - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") - - // Security headers - w.Header().Set("X-Content-Type-Options", "nosniff") - w.Header().Set("X-Frame-Options", "DENY") - w.Header().Set("X-XSS-Protection", "1; mode=block") - w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") - w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()") - - // Content Security Policy - if securityConfig.EnableCSP { - w.Header().Set("Content-Security-Policy", securityConfig.CSPPolicy) - } - - // Strict Transport Security (for HTTPS) - w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload") -} - -// getClientIdentifier gets a client identifier for rate limiting -func getClientIdentifier(r *http.Request) string { - // In WASM environment, we can't rely on real IP - // Use a combination of headers for identification - - // Try X-Forwarded-For - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { - return xff - } - - // Try X-Real-IP - if xri := r.Header.Get("X-Real-IP"); xri != "" { - return xri - } - - // Try Origin header (common in browser requests) - if origin := r.Header.Get("Origin"); origin != "" { - return origin - } - - // Try User-Agent as last resort - if ua := r.Header.Get("User-Agent"); ua != "" { - return ua - } - - // Default identifier - return "default-client" -} - -// ValidatePaymentData validates payment data for security -func ValidatePaymentData(data map[string]interface{}) error { - // Check for required fields - requiredFields := []string{"amount", "currency"} - for _, field := range requiredFields { - if _, exists := data[field]; !exists { - return fmt.Errorf("missing required field: %s", field) - } - } - - // Validate amount - if amount, ok := data["amount"].(float64); ok { - if amount <= 0 || amount > 1000000 { - return fmt.Errorf("invalid amount") - } - } - - // Validate currency - if currency, ok := data["currency"].(string); ok { - validCurrencies := []string{"USD", "EUR", "GBP", "JPY"} - valid := false - for _, vc := range validCurrencies { - if currency == vc { - valid = true - break - } - } - if !valid { - return fmt.Errorf("unsupported currency") - } - } - - return nil -} - -// SanitizeInput sanitizes user input -func SanitizeInput(input string) string { - // Remove any potentially dangerous characters - // This is a basic implementation - in production, use a proper sanitization library - sanitized := input - - // Remove script tags - sanitized = strings.ReplaceAll(sanitized, "", "") - - // Remove other potentially dangerous HTML - sanitized = strings.ReplaceAll(sanitized, "", "") - - // Limit length - if len(sanitized) > 1000 { - sanitized = sanitized[:1000] - } - - return sanitized -} - -// TokenizePaymentMethod creates a token for payment method -func TokenizePaymentMethod(method map[string]interface{}) string { - // Create a secure token representing the payment method - // In production, this would use proper tokenization service - - token := generateRandomString(32) - - // Store token mapping (in production, use secure storage) - // For now, just return the token - return "pmtoken_" + token -} - -// ValidateOrigin validates request origin -func ValidateOrigin(origin string) bool { - // List of allowed origins - allowedOrigins := []string{ - "https://motor.sonr.io", - "https://localhost:3000", - "http://localhost:3000", - "https://sonr.io", - } - - for _, allowed := range allowedOrigins { - if origin == allowed { - return true - } - } - - return false -} diff --git a/cmd/motr/version.go b/cmd/motr/version.go deleted file mode 100644 index a5a16c0a9..000000000 --- a/cmd/motr/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package main - -// Version is set by commitizen during release process -var Version = "dev" diff --git a/cmd/snrd/.goreleaser.yml b/cmd/snrd/.goreleaser.yml deleted file mode 100644 index f62806bb1..000000000 --- a/cmd/snrd/.goreleaser.yml +++ /dev/null @@ -1,331 +0,0 @@ -# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json ---- -version: 2 -dist: dist/snrd -monorepo: - tag_prefix: snrd/ - -project_name: snrd - -before: - hooks: - - go mod download - -builds: - # Darwin AMD64 Build - - id: snrd-darwin-amd64 - main: ./cmd/snrd - binary: snrd - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=o64-clang - - CXX=o64-clang++ - - CGO_LDFLAGS=-lm - goos: - - darwin - goarch: - - amd64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X github.com/cosmos/cosmos-sdk/version.Name=sonr - - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd - - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} - - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} - - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - -s -w - tags: - - netgo - - ledger - - # Darwin ARM64 Build - - id: snrd-darwin-arm64 - main: ./cmd/snrd - binary: snrd - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=oa64-clang - - CXX=oa64-clang++ - - CGO_LDFLAGS=-lm - goos: - - darwin - goarch: - - arm64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X github.com/cosmos/cosmos-sdk/version.Name=sonr - - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd - - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} - - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} - - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - -s -w - tags: - - netgo - - ledger - - # Linux AMD64 Build - - id: snrd-linux-amd64 - main: ./cmd/snrd - binary: snrd - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=x86_64-linux-gnu-gcc - - CXX=x86_64-linux-gnu-g++ - - CGO_LDFLAGS=-lm - goos: - - linux - goarch: - - amd64 - goamd64: - - v1 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X github.com/cosmos/cosmos-sdk/version.Name=sonr - - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd - - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} - - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} - - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - -s -w - tags: - - netgo - - ledger - - # Linux ARM64 Build - - id: snrd-linux-arm64 - main: ./cmd/snrd - binary: snrd - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=1 - - CC=aarch64-linux-gnu-gcc - - CXX=aarch64-linux-gnu-g++ - - CGO_LDFLAGS=-lm - goos: - - linux - goarch: - - arm64 - flags: - - -mod=readonly - - -trimpath - ldflags: - - -X github.com/cosmos/cosmos-sdk/version.Name=sonr - - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd - - -X github.com/cosmos/cosmos-sdk/version.Version={{.Version}} - - -X github.com/cosmos/cosmos-sdk/version.Commit={{.Commit}} - - -X "github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger" - - -s -w - tags: - - netgo - - ledger - -aur_sources: - - name: snrd - disable: true - homepage: "https://sonr.io" - description: "Sonr blockchain daemon - decentralized identity and data storage network" - maintainers: - - "Sonr " - license: "GPL-3.0" - private_key: "{{ .Env.AUR_KEY }}" - git_url: "ssh://[email protected]/snrd.git" - skip_upload: auto - provides: - - snrd - conflicts: - - snrd-bin - depends: - - glibc - makedepends: - - go - - git - - make - commit_msg_template: "Update to {{ .Tag }}" - commit_author: - name: goreleaserbot - email: "prad@sonr.io" - prepare: |- - cd "${pkgname}_${pkgver}" - go mod download - build: |- - cd "${pkgname}_${pkgver}" - export CGO_ENABLED=1 - export CGO_CPPFLAGS="${CPPFLAGS}" - export CGO_CFLAGS="${CFLAGS}" - export CGO_CXXFLAGS="${CXXFLAGS}" - export CGO_LDFLAGS="${LDFLAGS}" - export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw" - go build \ - -ldflags="-w -s -buildid='' -linkmode=external \ - -X github.com/cosmos/cosmos-sdk/version.Name=sonr \ - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd \ - -X github.com/cosmos/cosmos-sdk/version.Version=${pkgver} \ - -X 'github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger'" \ - -tags "netgo,ledger" \ - -o snrd ./cmd/snrd - chmod +x ./snrd - package: |- - cd "${pkgname}_${pkgver}" - - # bin - install -Dm755 "./snrd" "${pkgdir}/usr/bin/snrd" - - # license - if [ -f "./LICENSE" ]; then - install -Dm644 "./LICENSE" "${pkgdir}/usr/share/licenses/snrd/LICENSE" - fi - - # readme - if [ -f "./README.md" ]; then - install -Dm644 "./README.md" "${pkgdir}/usr/share/doc/snrd/README.md" - fi - - # config directory - install -dm755 "${pkgdir}/etc/snrd" - install -dm755 "${pkgdir}/var/lib/snrd" - backup: - - /etc/snrd/config.toml - - /etc/snrd/app.toml - -nix: - - name: snrd - ids: - - snrd - homepage: "https://sonr.io" - description: "Sonr blockchain daemon - decentralized identity network" - license: "gpl3" - path: pkgs/snrd/default.nix - commit_msg_template: "snrd: {{ .Tag }}" - dependencies: - - stdenv - - glibc - extra_install: |- - wrapProgram $out/bin/snrd --prefix PATH : ${lib.makeBinPath [ glibc stdenv.cc.cc.lib ]} - repository: - owner: sonr-io - name: nur - branch: main - token: "{{ .Env.GITHUB_TOKEN }}" - -archives: - - id: snrd - ids: - - snrd-linux-amd64 - - snrd-linux-arm64 - - snrd-darwin-amd64 - - snrd-darwin-arm64 - name_template: >- - snrd_{{ .Os }}_{{- if eq .Arch "amd64" }}x86_64 {{- else if eq .Arch "386" }}i386 {{- else }}{{ .Arch }}{{ end }} - formats: ["tar.gz"] - files: - - src: README* - wrap_in_directory: false - -homebrew_casks: - - name: snrd - ids: - - snrd - homepage: "https://sonr.io" - description: "Sonr blockchain daemon - decentralized identity and data storage network" - commit_msg_template: "Brew cask update for {{ .ProjectName }} version {{ .Tag }}" - directory: Casks - repository: - owner: sonr-io - name: homebrew-tap - branch: main - token: "{{ .Env.GITHUB_TOKEN }}" - commit_author: - name: goreleaserbot - email: "prad@sonr.io" - hooks: - post: - install: | - if OS.mac? - system_command "/usr/bin/xattr", args: ["-dr", "com.apple.quarantine", "#{staged_path}/snrd"] - end - -nfpms: - - id: snrd - package_name: snrd - ids: - - snrd-linux-amd64 - - snrd-linux-arm64 - file_name_template: "snrd_{{ .Os }}_{{ .Arch }}{{ .ConventionalExtension }}" - vendor: Sonr - homepage: "https://sonr.io" - maintainer: "Sonr " - description: "Sonr is a decentralized, permissionless, and censorship-resistant identity network." - license: "GPL-3.0" - formats: - - rpm - - deb - - apk - - archlinux - contents: - - src: README* - dst: /usr/share/doc/snrd - bindir: /usr/bin - section: net - priority: optional - -blobs: - - provider: s3 - endpoint: https://eb37925850388bca807b7fab964c12bb.r2.cloudflarestorage.com - bucket: releases - region: auto - directory: "snrd/{{ .Tag }}" - ids: - - snrd - -release: - disable: false - github: - owner: sonr-io - name: sonr - name_template: "{{.ProjectName}}/{{ .Tag }}" - draft: false - replace_existing_draft: false # Don't replace drafts - replace_existing_artifacts: false # Append, don't replace - mode: append # Explicitly set to append mode - -checksum: - name_template: "snrd_checksums.txt" - -npms: - - name: "@sonr.io/snrd" - ids: - - snrd - description: "Sonr blockchain daemon - decentralized identity and data storage network" - homepage: "https://sonr.io" - license: "GPL-3.0" - author: "Sonr " - repository: "https://github.com/sonr-io/sonr" - bugs: "https://github.com/sonr-io/sonr/issues" - keywords: - - blockchain - - cosmos - - did - - identity - - web3 - - sonr - access: public - format: tar.gz - -snapshot: - version_template: "{{ incpatch .Version }}-dev" - -# Changelog configuration -changelog: - sort: asc - filters: - exclude: - - "^docs:" - - "^test:" - - "^chore:" diff --git a/cmd/snrd/CHANGELOG.md b/cmd/snrd/CHANGELOG.md deleted file mode 100644 index 38fe5c7ee..000000000 --- a/cmd/snrd/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -## snrd/v0.0.3 (2025-10-04) - -## snrd/v0.0.2 (2025-10-04) - -## snrd/v0.0.1 (2025-10-03) diff --git a/cmd/snrd/Dockerfile b/cmd/snrd/Dockerfile deleted file mode 100644 index 0f374d3a1..000000000 --- a/cmd/snrd/Dockerfile +++ /dev/null @@ -1,89 +0,0 @@ -# Use build argument for base image to allow using pre-cached base -ARG BASE_IMAGE=golang:1.24.7-alpine3.22 - -FROM ${BASE_IMAGE} AS builder -SHELL ["/bin/sh", "-ecuxo", "pipefail"] - -# Install build dependencies -RUN apk add --no-cache \ - ca-certificates \ - build-base \ - git \ - linux-headers \ - bash \ - binutils-gold \ - wget - -WORKDIR /code - -# Copy entire source code (including crypto module) -COPY . . - -# Fix git ownership issue -RUN git config --global --add safe.directory /code - -# Download WasmVM library -RUN --mount=type=cache,target=/tmp/wasmvm \ - set -eux; \ - export ARCH=$(uname -m); \ - WASM_VERSION=$(go list -m all | grep github.com/CosmWasm/wasmvm | head -1 || echo ""); \ - if [ ! -z "${WASM_VERSION}" ]; then \ - WASMVM_REPO=$(echo $WASM_VERSION | awk '{print $1}'); \ - WASMVM_VERS=$(echo $WASM_VERSION | awk '{print $2}'); \ - WASMVM_FILE="libwasmvm_muslc.${ARCH}.a"; \ - if [ ! -f "/tmp/wasmvm/${WASMVM_FILE}" ]; then \ - wget -O "/tmp/wasmvm/${WASMVM_FILE}" "https://${WASMVM_REPO}/releases/download/${WASMVM_VERS}/${WASMVM_FILE}"; \ - fi; \ - cp "/tmp/wasmvm/${WASMVM_FILE}" /lib/libwasmvm_muslc.a; \ - fi - -# Download Go modules -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - go mod download - -# Build binary with optimizations -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - set -eux; \ - VERSION=$(git describe --tags --always 2>/dev/null || echo "dev"); \ - COMMIT=$(git log -1 --format='%H' 2>/dev/null || echo "unknown"); \ - LEDGER_ENABLED=false BUILD_TAGS=muslc LINK_STATICALLY=true \ - CGO_ENABLED=1 GOOS=linux \ - go build \ - -mod=readonly \ - -tags "netgo,ledger,muslc" \ - -ldflags "-X github.com/cosmos/cosmos-sdk/version.Name=sonr \ - -X github.com/cosmos/cosmos-sdk/version.AppName=snrd \ - -X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \ - -X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \ - -X github.com/cosmos/cosmos-sdk/version.BuildTags=netgo,ledger,muslc \ - -w -s -linkmode=external -extldflags '-Wl,-z,muldefs -static'" \ - -buildvcs=false \ - -trimpath \ - -o /code/build/snrd \ - ./cmd/snrd; \ - file /code/build/snrd; \ - echo "Ensuring binary is statically linked ..."; \ - (file /code/build/snrd | grep "statically linked") - -# -------------------------------------------------------- -# Final minimal runtime image -FROM alpine:3.17 - -LABEL org.opencontainers.image.title="Sonr Daemon" -LABEL org.opencontainers.image.source="https://github.com/sonr-io/sonr" - -# Copy binary from build stage -COPY --from=builder /code/build/snrd /usr/bin -COPY --from=builder /lib/libwasmvm_muslc.a /lib/libwasmvm_muslc.a -COPY --from=builder /code/scripts/test_node.sh /usr/bin/testnet -RUN chmod +x /usr/bin/testnet - -# Set up dependencies -ENV PACKAGES="curl make bash jq sed" - -# Install minimum necessary dependencies -RUN apk add --no-cache $PACKAGES - -WORKDIR /opt diff --git a/cmd/snrd/Makefile b/cmd/snrd/Makefile index a135dec15..a65fc89d0 100644 --- a/cmd/snrd/Makefile +++ b/cmd/snrd/Makefile @@ -109,13 +109,11 @@ test: release: @echo "Creating snrd release..." - @cd $(GIT_ROOT) && cz --config cmd/snrd/.cz.toml --no-raise 6,21 bump --yes --increment PATCH + @cd $(GIT_ROOT) && goreleaser release --clean snapshot: - @echo "Dry-Run Bumping snrd version..." - @cd $(GIT_ROOT) && cz --config cmd/snrd/.cz.toml bump --yes --dry-run --no-verify --increment PATCH @echo "Creating snrd snapshots for all platforms..." - @cd $(GIT_ROOT) && goreleaser release --snapshot --clean -f cmd/snrd/.goreleaser.yml + @cd $(GIT_ROOT) && goreleaser release --snapshot --clean # Docker build targets docker: diff --git a/cmd/snrd/go.mod b/cmd/snrd/go.mod deleted file mode 100644 index acfb4fa0e..000000000 --- a/cmd/snrd/go.mod +++ /dev/null @@ -1,441 +0,0 @@ -module snrd - -go 1.24.7 - -// overrides -replace ( - cosmossdk.io/core => cosmossdk.io/core v0.11.0 - cosmossdk.io/store => github.com/evmos/cosmos-sdk/store v0.0.0-20240718141609-414cbd051fbe - github.com/CosmWasm/wasmd => github.com/rollchains/wasmd v0.50.0-evm - - github.com/cosmos/cosmos-sdk => github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 - github.com/cosmos/evm => github.com/strangelove-ventures/cosmos-evm v0.2.0 - github.com/ethereum/go-ethereum => github.com/evmos/go-ethereum v1.10.26-evmos-rc2 - github.com/sonr-io/sonr => ../../ - github.com/sonr-io/sonr/crypto => ../../crypto - github.com/spf13/viper => github.com/spf13/viper v1.17.0 // v1.18+ breaks app overrides - nhooyr.io/websocket => nhooyr.io/websocket v1.8.17 -) - -replace ( - github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 - // Fix btcec version for evmos compatibility - github.com/btcsuite/btcd/btcec/v2 => github.com/btcsuite/btcd/btcec/v2 v2.3.2 - // dgrijalva/jwt-go is deprecated and doesn't receive security updates. - // See: https://github.com/cosmos/cosmos-sdk/issues/13134 - github.com/dgrijalva/jwt-go => github.com/golang-jwt/jwt/v4 v4.4.2 - // Fix upstream GHSA-h395-qcrw-5vmq vulnerability. - // See: https://github.com/cosmos/cosmos-sdk/issues/10409 - github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.8.1 - - // pin version! 126854af5e6d has issues with the store so that queries fail - github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 - github.com/tyler-smith/go-bip39 => github.com/go-sonr/go-bip39 v1.1.1 -) - -require ( - cosmossdk.io/log v1.5.0 - cosmossdk.io/tools/confix v0.1.2 - github.com/cometbft/cometbft v0.38.17 - github.com/cosmos/cosmos-db v1.1.1 - github.com/cosmos/cosmos-sdk v0.53.4 - github.com/cosmos/evm v0.1.0 - github.com/sonr-io/sonr v0.0.0-00010101000000-000000000000 - github.com/spf13/cast v1.9.2 - github.com/spf13/cobra v1.8.1 - github.com/spf13/viper v1.19.0 -) - -require ( - cosmossdk.io/api v0.7.6 // indirect - cosmossdk.io/client/v2 v2.0.0-beta.7 // indirect - cosmossdk.io/collections v0.4.0 // indirect - cosmossdk.io/core v0.12.0 // indirect - cosmossdk.io/depinject v1.1.0 // indirect - cosmossdk.io/errors v1.0.1 // indirect - cosmossdk.io/math v1.5.0 // indirect - cosmossdk.io/orm v1.0.0-beta.3 // indirect - cosmossdk.io/store v1.1.1 // indirect - cosmossdk.io/x/circuit v0.1.1 // indirect - cosmossdk.io/x/evidence v0.1.1 // indirect - cosmossdk.io/x/feegrant v0.1.1 // indirect - cosmossdk.io/x/nft v0.1.0 // indirect - cosmossdk.io/x/tx v0.13.7 // indirect - cosmossdk.io/x/upgrade v0.1.4 // indirect - github.com/CosmWasm/wasmvm v1.5.8 // indirect - github.com/Oudwins/zog v0.21.6 // indirect - github.com/asynkron/protoactor-go v0.0.0-20240822202345-3c0e61ca19c9 // indirect - github.com/biter777/countries v1.7.5 // indirect - github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect - github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/gogoproto v1.7.0 // indirect - github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v8 v8.1.1 // indirect - github.com/cosmos/ibc-apps/modules/rate-limiting/v8 v8.0.0 // indirect - github.com/cosmos/ibc-go/modules/capability v1.0.1 // indirect - github.com/cosmos/ibc-go/modules/light-clients/08-wasm v0.1.1-0.20231213092650-57fcdb9a9a9d // indirect - github.com/cosmos/ibc-go/v8 v8.7.0 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect - github.com/ethereum/go-ethereum v1.16.3 // indirect - github.com/extism/go-sdk v1.7.1 // indirect - github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/golang-jwt/jwt/v5 v5.3.0 // indirect - github.com/golang/protobuf v1.5.4 // indirect - github.com/google/go-tpm v0.9.5 // indirect - github.com/gorilla/mux v1.8.1 // indirect - github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect - github.com/ipfs/boxo v0.32.0 // indirect - github.com/ipfs/kubo v0.35.0 // indirect - github.com/jinzhu/inflection v1.0.0 // indirect - github.com/jinzhu/now v1.1.5 // indirect - github.com/labstack/echo/v4 v4.13.4 // indirect - github.com/labstack/gommon v0.4.2 // indirect - github.com/mattn/go-sqlite3 v1.14.22 // indirect - github.com/sonr-io/sonr/crypto v0.0.0-00010101000000-000000000000 // indirect - github.com/strangelove-ventures/tokenfactory v0.50.3 // indirect - github.com/stretchr/testify v1.10.0 // indirect - github.com/tklauser/go-sysconf v0.3.11 // indirect - github.com/tklauser/numcpus v0.6.1 // indirect - github.com/tyler-smith/go-bip39 v1.1.0 // indirect - github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect - google.golang.org/grpc v1.71.0 // indirect - google.golang.org/protobuf v1.36.6 // indirect - gorm.io/driver/sqlite v1.6.0 // indirect - gorm.io/gorm v1.30.1 // indirect - nhooyr.io/websocket v1.8.10 // indirect -) - -require ( - cloud.google.com/go v0.115.0 // indirect - cloud.google.com/go/auth v0.6.0 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect - cloud.google.com/go/compute/metadata v0.6.0 // indirect - cloud.google.com/go/iam v1.1.9 // indirect - cloud.google.com/go/storage v1.41.0 // indirect - filippo.io/edwards25519 v1.1.0 // indirect - github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect - github.com/99designs/keyring v1.2.1 // indirect - github.com/DataDog/datadog-go v3.2.0+incompatible // indirect - github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect - github.com/StackExchange/wmi v1.2.1 // indirect - github.com/VictoriaMetrics/fastcache v1.6.0 // indirect - github.com/Workiva/go-datastructures v1.1.3 // indirect - github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect - github.com/alexvec/go-bip39 v1.1.0 // indirect - github.com/aws/aws-sdk-go v1.55.6 // indirect - github.com/benbjohnson/clock v1.3.5 // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect - github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect - github.com/bits-and-blooms/bitset v1.24.0 // indirect - github.com/blang/semver/v4 v4.0.0 // indirect - github.com/btcsuite/btcd v0.24.2 // indirect - github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect - github.com/btcsuite/btcd/btcutil v1.1.6 // indirect - github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect - github.com/bwesterb/go-ristretto v1.2.3 // indirect - github.com/bytedance/sonic v1.14.0 // indirect - github.com/bytedance/sonic/loader v0.3.0 // indirect - github.com/caddyserver/certmagic v0.21.6 // indirect - github.com/caddyserver/zerossl v0.1.3 // indirect - github.com/cenkalti/backoff/v4 v4.3.0 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/chzyer/readline v1.5.1 // indirect - github.com/cloudwego/base64x v0.1.5 // indirect - github.com/cockroachdb/apd/v2 v2.0.2 // indirect - github.com/cockroachdb/apd/v3 v3.2.1 // indirect - github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect - github.com/cockroachdb/errors v1.11.3 // indirect - github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect - github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v1.1.2 // indirect - github.com/cockroachdb/pebble/v2 v2.0.3 // indirect - github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect - github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect - github.com/cometbft/cometbft-db v0.14.1 // indirect - github.com/consensys/gnark-crypto v0.19.0 // indirect - github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/gogogateway v1.2.0 // indirect - github.com/cosmos/iavl v1.2.2 // indirect - github.com/cosmos/ics23/go v0.11.0 // indirect - github.com/cosmos/ledger-cosmos-go v0.14.0 // indirect - github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf // indirect - github.com/creachadair/atomicfile v0.3.1 // indirect - github.com/creachadair/tomledit v0.0.24 // indirect - github.com/danieljoos/wincred v1.1.2 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect - github.com/deckarep/golang-set v1.8.0 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect - github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect - github.com/dgraph-io/badger/v4 v4.2.0 // indirect - github.com/dgraph-io/ristretto v0.1.1 // indirect - github.com/dlclark/regexp2 v1.11.0 // indirect - github.com/dop251/goja v0.0.0-20220405120441-9037c2b61cbf // indirect - github.com/dustin/go-humanize v1.0.1 // indirect - github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 // indirect - github.com/dvsekhvalnov/jose2go v1.6.0 // indirect - github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect - github.com/edsrzf/mmap-go v1.1.0 // indirect - github.com/emicklei/dot v1.6.2 // indirect - github.com/emirpasic/gods v1.18.1 // indirect - github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 // indirect - github.com/fatih/color v1.16.0 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/flynn/noise v1.1.0 // indirect - github.com/francoispqt/gojay v1.2.13 // indirect - github.com/fsnotify/fsnotify v1.7.0 // indirect - github.com/gammazero/deque v1.0.0 // indirect - github.com/getsentry/sentry-go v0.27.0 // indirect - github.com/go-kit/kit v0.13.0 // indirect - github.com/go-kit/log v0.2.1 // indirect - github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-ole/go-ole v1.2.6 // indirect - github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect - github.com/go-stack/stack v1.8.1 // indirect - github.com/gobwas/glob v0.2.3 // indirect - github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect - github.com/gogo/googleapis v1.4.1 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/gogo/status v1.1.0 // indirect - github.com/golang/glog v1.2.4 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/mock v1.6.0 // indirect - github.com/golang/snappy v0.0.5-0.20231225225746-43d5d4cd4e0e // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/flatbuffers v23.5.26+incompatible // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/google/gopacket v1.1.19 // indirect - github.com/google/orderedcode v0.0.1 // indirect - github.com/google/s2a-go v0.1.7 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect - github.com/googleapis/gax-go/v2 v2.12.5 // indirect - github.com/gopherjs/gopherjs v1.17.2 // indirect - github.com/gorilla/handlers v1.5.2 // indirect - github.com/gorilla/websocket v1.5.3 // indirect - github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect - github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect - github.com/gtank/merlin v0.1.1 // indirect - github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-getter v1.7.9 // indirect - github.com/hashicorp/go-hclog v1.5.0 // indirect - github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-metrics v0.5.3 // indirect - github.com/hashicorp/go-plugin v1.5.2 // indirect - github.com/hashicorp/go-safetemp v1.0.0 // indirect - github.com/hashicorp/go-version v1.7.0 // indirect - github.com/hashicorp/golang-lru v1.0.2 // indirect - github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect - github.com/hashicorp/hcl v1.0.0 // indirect - github.com/hashicorp/yamux v0.1.1 // indirect - github.com/hdevalence/ed25519consensus v0.1.0 // indirect - github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.3.2 // indirect - github.com/huandu/skiplist v1.2.0 // indirect - github.com/huin/goupnp v1.3.0 // indirect - github.com/iancoleman/orderedmap v0.3.0 // indirect - github.com/iancoleman/strcase v0.3.0 // indirect - github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect - github.com/improbable-eng/grpc-web v0.15.0 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/ipfs/bbloom v0.0.4 // indirect - github.com/ipfs/go-bitfield v1.1.0 // indirect - github.com/ipfs/go-block-format v0.2.1 // indirect - github.com/ipfs/go-cid v0.5.0 // indirect - github.com/ipfs/go-datastore v0.8.2 // indirect - github.com/ipfs/go-ds-measure v0.2.2 // indirect - github.com/ipfs/go-fs-lock v0.1.1 // indirect - github.com/ipfs/go-ipfs-cmds v0.14.1 // indirect - github.com/ipfs/go-ipld-cbor v0.2.0 // indirect - github.com/ipfs/go-ipld-format v0.6.1 // indirect - github.com/ipfs/go-ipld-legacy v0.2.1 // indirect - github.com/ipfs/go-log v1.0.5 // indirect - github.com/ipfs/go-log/v2 v2.6.0 // indirect - github.com/ipfs/go-metrics-interface v0.3.0 // indirect - github.com/ipfs/go-unixfsnode v1.10.1 // indirect - github.com/ipld/go-car/v2 v2.14.3 // indirect - github.com/ipld/go-codec-dagpb v1.7.0 // indirect - github.com/ipld/go-ipld-prime v0.21.0 // indirect - github.com/ipshipyard/p2p-forge v0.5.1 // indirect - github.com/jackpal/go-nat-pmp v1.0.2 // indirect - github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.18.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/koron/go-ssdp v0.0.6 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/kr/text v0.2.0 // indirect - github.com/lib/pq v1.10.9 // indirect - github.com/libdns/libdns v0.2.2 // 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.2.0 // indirect - github.com/libp2p/go-libp2p v0.43.0 // indirect - github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect - github.com/libp2p/go-libp2p-kad-dht v0.33.1 // indirect - github.com/libp2p/go-libp2p-kbucket v0.7.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.2.2 // indirect - github.com/libp2p/go-reuseport v0.4.0 // indirect - github.com/linxGnu/grocksdb v1.9.8 // indirect - github.com/lithammer/shortuuid/v4 v4.0.0 // indirect - github.com/lmittmann/tint v1.0.3 // indirect - github.com/magiconair/properties v1.8.7 // indirect - github.com/manifoldco/promptui v0.9.0 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mholt/acmez/v3 v3.0.0 // indirect - github.com/miekg/dns v1.1.66 // indirect - github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect - github.com/minio/highwayhash v1.0.3 // indirect - github.com/minio/sha256-simd v1.0.1 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/mitchellh/go-testing-interface v1.14.1 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/mr-tron/base58 v1.2.0 // indirect - github.com/mtibben/percent v0.2.1 // indirect - github.com/multiformats/go-base32 v0.1.0 // indirect - github.com/multiformats/go-base36 v0.2.0 // indirect - github.com/multiformats/go-multiaddr v0.16.0 // indirect - github.com/multiformats/go-multiaddr-dns v0.4.1 // indirect - github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect - github.com/multiformats/go-multibase v0.2.0 // indirect - github.com/multiformats/go-multicodec v0.9.1 // 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/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect - github.com/oklog/run v1.1.0 // indirect - github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect - github.com/orcaman/concurrent-map v1.0.0 // indirect - github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect - github.com/pelletier/go-toml/v2 v2.2.2 // indirect - github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 // indirect - github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect - github.com/pion/datachannel v1.5.10 // indirect - github.com/pion/dtls/v2 v2.2.12 // indirect - github.com/pion/dtls/v3 v3.0.6 // indirect - github.com/pion/ice/v4 v4.0.10 // indirect - github.com/pion/interceptor v0.1.40 // indirect - github.com/pion/logging v0.2.3 // indirect - github.com/pion/mdns/v2 v2.0.7 // indirect - github.com/pion/randutil v0.1.0 // indirect - github.com/pion/rtcp v1.2.15 // indirect - github.com/pion/rtp v1.8.19 // indirect - github.com/pion/sctp v1.8.39 // indirect - github.com/pion/sdp/v3 v3.0.13 // indirect - github.com/pion/srtp/v3 v3.0.6 // indirect - github.com/pion/stun v0.6.1 // indirect - github.com/pion/stun/v3 v3.0.0 // indirect - github.com/pion/transport/v2 v2.2.10 // indirect - github.com/pion/transport/v3 v3.0.7 // indirect - github.com/pion/turn/v4 v4.0.2 // indirect - github.com/pion/webrtc/v4 v4.1.2 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/polydawn/refmt v0.89.0 // indirect - github.com/prometheus/client_golang v1.22.0 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.64.0 // indirect - github.com/prometheus/procfs v0.16.1 // indirect - github.com/prometheus/tsdb v0.10.0 // indirect - github.com/quic-go/qpack v0.5.1 // indirect - github.com/quic-go/quic-go v0.54.0 // indirect - github.com/quic-go/webtransport-go v0.9.0 // indirect - github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - github.com/rjeczalik/notify v0.9.3 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/rs/cors v1.11.1 // indirect - github.com/rs/zerolog v1.33.0 // indirect - github.com/sagikazarmark/locafero v0.4.0 // indirect - github.com/sagikazarmark/slog-shim v0.1.0 // indirect - github.com/samber/lo v1.47.0 // indirect - github.com/sasha-s/go-deadlock v0.3.5 // indirect - github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect - github.com/smarty/assertions v1.15.0 // indirect - github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spaolacci/murmur3 v1.1.0 // indirect - github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/pflag v1.0.6 // indirect - github.com/subosito/gotenv v1.6.0 // indirect - github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - github.com/tendermint/go-amino v0.16.0 // indirect - github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect - github.com/tetratelabs/wazero v1.9.0 // indirect - github.com/tidwall/btree v1.7.0 // indirect - github.com/tidwall/gjson v1.18.0 // indirect - github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.1 // indirect - github.com/tidwall/sjson v1.2.5 // indirect - github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/twmb/murmur3 v1.1.8 // indirect - github.com/ulikunitz/xz v0.5.11 // indirect - github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc // indirect - github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 // indirect - github.com/whyrusleeping/cbor-gen v0.1.2 // indirect - github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f // indirect - github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect - github.com/wlynxg/anet v0.0.5 // indirect - github.com/zeebo/blake3 v0.2.4 // indirect - github.com/zondax/hid v0.9.2 // indirect - github.com/zondax/ledger-go v0.14.3 // indirect - go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect - go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 // indirect - go.opentelemetry.io/otel v1.35.0 // indirect - go.opentelemetry.io/otel/exporters/prometheus v0.44.0 // indirect - go.opentelemetry.io/otel/metric v1.35.0 // indirect - go.opentelemetry.io/otel/sdk v1.34.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.35.0 // indirect - go.opentelemetry.io/proto/otlp v1.3.1 // indirect - go.uber.org/dig v1.19.0 // indirect - go.uber.org/fx v1.24.0 // indirect - go.uber.org/mock v0.5.2 // indirect - go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.0 // indirect - go.uber.org/zap/exp v0.3.0 // indirect - go.yaml.in/yaml/v2 v2.4.2 // indirect - go4.org v0.0.0-20230225012048-214862532bf5 // indirect - golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.42.0 // indirect - golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect - golang.org/x/mod v0.27.0 // indirect - golang.org/x/net v0.43.0 // indirect - golang.org/x/oauth2 v0.30.0 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/sys v0.36.0 // indirect - golang.org/x/term v0.35.0 // indirect - golang.org/x/text v0.29.0 // indirect - golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.36.0 // indirect - golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect - gonum.org/v1/gonum v0.16.0 // indirect - google.golang.org/api v0.186.0 // indirect - google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - gotest.tools/v3 v3.5.1 // indirect - lukechampine.com/blake3 v1.4.1 // indirect - pgregory.net/rapid v1.1.0 // indirect - sigs.k8s.io/yaml v1.5.0 // indirect -) diff --git a/cmd/vault/.cz.toml b/cmd/vault/.cz.toml deleted file mode 100644 index 28bba469e..000000000 --- a/cmd/vault/.cz.toml +++ /dev/null @@ -1,18 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "vault/v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "scm" -update_changelog_on_bump = true -changelog_file = "CHANGELOG.md" -major_version_zero = true -annotated_tag = true -pre_bump_hooks = ["bash scripts/hook-bump-pre.sh"] -post_bump_hooks = ["goreleaser release --clean -f cmd/vault/.goreleaser.yml"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(vault\\)(!)?:" diff --git a/cmd/vault/.goreleaser.yml b/cmd/vault/.goreleaser.yml deleted file mode 100644 index 5d15faf15..000000000 --- a/cmd/vault/.goreleaser.yml +++ /dev/null @@ -1,71 +0,0 @@ -# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json ---- -version: 2 -dist: dist/vault -monorepo: - tag_prefix: vault/ - dir: cmd/vault - -project_name: vault -before: - hooks: - - go mod download - -builds: - - id: vault - main: main.go - binary: vault - no_unique_dist_dir: true - hooks: - post: - - cp dist/vault/vault.wasm x/dwn/client/plugin/vault.wasm - - cp dist/vault/vault.wasm packages/es/src/plugin/plugin.wasm - mod_timestamp: "{{ .CommitTimestamp }}" - env: - - CGO_ENABLED=0 - goos: - - wasip1 - goarch: - - wasm - flags: - - -mod=readonly - - -trimpath - ldflags: - - -s -w - - -X main.version={{.Version}} - - -X main.commit={{.Commit}} - - -X main.date={{.Date}} - -archives: - - id: vault-wasm-archive - name_template: "vault_wasm_{{ .Version }}" - formats: ["binary"] - wrap_in_directory: true - -blobs: - - provider: s3 - endpoint: https://eb37925850388bca807b7fab964c12bb.r2.cloudflarestorage.com - bucket: releases - region: auto - directory: "vault/{{ .Tag }}" - -release: - disable: false - github: - owner: sonr-io - name: sonr - name_template: "{{.ProjectName}}/{{ .Tag }}" - draft: false - replace_existing_draft: false # Don't replace drafts - replace_existing_artifacts: false # Append, don't replace - mode: append # Explicitly set to append mode - -checksum: - name_template: "vault_checksums.txt" - -snapshot: - version_template: "{{ incpatch .Version }}-dev" - -# Changelog configuration -changelog: - sort: asc diff --git a/cmd/vault/CHANGELOG.md b/cmd/vault/CHANGELOG.md deleted file mode 100644 index b6342ce9b..000000000 --- a/cmd/vault/CHANGELOG.md +++ /dev/null @@ -1,6 +0,0 @@ -## vault/v0.0.2 (2025-10-04) - -## vault/v0.0.1 (2025-10-03) - - -- feat(vault): introduce assembly of the initial vault diff --git a/cmd/vault/Makefile b/cmd/vault/Makefile deleted file mode 100644 index 354cb6db1..000000000 --- a/cmd/vault/Makefile +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/make -f - -# Output configuration - dual output for both plugin and ES package -GIT_ROOT := $(shell git rev-parse --show-toplevel) -PLUGIN_DIR := $(GIT_ROOT)/x/dwn/client/plugin -ES_PACKAGE_DIR := $(GIT_ROOT)/packages/es/src/plugin -OUTPUT_FILE := plugin.wasm -PLUGIN_PATH := $(PLUGIN_DIR)/vault.wasm -ES_PATH := $(ES_PACKAGE_DIR)/$(OUTPUT_FILE) - -# Build configuration for WASM -GOOS := wasip1 -GOARCH := wasm - -# Version information -VERSION := $(shell echo $(shell git describe --tags 2>/dev/null || echo "dev") | sed 's/^v//') -COMMIT := $(shell git log -1 --format='%H') - -.PHONY: all build clean install test version help - -all: build - -build: - @echo "Building vault WASM module..." - @echo "Targets: Plugin and ES package" - @mkdir -p $(PLUGIN_DIR) - @mkdir -p $(ES_PACKAGE_DIR) - @GOOS=$(GOOS) GOARCH=$(GOARCH) go build -o $(PLUGIN_PATH) main.go - @cp $(PLUGIN_PATH) $(ES_PATH) - @echo "✅ Vault WASM module built successfully" - @echo "Plugin output: $(PLUGIN_PATH)" - @echo "ES package output: $(ES_PATH)" - @ls -lh $(PLUGIN_PATH) | awk '{print "Plugin size: " $$5}' - @ls -lh $(ES_PATH) | awk '{print "ES package size: " $$5}' - -tidy: - @echo "Tidying vault build artifacts..." - @go mod tidy - @echo "✅ Tidy complete" - -test: - @echo "Running vault tests..." - @go test -v ./... - @cd $(GIT_ROOT) && go test -C . -mod=readonly -v github.com/sonr-io/sonr/x/dwn/client/plugin/... - -clean: - @echo "Cleaning vault build artifacts..." - @rm -f $(PLUGIN_PATH) - @rm -f $(ES_PATH) - @echo "✅ Clean complete" - -release: - @echo "Creating vault release..." - @cd $(GIT_ROOT) && cz --config cmd/vault/.cz.toml --no-raise 6,21 bump --yes --increment PATCH - -snapshot: - @echo "Dry-Run Bumping Vault version..." - @cd $(GIT_ROOT) && cz --config cmd/vault/.cz.toml bump --yes --dry-run --no-verify --increment PATCH - @echo "Creating vault snapshots for all platforms..." - @cd $(GIT_ROOT) && goreleaser release --snapshot --clean -f cmd/vault/.goreleaser.yml - -version: - @echo "Vault WASM Module" - @echo "=================" - @echo "Version: $(VERSION)" - @echo "Commit: $(COMMIT)" - @echo "Target OS: $(GOOS)" - @echo "Target Arch: $(GOARCH)" - @echo "Plugin output: $(PLUGIN_PATH)" - @echo "ES output: $(ES_PATH)" - -verify: build - @echo "Verifying WASM modules..." - @if [ -f "$(PLUGIN_PATH)" ]; then \ - file "$(PLUGIN_PATH)"; \ - echo "✅ Plugin WASM file exists"; \ - else \ - echo "❌ Plugin WASM file not found"; \ - exit 1; \ - fi - @if [ -f "$(ES_PATH)" ]; then \ - file "$(ES_PATH)"; \ - echo "✅ ES package WASM file exists"; \ - else \ - echo "❌ ES package WASM file not found"; \ - exit 1; \ - fi - @echo "Plugin size: $$(du -h $(PLUGIN_PATH) | cut -f1)" - @echo "ES size: $$(du -h $(ES_PATH) | cut -f1)" - @echo "✅ Verification complete" - -help: - @echo "Vault WASM Module Makefile" - @echo "==========================" - @echo "" - @echo "This Makefile builds the vault WebAssembly module for both the" - @echo "Sonr blockchain plugin system and the @sonr.io/es package." - @echo "" - @echo "Available targets:" - @echo " build - Build vault WASM module (default)" - @echo " clean - Remove built WASM artifacts" - @echo " test - Run vault tests" - @echo " tidy - Tidy Go module dependencies" - @echo " version - Display version information" - @echo " verify - Build and verify the WASM modules" - @echo " help - Show this help message" - @echo "" - @echo "Output locations:" - @echo " Plugin: $(PLUGIN_PATH)" - @echo " ES Package: $(ES_PATH)" - @echo "" - @echo "Integration:" - @echo " The WASM module is built for two purposes:" - @echo " 1. Plugin system in x/dwn/client/plugin" - @echo " 2. ES package for browser distribution via jsDelivr" - @echo "" - @echo "Examples:" - @echo " make build # Build WASM module to both locations" - @echo " make verify # Build and verify both outputs" - @echo " make clean # Remove all artifacts" diff --git a/cmd/vault/README.md b/cmd/vault/README.md deleted file mode 100644 index 61cc487eb..000000000 --- a/cmd/vault/README.md +++ /dev/null @@ -1,477 +0,0 @@ -# Vault - WebAssembly Vault Plugin - -Vault is a WebAssembly-based vault system for the Sonr blockchain that provides secure, isolated execution of cryptographic operations. Built using the Extism framework, Vault enables secure multi-party computation (MPC) and vault management within a sandboxed WebAssembly environment. - -## Overview - -Vault serves as a cryptographic vault system that: - -- Provides secure enclave-based key generation and management -- Supports multi-chain transaction signing (Cosmos, EVM) -- Implements WebAuthn-based authentication -- Offers secure import/export functionality via IPFS -- Enables isolated execution through WebAssembly - -## Architecture - -### Core Components - -- **MPC Enclave**: Multi-party computation system for secure key operations -- **Vault Management**: Create, unlock, and manage cryptographic vaults -- **IPFS Integration**: Secure backup and restore of encrypted vault data -- **WebAuthn Support**: Passwordless authentication for vault operations -- **Multi-Chain Support**: Transaction signing for different blockchain networks - -### Build Configuration - -Vault is built specifically for WebAssembly: - -```go -//go:build js && wasm -// +build js,wasm -``` - -## API Reference - -### Core Enclave Operations - -#### `generate` - -```go -//go:wasmexport generate -func generate() int32 -``` - -Creates a new MPC enclave and returns the enclave data and public key. - -**Input**: `GenerateRequest` - -```json -{ - "id": "string" -} -``` - -**Output**: `GenerateResponse` - -```json -{ - "data": "EnclaveData", - "public_key": "[]byte" -} -``` - -#### `refresh` - -```go -//go:wasmexport refresh -func refresh() int32 -``` - -Refreshes an existing enclave with new cryptographic material. - -**Input**: `RefreshRequest` - -```json -{ - "enclave": "EnclaveData" -} -``` - -**Output**: `RefreshResponse` - -```json -{ - "okay": "bool", - "data": "EnclaveData" -} -``` - -#### `sign` - -```go -//go:wasmexport sign -func sign() int32 -``` - -Signs a message using the enclave's private key. - -**Input**: `SignRequest` - -```json -{ - "message": "[]byte", - "enclave": "EnclaveData" -} -``` - -**Output**: `SignResponse` - -```json -{ - "signature": "[]byte" -} -``` - -#### `verify` - -```go -//go:wasmexport verify -func verify() int32 -``` - -Verifies a signature against a message and public key. - -**Input**: `VerifyRequest` - -```json -{ - "public_key": "[]byte", - "message": "[]byte", - "signature": "[]byte" -} -``` - -**Output**: `VerifyResponse` - -```json -{ - "valid": "bool" -} -``` - -### Vault Import/Export Operations - -#### `export` - -```go -//go:wasmexport export -func export() int32 -``` - -Encrypts and exports vault data to IPFS, returning a Content ID (CID). - -**Input**: `ExportRequest` - -```json -{ - "enclave": "EnclaveData", - "password": "[]byte" -} -``` - -**Output**: `ExportResponse` - -```json -{ - "cid": "string", - "success": "bool" -} -``` - -#### `import` - -```go -//go:wasmexport import -func importVault() int32 -``` - -Retrieves and decrypts vault data from IPFS using a CID and password. - -**Input**: `ImportRequest` - -```json -{ - "cid": "string", - "password": "[]byte" -} -``` - -**Output**: `ImportResponse` - -```json -{ - "enclave": "EnclaveData", - "success": "bool" -} -``` - -### Advanced Vault Operations - -#### `create_vault_enclave` - -```go -//go:wasmexport create_vault_enclave -func createVaultEnclave() int32 -``` - -Creates a new vault enclave with advanced configuration options. - -**Input**: `EnclaveConfig` - -```json -{ - "vault_id": "string", - "key_derivation_method": "string", - "encryption_algorithm": "string", - "signing_algorithm": "string", - "webauthn_enabled": "bool", - "auto_lock_timeout": "int64", - "key_rotation_interval": "int64", - "supported_chains": ["string"], - "max_concurrent_ops": "int", - "memory_limit": "uint64" -} -``` - -#### `unlock_vault_enclave` - -```go -//go:wasmexport unlock_vault_enclave -func unlockVaultEnclave() int32 -``` - -Unlocks a vault enclave, optionally using WebAuthn authentication. - -#### `lock_vault_enclave` - -```go -//go:wasmexport lock_vault_enclave -func lockVaultEnclave() int32 -``` - -Locks a vault enclave to prevent unauthorized access. - -#### `rotate_vault_key` - -```go -//go:wasmexport rotate_vault_key -func rotateVaultKey() int32 -``` - -Rotates the cryptographic keys within a vault enclave. - -### Multi-Chain Transaction Signing - -#### `sign_cosmos_transaction` - -```go -//go:wasmexport sign_cosmos_transaction -func signCosmosTransaction() int32 -``` - -Signs transactions for Cosmos SDK-based blockchains. - -#### `sign_evm_transaction` - -```go -//go:wasmexport sign_evm_transaction -func signEvmTransaction() int32 -``` - -Signs transactions for Ethereum Virtual Machine compatible chains. - -#### `sign_message` - -```go -//go:wasmexport sign_message -func signMessage() int32 -``` - -Signs arbitrary messages using the vault's private key. - -### Health and Monitoring - -#### `get_vault_health` - -```go -//go:wasmexport get_vault_health -func getVaultHealth() int32 -``` - -Returns the health status of a vault enclave. - -**Output**: `EnclaveHealth` - -```json -{ - "vault_id": "string", - "status": "string", - "last_activity": "int64", - "key_rotation_due": "bool", - "attestation_valid": "bool" -} -``` - -## Configuration - -### Environment Variables - -Motor supports configuration through Extism variables: - -- `chain_id`: Blockchain network identifier (default: "sonr-testnet-1") -- `password`: Default password for enclave operations (default: "password") -- `gateway`: IPFS gateway URL (default: "https://ipfs.did.run/ipfs/") - -Access these via helper functions: - -```go -func GetChainID() string -func GetPassword() []byte -func GetGateway() string -``` - -### IPFS Integration - -Motor integrates with IPFS for secure vault backup and restore: - -- **Storage Endpoint**: `http://127.0.0.1:5001/api/v0/add` -- **Retrieval Endpoint**: `http://127.0.0.1:5001/api/v0/cat` -- **Data Format**: Encrypted vault data stored as content-addressed objects -- **Security**: All vault data is encrypted before IPFS storage - -## Security Features - -### Enclave Isolation - -- WebAssembly sandbox provides memory isolation -- Secure execution environment prevents side-channel attacks -- Attestation mechanisms ensure enclave integrity - -### Authentication - -- WebAuthn support for passwordless authentication -- Challenge-response authentication flows -- Automatic vault locking with configurable timeouts - -### Key Management - -- Multi-party computation for enhanced security -- Automatic key rotation with configurable intervals -- Secure key derivation and storage - -### Data Protection - -- AES encryption for sensitive data -- Password-based encryption for import/export -- Secure memory handling within WASM environment - -## Usage Examples - -### Basic Enclave Operations - -```javascript -// Generate new enclave -const generateReq = { id: "my-vault" }; -const result = call_wasm_function("generate", generateReq); - -// Sign a message -const signReq = { - message: new Uint8Array([1, 2, 3, 4]), - enclave: result.data, -}; -const signature = call_wasm_function("sign", signReq); -``` - -### Vault Management - -```javascript -// Create vault with configuration -const config = { - vault_id: "user-vault-001", - webauthn_enabled: true, - auto_lock_timeout: 300, - supported_chains: ["cosmos", "ethereum"], -}; -const vault = call_wasm_function("create_vault_enclave", config); - -// Sign Cosmos transaction -const cosmosReq = { - vault_id: "user-vault-001", - chain_type: "cosmos", - chain_id: "cosmoshub-4", - message: transactionBytes, -}; -const cosmosResult = call_wasm_function("sign_cosmos_transaction", cosmosReq); -``` - -### Import/Export Operations - -```javascript -// Export vault to IPFS -const exportReq = { - enclave: vaultData, - password: new Uint8Array([ - /* password bytes */ - ]), -}; -const exportResult = call_wasm_function("export", exportReq); -console.log("Vault exported to CID:", exportResult.cid); - -// Import vault from IPFS -const importReq = { - cid: "QmXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx", - password: new Uint8Array([ - /* password bytes */ - ]), -}; -const importResult = call_wasm_function("import", importReq); -``` - -## Building and Deployment - -### Prerequisites - -- Go 1.24.4+ -- Extism runtime -- IPFS node (for import/export functionality) - -### Build Commands - -```bash -# Build WebAssembly module -GOOS=js GOARCH=wasm go build -o motr.wasm main.go - -# Build via Makefile -make motr -``` - -### Integration - -Motor is designed to be integrated with: - -- **Highway Service**: PostgreSQL-backed HTTP API -- **Sonr Blockchain**: Cosmos SDK-based blockchain node -- **IPFS Network**: Decentralized storage system -- **WebAuthn Infrastructure**: Passwordless authentication - -## Error Handling - -All functions return `int32` status codes: - -- `0`: Success -- `1`: Error (details available via `pdk.SetError`) - -Error information is logged using Extism's logging system: - -```go -pdk.Log(pdk.LogError, "Error message") -pdk.Log(pdk.LogInfo, "Info message") -``` - -## Dependencies - -### Core Dependencies - -- `github.com/extism/go-pdk`: WebAssembly plugin development kit -- `github.com/sonr-io/sonr/crypto/mpc`: Multi-party computation library - -### Cryptographic Libraries - -- `filippo.io/edwards25519`: Edwards25519 elliptic curve -- `github.com/btcsuite/btcd/btcec/v2`: Bitcoin cryptography -- `github.com/consensys/gnark-crypto`: Zero-knowledge proof cryptography - -## License - -Motor is part of the Sonr blockchain project. See the project's main license for terms and conditions. diff --git a/cmd/vault/go.mod b/cmd/vault/go.mod deleted file mode 100644 index fa976373c..000000000 --- a/cmd/vault/go.mod +++ /dev/null @@ -1,26 +0,0 @@ -module vault - -go 1.24.7 - -replace github.com/sonr-io/sonr/crypto => ../../crypto/ - -require ( - github.com/extism/go-pdk v1.1.3 - github.com/golang-jwt/jwt/v5 v5.3.0 - github.com/sonr-io/sonr/crypto v0.0.0-00010101000000-000000000000 -) - -require ( - filippo.io/edwards25519 v1.1.0 // indirect - github.com/bits-and-blooms/bitset v1.24.0 // indirect - github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect - github.com/bwesterb/go-ristretto v1.2.3 // indirect - github.com/consensys/gnark-crypto v0.19.0 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect - github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 // indirect - github.com/gtank/merlin v0.1.1 // indirect - github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect - github.com/pkg/errors v0.9.1 // indirect - golang.org/x/crypto v0.42.0 // indirect - golang.org/x/sys v0.36.0 // indirect -) diff --git a/cmd/vault/go.sum b/cmd/vault/go.sum deleted file mode 100644 index 8d77e9d75..000000000 --- a/cmd/vault/go.sum +++ /dev/null @@ -1,38 +0,0 @@ -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/bits-and-blooms/bitset v1.24.0 h1:H4x4TuulnokZKvHLfzVRTHJfFfnHEeSYJizujEZvmAM= -github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= -github.com/btcsuite/btcd/btcec/v2 v2.3.4 h1:3EJjcN70HCu/mwqlUsGK8GcNVyLVxFDlWurTXGPFfiQ= -github.com/btcsuite/btcd/btcec/v2 v2.3.4/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= -github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw= -github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/consensys/gnark-crypto v0.19.0 h1:zXCqeY2txSaMl6G5wFpZzMWJU9HPNh8qxPnYJ1BL9vA= -github.com/consensys/gnark-crypto v0.19.0/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= -github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 h1:I6KUy4CI6hHjqnyJLNCEi7YHVMkwwtfSr2k9splgdSM= -github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564/go.mod h1:yekO+3ZShy19S+bsmnERmznGy9Rfg6dWWWpiGJjNAz8= -github.com/extism/go-pdk v1.1.3 h1:hfViMPWrqjN6u67cIYRALZTZLk/enSPpNKa+rZ9X2SQ= -github.com/extism/go-pdk v1.1.3/go.mod h1:Gz+LIU/YCKnKXhgge8yo5Yu1F/lbv7KtKFkiCSzW/P4= -github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= -github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= -github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= -github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= -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/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= -github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/cmd/vault/main.go b/cmd/vault/main.go deleted file mode 100644 index 7f6ada21f..000000000 --- a/cmd/vault/main.go +++ /dev/null @@ -1,483 +0,0 @@ -//go:build js && wasm -// +build js,wasm - -package main - -import ( - "crypto/sha256" - "encoding/json" - "fmt" - "time" - - "github.com/extism/go-pdk" - "github.com/golang-jwt/jwt/v5" - "github.com/sonr-io/sonr/crypto/mpc" -) - -const ( - KeyChainID = "chain_id" - KeyEnclave = "enclave" - KeyVaultConfig = "vault_config" -) - -// GetChainID returns the chain ID to use for unlocking the enclave -func GetChainID() string { - v := pdk.GetVar(KeyChainID) - if v == nil { - return "sonr-testnet-1" - } - return string(v) -} - -// GetEnclaveData loads MPC enclave data from PDK environment -func GetEnclaveData() (*mpc.EnclaveData, error) { - v := pdk.GetVar(KeyEnclave) - if v == nil { - return nil, fmt.Errorf("enclave data not provided in environment") - } - - var data mpc.EnclaveData - if err := json.Unmarshal(v, &data); err != nil { - return nil, fmt.Errorf("failed to unmarshal enclave data: %w", err) - } - - return &data, nil -} - -// GetVaultConfig loads vault configuration from PDK environment -func GetVaultConfig() map[string]any { - v := pdk.GetVar(KeyVaultConfig) - if v == nil { - return make(map[string]any) - } - - var config map[string]any - if err := json.Unmarshal(v, &config); err != nil { - pdk.Log(pdk.LogWarn, fmt.Sprintf("Failed to parse vault config: %v", err)) - return make(map[string]any) - } - - return config -} - -// UCAN Token Request/Response types -type NewOriginTokenRequest struct { - AudienceDID string `json:"audience_did"` - Attenuations []map[string]any `json:"attenuations,omitempty"` - Facts []string `json:"facts,omitempty"` - NotBefore int64 `json:"not_before,omitempty"` - ExpiresAt int64 `json:"expires_at,omitempty"` -} - -type NewAttenuatedTokenRequest struct { - ParentToken string `json:"parent_token"` - AudienceDID string `json:"audience_did"` - Attenuations []map[string]any `json:"attenuations,omitempty"` - Facts []string `json:"facts,omitempty"` - NotBefore int64 `json:"not_before,omitempty"` - ExpiresAt int64 `json:"expires_at,omitempty"` -} - -type UCANTokenResponse struct { - Token string `json:"token"` - Issuer string `json:"issuer"` - Address string `json:"address"` - Error string `json:"error,omitempty"` -} - -type SignDataRequest struct { - Data []byte `json:"data"` -} - -type SignDataResponse struct { - Signature []byte `json:"signature"` - Error string `json:"error,omitempty"` -} - -type VerifyDataRequest struct { - Data []byte `json:"data"` - Signature []byte `json:"signature"` -} - -type VerifyDataResponse struct { - Valid bool `json:"valid"` - Error string `json:"error,omitempty"` -} - -type GetIssuerDIDResponse struct { - IssuerDID string `json:"issuer_did"` - Address string `json:"address"` - ChainCode string `json:"chain_code"` - Error string `json:"error,omitempty"` -} - -var ( - enclave mpc.Enclave - issuerDID string - address string -) - -func main() { - // Initialize MPC enclave from PDK environment - if err := initializeEnclave(); err != nil { - pdk.SetError(fmt.Errorf("failed to initialize enclave: %w", err)) - return - } - pdk.Log(pdk.LogInfo, "Motor plugin initialized as MPC-based UCAN source") -} - -// initializeEnclave initializes the MPC enclave from PDK environment -func initializeEnclave() error { - // Load enclave data from PDK environment - enclaveData, err := GetEnclaveData() - if err != nil { - return fmt.Errorf("failed to get enclave data: %w", err) - } - - // Import MPC enclave from data - enclave, err = mpc.ImportEnclave(mpc.WithEnclaveData(enclaveData)) - if err != nil { - return fmt.Errorf("failed to import enclave: %w", err) - } - - // Derive issuer DID and address from enclave public key - pubKeyBytes := enclave.PubKeyBytes() - issuerDID, address, err = deriveIssuerDIDFromBytes(pubKeyBytes) - if err != nil { - return fmt.Errorf("failed to derive issuer DID: %w", err) - } - return nil -} - -//go:wasmexport new_origin_token -func newOriginToken() int32 { - if !enclave.IsValid() { - pdk.SetError(fmt.Errorf("enclave not initialized")) - return 1 - } - - req := &NewOriginTokenRequest{} - err := pdk.InputJSON(req) - if err != nil { - pdk.SetError(fmt.Errorf("failed to parse request: %w", err)) - return 1 - } - - // Convert timestamps - var notBefore, expiresAt time.Time - if req.NotBefore > 0 { - notBefore = time.Unix(req.NotBefore, 0) - } - if req.ExpiresAt > 0 { - expiresAt = time.Unix(req.ExpiresAt, 0) - } - - // Create origin token using MPC signing - tokenString, err := createUCANToken( - req.AudienceDID, - nil, - req.Attenuations, - req.Facts, - notBefore, - expiresAt, - ) - if err != nil { - resp := &UCANTokenResponse{Error: err.Error()} - pdk.OutputJSON(resp) - return 1 - } - - resp := &UCANTokenResponse{ - Token: tokenString, - Issuer: issuerDID, - Address: address, - } - pdk.OutputJSON(resp) - return 0 -} - -//go:wasmexport new_attenuated_token -func newAttenuatedToken() int32 { - if !enclave.IsValid() { - pdk.SetError(fmt.Errorf("enclave not initialized")) - return 1 - } - - req := &NewAttenuatedTokenRequest{} - err := pdk.InputJSON(req) - if err != nil { - pdk.SetError(fmt.Errorf("failed to parse request: %w", err)) - return 1 - } - - // Convert timestamps - var notBefore, expiresAt time.Time - if req.NotBefore > 0 { - notBefore = time.Unix(req.NotBefore, 0) - } - if req.ExpiresAt > 0 { - expiresAt = time.Unix(req.ExpiresAt, 0) - } - - // Create proofs from parent token - proofs := []string{req.ParentToken} - - // Create attenuated token using MPC signing - tokenString, err := createUCANToken( - req.AudienceDID, - proofs, - req.Attenuations, - req.Facts, - notBefore, - expiresAt, - ) - if err != nil { - resp := &UCANTokenResponse{Error: err.Error()} - pdk.OutputJSON(resp) - return 1 - } - - resp := &UCANTokenResponse{ - Token: tokenString, - Issuer: issuerDID, - Address: address, - } - pdk.OutputJSON(resp) - return 0 -} - -//go:wasmexport sign_data -func signData() int32 { - if !enclave.IsValid() { - pdk.SetError(fmt.Errorf("enclave not initialized")) - return 1 - } - - req := &SignDataRequest{} - err := pdk.InputJSON(req) - if err != nil { - pdk.SetError(fmt.Errorf("failed to parse request: %w", err)) - return 1 - } - - // Sign data using MPC enclave - signature, err := enclave.Sign(req.Data) - if err != nil { - resp := &SignDataResponse{Error: err.Error()} - pdk.OutputJSON(resp) - return 1 - } - - resp := &SignDataResponse{Signature: signature} - pdk.OutputJSON(resp) - return 0 -} - -//go:wasmexport verify_data -func verifyData() int32 { - if !enclave.IsValid() { - pdk.SetError(fmt.Errorf("enclave not initialized")) - return 1 - } - - req := &VerifyDataRequest{} - err := pdk.InputJSON(req) - if err != nil { - pdk.SetError(fmt.Errorf("failed to parse request: %w", err)) - return 1 - } - - // Verify data using MPC enclave - valid, err := enclave.Verify(req.Data, req.Signature) - if err != nil { - resp := &VerifyDataResponse{Error: err.Error()} - pdk.OutputJSON(resp) - return 1 - } - - resp := &VerifyDataResponse{Valid: valid} - pdk.OutputJSON(resp) - return 0 -} - -//go:wasmexport get_issuer_did -func getIssuerDID() int32 { - if !enclave.IsValid() { - pdk.SetError(fmt.Errorf("enclave not initialized")) - return 1 - } - - // Get chain code for deterministic derivation - chainCode, err := getChainCode() - if err != nil { - resp := &GetIssuerDIDResponse{Error: err.Error()} - pdk.OutputJSON(resp) - return 1 - } - - resp := &GetIssuerDIDResponse{ - IssuerDID: issuerDID, - Address: address, - ChainCode: fmt.Sprintf("%x", chainCode), - } - pdk.OutputJSON(resp) - return 0 -} - -// UCAN token creation and MPC signing implementation - -// MPCSigningMethod implements JWT signing using MPC enclaves -type MPCSigningMethod struct { - Name string - enclave mpc.Enclave -} - -// Alg returns the signing method algorithm name -func (m *MPCSigningMethod) Alg() string { - return m.Name -} - -// Sign signs a JWT string using the MPC enclave -func (m *MPCSigningMethod) Sign(signingString string, key any) ([]byte, error) { - // Hash the signing string - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to sign the digest - sig, err := m.enclave.Sign(digest) - if err != nil { - return nil, fmt.Errorf("failed to sign with MPC: %w", err) - } - - return sig, nil -} - -// Verify verifies a JWT signature using the MPC enclave -func (m *MPCSigningMethod) Verify(signingString string, sig []byte, key any) error { - // Hash the signing string - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to verify signature - valid, err := m.enclave.Verify(digest, sig) - if err != nil { - return fmt.Errorf("failed to verify signature: %w", err) - } - - if !valid { - return fmt.Errorf("signature verification failed") - } - - return nil -} - -// createUCANToken creates a UCAN token using MPC signing -func createUCANToken( - audienceDID string, - proofs []string, - attenuations []map[string]any, - facts []string, - notBefore, expiresAt time.Time, -) (string, error) { - // Validate audience DID - if audienceDID == "" { - return "", fmt.Errorf("audience DID is required") - } - - // Create MPC signing method - signingMethod := &MPCSigningMethod{ - Name: "MPC256", - enclave: enclave, - } - - // Create JWT token - token := jwt.New(signingMethod) - - // Set UCAN version in header - token.Header["ucv"] = "0.9.0" - - // Prepare time claims - var nbfUnix, expUnix int64 - if !notBefore.IsZero() { - nbfUnix = notBefore.Unix() - } - if !expiresAt.IsZero() { - expUnix = expiresAt.Unix() - } - - // Set claims - claims := jwt.MapClaims{ - "iss": issuerDID, - "aud": audienceDID, - } - - // Add attenuations if provided - if len(attenuations) > 0 { - claims["att"] = attenuations - } - - // Add proofs if provided - if len(proofs) > 0 { - claims["prf"] = proofs - } - - // Add facts if provided - if len(facts) > 0 { - claims["fct"] = facts - } - - // Add time claims - if nbfUnix > 0 { - claims["nbf"] = nbfUnix - } - if expUnix > 0 { - claims["exp"] = expUnix - } - - token.Claims = claims - - // Sign the token using MPC enclave (key parameter is ignored for MPC signing) - tokenString, err := token.SignedString(nil) - if err != nil { - return "", fmt.Errorf("failed to sign token with MPC: %w", err) - } - - return tokenString, nil -} - -// deriveIssuerDIDFromBytes creates issuer DID and address from public key bytes -func deriveIssuerDIDFromBytes(pubKeyBytes []byte) (string, string, error) { - if len(pubKeyBytes) == 0 { - return "", "", fmt.Errorf("empty public key bytes") - } - - // Generate address from public key (simplified implementation) - address := fmt.Sprintf("sonr1%x", pubKeyBytes[:20]) - - // Create DID from address (simplified implementation) - issuerDID := fmt.Sprintf("did:sonr:%s", address) - - return issuerDID, address, nil -} - -// getChainCode derives a deterministic chain code from the enclave -func getChainCode() ([]byte, error) { - if !enclave.IsValid() { - return nil, fmt.Errorf("enclave is not valid") - } - - // Sign the address to create a deterministic chain code - sig, err := enclave.Sign([]byte(address)) - if err != nil { - return nil, fmt.Errorf("failed to sign address for chain code: %w", err) - } - - // Hash the signature to create a 32-byte chain code - hasher := sha256.New() - hasher.Write(sig) - hash := hasher.Sum(nil) - - return hash[:32], nil -} diff --git a/cmd/vault/version.go b/cmd/vault/version.go deleted file mode 100644 index a5a16c0a9..000000000 --- a/cmd/vault/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package main - -// Version is set by commitizen during release process -var Version = "dev" diff --git a/contracts/DAO/COMPLIANCE.md b/contracts/DAO/COMPLIANCE.md deleted file mode 100644 index 542926073..000000000 --- a/contracts/DAO/COMPLIANCE.md +++ /dev/null @@ -1,353 +0,0 @@ -# Wyoming DAO Compliance Verification - -## Executive Summary - -This document verifies that the Identity DAO implementation complies with Wyoming's Decentralized Autonomous Organization (DAO) legal framework under W.S. 17-31-101 through 17-31-116, ensuring the DAO can operate as a legally recognized entity. - -## Wyoming DAO Requirements Checklist - -### ✅ Formation Requirements (W.S. 17-31-104) - -#### 1. Named Entity -**Requirement**: The DAO must have a publicly stated name -**Implementation**: ✅ Complete -```rust -// contracts/core/src/state.rs -pub struct Config { - pub dao_name: String, // "Sonr Identity DAO" - pub dao_uri: String, // "https://sonr.io/dao" - // ... -} -``` - -#### 2. Public Address -**Requirement**: Maintain a publicly available address -**Implementation**: ✅ Complete -- Smart contract addresses on Cosmos Hub are immutable and public -- Deployment addresses stored in `artifacts/addresses.json` -- Published in documentation and on-chain metadata - -#### 3. Member Registry -**Requirement**: Maintain a record of members -**Implementation**: ✅ Complete -```rust -// contracts/voting/src/state.rs -pub const VOTERS: Map<&Addr, VoterInfo> = Map::new("voters"); -pub const DID_REGISTRY: Map<&str, Addr> = Map::new("did_registry"); -``` - -### ✅ Governance Requirements (W.S. 17-31-105) - -#### 1. Voting Mechanism -**Requirement**: Clear voting procedures and member rights -**Implementation**: ✅ Complete -```rust -// contracts/voting/src/contract.rs -pub fn execute_vote( - deps: DepsMut, - env: Env, - info: MessageInfo, - proposal_id: u64, - vote: Vote, -) -> Result -``` - -**Voting Rights Matrix**: -| Verification Level | Vote Weight | Proposal Rights | -|-------------------|-------------|-----------------| -| Basic (Level 1) | 1x | Standard | -| Advanced (Level 2) | 2x | Policy | -| Full (Level 3) | 3x | All | - -#### 2. Proposal Process -**Requirement**: Defined proposal submission and execution process -**Implementation**: ✅ Complete -- Pre-proposal review system -- Time-bound voting periods -- Automatic execution of passed proposals -- Transparent proposal lifecycle - -#### 3. Record Keeping -**Requirement**: Maintain governance records -**Implementation**: ✅ Complete -```rust -// All votes and proposals stored on-chain -pub const PROPOSALS: Map = Map::new("proposals"); -pub const VOTES: Map<(u64, &Addr), VoteInfo> = Map::new("votes"); -``` - -### ✅ Management Structure (W.S. 17-31-106) - -#### 1. Algorithmically Managed -**Requirement**: Can be algorithmically managed through smart contracts -**Implementation**: ✅ Complete -- Fully autonomous operation via smart contracts -- No requirement for human intervention in normal operations -- Automatic proposal execution - -#### 2. Administrator Rights -**Requirement**: Clear admin/management structure -**Implementation**: ✅ Complete -```rust -pub struct Config { - pub admin: Addr, // Can be DAO itself for full decentralization - pub proposal_modules: Vec, - pub voting_module: Addr, -} -``` - -### ✅ Member Rights (W.S. 17-31-107) - -#### 1. Inspection Rights -**Requirement**: Members can inspect DAO records -**Implementation**: ✅ Complete -- All data queryable on-chain -- Public query endpoints for all state - -#### 2. Information Rights -**Requirement**: Access to DAO information -**Implementation**: ✅ Complete -```rust -// Query endpoints provide full transparency -pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { - match msg { - QueryMsg::Config {} => to_json_binary(&query_config(deps)?), - QueryMsg::Proposal { id } => to_json_binary(&query_proposal(deps, id)?), - QueryMsg::ListProposals { ... } => to_json_binary(&query_proposals(deps, ...)?), - // ... all state queryable - } -} -``` - -#### 3. Withdrawal Rights -**Requirement**: Member withdrawal procedures -**Implementation**: ✅ Complete -- Members can withdraw pending proposals -- Refund mechanisms for deposits -- No locked voting periods - -### ✅ Dispute Resolution (W.S. 17-31-108) - -#### 1. On-Chain Resolution -**Requirement**: Dispute resolution mechanism -**Implementation**: ✅ Complete -- Governance proposals for dispute resolution -- Multi-signature approval for critical decisions -- Transparent voting on disputes - -#### 2. Alternative Dispute Resolution -**Requirement**: May include arbitration clauses -**Implementation**: ✅ Complete -```rust -// Configurable dispute resolution via governance -pub enum ProposalMessage { - DisputeResolution { - case_id: String, - resolution: String, - affected_parties: Vec, - }, - // ... -} -``` - -### ✅ Operating Agreement (W.S. 17-31-109) - -#### 1. Smart Contract as Operating Agreement -**Requirement**: Operating agreement can be algorithmic -**Implementation**: ✅ Complete -- Smart contract code serves as operating agreement -- Immutable rules unless upgraded via governance -- All terms encoded in contract logic - -#### 2. Amendment Process -**Requirement**: Process for amending operating agreement -**Implementation**: ✅ Complete -```rust -// Migration support for contract upgrades -pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result { - // Only through governance proposal - ensure_approved_by_governance(deps.as_ref(), &msg)?; - // ... migration logic -} -``` - -### ✅ Legal Capacity (W.S. 17-31-110) - -#### 1. Contract Rights -**Requirement**: Ability to enter contracts -**Implementation**: ✅ Complete -- Can hold and transfer assets -- Can execute arbitrary CosmWasm messages -- Can interact with other contracts - -#### 2. Legal Standing -**Requirement**: Sue and be sued -**Implementation**: ✅ Complete -- Named entity with public address -- Identifiable on-chain presence -- Governance-controlled treasury - -### ✅ Taxation (W.S. 17-31-111) - -#### 1. Tax Identification -**Requirement**: May need EIN for US operations -**Implementation**: ⚠️ Off-chain requirement -- Contract stores tax configuration if needed -- Governance can update tax parameters - -#### 2. Tax Reporting -**Requirement**: Maintain records for tax purposes -**Implementation**: ✅ Complete -- All transactions recorded on-chain -- Exportable transaction history -- Treasury tracking - -## Implementation Verification - -### Core Compliance Features - -```rust -// contracts/core/src/msg.rs -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct WyomingDAOConfig { - pub entity_name: String, // ✅ Named entity - pub public_address: Addr, // ✅ Public address - pub formation_date: Timestamp, // ✅ Formation record - pub operating_agreement_uri: String, // ✅ Operating agreement - pub tax_classification: Option, // ✅ Tax status - pub registered_agent: Option, // ✅ Wyoming agent -} - -// contracts/core/src/wyoming.rs -pub fn verify_wyoming_compliance(deps: Deps) -> StdResult { - let config = CONFIG.load(deps.storage)?; - - Ok(ComplianceStatus { - has_name: !config.dao_name.is_empty(), - has_public_address: true, // Always true for contracts - has_member_registry: VOTERS.keys(deps.storage, None, None, Order::Ascending) - .count()? > 0, - has_voting_mechanism: config.voting_module != Addr::unchecked(""), - has_governance_records: true, // On-chain storage - has_dispute_resolution: true, // Via governance - compliant: true, - }) -} -``` - -### Deployment Configuration - -```json -{ - "wyoming_dao_config": { - "entity_name": "Sonr Identity DAO LLC", - "formation_date": "2024-01-01T00:00:00Z", - "operating_agreement_uri": "ipfs://QmXxx...", - "tax_classification": "Partnership", - "registered_agent": "Wyoming Registered Agent LLC", - "registered_address": "30 N Gould St, Sheridan, WY 82801" - } -} -``` - -## Legal Integration Points - -### 1. With Existing Sonr Governance - -The Identity DAO integrates with Sonr's existing governance through: -- IBC channels for cross-chain proposals -- DID-based identity verification -- Shared treasury management protocols - -### 2. With Cosmos Hub Governance - -As deployed on Cosmos Hub: -- Respects Cosmos Hub governance parameters -- Can participate in Hub governance via IBC -- Maintains sovereign decision-making - -## Compliance Monitoring - -### On-Chain Metrics - -```rust -pub fn query_compliance_metrics(deps: Deps) -> StdResult { - Ok(ComplianceMetrics { - total_members: count_members(deps)?, - active_proposals: count_active_proposals(deps)?, - treasury_value: query_treasury_balance(deps)?, - last_activity: get_last_activity(deps)?, - formation_date: CONFIG.load(deps.storage)?.formation_date, - }) -} -``` - -### Off-Chain Requirements - -1. **Annual Report**: File with Wyoming Secretary of State -2. **Registered Agent**: Maintain Wyoming registered agent -3. **Tax Filings**: If applicable based on operations -4. **Legal Notices**: Serve through registered agent - -## Risk Mitigation - -### Legal Risks - -| Risk | Mitigation | -|------|------------| -| Regulatory Uncertainty | Conservative compliance approach | -| Cross-Border Issues | Clear jurisdictional statements | -| Tax Obligations | Governance-controlled tax parameters | -| Liability Concerns | Limited liability through LLC structure | - -### Technical Risks - -| Risk | Mitigation | -|------|------------| -| Smart Contract Bugs | Comprehensive testing and audits | -| Governance Attacks | Sybil resistance via DID verification | -| IBC Failures | Fallback governance mechanisms | - -## Recommendations - -### Immediate Actions - -1. ✅ **Register Wyoming LLC**: File with Wyoming Secretary of State -2. ✅ **Obtain EIN**: If US tax obligations exist -3. ✅ **Appoint Registered Agent**: Required for Wyoming entity -4. ✅ **Publish Operating Agreement**: Make smart contract addresses public - -### Ongoing Compliance - -1. **Annual Filings**: Maintain good standing in Wyoming -2. **Record Keeping**: Export on-chain data periodically -3. **Tax Compliance**: File required returns -4. **Legal Updates**: Monitor Wyoming DAO law changes - -## Conclusion - -The Identity DAO implementation **fully complies** with Wyoming DAO legal requirements as specified in W.S. 17-31-101 through 17-31-116. The smart contract architecture provides: - -✅ **Legal Recognition**: Meets all formation requirements -✅ **Governance Structure**: Complete voting and proposal systems -✅ **Member Rights**: Full transparency and participation -✅ **Operational Autonomy**: Algorithmic management capability -✅ **Legal Capacity**: Can conduct business as legal entity - -The implementation is ready for deployment as a Wyoming DAO LLC, pending only the administrative filing requirements with the Wyoming Secretary of State. - -## Appendix: Legal Resources - -- [Wyoming DAO Law (SF0038)](https://www.wyoleg.gov/2021/Introduced/SF0038.pdf) -- [Wyoming Secretary of State](https://sos.wyo.gov/) -- [DAO LLC Filing Instructions](https://sos.wyo.gov/business/FilingInstructions/DAO_FilingInstructions.pdf) -- [Registered Agent Services](https://www.wyomingagents.com/) - -## Certification - -This compliance verification was conducted based on the Identity DAO smart contract implementation as of the current version. Any modifications to the contracts should be reviewed for continued compliance. - -**Prepared by**: Identity DAO Development Team -**Date**: 2024 -**Version**: 1.0.0 -**Chain**: Cosmos Hub (via IBC to Sonr) \ No newline at end of file diff --git a/contracts/DAO/Cargo.toml b/contracts/DAO/Cargo.toml deleted file mode 100644 index caba07406..000000000 --- a/contracts/DAO/Cargo.toml +++ /dev/null @@ -1,72 +0,0 @@ -[workspace] -resolver = "2" -members = [ - "contracts/core", - "contracts/voting", - "contracts/proposals", - "contracts/pre-propose", - "packages/shared", -] - -[workspace.package] -version = "0.1.0" -edition = "2021" -authors = ["Sonr "] -license = "Apache-2.0" -repository = "https://github.com/sonr-io/sonr" -homepage = "https://sonr.io" -documentation = "https://sonr.dev" - -[workspace.dependencies] -# CosmWasm dependencies -cosmwasm-std = { version = "2.1", features = ["stargate", "staking", "cosmwasm_2_0"] } -cosmwasm-schema = "2.1" -cw2 = "2.0" -cw-storage-plus = "2.0" -cw-utils = "2.0" - -# DAO DAO dependencies for compatibility -dao-interface = "2.6" -dao-voting = "2.6" -dao-dao-macros = "2.6" -dao-pre-propose-base = "2.6" - -# Serialization -serde = { version = "1.0", default-features = false, features = ["derive"] } -serde_json = "1.0" -schemars = "0.8" -thiserror = "2.0" - -# Testing -cw-multi-test = "2.1" -anyhow = "1.0" - -# Shared types -identity-dao-shared = { path = "packages/shared" } - -[profile.release] -opt-level = 3 -debug = false -rpath = false -lto = true -debug-assertions = false -codegen-units = 1 -panic = 'abort' -incremental = false -overflow-checks = true - -[profile.release.package.identity-dao-core] -codegen-units = 1 -opt-level = 3 - -[profile.release.package.identity-dao-voting] -codegen-units = 1 -opt-level = 3 - -[profile.release.package.identity-dao-proposals] -codegen-units = 1 -opt-level = 3 - -[profile.release.package.identity-dao-pre-propose] -codegen-units = 1 -opt-level = 3 \ No newline at end of file diff --git a/contracts/DAO/IBC_INTEGRATION.md b/contracts/DAO/IBC_INTEGRATION.md deleted file mode 100644 index efded5f45..000000000 --- a/contracts/DAO/IBC_INTEGRATION.md +++ /dev/null @@ -1,458 +0,0 @@ -# IBC Integration for Identity DAO - -## Overview - -The Identity DAO will be deployed on Cosmos Hub and communicate with Sonr chain modules via IBC (Inter-Blockchain Communication). This document outlines the IBC integration architecture and implementation details. - -## Architecture - -```mermaid -graph LR - subgraph "Cosmos Hub" - A[Identity DAO Contracts] - B[IBC Light Client] - end - - subgraph "IBC Channel" - C[Relayer] - end - - subgraph "Sonr Chain" - D[x/did Module] - E[x/dwn Module] - F[x/svc Module] - end - - A -->|IBC Query| B - B <-->|Packets| C - C <-->|Packets| D - C <-->|Packets| E - C <-->|Packets| F -``` - -## IBC Channel Configuration - -### Channel Setup - -```bash -# Create IBC channel between Cosmos Hub and Sonr -hermes create channel \ - --a-chain cosmoshub-4 \ - --b-chain sonr-1 \ - --a-port wasm.cosmos1... \ - --b-port did \ - --order unordered \ - --version ics20-1 -``` - -### Connection Parameters - -```json -{ - "channel_id": "channel-xxx", - "port_id": "wasm.cosmos1abc...", - "counterparty_channel_id": "channel-yyy", - "counterparty_port_id": "did", - "connection_id": "connection-xxx", - "version": "ics20-1" -} -``` - -## Contract Modifications for IBC - -### 1. IBC Entry Points - -Add IBC entry points to each contract: - -```rust -// contracts/core/src/ibc.rs -use cosmwasm_std::{ - entry_point, IbcBasicResponse, IbcChannelCloseMsg, IbcChannelConnectMsg, - IbcChannelOpenMsg, IbcChannelOpenResponse, IbcPacketAckMsg, IbcPacketReceiveMsg, - IbcPacketTimeoutMsg, IbcReceiveResponse, Never, -}; - -#[entry_point] -pub fn ibc_channel_open( - _deps: DepsMut, - _env: Env, - msg: IbcChannelOpenMsg, -) -> Result { - // Validate channel parameters - validate_channel(&msg.channel)?; - Ok(None) -} - -#[entry_point] -pub fn ibc_channel_connect( - deps: DepsMut, - _env: Env, - msg: IbcChannelConnectMsg, -) -> Result { - // Store channel info - let channel = msg.channel(); - CHANNEL_INFO.save(deps.storage, &channel.endpoint, &channel)?; - - Ok(IbcBasicResponse::new() - .add_attribute("method", "ibc_channel_connect") - .add_attribute("channel_id", channel.endpoint.channel_id)) -} - -#[entry_point] -pub fn ibc_packet_receive( - deps: DepsMut, - env: Env, - msg: IbcPacketReceiveMsg, -) -> Result { - // Handle incoming IBC packets - let packet = msg.packet; - let res = handle_packet(deps, env, packet)?; - - Ok(IbcReceiveResponse::new() - .set_ack(res.acknowledgement) - .add_attributes(res.attributes)) -} -``` - -### 2. Cross-Chain DID Queries - -Replace Stargate queries with IBC queries: - -```rust -// contracts/voting/src/ibc_query.rs -use cosmwasm_std::{to_binary, Binary, Deps, Env, IbcMsg, IbcTimeout}; - -pub fn query_did_via_ibc( - deps: Deps, - env: Env, - did: String, -) -> Result { - let channel = CHANNEL_INFO.load(deps.storage)?; - - let query_msg = DIDQuery { - query_type: "get_did_document", - did, - }; - - let packet = IbcMsg::SendPacket { - channel_id: channel.endpoint.channel_id, - data: to_binary(&query_msg)?, - timeout: IbcTimeout::with_timestamp(env.block.time.plus_seconds(60)), - }; - - Ok(packet) -} - -pub fn handle_did_response( - deps: DepsMut, - response: Binary, -) -> Result<(), ContractError> { - let did_doc: DIDDocumentResponse = from_binary(&response)?; - - // Cache DID document for voting power calculation - DID_CACHE.save( - deps.storage, - &did_doc.document.id, - &did_doc, - )?; - - Ok(()) -} -``` - -### 3. Asynchronous Voting Power - -Since IBC queries are asynchronous, modify voting to handle this: - -```rust -// contracts/voting/src/state.rs -pub struct PendingVote { - pub voter: Addr, - pub proposal_id: u64, - pub vote: Vote, - pub did_query_id: String, -} - -pub const PENDING_VOTES: Map = Map::new("pending_votes"); - -// contracts/voting/src/contract.rs -pub fn execute_vote( - deps: DepsMut, - env: Env, - info: MessageInfo, - proposal_id: u64, - vote: Vote, -) -> Result { - // Check if we have cached DID info - let did = format!("did:sonr:{}", info.sender); - - if let Some(did_doc) = DID_CACHE.may_load(deps.storage, &did)? { - // Process vote immediately - process_vote(deps, env, info.sender, proposal_id, vote, did_doc) - } else { - // Queue vote and query DID via IBC - let query_id = generate_query_id(&env, &info.sender); - - PENDING_VOTES.save( - deps.storage, - &query_id, - &PendingVote { - voter: info.sender, - proposal_id, - vote, - did_query_id: query_id.clone(), - }, - )?; - - let ibc_msg = query_did_via_ibc(deps.as_ref(), env, did)?; - - Ok(Response::new() - .add_message(ibc_msg) - .add_attribute("action", "vote_pending") - .add_attribute("query_id", query_id)) - } -} -``` - -## IBC Packet Types - -### DID Query Packet - -```rust -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct DIDQueryPacket { - pub query_type: String, - pub did: String, - pub requester: String, - pub callback_id: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct DIDResponsePacket { - pub callback_id: String, - pub did_document: Option, - pub verification_status: VerificationStatus, - pub error: Option, -} -``` - -### Cross-Chain Proposal Packet - -```rust -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct CrossChainProposalPacket { - pub proposal_type: String, - pub target_module: String, // "did", "dwn", or "svc" - pub action: String, - pub params: Binary, - pub proposer_did: String, -} -``` - -## Deployment Scripts Update - -### Cosmos Hub Deployment - -```bash -#!/bin/bash -# deploy_cosmoshub.sh - -# Cosmos Hub configuration -CHAIN_ID="cosmoshub-4" -NODE="https://rpc.cosmos.network:443" -DEPLOYER="cosmos1..." -GAS_PRICES="0.025uatom" - -# Deploy contracts -gaiad tx wasm store artifacts/identity_dao_core.wasm \ - --from $DEPLOYER \ - --chain-id $CHAIN_ID \ - --node $NODE \ - --gas-prices $GAS_PRICES \ - --broadcast-mode block - -# Instantiate with IBC configuration -INIT_MSG=$(cat <|Submit Proposal| B[Pre-Propose Module] - B -->|Verify DID Status| C{Verification Check} - C -->|Pass| D[Pending Queue] - C -->|Fail| E[Rejected] - D -->|Admin Review| F{Approval} - F -->|Approved| G[Proposal Module] - F -->|Rejected| H[Refund Deposit] - G -->|Open Voting| I[Voting Module] - I -->|Cast Votes| J[Vote Tally] - J -->|Voting Period Ends| K{Result} - K -->|Pass| L[Execute] - K -->|Fail| M[Archive] - L -->|Run Messages| N[Core Module] -``` - -## Verification Levels - -The DAO recognizes four verification levels: - -| Level | Name | Voting Power Multiplier | Proposal Rights | -|-------|------|------------------------|-----------------| -| 0 | Unverified | 0x | None | -| 1 | Basic | 1x | Standard proposals | -| 2 | Advanced | 2x | Policy changes | -| 3 | Full | 3x | All proposals | - -## Wyoming DAO Compliance - -The Identity DAO includes features for Wyoming DAO legal compliance: - -- **Named Entity**: DAO name and URI stored on-chain -- **Member Registry**: DID-based membership tracking -- **Voting Records**: All votes recorded on-chain -- **Treasury Management**: Transparent fund management -- **Governance Rules**: Codified in smart contracts - -## Security Considerations - -### Access Control -- Admin functions restricted to DAO governance -- Module interactions validated -- DID verification required for participation - -### Economic Security -- Deposit requirements for proposals -- Refund mechanisms for failed proposals -- Anti-spam through verification requirements - -### Upgrade Security -- Migration support with admin approval -- Code ID tracking for audit trail -- Gradual rollout capabilities - -## Testing - -### Unit Tests -```bash -cd contracts/DAO -cargo test -``` - -### Integration Tests -```bash -# Run e2e tests (requires running testnet) -cd tests/e2e -go test -v ./... -``` - -### Local Testnet -```bash -# Start local testnet -make localnet - -# Deploy contracts -./scripts/deploy.sh - -# Run test transactions -./scripts/test_governance.sh -``` - -## Migration - -To migrate contracts to new versions: - -```bash -# Migrate single module -./scripts/migrate.sh core - -# Migrate all modules -./scripts/migrate.sh all -``` - -## Gas Optimization - -### Recommended Gas Settings -- **Store Code**: 5,000,000 gas -- **Instantiate**: 500,000 gas -- **Execute (simple)**: 200,000 gas -- **Execute (complex)**: 1,000,000 gas -- **Query**: No gas required - -### Optimization Tips -1. Batch operations when possible -2. Use efficient data structures -3. Minimize storage writes -4. Cache frequently accessed data - -## Troubleshooting - -### Common Issues - -**Issue**: "Insufficient verification level" -- **Solution**: Ensure your DID has the required verification level - -**Issue**: "Insufficient deposit" -- **Solution**: Include the minimum deposit amount with proposal submission - -**Issue**: "Unauthorized" -- **Solution**: Check that you have the correct role/permissions - -**Issue**: "Proposal already executed" -- **Solution**: Proposals can only be executed once - -## API Reference - -### Core Module - -#### Execute Messages -- `UpdateConfig`: Update DAO configuration -- `ExecuteProposal`: Execute approved proposal -- `UpdateAdmin`: Transfer admin rights - -#### Query Messages -- `Config`: Get DAO configuration -- `Admin`: Get current admin -- `ProposalModules`: List proposal modules - -### Voting Module - -#### Execute Messages -- `Vote`: Cast a vote on a proposal -- `UpdateConfig`: Update voting parameters - -#### Query Messages -- `VotingPower`: Get address voting power -- `ProposalVotes`: Get votes for a proposal -- `Config`: Get voting configuration - -### Proposals Module - -#### Execute Messages -- `Propose`: Create a new proposal -- `Execute`: Execute passed proposal -- `Close`: Close expired proposal - -#### Query Messages -- `Proposal`: Get proposal details -- `ListProposals`: List all proposals -- `ProposalResult`: Get proposal outcome - -### Pre-Propose Module - -#### Execute Messages -- `SubmitProposal`: Submit proposal for review -- `ApproveProposal`: Approve pending proposal -- `RejectProposal`: Reject pending proposal -- `WithdrawProposal`: Withdraw pending proposal - -#### Query Messages -- `PendingProposals`: List pending proposals -- `DepositInfo`: Get deposit information -- `Config`: Get module configuration - -## Contributing - -Please see the main [Sonr contribution guidelines](https://sonr.dev/contributing). - -## License - -This project is licensed under the Apache 2.0 License - see the [LICENSE](../../LICENSE) file for details. - -## Support - -- GitHub Issues: [sonr-io/sonr](https://github.com/sonr-io/sonr/issues) -- Discord: [Sonr Community](https://discord.gg/sonr) -- Documentation: [docs.sonr.io](https://sonr.dev) diff --git a/contracts/DAO/SECURITY_AUDIT.md b/contracts/DAO/SECURITY_AUDIT.md deleted file mode 100644 index 6220a672f..000000000 --- a/contracts/DAO/SECURITY_AUDIT.md +++ /dev/null @@ -1,286 +0,0 @@ -# Identity DAO Security Audit Report - -## Executive Summary - -This document provides a comprehensive security analysis of the Identity DAO smart contracts, identifying potential vulnerabilities and recommending mitigations. - -## Audit Scope - -- **Core Module** (`/contracts/core/`) -- **Voting Module** (`/contracts/voting/`) -- **Proposals Module** (`/contracts/proposals/`) -- **Pre-Propose Module** (`/contracts/pre-propose/`) - -## Security Findings - -### Critical Issues ✅ (None Found) - -No critical vulnerabilities identified that could lead to immediate fund loss or system compromise. - -### High Severity Issues - -#### H-1: Stargate Query Trust Assumptions -**Location**: All modules using Stargate queries -**Issue**: Contracts assume x/did module responses are always valid -**Impact**: Malicious or compromised x/did module could manipulate governance -**Mitigation**: -```rust -// Add validation for Stargate responses -fn validate_did_response(response: &DIDDocumentResponse) -> Result<(), ContractError> { - // Verify response contains expected fields - if response.document.id.is_empty() { - return Err(ContractError::InvalidDIDResponse {}); - } - // Add signature verification if available - Ok(()) -} -``` - -### Medium Severity Issues - -#### M-1: Proposal Execution Reentrancy -**Location**: `proposals/src/contract.rs:execute_proposal()` -**Issue**: External calls during proposal execution could re-enter -**Impact**: Potential state manipulation during execution -**Mitigation**: -```rust -// Add reentrancy guard -pub const EXECUTION_LOCK: Item = Item::new("execution_lock"); - -fn execute_proposal(deps: DepsMut, env: Env, proposal_id: u64) -> Result { - // Check and set lock - if EXECUTION_LOCK.may_load(deps.storage)?.unwrap_or(false) { - return Err(ContractError::ReentrantCall {}); - } - EXECUTION_LOCK.save(deps.storage, &true)?; - - // Execute proposal... - - // Clear lock - EXECUTION_LOCK.save(deps.storage, &false)?; - Ok(response) -} -``` - -#### M-2: Integer Overflow in Voting Power -**Location**: `voting/src/contract.rs:calculate_voting_power()` -**Issue**: Multiplication could overflow for large reputation scores -**Impact**: Incorrect voting power calculation -**Mitigation**: -```rust -// Use checked arithmetic -let power = base_power - .checked_mul(Uint128::from(verification_multiplier))? - .checked_add(Uint128::from(reputation_score))?; -``` - -### Low Severity Issues - -#### L-1: Missing Event Emissions -**Location**: Multiple locations -**Issue**: Some state changes don't emit events -**Impact**: Reduced observability -**Mitigation**: Add comprehensive event emissions for all state changes - -#### L-2: Unbounded Iteration -**Location**: `proposals/src/contract.rs:list_proposals()` -**Issue**: Could consume excessive gas with many proposals -**Impact**: DoS potential -**Mitigation**: Enforce pagination limits: -```rust -const MAX_LIMIT: u32 = 100; -let limit = limit.unwrap_or(30).min(MAX_LIMIT); -``` - -## Access Control Analysis - -### Admin Functions -✅ **Properly Protected**: -- Core module admin updates -- Proposal module configuration -- Emergency pause mechanisms - -### Public Functions -✅ **Appropriate Restrictions**: -- Voting requires DID verification -- Proposal submission requires minimum verification -- Execution requires proposal to pass - -## Gas Optimization Recommendations - -### Storage Optimizations - -#### 1. Pack Struct Fields -```rust -// Before - 3 storage slots -pub struct ProposalData { - pub id: u64, // 8 bytes - pub status: u8, // 1 byte - pub votes_yes: u128, // 16 bytes - new slot - pub votes_no: u128, // 16 bytes - new slot -} - -// After - 2 storage slots -pub struct ProposalData { - pub id: u64, // 8 bytes - pub status: u8, // 1 byte - pub reserved: [u8; 7], // 7 bytes padding - pub votes_yes: u128, // 16 bytes - pub votes_no: u128, // 16 bytes - same slot -} -``` - -#### 2. Use Lazy Loading -```rust -// Load only needed fields -let proposal_status = PROPOSALS - .may_load(deps.storage, proposal_id)? - .map(|p| p.status) - .ok_or(ContractError::ProposalNotFound {})?; -``` - -### Computation Optimizations - -#### 1. Cache Repeated Calculations -```rust -// Cache voting power instead of recalculating -pub const VOTING_POWER_CACHE: Map<&Addr, (u64, Uint128)> = Map::new("vp_cache"); - -fn get_voting_power(deps: Deps, address: &Addr, height: u64) -> StdResult { - // Check cache first - if let Some((cached_height, power)) = VOTING_POWER_CACHE.may_load(deps.storage, address)? { - if cached_height == height { - return Ok(power); - } - } - // Calculate and cache if not found - let power = calculate_voting_power(deps, address)?; - VOTING_POWER_CACHE.save(deps.storage, address, &(height, power))?; - Ok(power) -} -``` - -#### 2. Batch Operations -```rust -// Process multiple votes in one transaction -pub fn execute_batch_vote( - deps: DepsMut, - info: MessageInfo, - votes: Vec<(u64, Vote)>, -) -> Result { - let mut response = Response::new(); - for (proposal_id, vote) in votes { - // Process each vote - response = response.add_attribute("vote", format!("{}:{:?}", proposal_id, vote)); - } - Ok(response) -} -``` - -## Best Practices Compliance - -### ✅ Implemented -- Proper error handling with custom error types -- Input validation on all entry points -- State isolation between modules -- Upgrade mechanisms with admin control - -### ⚠️ Recommendations -1. Add circuit breaker for emergency pause -2. Implement time locks for critical operations -3. Add slashing mechanisms for malicious proposals -4. Include rate limiting for proposal submissions - -## Testing Recommendations - -### Unit Tests Required -```rust -#[cfg(test)] -mod security_tests { - #[test] - fn test_reentrancy_protection() { - // Test reentrancy guard - } - - #[test] - fn test_overflow_protection() { - // Test arithmetic overflow handling - } - - #[test] - fn test_access_control() { - // Test unauthorized access attempts - } -} -``` - -### Fuzzing Targets -1. Voting power calculation with extreme values -2. Proposal execution with complex message sequences -3. Deposit/refund mechanics with edge cases - -## Formal Verification Recommendations - -### Properties to Verify -1. **Conservation of Votes**: Total votes never exceed total voting power -2. **Proposal Finality**: Executed proposals cannot be re-executed -3. **Deposit Safety**: Deposits are always refundable or consumed - -### Invariants -```rust -// Invariant: Sum of all votes <= Total voting power -assert!(total_yes + total_no + total_abstain <= total_voting_power); - -// Invariant: Proposal status transitions are one-way -assert!(!(status == Status::Executed && new_status == Status::Open)); -``` - -## Security Checklist - -### Pre-Deployment -- [ ] Run static analysis tools (cargo-audit, clippy) -- [ ] Complete test coverage > 90% -- [ ] Perform gas profiling -- [ ] External security audit -- [ ] Bug bounty program setup - -### Post-Deployment -- [ ] Monitor for unusual activity -- [ ] Regular security updates -- [ ] Incident response plan -- [ ] Upgrade procedures tested - -## Conclusion - -The Identity DAO contracts demonstrate solid security practices with no critical vulnerabilities identified. The recommended improvements focus on: - -1. **Enhanced validation** of external data sources -2. **Gas optimizations** for scalability -3. **Additional safety mechanisms** for edge cases - -Implementation priority: -1. High severity mitigations (H-1) -2. Gas optimizations for frequently called functions -3. Medium severity fixes (M-1, M-2) -4. Low severity improvements - -## Appendix: Security Tools - -### Recommended Tools -- **Static Analysis**: `cargo-audit`, `clippy` -- **Fuzzing**: `cargo-fuzz`, `honggfuzz-rs` -- **Formal Verification**: `KEVM`, `Certora` -- **Gas Profiling**: `cosmwasm-gas-reporter` - -### Audit Commands -```bash -# Security checks -cargo audit -cargo clippy -- -W clippy::all - -# Test coverage -cargo tarpaulin --out Html - -# Gas profiling -cargo test --features gas_profiling -``` \ No newline at end of file diff --git a/contracts/DAO/contracts/core/Cargo.toml b/contracts/DAO/contracts/core/Cargo.toml deleted file mode 100644 index f837349ec..000000000 --- a/contracts/DAO/contracts/core/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "identity-dao-core" -version = { workspace = true } -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -homepage = { workspace = true } -documentation = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -library = [] - -[dependencies] -cosmwasm-std = { workspace = true } -cosmwasm-schema = { workspace = true } -cw2 = { workspace = true } -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -serde = { workspace = true } -schemars = { workspace = true } -thiserror = { workspace = true } -identity-dao-shared = { workspace = true } - -[dev-dependencies] -cw-multi-test = { workspace = true } -anyhow = { workspace = true } \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/contract.rs b/contracts/DAO/contracts/core/src/contract.rs deleted file mode 100644 index 50d7845bf..000000000 --- a/contracts/DAO/contracts/core/src/contract.rs +++ /dev/null @@ -1,318 +0,0 @@ -use cosmwasm_std::{ - entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, - Addr, CosmosMsg, Uint128, BankMsg, WasmMsg, -}; -use cw2::set_contract_version; -use cw_storage_plus::{Item, Map}; - -use identity_dao_shared::{ - ContractError, CoreInstantiateMsg, CoreExecuteMsg, CoreQueryMsg, - DaoConfigResponse, TreasuryInfo, ModuleConfig, DaoStatsResponse, - VotingConfig, -}; - -// Contract name and version -const CONTRACT_NAME: &str = "identity-dao-core"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -// State storage -pub const CONFIG: Item = Item::new("config"); -pub const MODULES: Item = Item::new("modules"); -pub const TREASURY: Item = Item::new("treasury"); -pub const PROPOSAL_COUNT: Item = Item::new("proposal_count"); -pub const EXECUTED_PROPOSALS: Map = Map::new("executed_proposals"); - -/// Core configuration -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub name: String, - pub description: String, - pub voting_config: VotingConfig, - pub admin: Option, - pub did_integration_enabled: bool, -} - -/// Module addresses -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct ModuleAddresses { - pub voting_module: Option, - pub proposal_module: Option, - pub pre_propose_module: Option, -} - -/// Treasury state -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct TreasuryState { - pub balance: Uint128, - pub reserved: Uint128, -} - -/// Instantiate contract -#[entry_point] -pub fn instantiate( - deps: DepsMut, - _env: Env, - info: MessageInfo, - msg: CoreInstantiateMsg, -) -> Result { - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - - let config = Config { - name: msg.name, - description: msg.description, - voting_config: msg.voting_config, - admin: msg.admin.map(|a| deps.api.addr_validate(&a)).transpose()?, - did_integration_enabled: msg.enable_did_integration, - }; - - let modules = ModuleAddresses { - voting_module: None, - proposal_module: None, - pre_propose_module: None, - }; - - let treasury = TreasuryState { - balance: Uint128::zero(), - reserved: Uint128::zero(), - }; - - CONFIG.save(deps.storage, &config)?; - MODULES.save(deps.storage, &modules)?; - TREASURY.save(deps.storage, &treasury)?; - PROPOSAL_COUNT.save(deps.storage, &0u64)?; - - Ok(Response::new() - .add_attribute("method", "instantiate") - .add_attribute("name", config.name) - .add_attribute("admin", info.sender.to_string())) -} - -/// Execute contract messages -#[entry_point] -pub fn execute( - deps: DepsMut, - env: Env, - info: MessageInfo, - msg: CoreExecuteMsg, -) -> Result { - match msg { - CoreExecuteMsg::ExecuteProposal { proposal_id } => { - execute_proposal(deps, env, info, proposal_id) - } - CoreExecuteMsg::UpdateConfig { voting_config } => { - update_config(deps, info, voting_config) - } - CoreExecuteMsg::UpdateModules { - voting_module, - proposal_module, - pre_propose_module, - } => update_modules(deps, info, voting_module, proposal_module, pre_propose_module), - CoreExecuteMsg::TransferFunds { recipient, amount } => { - transfer_funds(deps, info, recipient, amount) - } - } -} - -/// Execute a passed proposal -fn execute_proposal( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, -) -> Result { - // Verify caller is the proposal module - let modules = MODULES.load(deps.storage)?; - let proposal_module = modules - .proposal_module - .ok_or(ContractError::Unauthorized {})?; - - if info.sender != proposal_module { - return Err(ContractError::Unauthorized {}); - } - - // Check if already executed - if EXECUTED_PROPOSALS.may_load(deps.storage, proposal_id)?.unwrap_or(false) { - return Err(ContractError::CustomError { - msg: "Proposal already executed".to_string(), - }); - } - - // Mark as executed - EXECUTED_PROPOSALS.save(deps.storage, proposal_id, &true)?; - - Ok(Response::new() - .add_attribute("method", "execute_proposal") - .add_attribute("proposal_id", proposal_id.to_string())) -} - -/// Update voting configuration -fn update_config( - deps: DepsMut, - info: MessageInfo, - voting_config: VotingConfig, -) -> Result { - let mut config = CONFIG.load(deps.storage)?; - - // Check admin permission - if let Some(admin) = &config.admin { - if info.sender != *admin { - return Err(ContractError::Unauthorized {}); - } - } else { - return Err(ContractError::Unauthorized {}); - } - - config.voting_config = voting_config; - CONFIG.save(deps.storage, &config)?; - - Ok(Response::new() - .add_attribute("method", "update_config") - .add_attribute("admin", info.sender.to_string())) -} - -/// Update module addresses -fn update_modules( - deps: DepsMut, - info: MessageInfo, - voting_module: Option, - proposal_module: Option, - pre_propose_module: Option, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Check admin permission - if let Some(admin) = &config.admin { - if info.sender != *admin { - return Err(ContractError::Unauthorized {}); - } - } else { - return Err(ContractError::Unauthorized {}); - } - - let mut modules = MODULES.load(deps.storage)?; - - if let Some(addr) = voting_module { - modules.voting_module = Some(deps.api.addr_validate(&addr)?); - } - if let Some(addr) = proposal_module { - modules.proposal_module = Some(deps.api.addr_validate(&addr)?); - } - if let Some(addr) = pre_propose_module { - modules.pre_propose_module = Some(deps.api.addr_validate(&addr)?); - } - - MODULES.save(deps.storage, &modules)?; - - Ok(Response::new() - .add_attribute("method", "update_modules") - .add_attribute("admin", info.sender.to_string())) -} - -/// Transfer funds from treasury -fn transfer_funds( - deps: DepsMut, - info: MessageInfo, - recipient: String, - amount: Uint128, -) -> Result { - // Verify caller is the core module itself (called via proposal execution) - let modules = MODULES.load(deps.storage)?; - let proposal_module = modules - .proposal_module - .ok_or(ContractError::Unauthorized {})?; - - if info.sender != proposal_module { - return Err(ContractError::Unauthorized {}); - } - - let mut treasury = TREASURY.load(deps.storage)?; - - if treasury.balance < amount { - return Err(ContractError::CustomError { - msg: "Insufficient treasury balance".to_string(), - }); - } - - treasury.balance -= amount; - TREASURY.save(deps.storage, &treasury)?; - - let recipient_addr = deps.api.addr_validate(&recipient)?; - - Ok(Response::new() - .add_message(BankMsg::Send { - to_address: recipient_addr.to_string(), - amount: vec![cosmwasm_std::Coin { - denom: "usnr".to_string(), - amount, - }], - }) - .add_attribute("method", "transfer_funds") - .add_attribute("recipient", recipient) - .add_attribute("amount", amount.to_string())) -} - -/// Query contract state -#[entry_point] -pub fn query(deps: Deps, _env: Env, msg: CoreQueryMsg) -> StdResult { - match msg { - CoreQueryMsg::Config {} => to_json_binary(&query_config(deps)?), - CoreQueryMsg::Treasury {} => to_json_binary(&query_treasury(deps)?), - CoreQueryMsg::Modules {} => to_json_binary(&query_modules(deps)?), - CoreQueryMsg::Stats {} => to_json_binary(&query_stats(deps)?), - } -} - -/// Query DAO configuration -fn query_config(deps: Deps) -> StdResult { - let config = CONFIG.load(deps.storage)?; - Ok(DaoConfigResponse { - name: config.name, - description: config.description, - voting_config: config.voting_config, - admin: config.admin, - did_integration_enabled: config.did_integration_enabled, - }) -} - -/// Query treasury information -fn query_treasury(deps: Deps) -> StdResult { - let treasury = TREASURY.load(deps.storage)?; - let addr = deps.api.addr_validate(deps.api.addr_humanize(&deps.api.addr_canonicalize( - &deps.querier.query_bonded_denom()?.to_string() - )?)?.as_str())?; - - Ok(TreasuryInfo { - address: addr, - balance: treasury.balance, - reserved: treasury.reserved, - }) -} - -/// Query module addresses -fn query_modules(deps: Deps) -> StdResult { - let modules = MODULES.load(deps.storage)?; - let dao_core = deps.api.addr_validate( - &deps.querier.query_bonded_denom()?.to_string() - )?; - - Ok(ModuleConfig { - dao_core, - voting_module: modules.voting_module.unwrap_or(Addr::unchecked("")), - proposal_module: modules.proposal_module.unwrap_or(Addr::unchecked("")), - pre_propose_module: modules.pre_propose_module.unwrap_or(Addr::unchecked("")), - did_integration_enabled: CONFIG.load(deps.storage)?.did_integration_enabled, - }) -} - -/// Query DAO statistics -fn query_stats(deps: Deps) -> StdResult { - let proposal_count = PROPOSAL_COUNT.load(deps.storage)?; - let treasury = TREASURY.load(deps.storage)?; - - Ok(DaoStatsResponse { - total_proposals: proposal_count, - active_proposals: 0, // Would query from proposal module - total_voters: 0, // Would query from voting module - treasury_balance: treasury.balance, - }) -} \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/lib.rs b/contracts/DAO/contracts/core/src/lib.rs deleted file mode 100644 index 382c3a024..000000000 --- a/contracts/DAO/contracts/core/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod contract; -pub mod state; -pub mod msg; -pub mod query; - -pub use crate::contract::{instantiate, execute, query}; \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/msg.rs b/contracts/DAO/contracts/core/src/msg.rs deleted file mode 100644 index 1cb332de4..000000000 --- a/contracts/DAO/contracts/core/src/msg.rs +++ /dev/null @@ -1,33 +0,0 @@ -use cosmwasm_schema::cw_serde; -use cosmwasm_std::Uint128; -use identity_dao_shared::VotingConfig; - -/// Instantiate message -#[cw_serde] -pub struct InstantiateMsg { - pub name: String, - pub description: String, - pub voting_config: VotingConfig, - pub admin: Option, - pub enable_did_integration: bool, -} - -/// Execute messages -#[cw_serde] -pub enum ExecuteMsg { - /// Execute a proposal - ExecuteProposal { proposal_id: u64 }, - /// Update voting configuration - UpdateConfig { voting_config: VotingConfig }, - /// Update module addresses - UpdateModules { - voting_module: Option, - proposal_module: Option, - pre_propose_module: Option, - }, - /// Transfer treasury funds - TransferFunds { - recipient: String, - amount: Uint128, - }, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/query.rs b/contracts/DAO/contracts/core/src/query.rs deleted file mode 100644 index c697f0a1a..000000000 --- a/contracts/DAO/contracts/core/src/query.rs +++ /dev/null @@ -1,43 +0,0 @@ -use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::{Addr, Uint128}; -use identity_dao_shared::{VotingConfig, TreasuryInfo, ModuleConfig}; - -/// Query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum QueryMsg { - /// Get DAO configuration - #[returns(DaoConfigResponse)] - Config {}, - - /// Get treasury information - #[returns(TreasuryInfo)] - Treasury {}, - - /// Get module addresses - #[returns(ModuleConfig)] - Modules {}, - - /// Get DAO stats - #[returns(DaoStatsResponse)] - Stats {}, -} - -/// DAO configuration response -#[cw_serde] -pub struct DaoConfigResponse { - pub name: String, - pub description: String, - pub voting_config: VotingConfig, - pub admin: Option, - pub did_integration_enabled: bool, -} - -/// DAO statistics response -#[cw_serde] -pub struct DaoStatsResponse { - pub total_proposals: u64, - pub active_proposals: u64, - pub total_voters: u64, - pub treasury_balance: Uint128, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/state.rs b/contracts/DAO/contracts/core/src/state.rs deleted file mode 100644 index f26b9acb6..000000000 --- a/contracts/DAO/contracts/core/src/state.rs +++ /dev/null @@ -1,36 +0,0 @@ -use cosmwasm_std::{Addr, Uint128}; -use cw_storage_plus::{Item, Map}; -use identity_dao_shared::VotingConfig; -use serde::{Deserialize, Serialize}; - -/// Core configuration -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub name: String, - pub description: String, - pub voting_config: VotingConfig, - pub admin: Option, - pub did_integration_enabled: bool, -} - -/// Module addresses -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct ModuleAddresses { - pub voting_module: Option, - pub proposal_module: Option, - pub pre_propose_module: Option, -} - -/// Treasury state -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct TreasuryState { - pub balance: Uint128, - pub reserved: Uint128, -} - -/// State storage items -pub const CONFIG: Item = Item::new("config"); -pub const MODULES: Item = Item::new("modules"); -pub const TREASURY: Item = Item::new("treasury"); -pub const PROPOSAL_COUNT: Item = Item::new("proposal_count"); -pub const EXECUTED_PROPOSALS: Map = Map::new("executed_proposals"); \ No newline at end of file diff --git a/contracts/DAO/contracts/core/src/tests.rs b/contracts/DAO/contracts/core/src/tests.rs deleted file mode 100644 index 7a9eace82..000000000 --- a/contracts/DAO/contracts/core/src/tests.rs +++ /dev/null @@ -1,424 +0,0 @@ -#[cfg(test)] -mod tests { - use super::*; - use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; - use cosmwasm_std::{coins, from_json, Addr, Coin, Uint128}; - use identity_dao_shared::{ - CoreInstantiateMsg, CoreExecuteMsg, CoreQueryMsg, DaoConfigResponse, - ModuleConfig, ProposalExecuteMsg, TreasuryInfo, VotingConfig, - DaoStatsResponse, - }; - - fn setup_contract() -> (cosmwasm_std::DepsMut<'_>, Env, MessageInfo) { - let mut deps = mock_dependencies(); - let env = mock_env(); - let info = mock_info("creator", &[]); - - let msg = CoreInstantiateMsg { - name: "Test Identity DAO".to_string(), - description: "A test DAO for identity management".to_string(), - voting_config: VotingConfig { - threshold: cosmwasm_std::Decimal::percent(51), - quorum: cosmwasm_std::Decimal::percent(10), - voting_period: 86400, // 24 hours - proposal_deposit: Uint128::from(1000000u128), - }, - admin: Some("admin".to_string()), - enable_did_integration: true, - }; - - let res = instantiate(deps.branch(), env.clone(), info.clone(), msg); - assert!(res.is_ok()); - - (deps.as_mut(), env, info) - } - - #[test] - fn test_instantiate() { - let mut deps = mock_dependencies(); - let env = mock_env(); - let info = mock_info("creator", &[]); - - let msg = CoreInstantiateMsg { - name: "Identity DAO".to_string(), - description: "Decentralized Identity DAO".to_string(), - voting_config: VotingConfig { - threshold: cosmwasm_std::Decimal::percent(60), - quorum: cosmwasm_std::Decimal::percent(20), - voting_period: 604800, // 7 days - proposal_deposit: Uint128::from(5000000u128), - }, - admin: Some("admin".to_string()), - enable_did_integration: true, - }; - - let res = instantiate(deps.as_mut(), env, info, msg.clone()).unwrap(); - assert_eq!(res.attributes.len(), 3); - assert_eq!(res.attributes[0].value, "instantiate"); - assert_eq!(res.attributes[1].value, msg.name); - - // Verify state was saved correctly - let config = CONFIG.load(&deps.storage).unwrap(); - assert_eq!(config.name, "Identity DAO"); - assert_eq!(config.description, "Decentralized Identity DAO"); - assert_eq!(config.voting_config.threshold, cosmwasm_std::Decimal::percent(60)); - assert_eq!(config.did_integration_enabled, true); - - let modules = MODULES.load(&deps.storage).unwrap(); - assert_eq!(modules.voting_module, None); - assert_eq!(modules.proposal_module, None); - assert_eq!(modules.pre_propose_module, None); - - let treasury = TREASURY.load(&deps.storage).unwrap(); - assert_eq!(treasury.balance, Uint128::zero()); - assert_eq!(treasury.reserved, Uint128::zero()); - - let proposal_count = PROPOSAL_COUNT.load(&deps.storage).unwrap(); - assert_eq!(proposal_count, 0); - } - - #[test] - fn test_register_voting_module() { - let (mut deps, env, _) = setup_contract(); - let admin_info = mock_info("admin", &[]); - - let msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - - let res = execute(deps.branch(), env, admin_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "register_module"); - assert_eq!(res.attributes[1].value, "voting"); - - let modules = MODULES.load(&deps.storage).unwrap(); - assert_eq!(modules.voting_module, Some(Addr::unchecked("voting_module_addr"))); - } - - #[test] - fn test_register_proposal_module() { - let (mut deps, env, _) = setup_contract(); - let admin_info = mock_info("admin", &[]); - - let msg = CoreExecuteMsg::RegisterModule { - module_type: "proposal".to_string(), - module_address: "proposal_module_addr".to_string(), - }; - - let res = execute(deps.branch(), env, admin_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "register_module"); - assert_eq!(res.attributes[1].value, "proposal"); - - let modules = MODULES.load(&deps.storage).unwrap(); - assert_eq!(modules.proposal_module, Some(Addr::unchecked("proposal_module_addr"))); - } - - #[test] - fn test_register_pre_propose_module() { - let (mut deps, env, _) = setup_contract(); - let admin_info = mock_info("admin", &[]); - - let msg = CoreExecuteMsg::RegisterModule { - module_type: "pre_propose".to_string(), - module_address: "pre_propose_module_addr".to_string(), - }; - - let res = execute(deps.branch(), env, admin_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "register_module"); - assert_eq!(res.attributes[1].value, "pre_propose"); - - let modules = MODULES.load(&deps.storage).unwrap(); - assert_eq!(modules.pre_propose_module, Some(Addr::unchecked("pre_propose_module_addr"))); - } - - #[test] - fn test_unauthorized_register_module() { - let (mut deps, env, _) = setup_contract(); - let unauthorized_info = mock_info("unauthorized", &[]); - - let msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - - let err = execute(deps.branch(), env, unauthorized_info, msg).unwrap_err(); - assert!(matches!(err, ContractError::Unauthorized {})); - } - - #[test] - fn test_execute_proposal() { - let (mut deps, env, _) = setup_contract(); - - // Register voting module first - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - // Execute proposal from voting module - let voting_info = mock_info("voting_module_addr", &[]); - let msg = CoreExecuteMsg::ExecuteProposal { proposal_id: 1 }; - - let res = execute(deps.branch(), env, voting_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "execute_proposal"); - assert_eq!(res.attributes[1].value, "1"); - - // Verify proposal was marked as executed - let executed = EXECUTED_PROPOSALS.load(&deps.storage, 1).unwrap(); - assert_eq!(executed, true); - } - - #[test] - fn test_unauthorized_execute_proposal() { - let (mut deps, env, _) = setup_contract(); - let unauthorized_info = mock_info("unauthorized", &[]); - - let msg = CoreExecuteMsg::ExecuteProposal { proposal_id: 1 }; - - let err = execute(deps.branch(), env, unauthorized_info, msg).unwrap_err(); - assert!(matches!(err, ContractError::Unauthorized {})); - } - - #[test] - fn test_update_config() { - let (mut deps, env, _) = setup_contract(); - let admin_info = mock_info("admin", &[]); - - let msg = CoreExecuteMsg::UpdateConfig { - name: Some("Updated DAO".to_string()), - description: Some("Updated description".to_string()), - voting_config: None, - admin: Some("new_admin".to_string()), - }; - - let res = execute(deps.branch(), env, admin_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "update_config"); - - let config = CONFIG.load(&deps.storage).unwrap(); - assert_eq!(config.name, "Updated DAO"); - assert_eq!(config.description, "Updated description"); - assert_eq!(config.admin, Some(Addr::unchecked("new_admin"))); - } - - #[test] - fn test_deposit_to_treasury() { - let (mut deps, env, _) = setup_contract(); - let depositor_info = mock_info("depositor", &coins(1000000, "usnr")); - - let msg = CoreExecuteMsg::DepositToTreasury {}; - - let res = execute(deps.branch(), env, depositor_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "deposit_treasury"); - assert_eq!(res.attributes[1].value, "1000000"); - - let treasury = TREASURY.load(&deps.storage).unwrap(); - assert_eq!(treasury.balance, Uint128::from(1000000u128)); - } - - #[test] - fn test_withdraw_from_treasury() { - let (mut deps, env, _) = setup_contract(); - - // First deposit some funds - let depositor_info = mock_info("depositor", &coins(2000000, "usnr")); - let deposit_msg = CoreExecuteMsg::DepositToTreasury {}; - execute(deps.branch(), env.clone(), depositor_info, deposit_msg).unwrap(); - - // Register voting module - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - // Withdraw from treasury (through voting module) - let voting_info = mock_info("voting_module_addr", &[]); - let msg = CoreExecuteMsg::WithdrawFromTreasury { - recipient: "recipient".to_string(), - amount: Uint128::from(1000000u128), - denom: "usnr".to_string(), - }; - - let res = execute(deps.branch(), env, voting_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "withdraw_treasury"); - assert_eq!(res.attributes[1].value, "1000000"); - - // Check bank message was created - assert_eq!(res.messages.len(), 1); - - let treasury = TREASURY.load(&deps.storage).unwrap(); - assert_eq!(treasury.balance, Uint128::from(1000000u128)); - } - - #[test] - fn test_query_config() { - let (deps, _, _) = setup_contract(); - - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::GetConfig {}).unwrap(); - let config_response: DaoConfigResponse = from_json(&res).unwrap(); - - assert_eq!(config_response.name, "Test Identity DAO"); - assert_eq!(config_response.description, "A test DAO for identity management"); - assert_eq!(config_response.did_integration_enabled, true); - } - - #[test] - fn test_query_modules() { - let (mut deps, env, _) = setup_contract(); - - // Register all modules - let admin_info = mock_info("admin", &[]); - - execute(deps.branch(), env.clone(), admin_info.clone(), CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_addr".to_string(), - }).unwrap(); - - execute(deps.branch(), env.clone(), admin_info.clone(), CoreExecuteMsg::RegisterModule { - module_type: "proposal".to_string(), - module_address: "proposal_addr".to_string(), - }).unwrap(); - - execute(deps.branch(), env.clone(), admin_info, CoreExecuteMsg::RegisterModule { - module_type: "pre_propose".to_string(), - module_address: "pre_propose_addr".to_string(), - }).unwrap(); - - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::GetModules {}).unwrap(); - let modules_response: ModuleConfig = from_json(&res).unwrap(); - - assert_eq!(modules_response.voting_module, Some("voting_addr".to_string())); - assert_eq!(modules_response.proposal_module, Some("proposal_addr".to_string())); - assert_eq!(modules_response.pre_propose_module, Some("pre_propose_addr".to_string())); - } - - #[test] - fn test_query_treasury() { - let (mut deps, env, _) = setup_contract(); - - // Deposit funds - let depositor_info = mock_info("depositor", &coins(5000000, "usnr")); - let deposit_msg = CoreExecuteMsg::DepositToTreasury {}; - execute(deps.branch(), env, depositor_info, deposit_msg).unwrap(); - - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::GetTreasury {}).unwrap(); - let treasury_response: TreasuryInfo = from_json(&res).unwrap(); - - assert_eq!(treasury_response.balance, Uint128::from(5000000u128)); - assert_eq!(treasury_response.reserved, Uint128::zero()); - } - - #[test] - fn test_query_dao_stats() { - let (mut deps, env, _) = setup_contract(); - - // Register voting module and execute some proposals - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - let voting_info = mock_info("voting_module_addr", &[]); - - // Execute multiple proposals - for i in 1..=3 { - let msg = CoreExecuteMsg::ExecuteProposal { proposal_id: i }; - execute(deps.branch(), env.clone(), voting_info.clone(), msg).unwrap(); - } - - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::GetStats {}).unwrap(); - let stats_response: DaoStatsResponse = from_json(&res).unwrap(); - - assert_eq!(stats_response.total_proposals, 3); - assert_eq!(stats_response.executed_proposals, 3); - assert_eq!(stats_response.treasury_balance, Uint128::zero()); - } - - #[test] - fn test_is_proposal_executed() { - let (mut deps, env, _) = setup_contract(); - - // Register voting module - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - // Execute proposal - let voting_info = mock_info("voting_module_addr", &[]); - let msg = CoreExecuteMsg::ExecuteProposal { proposal_id: 42 }; - execute(deps.branch(), env, voting_info, msg).unwrap(); - - // Query if proposal is executed - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::IsProposalExecuted { - proposal_id: 42 - }).unwrap(); - let is_executed: bool = from_json(&res).unwrap(); - assert_eq!(is_executed, true); - - // Query non-executed proposal - let res = query(deps.as_ref(), mock_env(), CoreQueryMsg::IsProposalExecuted { - proposal_id: 99 - }).unwrap(); - let is_executed: bool = from_json(&res).unwrap(); - assert_eq!(is_executed, false); - } - - #[test] - fn test_execute_proposal_messages() { - let (mut deps, env, _) = setup_contract(); - - // Register voting module - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - // Execute proposal with messages - let voting_info = mock_info("voting_module_addr", &[]); - let bank_msg = CosmosMsg::Bank(BankMsg::Send { - to_address: "recipient".to_string(), - amount: coins(100000, "usnr"), - }); - - let msg = CoreExecuteMsg::ExecuteProposalWithMessages { - proposal_id: 1, - messages: vec![bank_msg.clone()], - }; - - let res = execute(deps.branch(), env, voting_info, msg).unwrap(); - assert_eq!(res.messages.len(), 1); - assert_eq!(res.messages[0].msg, bank_msg); - } - - #[test] - fn test_double_execution_prevention() { - let (mut deps, env, _) = setup_contract(); - - // Register voting module - let admin_info = mock_info("admin", &[]); - let register_msg = CoreExecuteMsg::RegisterModule { - module_type: "voting".to_string(), - module_address: "voting_module_addr".to_string(), - }; - execute(deps.branch(), env.clone(), admin_info, register_msg).unwrap(); - - // Execute proposal first time - let voting_info = mock_info("voting_module_addr", &[]); - let msg = CoreExecuteMsg::ExecuteProposal { proposal_id: 1 }; - execute(deps.branch(), env.clone(), voting_info.clone(), msg.clone()).unwrap(); - - // Try to execute same proposal again - let err = execute(deps.branch(), env, voting_info, msg).unwrap_err(); - assert!(matches!(err, ContractError::ProposalAlreadyExecuted { .. })); - } -} \ No newline at end of file diff --git a/contracts/DAO/contracts/pre-propose/Cargo.toml b/contracts/DAO/contracts/pre-propose/Cargo.toml deleted file mode 100644 index dc87ea643..000000000 --- a/contracts/DAO/contracts/pre-propose/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "identity-dao-pre-propose" -version = { workspace = true } -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -homepage = { workspace = true } -documentation = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -library = [] - -[dependencies] -cosmwasm-std = { workspace = true } -cosmwasm-schema = { workspace = true } -cw2 = { workspace = true } -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -serde = { workspace = true } -schemars = { workspace = true } -thiserror = { workspace = true } -identity-dao-shared = { workspace = true } - -[dev-dependencies] -cw-multi-test = { workspace = true } -anyhow = { workspace = true } \ No newline at end of file diff --git a/contracts/DAO/contracts/pre-propose/src/contract.rs b/contracts/DAO/contracts/pre-propose/src/contract.rs deleted file mode 100644 index 5b9e20a25..000000000 --- a/contracts/DAO/contracts/pre-propose/src/contract.rs +++ /dev/null @@ -1,381 +0,0 @@ -use cosmwasm_std::{ - entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, - StdResult, Addr, Uint128, CosmosMsg, WasmMsg, BankMsg, Coin, -}; -use cw2::set_contract_version; -use cw_storage_plus::{Item, Map}; - -use identity_dao_shared::{ - ContractError, PreProposeInstantiateMsg, PreProposeExecuteMsg, PreProposeQueryMsg, - PendingProposalsResponse, PendingProposal, DepositInfoResponse, PreProposeConfigResponse, - VerificationStatus, ProposalMessage, -}; -use crate::verification::{verify_did_status, check_verification_requirements}; - -// Contract name and version -const CONTRACT_NAME: &str = "identity-dao-pre-propose"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -// State storage -pub const CONFIG: Item = Item::new("config"); -pub const PENDING_COUNT: Item = Item::new("pending_count"); -pub const PENDING_PROPOSALS: Map = Map::new("pending_proposals"); -pub const DEPOSITS: Map<&str, DepositData> = Map::new("deposits"); - -/// Pre-propose module configuration -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub proposal_module: Addr, - pub min_verification_status: VerificationStatus, - pub deposit_amount: Uint128, - pub deposit_denom: String, - pub refund_failed_proposals: bool, -} - -/// Pending proposal data -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct PendingProposalData { - pub id: u64, - pub proposer: Addr, - pub title: String, - pub description: String, - pub messages: Vec, - pub submitted_at: u64, - pub deposit_amount: Uint128, -} - -/// Deposit data -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct DepositData { - pub depositor: Addr, - pub amount: Uint128, - pub refundable: bool, - pub proposal_id: Option, -} - -/// Instantiate contract -#[entry_point] -pub fn instantiate( - deps: DepsMut, - _env: Env, - _info: MessageInfo, - msg: PreProposeInstantiateMsg, -) -> Result { - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - - let config = Config { - proposal_module: deps.api.addr_validate(&msg.proposal_module)?, - min_verification_status: msg.min_verification_status, - deposit_amount: msg.deposit_amount, - deposit_denom: msg.deposit_denom, - refund_failed_proposals: true, - }; - - CONFIG.save(deps.storage, &config)?; - PENDING_COUNT.save(deps.storage, &0u64)?; - - Ok(Response::new() - .add_attribute("method", "instantiate") - .add_attribute("proposal_module", config.proposal_module.to_string()) - .add_attribute("deposit_amount", config.deposit_amount.to_string())) -} - -/// Execute contract messages -#[entry_point] -pub fn execute( - deps: DepsMut, - env: Env, - info: MessageInfo, - msg: PreProposeExecuteMsg, -) -> Result { - match msg { - PreProposeExecuteMsg::SubmitProposal { title, description, msgs } => { - execute_submit_proposal(deps, env, info, title, description, msgs) - } - PreProposeExecuteMsg::ApproveProposal { proposal_id } => { - execute_approve_proposal(deps, env, info, proposal_id) - } - PreProposeExecuteMsg::RejectProposal { proposal_id, reason } => { - execute_reject_proposal(deps, env, info, proposal_id, reason) - } - PreProposeExecuteMsg::WithdrawProposal { proposal_id } => { - execute_withdraw_proposal(deps, env, info, proposal_id) - } - } -} - -/// Submit a proposal for approval -fn execute_submit_proposal( - deps: DepsMut, - env: Env, - info: MessageInfo, - title: String, - description: String, - msgs: Vec, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Verify DID status - let did = format!("did:sonr:{}", info.sender); - let verification = verify_did_status(deps.as_ref(), &did)?; - - if !verification.is_verified { - return Err(ContractError::DIDNotVerified {}); - } - - // Check minimum verification level - let status = match verification.verification_level { - 0 => VerificationStatus::Unverified, - 1 => VerificationStatus::Basic, - 2 => VerificationStatus::Advanced, - _ => VerificationStatus::Full, - }; - - if (status as u8) < (config.min_verification_status as u8) { - return Err(ContractError::CustomError { - msg: "Insufficient verification level".to_string(), - }); - } - - // Check deposit - let deposit_paid = info - .funds - .iter() - .find(|c| c.denom == config.deposit_denom) - .map(|c| c.amount) - .unwrap_or(Uint128::zero()); - - if deposit_paid < config.deposit_amount { - return Err(ContractError::CustomError { - msg: "Insufficient deposit".to_string(), - }); - } - - // Create pending proposal - let proposal_id = PENDING_COUNT.load(deps.storage)? + 1; - PENDING_COUNT.save(deps.storage, &proposal_id)?; - - let pending = PendingProposalData { - id: proposal_id, - proposer: info.sender.clone(), - title, - description, - messages: msgs, - submitted_at: env.block.time.seconds(), - deposit_amount: deposit_paid, - }; - - PENDING_PROPOSALS.save(deps.storage, proposal_id, &pending)?; - - // Save deposit info - let deposit = DepositData { - depositor: info.sender.clone(), - amount: deposit_paid, - refundable: config.refund_failed_proposals, - proposal_id: Some(proposal_id), - }; - - DEPOSITS.save(deps.storage, info.sender.as_str(), &deposit)?; - - Ok(Response::new() - .add_attribute("method", "submit_proposal") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("proposer", info.sender.to_string()) - .add_attribute("title", pending.title)) -} - -/// Approve a pending proposal -fn execute_approve_proposal( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Only admin or governance can approve - // For now, allow anyone (would check permissions in production) - - let pending = PENDING_PROPOSALS.load(deps.storage, proposal_id)?; - - // Remove from pending - PENDING_PROPOSALS.remove(deps.storage, proposal_id); - - // Create proposal in proposal module - let propose_msg = WasmMsg::Execute { - contract_addr: config.proposal_module.to_string(), - msg: to_json_binary(&identity_dao_shared::ProposalExecuteMsg::Propose { - title: pending.title, - description: pending.description, - msgs: pending.messages, - })?, - funds: vec![], - }; - - Ok(Response::new() - .add_message(propose_msg) - .add_attribute("method", "approve_proposal") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("approver", info.sender.to_string())) -} - -/// Reject a pending proposal -fn execute_reject_proposal( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, - reason: String, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Only admin or governance can reject - // For now, allow anyone (would check permissions in production) - - let pending = PENDING_PROPOSALS.load(deps.storage, proposal_id)?; - - // Remove from pending - PENDING_PROPOSALS.remove(deps.storage, proposal_id); - - // Refund deposit if configured - let mut messages = vec![]; - if config.refund_failed_proposals { - if let Some(mut deposit) = DEPOSITS.may_load(deps.storage, pending.proposer.as_str())? { - deposit.refundable = false; - DEPOSITS.save(deps.storage, pending.proposer.as_str(), &deposit)?; - - messages.push(CosmosMsg::Bank(BankMsg::Send { - to_address: pending.proposer.to_string(), - amount: vec![Coin { - denom: config.deposit_denom, - amount: pending.deposit_amount, - }], - })); - } - } - - Ok(Response::new() - .add_messages(messages) - .add_attribute("method", "reject_proposal") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("rejector", info.sender.to_string()) - .add_attribute("reason", reason)) -} - -/// Withdraw a pending proposal -fn execute_withdraw_proposal( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, -) -> Result { - let config = CONFIG.load(deps.storage)?; - let pending = PENDING_PROPOSALS.load(deps.storage, proposal_id)?; - - // Only proposer can withdraw - if info.sender != pending.proposer { - return Err(ContractError::Unauthorized {}); - } - - // Remove from pending - PENDING_PROPOSALS.remove(deps.storage, proposal_id); - - // Refund deposit - let mut messages = vec![]; - if let Some(mut deposit) = DEPOSITS.may_load(deps.storage, info.sender.as_str())? { - deposit.refundable = false; - deposit.proposal_id = None; - DEPOSITS.save(deps.storage, info.sender.as_str(), &deposit)?; - - messages.push(CosmosMsg::Bank(BankMsg::Send { - to_address: info.sender.to_string(), - amount: vec![Coin { - denom: config.deposit_denom, - amount: pending.deposit_amount, - }], - })); - } - - Ok(Response::new() - .add_messages(messages) - .add_attribute("method", "withdraw_proposal") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("proposer", info.sender.to_string())) -} - -// Verification functions are now imported from the verification module - -/// Query contract state -#[entry_point] -pub fn query(deps: Deps, _env: Env, msg: PreProposeQueryMsg) -> StdResult { - match msg { - PreProposeQueryMsg::PendingProposals { start_after, limit } => { - to_json_binary(&query_pending_proposals(deps, start_after, limit)?) - } - PreProposeQueryMsg::DepositInfo { proposer } => { - to_json_binary(&query_deposit_info(deps, proposer)?) - } - PreProposeQueryMsg::Config {} => { - to_json_binary(&query_config(deps)?) - } - } -} - -/// Query pending proposals -fn query_pending_proposals( - deps: Deps, - start_after: Option, - limit: Option, -) -> StdResult { - let limit = limit.unwrap_or(30).min(100) as usize; - let start = start_after.map(|id| cosmwasm_std::Bound::exclusive(id)); - - let proposals: Vec = PENDING_PROPOSALS - .range(deps.storage, start, None, cosmwasm_std::Order::Ascending) - .take(limit) - .map(|item| { - let (_, data) = item?; - Ok(PendingProposal { - id: data.id, - proposer: data.proposer.to_string(), - title: data.title, - submitted_at: data.submitted_at, - }) - }) - .collect::>>()?; - - let total = PENDING_COUNT.load(deps.storage)?; - - Ok(PendingProposalsResponse { proposals, total }) -} - -/// Query deposit info -fn query_deposit_info(deps: Deps, proposer: String) -> StdResult { - let deposit = DEPOSITS.may_load(deps.storage, &proposer)?; - - if let Some(deposit) = deposit { - Ok(DepositInfoResponse { - depositor: deposit.depositor.to_string(), - amount: deposit.amount, - refundable: deposit.refundable, - }) - } else { - Ok(DepositInfoResponse { - depositor: proposer, - amount: Uint128::zero(), - refundable: false, - }) - } -} - -/// Query module config -fn query_config(deps: Deps) -> StdResult { - let config = CONFIG.load(deps.storage)?; - - Ok(PreProposeConfigResponse { - proposal_module: config.proposal_module, - min_verification_status: format!("{:?}", config.min_verification_status), - deposit_amount: config.deposit_amount, - deposit_denom: config.deposit_denom, - }) -} \ No newline at end of file diff --git a/contracts/DAO/contracts/pre-propose/src/lib.rs b/contracts/DAO/contracts/pre-propose/src/lib.rs deleted file mode 100644 index af55cfd28..000000000 --- a/contracts/DAO/contracts/pre-propose/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod contract; -pub mod state; -pub mod msg; -pub mod query; -pub mod verification; - -pub use crate::contract::{instantiate, execute, query}; \ No newline at end of file diff --git a/contracts/DAO/contracts/pre-propose/src/state.rs b/contracts/DAO/contracts/pre-propose/src/state.rs deleted file mode 100644 index 5d15a48d9..000000000 --- a/contracts/DAO/contracts/pre-propose/src/state.rs +++ /dev/null @@ -1,41 +0,0 @@ -use cosmwasm_std::{Addr, Uint128}; -use cw_storage_plus::{Item, Map}; -use identity_dao_shared::{VerificationStatus, ProposalMessage}; -use serde::{Deserialize, Serialize}; - -/// Pre-propose module configuration -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub proposal_module: Addr, - pub min_verification_status: VerificationStatus, - pub deposit_amount: Uint128, - pub deposit_denom: String, - pub refund_failed_proposals: bool, -} - -/// Pending proposal data -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct PendingProposalData { - pub id: u64, - pub proposer: Addr, - pub title: String, - pub description: String, - pub messages: Vec, - pub submitted_at: u64, - pub deposit_amount: Uint128, -} - -/// Deposit data -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct DepositData { - pub depositor: Addr, - pub amount: Uint128, - pub refundable: bool, - pub proposal_id: Option, -} - -/// State storage items -pub const CONFIG: Item = Item::new("config"); -pub const PENDING_COUNT: Item = Item::new("pending_count"); -pub const PENDING_PROPOSALS: Map = Map::new("pending_proposals"); -pub const DEPOSITS: Map<&str, DepositData> = Map::new("deposits"); \ No newline at end of file diff --git a/contracts/DAO/contracts/pre-propose/src/verification.rs b/contracts/DAO/contracts/pre-propose/src/verification.rs deleted file mode 100644 index 3e41f61ae..000000000 --- a/contracts/DAO/contracts/pre-propose/src/verification.rs +++ /dev/null @@ -1,151 +0,0 @@ -use cosmwasm_std::{Deps, StdResult, Addr}; -use identity_dao_shared::{ - VerificationStatus, AttestationType, - bindings::{DIDDocumentResponse, VerificationResponse, SonrQuery}, -}; - -/// Verify DID status and verification level -pub fn verify_did_status(deps: Deps, did: &str) -> StdResult { - // For production, would use Stargate query to x/did module - // Mock response for development - Ok(VerificationResponse { - is_verified: true, - verification_level: 2, - last_verified: Some(1700000000), - }) -} - -/// Check if proposer meets minimum verification requirements -pub fn check_verification_requirements( - deps: Deps, - proposer: &Addr, - min_status: VerificationStatus, -) -> StdResult { - let did = format!("did:sonr:{}", proposer); - let verification = verify_did_status(deps, &did)?; - - if !verification.is_verified { - return Ok(false); - } - - let status = match verification.verification_level { - 0 => VerificationStatus::Unverified, - 1 => VerificationStatus::Basic, - 2 => VerificationStatus::Advanced, - _ => VerificationStatus::Full, - }; - - Ok(status as u8 >= min_status as u8) -} - -/// Verify specific attestations for proposer -pub fn verify_attestations( - _deps: Deps, - _proposer: &Addr, - required_types: &[AttestationType], -) -> StdResult { - // Would query attestations from x/did module - // For now, return true for development - if required_types.is_empty() { - return Ok(true); - } - - // Mock: assume proposer has all required attestations - Ok(true) -} - -/// Calculate deposit amount based on verification level -pub fn calculate_deposit_multiplier(verification_level: u8) -> u64 { - match verification_level { - 0 => 100, // Unverified: 100% deposit - 1 => 75, // Basic: 75% deposit - 2 => 50, // Advanced: 50% deposit - _ => 25, // Full: 25% deposit - } -} - -/// Validate proposal content based on proposer verification -pub fn validate_proposal_content( - deps: Deps, - proposer: &Addr, - proposal_type: &str, -) -> StdResult { - let did = format!("did:sonr:{}", proposer); - let verification = verify_did_status(deps, &did)?; - - match proposal_type { - "treasury" => { - // Treasury proposals require advanced verification - Ok(verification.verification_level >= 2) - } - "parameter" => { - // Parameter changes require full verification - Ok(verification.verification_level >= 3) - } - "identity_policy" => { - // Identity policy changes require full verification - Ok(verification.verification_level >= 3) - } - _ => { - // Default proposals require basic verification - Ok(verification.verification_level >= 1) - } - } -} - -/// Check if proposer has active proposals -pub fn has_active_proposals( - _deps: Deps, - _proposer: &Addr, -) -> StdResult { - // Would query active proposals for this proposer - // For now, return 0 for development - Ok(0) -} - -/// Validate proposal limits based on verification -pub fn validate_proposal_limits( - deps: Deps, - proposer: &Addr, - max_active: u64, -) -> StdResult { - let active_count = has_active_proposals(deps, proposer)?; - Ok(active_count < max_active) -} - -#[cfg(test)] -mod tests { - use super::*; - use cosmwasm_std::testing::mock_dependencies; - - #[test] - fn test_calculate_deposit_multiplier() { - assert_eq!(calculate_deposit_multiplier(0), 100); - assert_eq!(calculate_deposit_multiplier(1), 75); - assert_eq!(calculate_deposit_multiplier(2), 50); - assert_eq!(calculate_deposit_multiplier(3), 25); - assert_eq!(calculate_deposit_multiplier(10), 25); - } - - #[test] - fn test_check_verification_requirements() { - let deps = mock_dependencies(); - let proposer = Addr::unchecked("sonr1user"); - - // Mock returns verification level 2 (Advanced) - let result = check_verification_requirements( - deps.as_ref(), - &proposer, - VerificationStatus::Basic, - ).unwrap(); - assert!(result); - - let result = check_verification_requirements( - deps.as_ref(), - &proposer, - VerificationStatus::Full, - ).unwrap(); - // Would be false with real verification - assert!(result); // Mock always returns true for now - } -} \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/Cargo.toml b/contracts/DAO/contracts/proposals/Cargo.toml deleted file mode 100644 index 78dd0f5d4..000000000 --- a/contracts/DAO/contracts/proposals/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "identity-dao-proposals" -version = { workspace = true } -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -homepage = { workspace = true } -documentation = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -library = [] - -[dependencies] -cosmwasm-std = { workspace = true } -cosmwasm-schema = { workspace = true } -cw2 = { workspace = true } -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -serde = { workspace = true } -schemars = { workspace = true } -thiserror = { workspace = true } -identity-dao-shared = { workspace = true } - -[dev-dependencies] -cw-multi-test = { workspace = true } -anyhow = { workspace = true } \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/contract.rs b/contracts/DAO/contracts/proposals/src/contract.rs deleted file mode 100644 index 88542b939..000000000 --- a/contracts/DAO/contracts/proposals/src/contract.rs +++ /dev/null @@ -1,404 +0,0 @@ -use cosmwasm_std::{ - entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, - StdResult, Addr, Uint128, CosmosMsg, WasmMsg, Order, -}; -use cw2::set_contract_version; -use cw_storage_plus::{Item, Map}; - -use identity_dao_shared::{ - ContractError, ProposalInstantiateMsg, ProposalExecuteMsg, ProposalQueryMsg, - ProposalResponse, ProposalsListResponse, ProposalVotesResponse, ProposalResultResponse, - ProposalStatus, ProposalMessage, ProposalResult, ProposalVotes, VoteInfo, - ProposalStatusUpdate, -}; - -// Contract name and version -const CONTRACT_NAME: &str = "identity-dao-proposals"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -// State storage -pub const CONFIG: Item = Item::new("config"); -pub const PROPOSAL_COUNT: Item = Item::new("proposal_count"); -pub const PROPOSALS: Map = Map::new("proposals"); -pub const PROPOSAL_VOTES: Map = Map::new("proposal_votes"); - -/// Proposal module configuration -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub dao_core: Addr, - pub voting_module: Addr, - pub pre_propose_module: Option, - pub allow_multiple_choice: bool, - pub voting_period: u64, - pub execution_delay: u64, -} - -/// Proposal data -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct Proposal { - pub id: u64, - pub title: String, - pub description: String, - pub proposer: Addr, - pub messages: Vec, - pub status: ProposalStatus, - pub start_time: u64, - pub end_time: u64, - pub execution_time: Option, -} - -/// Instantiate contract -#[entry_point] -pub fn instantiate( - deps: DepsMut, - env: Env, - _info: MessageInfo, - msg: ProposalInstantiateMsg, -) -> Result { - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - - let config = Config { - dao_core: deps.api.addr_validate(&msg.dao_core)?, - voting_module: deps.api.addr_validate(&msg.voting_module)?, - pre_propose_module: msg.pre_propose_module - .map(|a| deps.api.addr_validate(&a)) - .transpose()?, - allow_multiple_choice: msg.allow_multiple_choice, - voting_period: 7 * 24 * 60 * 60, // 7 days - execution_delay: 24 * 60 * 60, // 1 day - }; - - CONFIG.save(deps.storage, &config)?; - PROPOSAL_COUNT.save(deps.storage, &0u64)?; - - Ok(Response::new() - .add_attribute("method", "instantiate") - .add_attribute("dao_core", config.dao_core.to_string()) - .add_attribute("voting_module", config.voting_module.to_string())) -} - -/// Execute contract messages -#[entry_point] -pub fn execute( - deps: DepsMut, - env: Env, - info: MessageInfo, - msg: ProposalExecuteMsg, -) -> Result { - match msg { - ProposalExecuteMsg::Propose { title, description, msgs } => { - execute_propose(deps, env, info, title, description, msgs) - } - ProposalExecuteMsg::Execute { proposal_id } => { - execute_proposal(deps, env, info, proposal_id) - } - ProposalExecuteMsg::Close { proposal_id } => { - execute_close(deps, env, info, proposal_id) - } - ProposalExecuteMsg::UpdateStatus { proposal_id, status } => { - execute_update_status(deps, env, info, proposal_id, status) - } - } -} - -/// Create a new proposal -fn execute_propose( - deps: DepsMut, - env: Env, - info: MessageInfo, - title: String, - description: String, - msgs: Vec, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Check if pre-propose module is set and sender is authorized - if let Some(pre_propose) = &config.pre_propose_module { - if info.sender != *pre_propose { - return Err(ContractError::Unauthorized {}); - } - } - - // Increment proposal count - let proposal_id = PROPOSAL_COUNT.load(deps.storage)? + 1; - PROPOSAL_COUNT.save(deps.storage, &proposal_id)?; - - // Create proposal - let proposal = Proposal { - id: proposal_id, - title, - description, - proposer: info.sender.clone(), - messages: msgs, - status: ProposalStatus::Open, - start_time: env.block.time.seconds(), - end_time: env.block.time.seconds() + config.voting_period, - execution_time: None, - }; - - // Initialize vote counts - let votes = ProposalVotes { - yes: Uint128::zero(), - no: Uint128::zero(), - abstain: Uint128::zero(), - no_with_veto: Uint128::zero(), - }; - - PROPOSALS.save(deps.storage, proposal_id, &proposal)?; - PROPOSAL_VOTES.save(deps.storage, proposal_id, &votes)?; - - Ok(Response::new() - .add_attribute("method", "propose") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("proposer", info.sender.to_string()) - .add_attribute("title", proposal.title)) -} - -/// Execute a passed proposal -fn execute_proposal( - deps: DepsMut, - env: Env, - info: MessageInfo, - proposal_id: u64, -) -> Result { - let mut proposal = PROPOSALS.load(deps.storage, proposal_id)?; - - // Check if proposal has passed - if proposal.status != ProposalStatus::Passed { - return Err(ContractError::CustomError { - msg: "Proposal has not passed".to_string(), - }); - } - - // Check execution delay - if let Some(exec_time) = proposal.execution_time { - if env.block.time.seconds() < exec_time { - return Err(ContractError::CustomError { - msg: "Execution delay not met".to_string(), - }); - } - } - - // Update status - proposal.status = ProposalStatus::Executed; - PROPOSALS.save(deps.storage, proposal_id, &proposal)?; - - // Execute messages - let mut messages = vec![]; - for msg in proposal.messages { - messages.push(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: msg.contract, - msg: msg.msg, - funds: msg.funds, - })); - } - - // Notify core module - let core_msg = WasmMsg::Execute { - contract_addr: CONFIG.load(deps.storage)?.dao_core.to_string(), - msg: to_json_binary(&identity_dao_shared::CoreExecuteMsg::ExecuteProposal { - proposal_id - })?, - funds: vec![], - }; - messages.push(CosmosMsg::Wasm(core_msg)); - - Ok(Response::new() - .add_messages(messages) - .add_attribute("method", "execute_proposal") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("executor", info.sender.to_string())) -} - -/// Close an expired proposal -fn execute_close( - deps: DepsMut, - env: Env, - _info: MessageInfo, - proposal_id: u64, -) -> Result { - let mut proposal = PROPOSALS.load(deps.storage, proposal_id)?; - - // Check if voting period has ended - if env.block.time.seconds() < proposal.end_time { - return Err(ContractError::VotingPeriodNotEnded {}); - } - - // Check if proposal is still open - if proposal.status != ProposalStatus::Open { - return Err(ContractError::CustomError { - msg: "Proposal is not open".to_string(), - }); - } - - // Determine result based on votes - let votes = PROPOSAL_VOTES.load(deps.storage, proposal_id)?; - let total_votes = votes.yes + votes.no + votes.abstain + votes.no_with_veto; - - // Get voting config from core - let config = CONFIG.load(deps.storage)?; - - // Simple majority for now (would query from core for actual config) - let threshold = Uint128::from(50u128); - let quorum = Uint128::from(33u128); - - let participation = if total_votes.is_zero() { - Uint128::zero() - } else { - total_votes * Uint128::from(100u128) / total_votes // Would get total power from voting module - }; - - if participation < quorum { - proposal.status = ProposalStatus::Rejected; - } else if votes.yes * Uint128::from(100u128) > total_votes * threshold { - proposal.status = ProposalStatus::Passed; - proposal.execution_time = Some(env.block.time.seconds() + config.execution_delay); - } else { - proposal.status = ProposalStatus::Rejected; - } - - PROPOSALS.save(deps.storage, proposal_id, &proposal)?; - - Ok(Response::new() - .add_attribute("method", "close") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("status", format!("{:?}", proposal.status))) -} - -/// Update proposal status -fn execute_update_status( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, - status: ProposalStatusUpdate, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Only voting module can update status - if info.sender != config.voting_module { - return Err(ContractError::Unauthorized {}); - } - - let mut proposal = PROPOSALS.load(deps.storage, proposal_id)?; - - proposal.status = match status { - ProposalStatusUpdate::Passed => ProposalStatus::Passed, - ProposalStatusUpdate::Rejected => ProposalStatus::Rejected, - ProposalStatusUpdate::Executed => ProposalStatus::Executed, - ProposalStatusUpdate::ExecutionFailed { .. } => ProposalStatus::ExecutionFailed, - }; - - PROPOSALS.save(deps.storage, proposal_id, &proposal)?; - - Ok(Response::new() - .add_attribute("method", "update_status") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("status", format!("{:?}", proposal.status))) -} - -/// Query contract state -#[entry_point] -pub fn query(deps: Deps, _env: Env, msg: ProposalQueryMsg) -> StdResult { - match msg { - ProposalQueryMsg::Proposal { proposal_id } => { - to_json_binary(&query_proposal(deps, proposal_id)?) - } - ProposalQueryMsg::ListProposals { status, start_after, limit } => { - to_json_binary(&query_list_proposals(deps, status, start_after, limit)?) - } - ProposalQueryMsg::ProposalVotes { proposal_id, start_after, limit } => { - to_json_binary(&query_proposal_votes(deps, proposal_id, start_after, limit)?) - } - ProposalQueryMsg::ProposalResult { proposal_id } => { - to_json_binary(&query_proposal_result(deps, proposal_id)?) - } - } -} - -/// Query proposal details -fn query_proposal(deps: Deps, proposal_id: u64) -> StdResult { - let proposal = PROPOSALS.load(deps.storage, proposal_id)?; - let votes = PROPOSAL_VOTES.load(deps.storage, proposal_id)?; - - Ok(ProposalResponse { - id: proposal.id, - title: proposal.title, - description: proposal.description, - proposer: proposal.proposer.to_string(), - status: proposal.status, - votes, - start_time: proposal.start_time, - end_time: proposal.end_time, - }) -} - -/// List proposals with filters -fn query_list_proposals( - deps: Deps, - status: Option, - start_after: Option, - limit: Option, -) -> StdResult { - let limit = limit.unwrap_or(30).min(100) as usize; - let start = start_after.map(|id| cosmwasm_std::Bound::exclusive(id)); - - let proposals: Vec = PROPOSALS - .range(deps.storage, start, None, Order::Ascending) - .filter(|item| { - if let Ok((_, proposal)) = item { - status.is_none() || status == Some(proposal.status.clone()) - } else { - false - } - }) - .take(limit) - .map(|item| { - let (id, proposal) = item?; - let votes = PROPOSAL_VOTES.load(deps.storage, id)?; - Ok(ProposalResponse { - id: proposal.id, - title: proposal.title, - description: proposal.description, - proposer: proposal.proposer.to_string(), - status: proposal.status, - votes, - start_time: proposal.start_time, - end_time: proposal.end_time, - }) - }) - .collect::>>()?; - - let total = PROPOSAL_COUNT.load(deps.storage)?; - - Ok(ProposalsListResponse { proposals, total }) -} - -/// Query proposal votes (placeholder - would integrate with voting module) -fn query_proposal_votes( - _deps: Deps, - proposal_id: u64, - _start_after: Option, - _limit: Option, -) -> StdResult { - Ok(ProposalVotesResponse { - votes: vec![], - total: 0, - }) -} - -/// Query proposal result -fn query_proposal_result(deps: Deps, proposal_id: u64) -> StdResult { - let proposal = PROPOSALS.load(deps.storage, proposal_id)?; - - let result = match proposal.status { - ProposalStatus::Passed | ProposalStatus::Executed => ProposalResult::Passed, - ProposalStatus::Rejected | ProposalStatus::ExecutionFailed => ProposalResult::Rejected, - _ => ProposalResult::InProgress, - }; - - Ok(ProposalResultResponse { - proposal_id, - result, - }) -} \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/identity.rs b/contracts/DAO/contracts/proposals/src/identity.rs deleted file mode 100644 index 630d2bfb9..000000000 --- a/contracts/DAO/contracts/proposals/src/identity.rs +++ /dev/null @@ -1,104 +0,0 @@ -use cosmwasm_std::{Deps, StdResult, Addr}; -use identity_dao_shared::{ - IdentityAttestation, AttestationType, VerificationStatus, - bindings::{DIDDocumentResponse, VerificationResponse}, -}; - -/// Verify proposer identity meets requirements -pub fn verify_proposer_identity( - deps: Deps, - proposer: &Addr, - min_verification: VerificationStatus, -) -> StdResult { - // Query DID by address (mock for now) - let did = format!("did:sonr:{}", proposer); - - // Query verification status - let verification = query_did_verification(deps, &did)?; - - // Check verification level - let status = match verification.verification_level { - 0 => VerificationStatus::Unverified, - 1 => VerificationStatus::Basic, - 2 => VerificationStatus::Advanced, - 3.. => VerificationStatus::Full, - }; - - Ok(status as u8 >= min_verification as u8) -} - -/// Query DID verification status -fn query_did_verification(_deps: Deps, _did: &str) -> StdResult { - // Mock response for development - Ok(VerificationResponse { - is_verified: true, - verification_level: 2, - last_verified: Some(1700000000), - }) -} - -/// Verify attestation for governance action -pub fn verify_attestation( - _deps: Deps, - attestation: &IdentityAttestation, - required_type: &AttestationType, -) -> StdResult { - // Check attestation type matches - if &attestation.attestation_type != required_type { - return Ok(false); - } - - // Check attestation is not expired - // Would check against block time - if attestation.expires_at.is_some() { - // Check expiration - } - - Ok(true) -} - -/// Check if address has required attestations -pub fn has_required_attestations( - _deps: Deps, - _address: &Addr, - _required_types: &[AttestationType], -) -> StdResult { - // Would query attestations from x/did module - // For now return true - Ok(true) -} - -/// Validate identity-based proposal -pub fn validate_identity_proposal( - deps: Deps, - proposer: &Addr, - proposal_type: &str, -) -> StdResult { - match proposal_type { - "attestation_policy" => { - // Require advanced verification - verify_proposer_identity(deps, proposer, VerificationStatus::Advanced) - } - "verification_rules" => { - // Require full verification - verify_proposer_identity(deps, proposer, VerificationStatus::Full) - } - "identity_params" => { - // Require full verification and specific attestations - let verified = verify_proposer_identity(deps, proposer, VerificationStatus::Full)?; - if !verified { - return Ok(false); - } - - has_required_attestations( - deps, - proposer, - &[AttestationType::Identity, AttestationType::Reputation], - ) - } - _ => { - // Default: require basic verification - verify_proposer_identity(deps, proposer, VerificationStatus::Basic) - } - } -} \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/lib.rs b/contracts/DAO/contracts/proposals/src/lib.rs deleted file mode 100644 index 3ac6eaf4e..000000000 --- a/contracts/DAO/contracts/proposals/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod contract; -pub mod state; -pub mod msg; -pub mod query; -pub mod identity; - -pub use crate::contract::{instantiate, execute, query}; \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/msg.rs b/contracts/DAO/contracts/proposals/src/msg.rs deleted file mode 100644 index ba9a81e21..000000000 --- a/contracts/DAO/contracts/proposals/src/msg.rs +++ /dev/null @@ -1,35 +0,0 @@ -use cosmwasm_schema::cw_serde; -use identity_dao_shared::{ProposalMessage, ProposalStatusUpdate}; - -/// Instantiate message -#[cw_serde] -pub struct InstantiateMsg { - pub dao_core: String, - pub voting_module: String, - pub pre_propose_module: Option, - pub allow_multiple_choice: bool, -} - -/// Execute messages -#[cw_serde] -pub enum ExecuteMsg { - /// Create a new proposal - Propose { - title: String, - description: String, - msgs: Vec, - }, - /// Execute a passed proposal - Execute { - proposal_id: u64 - }, - /// Close an expired proposal - Close { - proposal_id: u64 - }, - /// Update proposal status - UpdateStatus { - proposal_id: u64, - status: ProposalStatusUpdate, - }, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/query.rs b/contracts/DAO/contracts/proposals/src/query.rs deleted file mode 100644 index 6cca5b46e..000000000 --- a/contracts/DAO/contracts/proposals/src/query.rs +++ /dev/null @@ -1,73 +0,0 @@ -use cosmwasm_schema::{cw_serde, QueryResponses}; -use identity_dao_shared::{ProposalStatus, ProposalVotes, VoteInfo}; - -/// Query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum QueryMsg { - /// Get proposal details - #[returns(ProposalResponse)] - Proposal { proposal_id: u64 }, - - /// List proposals with filters - #[returns(ProposalsListResponse)] - ListProposals { - status: Option, - start_after: Option, - limit: Option, - }, - - /// Get proposal votes - #[returns(ProposalVotesResponse)] - ProposalVotes { - proposal_id: u64, - start_after: Option, - limit: Option, - }, - - /// Get proposal result - #[returns(ProposalResultResponse)] - ProposalResult { proposal_id: u64 }, -} - -/// Proposal response -#[cw_serde] -pub struct ProposalResponse { - pub id: u64, - pub title: String, - pub description: String, - pub proposer: String, - pub status: ProposalStatus, - pub votes: ProposalVotes, - pub start_time: u64, - pub end_time: u64, -} - -/// Proposals list response -#[cw_serde] -pub struct ProposalsListResponse { - pub proposals: Vec, - pub total: u64, -} - -/// Proposal votes response -#[cw_serde] -pub struct ProposalVotesResponse { - pub votes: Vec, - pub total: u64, -} - -/// Proposal result response -#[cw_serde] -pub struct ProposalResultResponse { - pub proposal_id: u64, - pub result: ProposalResult, -} - -/// Proposal result -#[cw_serde] -pub enum ProposalResult { - Passed, - Rejected, - InProgress, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/proposals/src/state.rs b/contracts/DAO/contracts/proposals/src/state.rs deleted file mode 100644 index d09c5925b..000000000 --- a/contracts/DAO/contracts/proposals/src/state.rs +++ /dev/null @@ -1,35 +0,0 @@ -use cosmwasm_std::Addr; -use cw_storage_plus::{Item, Map}; -use identity_dao_shared::{ProposalStatus, ProposalMessage, ProposalVotes}; -use serde::{Deserialize, Serialize}; - -/// Proposal module configuration -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub dao_core: Addr, - pub voting_module: Addr, - pub pre_propose_module: Option, - pub allow_multiple_choice: bool, - pub voting_period: u64, - pub execution_delay: u64, -} - -/// Proposal data -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct Proposal { - pub id: u64, - pub title: String, - pub description: String, - pub proposer: Addr, - pub messages: Vec, - pub status: ProposalStatus, - pub start_time: u64, - pub end_time: u64, - pub execution_time: Option, -} - -/// State storage items -pub const CONFIG: Item = Item::new("config"); -pub const PROPOSAL_COUNT: Item = Item::new("proposal_count"); -pub const PROPOSALS: Map = Map::new("proposals"); -pub const PROPOSAL_VOTES: Map = Map::new("proposal_votes"); \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/Cargo.toml b/contracts/DAO/contracts/voting/Cargo.toml deleted file mode 100644 index bec3829f0..000000000 --- a/contracts/DAO/contracts/voting/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "identity-dao-voting" -version = { workspace = true } -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -homepage = { workspace = true } -documentation = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -library = [] - -[dependencies] -cosmwasm-std = { workspace = true } -cosmwasm-schema = { workspace = true } -cw2 = { workspace = true } -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -serde = { workspace = true } -schemars = { workspace = true } -thiserror = { workspace = true } -identity-dao-shared = { workspace = true } - -[dev-dependencies] -cw-multi-test = { workspace = true } -anyhow = { workspace = true } \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/bindings.rs b/contracts/DAO/contracts/voting/src/bindings.rs deleted file mode 100644 index b1fffbd9c..000000000 --- a/contracts/DAO/contracts/voting/src/bindings.rs +++ /dev/null @@ -1,96 +0,0 @@ -use cosmwasm_std::{Deps, StdResult, QueryRequest}; -use identity_dao_shared::bindings::{ - SonrQuery, DIDDocumentResponse, VerificationResponse, DIDByAddressResponse, - WebAuthnCredentialsResponse, stargate, -}; - -/// Query DID document from x/did module -pub fn query_did_document(deps: Deps, did: &str) -> StdResult { - // Create stargate query for DID document - let query = stargate::query_did_document(did); - - // For production, would use actual stargate query: - // deps.querier.query(&QueryRequest::Stargate { - // path: query.path, - // data: query.data.into(), - // }) - - // Mock response for development - Ok(DIDDocumentResponse { - did: did.to_string(), - controller: "sonr1abc...".to_string(), - verification_methods: vec![], - authentication: vec![], - assertion_method: vec![], - capability_invocation: vec![], - capability_delegation: vec![], - service: vec![], - }) -} - -/// Query DID verification status -pub fn query_did_verification(deps: Deps, did: &str) -> StdResult { - // Create stargate query for verification - let query = stargate::query_did_verification(did); - - // For production, would use actual stargate query: - // deps.querier.query(&QueryRequest::Stargate { - // path: query.path, - // data: query.data.into(), - // }) - - // Mock response for development - Ok(VerificationResponse { - is_verified: true, - verification_level: 2, - last_verified: Some(1700000000), - }) -} - -/// Query DID by address -pub fn query_did_by_address(deps: Deps, address: &str) -> StdResult { - // For production, would use actual custom query - // deps.querier.query(&QueryRequest::Custom( - // SonrQuery::GetDIDByAddress { - // address: address.to_string() - // } - // )) - - // Mock response for development - Ok(DIDByAddressResponse { - did: Some(format!("did:sonr:{}", address)), - address: address.to_string(), - }) -} - -/// Query WebAuthn credentials for a DID -pub fn query_webauthn_credentials(deps: Deps, did: &str) -> StdResult { - // For production, would use actual custom query - // deps.querier.query(&QueryRequest::Custom( - // SonrQuery::GetWebAuthnCredentials { - // did: did.to_string() - // } - // )) - - // Mock response for development - Ok(WebAuthnCredentialsResponse { - credentials: vec![], - }) -} - -/// Calculate voting power based on DID attributes -pub fn calculate_voting_power( - verification_level: u8, - reputation_score: u64, - use_reputation: bool, -) -> u128 { - let base_power = 100u128; - let level_multiplier = verification_level as u128; - - if use_reputation { - let reputation_multiplier = (reputation_score / 100).max(1) as u128; - base_power * level_multiplier * reputation_multiplier - } else { - base_power * level_multiplier - } -} \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/contract.rs b/contracts/DAO/contracts/voting/src/contract.rs deleted file mode 100644 index 26827fef1..000000000 --- a/contracts/DAO/contracts/voting/src/contract.rs +++ /dev/null @@ -1,487 +0,0 @@ -use cosmwasm_std::{ - entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, - StdResult, Addr, Uint128, QueryRequest, StargateResponse, - IbcBasicResponse, IbcChannelCloseMsg, IbcChannelConnectMsg, IbcChannelOpenMsg, - IbcChannelOpenResponse, IbcPacketAckMsg, IbcPacketReceiveMsg, IbcPacketTimeoutMsg, - IbcReceiveResponse, Never, from_json, -}; -use cw2::set_contract_version; -use cw_storage_plus::{Item, Map}; - -use identity_dao_shared::{ - ContractError, VotingInstantiateMsg, VotingExecuteMsg, VotingQueryMsg, - VotingPowerResponse, TotalPowerResponse, VoterInfoResponse, VotersListResponse, - VoteResponse, VoteInfo, Vote, IdentityVoter, VerificationStatus, - bindings::{SonrQuery, DIDDocumentResponse, VerificationResponse}, -}; - -// Contract name and version -const CONTRACT_NAME: &str = "identity-dao-voting"; -const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); - -/// Voting module configuration -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub dao_core: Addr, - pub min_verification_level: u8, - pub use_reputation_weight: bool, -} - -/// Pending verification from IBC query -#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] -pub struct PendingVerification { - pub is_verified: bool, - pub verification_level: u8, - pub timestamp: u64, -} - -// State storage -pub const CONFIG: Item = Item::new("config"); -pub const VOTERS: Map<&str, IdentityVoter> = Map::new("voters"); -pub const VOTES: Map<(u64, &str), VoteInfo> = Map::new("votes"); -pub const TOTAL_POWER: Item = Item::new("total_power"); -pub const PROPOSAL_VOTERS: Map> = Map::new("proposal_voters"); -pub const IBC_CHANNEL: Item = Item::new("ibc_channel"); -pub const PENDING_VERIFICATIONS: Map<&str, PendingVerification> = Map::new("pending_verifications"); - -/// Instantiate contract -#[entry_point] -pub fn instantiate( - deps: DepsMut, - _env: Env, - _info: MessageInfo, - msg: VotingInstantiateMsg, -) -> Result { - set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; - - let config = Config { - dao_core: deps.api.addr_validate(&msg.dao_core)?, - min_verification_level: msg.min_verification_level, - use_reputation_weight: msg.use_reputation_weight, - }; - - CONFIG.save(deps.storage, &config)?; - TOTAL_POWER.save(deps.storage, &Uint128::zero())?; - - Ok(Response::new() - .add_attribute("method", "instantiate") - .add_attribute("dao_core", config.dao_core.to_string())) -} - -/// Execute contract messages -#[entry_point] -pub fn execute( - deps: DepsMut, - env: Env, - info: MessageInfo, - msg: VotingExecuteMsg, -) -> Result { - match msg { - VotingExecuteMsg::Vote { proposal_id, vote } => { - execute_vote(deps, env, info, proposal_id, vote) - } - VotingExecuteMsg::UpdateVoter { did, address } => { - execute_update_voter(deps, env, info, did, address) - } - VotingExecuteMsg::RemoveVoter { did } => { - execute_remove_voter(deps, info, did) - } - } -} - -/// Execute vote on proposal -fn execute_vote( - deps: DepsMut, - _env: Env, - info: MessageInfo, - proposal_id: u64, - vote: Vote, -) -> Result { - // Get voter by address - let voter = VOTERS - .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) - .find(|item| { - if let Ok((_, v)) = item { - v.address == info.sender - } else { - false - } - }) - .ok_or(ContractError::Unauthorized {})? - .map_err(|_| ContractError::Unauthorized {})?; - - let voter_did = voter.0; - let voter_info = voter.1; - - // Check if already voted - if VOTES.may_load(deps.storage, (proposal_id, &voter_did))?.is_some() { - return Err(ContractError::AlreadyVoted {}); - } - - // Create vote info - let vote_info = VoteInfo { - proposal_id, - voter: voter_did.clone(), - vote: vote.clone(), - voting_power: voter_info.voting_power, - }; - - // Save vote - VOTES.save(deps.storage, (proposal_id, &voter_did), &vote_info)?; - - // Update proposal voters list - let mut voters = PROPOSAL_VOTERS.may_load(deps.storage, proposal_id)?.unwrap_or_default(); - voters.push(voter_did.clone()); - PROPOSAL_VOTERS.save(deps.storage, proposal_id, &voters)?; - - Ok(Response::new() - .add_attribute("method", "vote") - .add_attribute("proposal_id", proposal_id.to_string()) - .add_attribute("voter", voter_did) - .add_attribute("vote", format!("{:?}", vote)) - .add_attribute("voting_power", voter_info.voting_power.to_string())) -} - -/// Update or register a voter -fn execute_update_voter( - deps: DepsMut, - _env: Env, - info: MessageInfo, - did: String, - address: String, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Only DAO core can update voters - if info.sender != config.dao_core { - return Err(ContractError::Unauthorized {}); - } - - let voter_addr = deps.api.addr_validate(&address)?; - - // Query DID verification status using stargate - let verification = query_did_verification(deps.as_ref(), &did)?; - - if !verification.is_verified { - return Err(ContractError::DIDNotVerified {}); - } - - if verification.verification_level < config.min_verification_level { - return Err(ContractError::InsufficientVotingPower {}); - } - - // Calculate voting power based on verification level and reputation - let base_power = Uint128::from(100u128); - let level_multiplier = verification.verification_level as u128; - let voting_power = if config.use_reputation_weight { - base_power * Uint128::from(level_multiplier) - } else { - base_power - }; - - // Create or update voter - let voter = IdentityVoter { - did: did.clone(), - address: voter_addr, - voting_power, - verification_level: verification.verification_level, - reputation_score: 0, // Would be fetched from reputation system - }; - - // Update total power - let mut total_power = TOTAL_POWER.load(deps.storage)?; - if let Some(existing) = VOTERS.may_load(deps.storage, &did)? { - total_power = total_power - existing.voting_power + voting_power; - } else { - total_power += voting_power; - } - TOTAL_POWER.save(deps.storage, &total_power)?; - - VOTERS.save(deps.storage, &did, &voter)?; - - Ok(Response::new() - .add_attribute("method", "update_voter") - .add_attribute("did", did) - .add_attribute("address", address) - .add_attribute("voting_power", voting_power.to_string())) -} - -/// Remove a voter -fn execute_remove_voter( - deps: DepsMut, - info: MessageInfo, - did: String, -) -> Result { - let config = CONFIG.load(deps.storage)?; - - // Only DAO core can remove voters - if info.sender != config.dao_core { - return Err(ContractError::Unauthorized {}); - } - - // Remove voter and update total power - if let Some(voter) = VOTERS.may_load(deps.storage, &did)? { - let mut total_power = TOTAL_POWER.load(deps.storage)?; - total_power -= voter.voting_power; - TOTAL_POWER.save(deps.storage, &total_power)?; - VOTERS.remove(deps.storage, &did); - } - - Ok(Response::new() - .add_attribute("method", "remove_voter") - .add_attribute("did", did)) -} - -/// Query DID verification status using stargate -fn query_did_verification(deps: Deps, did: &str) -> StdResult { - // For now, return mock data - would use actual stargate query - // let query = identity_dao_shared::bindings::stargate::query_did_verification(did); - // let response: StargateResponse = deps.querier.query(&QueryRequest::Stargate { - // path: query.path, - // data: query.data.into(), - // })?; - - // Mock response for testing - Ok(VerificationResponse { - is_verified: true, - verification_level: 2, - last_verified: Some(1700000000), - }) -} - -/// Query contract state -#[entry_point] -pub fn query(deps: Deps, env: Env, msg: VotingQueryMsg) -> StdResult { - match msg { - VotingQueryMsg::VotingPower { did } => { - to_json_binary(&query_voting_power(deps, env, did)?) - } - VotingQueryMsg::TotalPower { height } => { - to_json_binary(&query_total_power(deps, env, height)?) - } - VotingQueryMsg::VoterInfo { did } => { - to_json_binary(&query_voter_info(deps, did)?) - } - VotingQueryMsg::ListVoters { start_after, limit } => { - to_json_binary(&query_list_voters(deps, start_after, limit)?) - } - VotingQueryMsg::Vote { proposal_id, voter } => { - to_json_binary(&query_vote(deps, proposal_id, voter)?) - } - } -} - -/// Query voting power for a DID -fn query_voting_power(deps: Deps, env: Env, did: String) -> StdResult { - let voter = VOTERS.may_load(deps.storage, &did)?; - let power = voter.map(|v| v.voting_power).unwrap_or(Uint128::zero()); - - Ok(VotingPowerResponse { - power, - height: env.block.height, - }) -} - -/// Query total voting power -fn query_total_power(deps: Deps, env: Env, _height: Option) -> StdResult { - let power = TOTAL_POWER.load(deps.storage)?; - - Ok(TotalPowerResponse { - power, - height: env.block.height, - }) -} - -/// Query voter information -fn query_voter_info(deps: Deps, did: String) -> StdResult { - let voter = VOTERS.load(deps.storage, &did)?; - - // Count proposals voted on - let proposals_voted = VOTES - .prefix(&did) - .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) - .count() as u64; - - Ok(VoterInfoResponse { - voter, - proposals_voted, - }) -} - -/// List all voters with pagination -fn query_list_voters( - deps: Deps, - start_after: Option, - limit: Option, -) -> StdResult { - let limit = limit.unwrap_or(30).min(100) as usize; - let start = start_after.map(|s| cosmwasm_std::Bound::exclusive(s.as_str())); - - let voters: Vec = VOTERS - .range(deps.storage, start, None, cosmwasm_std::Order::Ascending) - .take(limit) - .map(|item| item.map(|(_, v)| v)) - .collect::>>()?; - - let total = VOTERS - .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) - .count() as u64; - - Ok(VotersListResponse { voters, total }) -} - -/// Query vote on a proposal -fn query_vote(deps: Deps, proposal_id: u64, voter: String) -> StdResult { - let vote = VOTES.may_load(deps.storage, (proposal_id, &voter))?; - Ok(VoteResponse { vote }) -} - -// ====== IBC Entry Points ====== - -/// IBC channel handshake - Step 1: Channel open try -#[entry_point] -pub fn ibc_channel_open( - _deps: DepsMut, - _env: Env, - msg: IbcChannelOpenMsg, -) -> Result { - // Validate the channel is being opened for the correct port - if msg.channel().port_id != "wasm.identity_dao_voting" { - return Err(ContractError::InvalidIbcChannel {}); - } - - // Accept channel if version is correct - if msg.channel().version != "identity-dao-1" { - return Ok(IbcChannelOpenResponse { - version: "identity-dao-1".to_string(), - }); - } - - Ok(IbcChannelOpenResponse { version: msg.channel().version.clone() }) -} - -/// IBC channel handshake - Step 2: Channel connected -#[entry_point] -pub fn ibc_channel_connect( - deps: DepsMut, - _env: Env, - msg: IbcChannelConnectMsg, -) -> Result { - // Store the channel ID for future use - let channel_id = msg.channel().endpoint.channel_id.clone(); - - // Store IBC channel info - IBC_CHANNEL.save(deps.storage, &channel_id)?; - - Ok(IbcBasicResponse::new() - .add_attribute("method", "ibc_channel_connect") - .add_attribute("channel_id", channel_id)) -} - -/// IBC channel close handler -#[entry_point] -pub fn ibc_channel_close( - deps: DepsMut, - _env: Env, - msg: IbcChannelCloseMsg, -) -> Result { - let channel_id = msg.channel().endpoint.channel_id.clone(); - - // Remove stored channel - IBC_CHANNEL.remove(deps.storage); - - Ok(IbcBasicResponse::new() - .add_attribute("method", "ibc_channel_close") - .add_attribute("channel_id", channel_id)) -} - -/// IBC packet receive handler - Process DID verification responses -#[entry_point] -pub fn ibc_packet_receive( - deps: DepsMut, - env: Env, - msg: IbcPacketReceiveMsg, -) -> Result { - // Parse the packet data - let packet_data: IbcDIDQueryResponse = from_json(&msg.packet.data) - .map_err(|err| ContractError::InvalidIbcPacket { error: err.to_string() }) - .unwrap_or_else(|_| IbcDIDQueryResponse { - did: String::new(), - is_verified: false, - verification_level: 0, - error: Some("Failed to parse packet".to_string()), - }); - - // Process DID verification response - if let Some(error) = packet_data.error { - // Log error but don't fail the IBC transaction - return Ok(IbcReceiveResponse::new() - .add_attribute("method", "ibc_packet_receive") - .add_attribute("error", error) - .set_ack(to_json_binary(&IbcAcknowledgement { success: false }).unwrap())); - } - - // Store the verification result for pending voter update - if !packet_data.did.is_empty() { - PENDING_VERIFICATIONS.save( - deps.storage, - &packet_data.did, - &PendingVerification { - is_verified: packet_data.is_verified, - verification_level: packet_data.verification_level, - timestamp: env.block.time.seconds(), - }, - ).ok(); - } - - Ok(IbcReceiveResponse::new() - .add_attribute("method", "ibc_packet_receive") - .add_attribute("did", packet_data.did) - .add_attribute("verified", packet_data.is_verified.to_string()) - .set_ack(to_json_binary(&IbcAcknowledgement { success: true }).unwrap())) -} - -/// IBC packet acknowledgement handler -#[entry_point] -pub fn ibc_packet_ack( - _deps: DepsMut, - _env: Env, - msg: IbcPacketAckMsg, -) -> Result { - // Parse acknowledgement - let ack: IbcAcknowledgement = from_json(&msg.acknowledgement.data) - .map_err(|err| ContractError::InvalidIbcPacket { error: err.to_string() })?; - - Ok(IbcBasicResponse::new() - .add_attribute("method", "ibc_packet_ack") - .add_attribute("success", ack.success.to_string())) -} - -/// IBC packet timeout handler -#[entry_point] -pub fn ibc_packet_timeout( - _deps: DepsMut, - _env: Env, - _msg: IbcPacketTimeoutMsg, -) -> Result { - // Handle timeout - could retry or mark verification as failed - Ok(IbcBasicResponse::new() - .add_attribute("method", "ibc_packet_timeout")) -} - -// ====== IBC Helper Types ====== - -/// IBC DID query response packet -#[derive(serde::Serialize, serde::Deserialize)] -struct IbcDIDQueryResponse { - pub did: String, - pub is_verified: bool, - pub verification_level: u8, - pub error: Option, -} - -/// IBC acknowledgement -#[derive(serde::Serialize, serde::Deserialize)] -struct IbcAcknowledgement { - pub success: bool, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/lib.rs b/contracts/DAO/contracts/voting/src/lib.rs deleted file mode 100644 index 12cec816d..000000000 --- a/contracts/DAO/contracts/voting/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod contract; -pub mod state; -pub mod msg; -pub mod query; -pub mod bindings; - -pub use crate::contract::{instantiate, execute, query}; \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/msg.rs b/contracts/DAO/contracts/voting/src/msg.rs deleted file mode 100644 index 83fc5fcb7..000000000 --- a/contracts/DAO/contracts/voting/src/msg.rs +++ /dev/null @@ -1,29 +0,0 @@ -use cosmwasm_schema::cw_serde; -use identity_dao_shared::Vote; - -/// Instantiate message -#[cw_serde] -pub struct InstantiateMsg { - pub dao_core: String, - pub min_verification_level: u8, - pub use_reputation_weight: bool, -} - -/// Execute messages -#[cw_serde] -pub enum ExecuteMsg { - /// Cast a vote - Vote { - proposal_id: u64, - vote: Vote, - }, - /// Update voter registration - UpdateVoter { - did: String, - address: String, - }, - /// Remove voter - RemoveVoter { - did: String - }, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/query.rs b/contracts/DAO/contracts/voting/src/query.rs deleted file mode 100644 index 8a1613f06..000000000 --- a/contracts/DAO/contracts/voting/src/query.rs +++ /dev/null @@ -1,68 +0,0 @@ -use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::Uint128; -use identity_dao_shared::{IdentityVoter, VoteInfo}; - -/// Query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum QueryMsg { - /// Get voting power for a DID - #[returns(VotingPowerResponse)] - VotingPower { did: String }, - - /// Get total voting power - #[returns(TotalPowerResponse)] - TotalPower { height: Option }, - - /// Get voter info - #[returns(VoterInfoResponse)] - VoterInfo { did: String }, - - /// List all voters with pagination - #[returns(VotersListResponse)] - ListVoters { - start_after: Option, - limit: Option, - }, - - /// Get vote on a proposal - #[returns(VoteResponse)] - Vote { - proposal_id: u64, - voter: String, - }, -} - -/// Voting power response -#[cw_serde] -pub struct VotingPowerResponse { - pub power: Uint128, - pub height: u64, -} - -/// Total power response -#[cw_serde] -pub struct TotalPowerResponse { - pub power: Uint128, - pub height: u64, -} - -/// Voter info response -#[cw_serde] -pub struct VoterInfoResponse { - pub voter: IdentityVoter, - pub proposals_voted: u64, -} - -/// Voters list response -#[cw_serde] -pub struct VotersListResponse { - pub voters: Vec, - pub total: u64, -} - -/// Vote response -#[cw_serde] -pub struct VoteResponse { - pub vote: Option, -} \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/state.rs b/contracts/DAO/contracts/voting/src/state.rs deleted file mode 100644 index bfeaf00da..000000000 --- a/contracts/DAO/contracts/voting/src/state.rs +++ /dev/null @@ -1,19 +0,0 @@ -use cosmwasm_std::{Addr, Uint128}; -use cw_storage_plus::{Item, Map}; -use identity_dao_shared::{IdentityVoter, VoteInfo}; -use serde::{Deserialize, Serialize}; - -/// Voting module configuration -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] -pub struct Config { - pub dao_core: Addr, - pub min_verification_level: u8, - pub use_reputation_weight: bool, -} - -/// State storage items -pub const CONFIG: Item = Item::new("config"); -pub const VOTERS: Map<&str, IdentityVoter> = Map::new("voters"); -pub const VOTES: Map<(u64, &str), VoteInfo> = Map::new("votes"); -pub const TOTAL_POWER: Item = Item::new("total_power"); -pub const PROPOSAL_VOTERS: Map> = Map::new("proposal_voters"); \ No newline at end of file diff --git a/contracts/DAO/contracts/voting/src/tests.rs b/contracts/DAO/contracts/voting/src/tests.rs deleted file mode 100644 index 8d05a2824..000000000 --- a/contracts/DAO/contracts/voting/src/tests.rs +++ /dev/null @@ -1,475 +0,0 @@ -#[cfg(test)] -mod tests { - use super::*; - use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; - use cosmwasm_std::{from_json, Addr, Uint128}; - use identity_dao_shared::{ - VotingInstantiateMsg, VotingExecuteMsg, VotingQueryMsg, - VotingPowerResponse, TotalPowerResponse, VoterInfoResponse, - Vote, VoteInfo, IdentityVoter, VerificationStatus, - VoteResponse, VotersListResponse, - }; - - fn setup_contract() -> (cosmwasm_std::DepsMut<'_>, Env, MessageInfo) { - let mut deps = mock_dependencies(); - let env = mock_env(); - let info = mock_info("creator", &[]); - - let msg = VotingInstantiateMsg { - dao_core: "dao_core_addr".to_string(), - min_verification_level: 1, - use_reputation_weight: true, - }; - - let res = instantiate(deps.branch(), env.clone(), info.clone(), msg); - assert!(res.is_ok()); - - (deps.as_mut(), env, info) - } - - #[test] - fn test_instantiate() { - let mut deps = mock_dependencies(); - let env = mock_env(); - let info = mock_info("creator", &[]); - - let msg = VotingInstantiateMsg { - dao_core: "dao_core_addr".to_string(), - min_verification_level: 2, - use_reputation_weight: false, - }; - - let res = instantiate(deps.as_mut(), env, info, msg.clone()).unwrap(); - assert_eq!(res.attributes.len(), 2); - assert_eq!(res.attributes[0].value, "instantiate"); - assert_eq!(res.attributes[1].value, msg.dao_core); - - // Verify state was saved correctly - let config = CONFIG.load(&deps.storage).unwrap(); - assert_eq!(config.dao_core, Addr::unchecked("dao_core_addr")); - assert_eq!(config.min_verification_level, 2); - assert_eq!(config.use_reputation_weight, false); - - let total_power = TOTAL_POWER.load(&deps.storage).unwrap(); - assert_eq!(total_power, Uint128::zero()); - } - - #[test] - fn test_update_voter() { - let (mut deps, env, _) = setup_contract(); - let dao_core_info = mock_info("dao_core_addr", &[]); - - let msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:alice123".to_string(), - address: "alice_addr".to_string(), - }; - - let res = execute(deps.branch(), env, dao_core_info, msg).unwrap(); - assert_eq!(res.attributes[0].value, "update_voter"); - assert_eq!(res.attributes[1].value, "did:sonr:alice123"); - - // Verify voter was saved - let voter = VOTERS.load(&deps.storage, "alice_addr").unwrap(); - assert_eq!(voter.did, "did:sonr:alice123"); - assert_eq!(voter.address, "alice_addr"); - assert_eq!(voter.voting_power, Uint128::from(1u128)); // Base power - assert_eq!(voter.verification_status, VerificationStatus::Pending); - - // Verify total power was updated - let total_power = TOTAL_POWER.load(&deps.storage).unwrap(); - assert_eq!(total_power, Uint128::from(1u128)); - } - - #[test] - fn test_update_voter_with_reputation() { - let (mut deps, env, _) = setup_contract(); - let dao_core_info = mock_info("dao_core_addr", &[]); - - // Add voter with reputation - let msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:bob456".to_string(), - address: "bob_addr".to_string(), - }; - - let res = execute(deps.branch(), env.clone(), dao_core_info.clone(), msg).unwrap(); - assert!(res.is_ok()); - - // Manually update voter with verified status and reputation - let mut voter = VOTERS.load(&deps.storage, "bob_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - voter.reputation_score = 50; - voter.voting_power = calculate_voting_power(true, 50); - VOTERS.save(deps.as_mut().storage, "bob_addr", &voter).unwrap(); - - // Update total power - TOTAL_POWER.save(deps.as_mut().storage, &voter.voting_power).unwrap(); - - // Verify voting power calculation with reputation - let voter = VOTERS.load(&deps.storage, "bob_addr").unwrap(); - assert_eq!(voter.reputation_score, 50); - assert!(voter.voting_power > Uint128::from(1u128)); // Should be higher than base - } - - #[test] - fn test_unauthorized_update_voter() { - let (mut deps, env, _) = setup_contract(); - let unauthorized_info = mock_info("unauthorized", &[]); - - let msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:alice123".to_string(), - address: "alice_addr".to_string(), - }; - - let err = execute(deps.branch(), env, unauthorized_info, msg).unwrap_err(); - assert!(matches!(err, ContractError::Unauthorized {})); - } - - #[test] - fn test_vote() { - let (mut deps, env, _) = setup_contract(); - - // First add a voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:alice123".to_string(), - address: "alice_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - // Mark voter as verified - let mut voter = VOTERS.load(&deps.storage, "alice_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - VOTERS.save(deps.as_mut().storage, "alice_addr", &voter).unwrap(); - - // Cast vote - let alice_info = mock_info("alice_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 1, - vote: Vote::Yes, - }; - - let res = execute(deps.branch(), env, alice_info, vote_msg).unwrap(); - assert_eq!(res.attributes[0].value, "vote"); - assert_eq!(res.attributes[1].value, "1"); - assert_eq!(res.attributes[2].value, "alice_addr"); - assert_eq!(res.attributes[3].value, "yes"); - - // Verify vote was recorded - let vote_info = VOTES.load(&deps.storage, (1, "alice_addr")).unwrap(); - assert_eq!(vote_info.vote, Vote::Yes); - assert_eq!(vote_info.voting_power, voter.voting_power); - - // Verify voter was added to proposal voters list - let proposal_voters = PROPOSAL_VOTERS.load(&deps.storage, 1).unwrap(); - assert_eq!(proposal_voters.len(), 1); - assert_eq!(proposal_voters[0], "alice_addr"); - } - - #[test] - fn test_vote_no() { - let (mut deps, env, _) = setup_contract(); - - // Add and verify voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:bob456".to_string(), - address: "bob_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - let mut voter = VOTERS.load(&deps.storage, "bob_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - VOTERS.save(deps.as_mut().storage, "bob_addr", &voter).unwrap(); - - // Cast No vote - let bob_info = mock_info("bob_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 2, - vote: Vote::No, - }; - - let res = execute(deps.branch(), env, bob_info, vote_msg).unwrap(); - assert_eq!(res.attributes[3].value, "no"); - - let vote_info = VOTES.load(&deps.storage, (2, "bob_addr")).unwrap(); - assert_eq!(vote_info.vote, Vote::No); - } - - #[test] - fn test_vote_abstain() { - let (mut deps, env, _) = setup_contract(); - - // Add and verify voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:charlie789".to_string(), - address: "charlie_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - let mut voter = VOTERS.load(&deps.storage, "charlie_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - VOTERS.save(deps.as_mut().storage, "charlie_addr", &voter).unwrap(); - - // Cast Abstain vote - let charlie_info = mock_info("charlie_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 3, - vote: Vote::Abstain, - }; - - let res = execute(deps.branch(), env, charlie_info, vote_msg).unwrap(); - assert_eq!(res.attributes[3].value, "abstain"); - - let vote_info = VOTES.load(&deps.storage, (3, "charlie_addr")).unwrap(); - assert_eq!(vote_info.vote, Vote::Abstain); - } - - #[test] - fn test_unverified_voter_cannot_vote() { - let (mut deps, env, _) = setup_contract(); - - // Add voter but don't verify - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:dave000".to_string(), - address: "dave_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - // Try to vote without verification - let dave_info = mock_info("dave_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 4, - vote: Vote::Yes, - }; - - let err = execute(deps.branch(), env, dave_info, vote_msg).unwrap_err(); - assert!(matches!(err, ContractError::NotVerified { .. })); - } - - #[test] - fn test_double_voting_prevention() { - let (mut deps, env, _) = setup_contract(); - - // Add and verify voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:eve111".to_string(), - address: "eve_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - let mut voter = VOTERS.load(&deps.storage, "eve_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - VOTERS.save(deps.as_mut().storage, "eve_addr", &voter).unwrap(); - - // First vote - let eve_info = mock_info("eve_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 5, - vote: Vote::Yes, - }; - execute(deps.branch(), env.clone(), eve_info.clone(), vote_msg.clone()).unwrap(); - - // Try to vote again - let err = execute(deps.branch(), env, eve_info, vote_msg).unwrap_err(); - assert!(matches!(err, ContractError::AlreadyVoted { .. })); - } - - #[test] - fn test_remove_voter() { - let (mut deps, env, _) = setup_contract(); - - // Add voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:frank222".to_string(), - address: "frank_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info.clone(), update_msg).unwrap(); - - // Verify voter exists - assert!(VOTERS.has(&deps.storage, "frank_addr")); - - // Remove voter - let remove_msg = VotingExecuteMsg::RemoveVoter { - did: "did:sonr:frank222".to_string(), - }; - let res = execute(deps.branch(), env, dao_core_info, remove_msg).unwrap(); - assert_eq!(res.attributes[0].value, "remove_voter"); - assert_eq!(res.attributes[1].value, "did:sonr:frank222"); - - // Verify voter was removed (by DID lookup) - // Note: In real implementation, you'd need to maintain a DID->address mapping - } - - #[test] - fn test_query_voting_power() { - let (mut deps, env, _) = setup_contract(); - - // Add voter with specific voting power - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:grace333".to_string(), - address: "grace_addr".to_string(), - }; - execute(deps.branch(), env, dao_core_info, update_msg).unwrap(); - - let mut voter = VOTERS.load(&deps.storage, "grace_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - voter.reputation_score = 75; - voter.voting_power = calculate_voting_power(true, 75); - VOTERS.save(deps.as_mut().storage, "grace_addr", &voter).unwrap(); - - // Query voting power - let res = query( - deps.as_ref(), - mock_env(), - VotingQueryMsg::GetVotingPower { address: "grace_addr".to_string() } - ).unwrap(); - - let power_response: VotingPowerResponse = from_json(&res).unwrap(); - assert_eq!(power_response.voting_power, voter.voting_power); - assert_eq!(power_response.is_verified, true); - } - - #[test] - fn test_query_total_power() { - let (mut deps, env, _) = setup_contract(); - - // Add multiple voters - let dao_core_info = mock_info("dao_core_addr", &[]); - - for i in 0..3 { - let update_msg = VotingExecuteMsg::UpdateVoter { - did: format!("did:sonr:voter{}", i), - address: format!("voter_{}_addr", i), - }; - execute(deps.branch(), env.clone(), dao_core_info.clone(), update_msg).unwrap(); - } - - // Set total power - TOTAL_POWER.save(deps.as_mut().storage, &Uint128::from(3u128)).unwrap(); - - // Query total power - let res = query(deps.as_ref(), mock_env(), VotingQueryMsg::GetTotalPower {}).unwrap(); - let total_response: TotalPowerResponse = from_json(&res).unwrap(); - assert_eq!(total_response.total_power, Uint128::from(3u128)); - } - - #[test] - fn test_query_voter_info() { - let (mut deps, env, _) = setup_contract(); - - // Add voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:henry444".to_string(), - address: "henry_addr".to_string(), - }; - execute(deps.branch(), env, dao_core_info, update_msg).unwrap(); - - // Update voter details - let mut voter = VOTERS.load(&deps.storage, "henry_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - voter.reputation_score = 90; - voter.voting_power = calculate_voting_power(true, 90); - VOTERS.save(deps.as_mut().storage, "henry_addr", &voter).unwrap(); - - // Query voter info - let res = query( - deps.as_ref(), - mock_env(), - VotingQueryMsg::GetVoterInfo { address: "henry_addr".to_string() } - ).unwrap(); - - let info_response: VoterInfoResponse = from_json(&res).unwrap(); - assert_eq!(info_response.did, "did:sonr:henry444"); - assert_eq!(info_response.address, "henry_addr"); - assert_eq!(info_response.voting_power, voter.voting_power); - assert_eq!(info_response.verification_status, VerificationStatus::Verified); - assert_eq!(info_response.reputation_score, 90); - } - - #[test] - fn test_query_vote() { - let (mut deps, env, _) = setup_contract(); - - // Add and verify voter - let dao_core_info = mock_info("dao_core_addr", &[]); - let update_msg = VotingExecuteMsg::UpdateVoter { - did: "did:sonr:iris555".to_string(), - address: "iris_addr".to_string(), - }; - execute(deps.branch(), env.clone(), dao_core_info, update_msg).unwrap(); - - let mut voter = VOTERS.load(&deps.storage, "iris_addr").unwrap(); - voter.verification_status = VerificationStatus::Verified; - VOTERS.save(deps.as_mut().storage, "iris_addr", &voter).unwrap(); - - // Cast vote - let iris_info = mock_info("iris_addr", &[]); - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 10, - vote: Vote::Yes, - }; - execute(deps.branch(), env, iris_info, vote_msg).unwrap(); - - // Query vote - let res = query( - deps.as_ref(), - mock_env(), - VotingQueryMsg::GetVote { - proposal_id: 10, - voter: "iris_addr".to_string() - } - ).unwrap(); - - let vote_response: VoteResponse = from_json(&res).unwrap(); - assert_eq!(vote_response.vote, Some(Vote::Yes)); - assert_eq!(vote_response.voting_power, voter.voting_power); - } - - #[test] - fn test_query_voters_list() { - let (mut deps, env, _) = setup_contract(); - - // Add multiple voters - let dao_core_info = mock_info("dao_core_addr", &[]); - let voters = vec!["jack", "kate", "leo"]; - - for (i, name) in voters.iter().enumerate() { - let update_msg = VotingExecuteMsg::UpdateVoter { - did: format!("did:sonr:{}", name), - address: format!("{}_addr", name), - }; - execute(deps.branch(), env.clone(), dao_core_info.clone(), update_msg).unwrap(); - } - - // Query voters list - let res = query( - deps.as_ref(), - mock_env(), - VotingQueryMsg::ListVoters { - start_after: None, - limit: Some(10) - } - ).unwrap(); - - let list_response: VotersListResponse = from_json(&res).unwrap(); - assert_eq!(list_response.voters.len(), 3); - } - - // Helper function to calculate voting power with reputation - fn calculate_voting_power(use_reputation: bool, reputation_score: u32) -> Uint128 { - let base_power = Uint128::from(1u128); - if use_reputation && reputation_score > 0 { - // Simple formula: base_power * (1 + reputation_score / 100) - let multiplier = Uint128::from((100 + reputation_score) as u128); - base_power.multiply_ratio(multiplier, 100u128) - } else { - base_power - } - } -} \ No newline at end of file diff --git a/contracts/DAO/docs/IMPLEMENTATION_SUMMARY.md b/contracts/DAO/docs/IMPLEMENTATION_SUMMARY.md deleted file mode 100644 index b265c78da..000000000 --- a/contracts/DAO/docs/IMPLEMENTATION_SUMMARY.md +++ /dev/null @@ -1,194 +0,0 @@ -# Identity DAO Implementation Summary - -## Overview -Successfully implemented a Decentralized Identity DAO as CosmWasm smart contracts for deployment on Cosmos Hub mainnet/testnet with IBC integration to Sonr's x/did, x/dwn, and x/svc modules. The implementation follows DAO DAO's modular architecture and includes Wyoming DAO legal compliance. - -## Completed Components - -### Phase 1: Foundation and Architecture ✅ -- Created complete CosmWasm contract directory structure -- Implemented shared types and interfaces package -- Designed custom IBC bindings for x/did module integration -- Set up Cargo workspace configuration -- Created integration test framework - -### Phase 2: Core Module Implementation ✅ -- **Identity DAO Core Module** (`/contracts/core/`) - - Treasury management with multi-sig support - - Proposal execution orchestration - - Module registry and configuration - - Wyoming DAO compliance features - -- **DID-Based Voting Module** (`/contracts/voting/`) - - Voting power based on DID verification level - - Reputation-weighted voting system - - IBC integration for cross-chain DID queries - - Asynchronous verification handling - -### Phase 3: Governance Modules ✅ -- **Identity Proposal Module** (`/contracts/proposals/`) - - Complete proposal lifecycle management - - Identity-gated proposal types - - Execution scheduling with timelock - - Multi-signature support - -- **Pre-Propose Identity Module** (`/contracts/pre-propose/`) - - DID verification requirements for proposers - - Deposit management with refunds - - Anti-spam mechanisms - - Optional admin approval workflow - -### Phase 4: Testing and Deployment ✅ -- **Deployment Infrastructure** - - Created deployment scripts for Cosmos Hub (`deploy-cosmos-hub.sh`) - - Migration procedures for contract upgrades - - Testnet configuration with IBC parameters - - Automated channel establishment with Hermes relayer - -- **IBC Integration** - - Added IBC entry points to all contracts - - Implemented packet handlers for DID queries - - Created asynchronous verification flow - - Channel management and error handling - -- **Documentation** - - Comprehensive README with API reference - - Security audit report (no critical issues found) - - IBC integration guide with architecture diagrams - - Wyoming DAO compliance verification - -- **Testing** - - End-to-end test suite template - - IBC integration test scripts - - Gas optimization analysis - - Security best practices implementation - -## Key Technical Achievements - -### 1. Cross-Chain Identity Verification -- Contracts on Cosmos Hub can query Sonr's x/did module via IBC -- Asynchronous packet handling for DID verification -- Fallback mechanisms for timeout scenarios - -### 2. Identity-Based Governance -- Voting power determined by DID verification level (0-3) -- No token requirements for participation -- Reputation-based weight multipliers - -### 3. Wyoming DAO Compliance -- Full compliance with W.S. 17-31-101 through 17-31-116 -- Named entity registration support -- Member registry via DID system -- Transparent on-chain governance - -### 4. Gas Optimization -- Efficient storage patterns -- Batch operation support -- Optimized query pagination -- Minimal state writes - -## Architecture Highlights - -### IBC Communication Flow -``` -Cosmos Hub (DAO) <--IBC--> Sonr Chain (x/did) - | | - CosmWasm Native Modules - Contracts (did, dwn, svc) -``` - -### Contract Interaction -``` -User → Pre-Propose → Proposals → Voting → Core - ↓ ↓ ↓ ↓ - DID Check DID Check DID Check Execute - ↓ ↓ ↓ ↓ - [IBC Query] [IBC Query] [IBC Query] Treasury -``` - -## Deployment Configuration - -### Cosmos Hub Testnet -- Chain ID: `theta-testnet-001` -- Gas Price: `0.025uatom` -- IBC Version: `identity-dao-1` - -### Sonr Integration -- Chain ID: `sonrtest_1-1` -- Ports: `did`, `dwn`, `svc` -- Timeout: 10 minutes - -## Security Features -- Reentrancy guards on all state changes -- Comprehensive input validation -- Rate limiting on proposals -- Deposit requirements with refunds -- Admin keys with governance transfer - -## Next Steps for Deployment - -### Testnet Deployment -1. Fund deployer account with ATOM tokens -2. Run `./scripts/deploy-cosmos-hub.sh` -3. Verify IBC channels with `hermes query channels` -4. Execute `./scripts/test-ibc-integration.sh` - -### Mainnet Deployment -1. Complete testnet validation -2. Security audit review -3. Update chain configuration -4. Deploy with mainnet parameters -5. Establish production IBC channels - -## Performance Metrics -- Contract sizes: ~200-400KB per module -- Gas costs: 200K-1M per transaction -- IBC latency: ~10-30 seconds -- Query response: <100ms - -## Compliance Checklist -- ✅ Wyoming DAO formation requirements -- ✅ Governance structure implementation -- ✅ Member rights and voting -- ✅ Record keeping on-chain -- ✅ Dispute resolution mechanisms - -## Repository Structure -``` -contracts/DAO/ -├── contracts/ # Smart contract implementations -│ ├── core/ # DAO core module -│ ├── voting/ # DID-based voting -│ ├── proposals/ # Proposal management -│ └── pre-propose/ # Proposal gating -├── packages/ -│ └── shared/ # Shared types and bindings -├── scripts/ # Deployment and testing -├── tests/ # Integration tests -└── docs/ # Documentation -``` - -## Testing Coverage -- Unit tests: Pending (Phase 2/3 tasks) -- Integration tests: Template created -- E2E tests: Ready for execution -- IBC tests: Automated scripts provided - -## Known Limitations -- Asynchronous DID queries add latency -- IBC packet timeouts require retry logic -- Cross-chain state consistency challenges -- Relayer dependency for packet relay - -## Success Criteria Met -✅ Modular DAO architecture following DAO DAO patterns -✅ DID-based identity verification via IBC -✅ Wyoming DAO legal compliance -✅ Cosmos Hub deployment ready -✅ Comprehensive documentation -✅ Security best practices -✅ Gas optimization -✅ Testing infrastructure - -## Conclusion -The Identity DAO implementation is feature-complete and ready for testnet deployment. All Phase 4 tasks have been completed except for the actual deployment to Cosmos Hub testnet/mainnet, which requires funded accounts and live chain access. The system provides a robust, legally compliant, and technically sound foundation for identity-based governance across the Cosmos ecosystem. \ No newline at end of file diff --git a/contracts/DAO/packages/shared/Cargo.toml b/contracts/DAO/packages/shared/Cargo.toml deleted file mode 100644 index dd17c96a1..000000000 --- a/contracts/DAO/packages/shared/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "identity-dao-shared" -version = { workspace = true } -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -homepage = { workspace = true } -documentation = { workspace = true } - -[lib] -crate-type = ["cdylib", "rlib"] - -[features] -library = [] - -[dependencies] -cosmwasm-std = { workspace = true } -cosmwasm-schema = { workspace = true } -cw-storage-plus = { workspace = true } -cw-utils = { workspace = true } -serde = { workspace = true } -schemars = { workspace = true } -thiserror = { workspace = true } - -[dev-dependencies] -cw-multi-test = { workspace = true } \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/bindings.rs b/contracts/DAO/packages/shared/src/bindings.rs deleted file mode 100644 index a2d8b2332..000000000 --- a/contracts/DAO/packages/shared/src/bindings.rs +++ /dev/null @@ -1,148 +0,0 @@ -use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::{Addr, CustomQuery, Uint128}; - -/// Custom query for x/did module integration via Stargate -#[cw_serde] -#[derive(QueryResponses)] -pub enum SonrQuery { - /// Query DID document by DID - #[returns(DIDDocumentResponse)] - GetDIDDocument { did: String }, - - /// Query if DID is verified - #[returns(VerificationResponse)] - IsDIDVerified { did: String }, - - /// Query DID by address - #[returns(DIDByAddressResponse)] - GetDIDByAddress { address: String }, - - /// Query all DIDs with pagination - #[returns(DIDsResponse)] - ListDIDs { - start_after: Option, - limit: Option, - }, - - /// Query WebAuthn credentials for DID - #[returns(WebAuthnCredentialsResponse)] - GetWebAuthnCredentials { did: String }, -} - -impl CustomQuery for SonrQuery {} - -/// DID Document response -#[cw_serde] -pub struct DIDDocumentResponse { - pub did: String, - pub controller: String, - pub verification_methods: Vec, - pub authentication: Vec, - pub assertion_method: Vec, - pub capability_invocation: Vec, - pub capability_delegation: Vec, - pub service: Vec, -} - -/// Verification method in DID document -#[cw_serde] -pub struct VerificationMethod { - pub id: String, - pub controller: String, - pub method_type: String, - pub public_key: String, -} - -/// Service endpoint in DID document -#[cw_serde] -pub struct Service { - pub id: String, - pub service_type: String, - pub service_endpoint: String, -} - -/// DID verification response -#[cw_serde] -pub struct VerificationResponse { - pub is_verified: bool, - pub verification_level: u8, - pub last_verified: Option, -} - -/// DID by address response -#[cw_serde] -pub struct DIDByAddressResponse { - pub did: Option, - pub address: String, -} - -/// List of DIDs response -#[cw_serde] -pub struct DIDsResponse { - pub dids: Vec, - pub total: u64, -} - -/// Basic DID information -#[cw_serde] -pub struct DIDInfo { - pub did: String, - pub controller: Addr, - pub created_at: u64, - pub updated_at: u64, -} - -/// WebAuthn credentials response -#[cw_serde] -pub struct WebAuthnCredentialsResponse { - pub credentials: Vec, -} - -/// WebAuthn credential -#[cw_serde] -pub struct WebAuthnCredential { - pub credential_id: String, - pub public_key: String, - pub attestation_type: String, - pub user_verified: bool, -} - -/// Stargate query wrapper for x/did module -#[cw_serde] -pub struct StargateQuery { - /// Path to the module query endpoint - pub path: String, - /// Protobuf encoded query data - pub data: Vec, -} - -/// Helper to create stargate queries for x/did module -pub mod stargate { - use super::*; - - /// Query path for x/did module - pub const DID_MODULE_PATH: &str = "/sonr.did.v1.Query"; - - /// Create a stargate query for DID document - pub fn query_did_document(did: &str) -> StargateQuery { - StargateQuery { - path: format!("{}/DIDDocument", DID_MODULE_PATH), - data: encode_did_query(did), - } - } - - /// Create a stargate query for DID verification - pub fn query_did_verification(did: &str) -> StargateQuery { - StargateQuery { - path: format!("{}/VerifyDID", DID_MODULE_PATH), - data: encode_did_query(did), - } - } - - // Helper to encode DID query (simplified - actual implementation would use prost) - fn encode_did_query(did: &str) -> Vec { - // This would use prost to encode the protobuf message - // For now, returning a placeholder - did.as_bytes().to_vec() - } -} \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/error.rs b/contracts/DAO/packages/shared/src/error.rs deleted file mode 100644 index 52c71a033..000000000 --- a/contracts/DAO/packages/shared/src/error.rs +++ /dev/null @@ -1,48 +0,0 @@ -use cosmwasm_std::StdError; -use thiserror::Error; - -/// Common errors for Identity DAO contracts -#[derive(Error, Debug, PartialEq)] -pub enum ContractError { - #[error("{0}")] - Std(#[from] StdError), - - #[error("Unauthorized")] - Unauthorized {}, - - #[error("Invalid DID: {did}")] - InvalidDID { did: String }, - - #[error("DID not verified")] - DIDNotVerified {}, - - #[error("Insufficient voting power")] - InsufficientVotingPower {}, - - #[error("Proposal not found")] - ProposalNotFound {}, - - #[error("Voting period ended")] - VotingPeriodEnded {}, - - #[error("Voting period not ended")] - VotingPeriodNotEnded {}, - - #[error("Already voted")] - AlreadyVoted {}, - - #[error("Invalid threshold")] - InvalidThreshold {}, - - #[error("No attestation found for DID: {did}")] - NoAttestation { did: String }, - - #[error("Custom error: {msg}")] - CustomError { msg: String }, - - #[error("Invalid IBC channel")] - InvalidIbcChannel {}, - - #[error("Invalid IBC packet: {error}")] - InvalidIbcPacket { error: String }, -} \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/lib.rs b/contracts/DAO/packages/shared/src/lib.rs deleted file mode 100644 index 5f1a73477..000000000 --- a/contracts/DAO/packages/shared/src/lib.rs +++ /dev/null @@ -1,12 +0,0 @@ -/// Shared types and utilities for Identity DAO contracts -pub mod msg; -pub mod query; -pub mod bindings; -pub mod types; -pub mod error; - -pub use msg::*; -pub use query::*; -pub use bindings::*; -pub use types::*; -pub use error::*; \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/msg.rs b/contracts/DAO/packages/shared/src/msg.rs deleted file mode 100644 index 42a8cd56a..000000000 --- a/contracts/DAO/packages/shared/src/msg.rs +++ /dev/null @@ -1,156 +0,0 @@ -use cosmwasm_schema::cw_serde; -use cosmwasm_std::{Addr, Binary, Uint128}; -use crate::types::{Vote, VotingConfig, VerificationStatus}; - -/// Core DAO instantiate message -#[cw_serde] -pub struct CoreInstantiateMsg { - /// Name of the DAO - pub name: String, - /// Description of the DAO - pub description: String, - /// Initial voting configuration - pub voting_config: VotingConfig, - /// Admin address (optional) - pub admin: Option, - /// Enable x/did integration - pub enable_did_integration: bool, -} - -/// Core DAO execute messages -#[cw_serde] -pub enum CoreExecuteMsg { - /// Execute a proposal - ExecuteProposal { proposal_id: u64 }, - /// Update voting configuration - UpdateConfig { voting_config: VotingConfig }, - /// Update module addresses - UpdateModules { - voting_module: Option, - proposal_module: Option, - pre_propose_module: Option, - }, - /// Transfer treasury funds - TransferFunds { - recipient: String, - amount: Uint128, - }, -} - -/// Voting module instantiate message -#[cw_serde] -pub struct VotingInstantiateMsg { - /// Core DAO contract address - pub dao_core: String, - /// Minimum verification level required to vote - pub min_verification_level: u8, - /// Enable reputation-based voting weight - pub use_reputation_weight: bool, -} - -/// Voting module execute messages -#[cw_serde] -pub enum VotingExecuteMsg { - /// Cast a vote - Vote { - proposal_id: u64, - vote: Vote, - }, - /// Update voter registration - UpdateVoter { - did: String, - address: String, - }, - /// Remove voter - RemoveVoter { did: String }, -} - -/// Proposal module instantiate message -#[cw_serde] -pub struct ProposalInstantiateMsg { - /// Core DAO contract address - pub dao_core: String, - /// Voting module address - pub voting_module: String, - /// Pre-propose module address - pub pre_propose_module: Option, - /// Allow multiple choice proposals - pub allow_multiple_choice: bool, -} - -/// Proposal module execute messages -#[cw_serde] -pub enum ProposalExecuteMsg { - /// Create a new proposal - Propose { - title: String, - description: String, - msgs: Vec, - }, - /// Execute a passed proposal - Execute { proposal_id: u64 }, - /// Close an expired proposal - Close { proposal_id: u64 }, - /// Update proposal status - UpdateStatus { - proposal_id: u64, - status: ProposalStatusUpdate, - }, -} - -/// Pre-propose module instantiate message -#[cw_serde] -pub struct PreProposeInstantiateMsg { - /// Proposal module address - pub proposal_module: String, - /// Minimum verification status required - pub min_verification_status: VerificationStatus, - /// Deposit required for proposal - pub deposit_amount: Uint128, - /// Deposit denom - pub deposit_denom: String, -} - -/// Pre-propose module execute messages -#[cw_serde] -pub enum PreProposeExecuteMsg { - /// Submit a proposal for approval - SubmitProposal { - title: String, - description: String, - msgs: Vec, - }, - /// Approve a pending proposal - ApproveProposal { proposal_id: u64 }, - /// Reject a pending proposal - RejectProposal { - proposal_id: u64, - reason: String, - }, - /// Withdraw a pending proposal - WithdrawProposal { proposal_id: u64 }, -} - -/// Message to be executed by a proposal -#[cw_serde] -pub struct ProposalMessage { - /// Contract address to execute on - pub contract: String, - /// Message to execute - pub msg: Binary, - /// Funds to send with the message - pub funds: Vec, -} - -/// Proposal status update -#[cw_serde] -pub enum ProposalStatusUpdate { - /// Mark as passed - Passed, - /// Mark as rejected - Rejected, - /// Mark as executed - Executed, - /// Mark as failed - ExecutionFailed { reason: String }, -} \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/query.rs b/contracts/DAO/packages/shared/src/query.rs deleted file mode 100644 index cde1a8a65..000000000 --- a/contracts/DAO/packages/shared/src/query.rs +++ /dev/null @@ -1,237 +0,0 @@ -use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::{Addr, Uint128}; -use crate::types::{ - IdentityVoter, ProposalStatus, Vote, VotingConfig, - IdentityAttestation, TreasuryInfo, ModuleConfig -}; - -/// Core DAO query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum CoreQueryMsg { - /// Get DAO configuration - #[returns(DaoConfigResponse)] - Config {}, - - /// Get treasury information - #[returns(TreasuryInfo)] - Treasury {}, - - /// Get module addresses - #[returns(ModuleConfig)] - Modules {}, - - /// Get DAO stats - #[returns(DaoStatsResponse)] - Stats {}, -} - -/// Voting module query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum VotingQueryMsg { - /// Get voting power for a DID - #[returns(VotingPowerResponse)] - VotingPower { did: String }, - - /// Get total voting power - #[returns(TotalPowerResponse)] - TotalPower { height: Option }, - - /// Get voter info - #[returns(VoterInfoResponse)] - VoterInfo { did: String }, - - /// List all voters with pagination - #[returns(VotersListResponse)] - ListVoters { - start_after: Option, - limit: Option, - }, - - /// Get vote on a proposal - #[returns(VoteResponse)] - Vote { - proposal_id: u64, - voter: String, - }, -} - -/// Proposal module query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum ProposalQueryMsg { - /// Get proposal details - #[returns(ProposalResponse)] - Proposal { proposal_id: u64 }, - - /// List proposals with filters - #[returns(ProposalsListResponse)] - ListProposals { - status: Option, - start_after: Option, - limit: Option, - }, - - /// Get proposal votes - #[returns(ProposalVotesResponse)] - ProposalVotes { - proposal_id: u64, - start_after: Option, - limit: Option, - }, - - /// Get proposal result - #[returns(ProposalResultResponse)] - ProposalResult { proposal_id: u64 }, -} - -/// Pre-propose module query messages -#[cw_serde] -#[derive(QueryResponses)] -pub enum PreProposeQueryMsg { - /// Get pending proposals - #[returns(PendingProposalsResponse)] - PendingProposals { - start_after: Option, - limit: Option, - }, - - /// Get deposit info - #[returns(DepositInfoResponse)] - DepositInfo { proposer: String }, - - /// Get module config - #[returns(PreProposeConfigResponse)] - Config {}, -} - -// Response types - -#[cw_serde] -pub struct DaoConfigResponse { - pub name: String, - pub description: String, - pub voting_config: VotingConfig, - pub admin: Option, - pub did_integration_enabled: bool, -} - -#[cw_serde] -pub struct DaoStatsResponse { - pub total_proposals: u64, - pub active_proposals: u64, - pub total_voters: u64, - pub treasury_balance: Uint128, -} - -#[cw_serde] -pub struct VotingPowerResponse { - pub power: Uint128, - pub height: u64, -} - -#[cw_serde] -pub struct TotalPowerResponse { - pub power: Uint128, - pub height: u64, -} - -#[cw_serde] -pub struct VoterInfoResponse { - pub voter: IdentityVoter, - pub proposals_voted: u64, -} - -#[cw_serde] -pub struct VotersListResponse { - pub voters: Vec, - pub total: u64, -} - -#[cw_serde] -pub struct VoteResponse { - pub vote: Option, -} - -#[cw_serde] -pub struct VoteInfo { - pub proposal_id: u64, - pub voter: String, - pub vote: Vote, - pub voting_power: Uint128, -} - -#[cw_serde] -pub struct ProposalResponse { - pub id: u64, - pub title: String, - pub description: String, - pub proposer: String, - pub status: ProposalStatus, - pub votes: ProposalVotes, - pub start_time: u64, - pub end_time: u64, -} - -#[cw_serde] -pub struct ProposalVotes { - pub yes: Uint128, - pub no: Uint128, - pub abstain: Uint128, - pub no_with_veto: Uint128, -} - -#[cw_serde] -pub struct ProposalsListResponse { - pub proposals: Vec, - pub total: u64, -} - -#[cw_serde] -pub struct ProposalVotesResponse { - pub votes: Vec, - pub total: u64, -} - -#[cw_serde] -pub struct ProposalResultResponse { - pub proposal_id: u64, - pub result: ProposalResult, -} - -#[cw_serde] -pub enum ProposalResult { - Passed, - Rejected, - InProgress, -} - -#[cw_serde] -pub struct PendingProposalsResponse { - pub proposals: Vec, - pub total: u64, -} - -#[cw_serde] -pub struct PendingProposal { - pub id: u64, - pub proposer: String, - pub title: String, - pub submitted_at: u64, -} - -#[cw_serde] -pub struct DepositInfoResponse { - pub depositor: String, - pub amount: Uint128, - pub refundable: bool, -} - -#[cw_serde] -pub struct PreProposeConfigResponse { - pub proposal_module: Addr, - pub min_verification_status: String, - pub deposit_amount: Uint128, - pub deposit_denom: String, -} \ No newline at end of file diff --git a/contracts/DAO/packages/shared/src/types.rs b/contracts/DAO/packages/shared/src/types.rs deleted file mode 100644 index dc2b17261..000000000 --- a/contracts/DAO/packages/shared/src/types.rs +++ /dev/null @@ -1,127 +0,0 @@ -use cosmwasm_schema::cw_serde; -use cosmwasm_std::{Addr, Timestamp, Uint128}; - -/// Represents a DID holder with voting power -#[cw_serde] -pub struct IdentityVoter { - /// DID of the voter - pub did: String, - /// Address associated with the DID - pub address: Addr, - /// Voting power based on identity attributes - pub voting_power: Uint128, - /// Verification level (0-100) - pub verification_level: u8, - /// Reputation score - pub reputation_score: u64, -} - -/// Identity verification status -#[cw_serde] -pub enum VerificationStatus { - /// Not verified - Unverified, - /// Basic verification completed - Basic, - /// Advanced verification with KYC - Advanced, - /// Full verification with attestations - Full, -} - -/// Proposal status in the DAO -#[cw_serde] -pub enum ProposalStatus { - /// Pending approval from pre-propose module - Pending, - /// Open for voting - Open, - /// Voting period ended, waiting execution - Passed, - /// Proposal rejected - Rejected, - /// Proposal executed - Executed, - /// Proposal execution failed - ExecutionFailed, -} - -/// Vote option -#[cw_serde] -pub enum Vote { - Yes, - No, - Abstain, - NoWithVeto, -} - -/// Voting configuration -#[cw_serde] -pub struct VotingConfig { - /// Minimum percentage of yes votes required - pub threshold: Decimal, - /// Minimum voter turnout percentage - pub quorum: Decimal, - /// Voting duration in seconds - pub voting_period: u64, - /// Proposal deposit amount - pub proposal_deposit: Uint128, -} - -/// Identity attestation -#[cw_serde] -pub struct IdentityAttestation { - /// DID being attested - pub did: String, - /// Attester's DID - pub attester_did: String, - /// Type of attestation - pub attestation_type: AttestationType, - /// Attestation data - pub data: String, - /// Timestamp of attestation - pub timestamp: Timestamp, - /// Expiration time - pub expires_at: Option, -} - -/// Types of attestations -#[cw_serde] -pub enum AttestationType { - /// Identity verification - Identity, - /// Skill or credential - Credential, - /// Reputation endorsement - Reputation, - /// Custom attestation - Custom(String), -} - -/// DAO treasury info -#[cw_serde] -pub struct TreasuryInfo { - /// Treasury address - pub address: Addr, - /// Available balance - pub balance: Uint128, - /// Reserved funds for proposals - pub reserved: Uint128, -} - -/// Module configuration -#[cw_serde] -pub struct ModuleConfig { - /// Core DAO contract address - pub dao_core: Addr, - /// Voting module address - pub voting_module: Addr, - /// Proposal module address - pub proposal_module: Addr, - /// Pre-propose module address - pub pre_propose_module: Addr, - /// x/did module integration enabled - pub did_integration_enabled: bool, -} - -use cosmwasm_std::Decimal; \ No newline at end of file diff --git a/contracts/DAO/scripts/build_contracts.sh b/contracts/DAO/scripts/build_contracts.sh deleted file mode 100644 index ca87bc351..000000000 --- a/contracts/DAO/scripts/build_contracts.sh +++ /dev/null @@ -1,203 +0,0 @@ -#!/bin/bash - -# Build and optimize Identity DAO contracts for deployment -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Helper functions -log_info() { - echo -e "${GREEN}[INFO]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -log_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -# Configuration -PROJECT_ROOT="$(dirname "$0")/.." -CONTRACTS_DIR="${PROJECT_ROOT}/contracts" -TARGET_DIR="${PROJECT_ROOT}/target/wasm32-unknown-unknown/release" -ARTIFACTS_DIR="${PROJECT_ROOT}/artifacts" - -# Contract names -CONTRACTS=( - "identity-dao-core" - "identity-dao-voting" - "identity-dao-proposals" - "identity-dao-pre-propose" -) - -# Check for Rust and wasm32 target -check_requirements() { - log_info "Checking build requirements..." - - if ! command -v cargo &> /dev/null; then - log_error "Rust/Cargo not found. Please install Rust." - exit 1 - fi - - if ! rustup target list --installed | grep -q wasm32-unknown-unknown; then - log_warning "wasm32-unknown-unknown target not installed. Installing..." - rustup target add wasm32-unknown-unknown - fi - - if ! command -v docker &> /dev/null; then - log_error "Docker not found. Docker is required for contract optimization." - exit 1 - fi - - log_info "All requirements satisfied" -} - -# Build contracts -build_contracts() { - log_info "Building contracts..." - - cd "${PROJECT_ROOT}" - - # Clean previous builds - cargo clean - - # Build all contracts in release mode - RUSTFLAGS='-C link-arg=-s' cargo build --release --target wasm32-unknown-unknown - - if [ $? -eq 0 ]; then - log_info "Contracts built successfully" - else - log_error "Failed to build contracts" - exit 1 - fi -} - -# Optimize contracts using CosmWasm optimizer -optimize_contracts() { - log_info "Optimizing contracts for deployment..." - - # Create artifacts directory - mkdir -p "${ARTIFACTS_DIR}" - - # Run optimizer in Docker - docker run --rm -v "${PROJECT_ROOT}":/code \ - --mount type=volume,source="dao_contracts_cache",target=/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/optimizer:0.16.0 - - if [ $? -eq 0 ]; then - log_info "Contract optimization complete" - - # Move optimized contracts to artifacts - mv "${PROJECT_ROOT}"/artifacts/*.wasm "${ARTIFACTS_DIR}/" 2>/dev/null || true - else - log_error "Failed to optimize contracts" - exit 1 - fi -} - -# Generate schemas -generate_schemas() { - log_info "Generating contract schemas..." - - cd "${PROJECT_ROOT}" - - for contract in "${CONTRACTS[@]}"; do - contract_dir="${CONTRACTS_DIR}/${contract//-/_}" - - if [ -d "${contract_dir}" ]; then - log_info "Generating schema for ${contract}..." - cd "${contract_dir}" - cargo schema - fi - done - - log_info "Schema generation complete" -} - -# Verify contract sizes -verify_sizes() { - log_info "Verifying contract sizes..." - - MAX_SIZE=$((600 * 1024)) # 600 KB max size for Cosmos chains - - for wasm_file in "${ARTIFACTS_DIR}"/*.wasm; do - if [ -f "$wasm_file" ]; then - size=$(stat -f%z "$wasm_file" 2>/dev/null || stat -c%s "$wasm_file" 2>/dev/null) - size_kb=$((size / 1024)) - filename=$(basename "$wasm_file") - - if [ $size -gt $MAX_SIZE ]; then - log_error "$filename is too large: ${size_kb}KB (max: 600KB)" - exit 1 - else - log_info "$filename: ${size_kb}KB ✓" - fi - fi - done -} - -# Generate checksums -generate_checksums() { - log_info "Generating checksums..." - - cd "${ARTIFACTS_DIR}" - - if [ -f checksums.txt ]; then - rm checksums.txt - fi - - for wasm_file in *.wasm; do - if [ -f "$wasm_file" ]; then - if command -v sha256sum &> /dev/null; then - sha256sum "$wasm_file" >> checksums.txt - else - shasum -a 256 "$wasm_file" >> checksums.txt - fi - fi - done - - log_info "Checksums saved to artifacts/checksums.txt" -} - -# Main build flow -main() { - log_info "Starting Identity DAO contract build process..." - - # Check requirements - check_requirements - - # Build contracts - build_contracts - - # Optimize contracts - optimize_contracts - - # Generate schemas - generate_schemas - - # Verify sizes - verify_sizes - - # Generate checksums - generate_checksums - - log_info "✅ Build complete!" - log_info "" - log_info "=== Build Summary ===" - log_info "Optimized contracts location: ${ARTIFACTS_DIR}" - log_info "Contract schemas location: ${CONTRACTS_DIR}/*/schema" - log_info "" - log_info "Next steps:" - log_info "1. Review contract sizes in ${ARTIFACTS_DIR}" - log_info "2. Deploy contracts using: ./scripts/deploy_testnet.sh" -} - -# Run main build -main "$@" \ No newline at end of file diff --git a/contracts/DAO/scripts/deploy-cosmos-hub.sh b/contracts/DAO/scripts/deploy-cosmos-hub.sh deleted file mode 100755 index 60b594909..000000000 --- a/contracts/DAO/scripts/deploy-cosmos-hub.sh +++ /dev/null @@ -1,364 +0,0 @@ -#!/bin/bash - -# Identity DAO Deployment Script for Cosmos Hub -# Deploys contracts to Cosmos Hub and establishes IBC channels to Sonr - -set -e - -# Configuration -COSMOS_HUB_CHAIN_ID="${COSMOS_HUB_CHAIN_ID:-cosmoshub-testnet}" -COSMOS_HUB_NODE="${COSMOS_HUB_NODE:-https://rpc.testnet.cosmos.network:443}" -SONR_CHAIN_ID="${SONR_CHAIN_ID:-sonrtest_1-1}" -SONR_NODE="${SONR_NODE:-http://localhost:26657}" -DEPLOYER="${DEPLOYER:-deployer}" -GAS_PRICES="${GAS_PRICES:-0.025uatom}" -CONTRACTS_DIR="../artifacts" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -BLUE='\033[0;34m' -NC='\033[0m' - -echo -e "${BLUE}========================================${NC}" -echo -e "${BLUE}Identity DAO Deployment to Cosmos Hub${NC}" -echo -e "${BLUE}========================================${NC}" - -# Function to store contract code -store_contract() { - local wasm_file=$1 - local label=$2 - - echo -e "${GREEN}Storing contract: ${label}${NC}" - - TX_HASH=$(gaiad tx wasm store "$wasm_file" \ - --from "$DEPLOYER" \ - --chain-id "$COSMOS_HUB_CHAIN_ID" \ - --node "$COSMOS_HUB_NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas auto \ - --gas-adjustment 1.5 \ - --broadcast-mode sync \ - --yes \ - --output json | jq -r '.txhash') - - echo "Waiting for transaction..." - sleep 6 - - CODE_ID=$(gaiad query tx "$TX_HASH" \ - --node "$COSMOS_HUB_NODE" \ - --output json | jq -r '.logs[0].events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') - - echo -e "${GREEN}✓ Stored ${label} with code ID: ${CODE_ID}${NC}" - echo "$CODE_ID" -} - -# Function to instantiate contract -instantiate_contract() { - local code_id=$1 - local init_msg=$2 - local label=$3 - - echo -e "${GREEN}Instantiating: ${label}${NC}" - - TX_HASH=$(gaiad tx wasm instantiate "$code_id" "$init_msg" \ - --from "$DEPLOYER" \ - --label "$label" \ - --chain-id "$COSMOS_HUB_CHAIN_ID" \ - --node "$COSMOS_HUB_NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas auto \ - --gas-adjustment 1.5 \ - --admin "$DEPLOYER" \ - --broadcast-mode sync \ - --yes \ - --output json | jq -r '.txhash') - - echo "Waiting for transaction..." - sleep 6 - - CONTRACT_ADDR=$(gaiad query tx "$TX_HASH" \ - --node "$COSMOS_HUB_NODE" \ - --output json | jq -r '.logs[0].events[] | select(.type=="instantiate") | .attributes[] | select(.key=="_contract_address") | .value') - - echo -e "${GREEN}✓ Instantiated ${label} at: ${CONTRACT_ADDR}${NC}" - echo "$CONTRACT_ADDR" -} - -# Check prerequisites -echo -e "${BLUE}Checking prerequisites...${NC}" - -if ! command -v gaiad &>/dev/null; then - echo -e "${RED}Error: gaiad not found. Please install Gaia (Cosmos Hub client)${NC}" - exit 1 -fi - -if ! command -v hermes &>/dev/null; then - echo -e "${RED}Error: hermes not found. Please install Hermes IBC relayer${NC}" - exit 1 -fi - -# Build contracts if needed -if [ ! -d "$CONTRACTS_DIR" ]; then - echo -e "${BLUE}Building contracts...${NC}" - cd .. - docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/workspace-optimizer:0.13.0 - cd scripts -fi - -# Store contract codes -echo -e "${BLUE}Storing contract codes on Cosmos Hub...${NC}" - -CORE_CODE_ID=$(store_contract "$CONTRACTS_DIR/identity_dao_core.wasm" "Identity DAO Core") -VOTING_CODE_ID=$(store_contract "$CONTRACTS_DIR/did_voting.wasm" "DID-Based Voting") -PROPOSALS_CODE_ID=$(store_contract "$CONTRACTS_DIR/identity_proposals.wasm" "Identity Proposals") -PRE_PROPOSE_CODE_ID=$(store_contract "$CONTRACTS_DIR/pre_propose_identity.wasm" "Pre-Propose Identity") - -# Instantiate contracts -echo -e "${BLUE}Instantiating contracts...${NC}" - -# Core module -CORE_INIT='{ - "admin": "'$DEPLOYER'", - "dao_name": "Sonr Identity DAO", - "dao_uri": "https://sonr.io/dao", - "voting_module": null, - "proposal_modules": [], - "wyoming_dao_info": { - "entity_name": "Sonr Identity DAO LLC", - "entity_type": "LLC", - "registered_agent": "Wyoming Registered Agent LLC", - "ein": "00-0000000" - } -}' -CORE_ADDR=$(instantiate_contract "$CORE_CODE_ID" "$CORE_INIT" "identity-dao-core") - -# Voting module -VOTING_INIT='{ - "dao_core": "'$CORE_ADDR'", - "min_verification_level": 1, - "use_reputation_weight": true -}' -VOTING_ADDR=$(instantiate_contract "$VOTING_CODE_ID" "$VOTING_INIT" "did-voting") - -# Proposals module -PROPOSALS_INIT='{ - "dao_core": "'$CORE_ADDR'", - "voting_module": "'$VOTING_ADDR'", - "min_voting_period": 86400, - "max_voting_period": 604800, - "pass_threshold": {"absolute_percentage": {"percentage": "0.5"}}, - "min_verification_level": 1 -}' -PROPOSALS_ADDR=$(instantiate_contract "$PROPOSALS_CODE_ID" "$PROPOSALS_INIT" "identity-proposals") - -# Pre-propose module -PRE_PROPOSE_INIT='{ - "dao_core": "'$CORE_ADDR'", - "proposal_module": "'$PROPOSALS_ADDR'", - "deposit_amount": "1000000", - "deposit_denom": "uatom", - "min_verification_level": 1, - "admin_approval_required": false -}' -PRE_PROPOSE_ADDR=$(instantiate_contract "$PRE_PROPOSE_CODE_ID" "$PRE_PROPOSE_INIT" "pre-propose-identity") - -# Update core configuration -echo -e "${BLUE}Updating core configuration...${NC}" - -UPDATE_MSG='{ - "update_config": { - "voting_module": "'$VOTING_ADDR'", - "proposal_modules": ["'$PROPOSALS_ADDR'"] - } -}' - -gaiad tx wasm execute "$CORE_ADDR" "$UPDATE_MSG" \ - --from "$DEPLOYER" \ - --chain-id "$COSMOS_HUB_CHAIN_ID" \ - --node "$COSMOS_HUB_NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas auto \ - --gas-adjustment 1.5 \ - --yes - -echo -e "${GREEN}✓ Core configuration updated${NC}" - -# Setup IBC channels -echo -e "${BLUE}========================================${NC}" -echo -e "${BLUE}Setting up IBC Channels${NC}" -echo -e "${BLUE}========================================${NC}" - -# Create Hermes config if not exists -HERMES_CONFIG="$HOME/.hermes/config.toml" -if [ ! -f "$HERMES_CONFIG" ]; then - echo -e "${BLUE}Creating Hermes configuration...${NC}" - mkdir -p "$HOME/.hermes" - cat >"$HERMES_CONFIG" </dev/null | hermes keys add --chain "$COSMOS_HUB_CHAIN_ID" --key-file /dev/stdin || true -snrd keys export "$DEPLOYER" 2>/dev/null | hermes keys add --chain "$SONR_CHAIN_ID" --key-file /dev/stdin || true - -# Create IBC connection -echo -e "${BLUE}Creating IBC connection...${NC}" - -CONNECTION_RESULT=$(hermes create connection \ - --a-chain "$COSMOS_HUB_CHAIN_ID" \ - --b-chain "$SONR_CHAIN_ID") - -CONNECTION_ID=$(echo "$CONNECTION_RESULT" | grep -oP 'connection-\d+' | head -1) - -echo -e "${GREEN}✓ Created IBC connection: ${CONNECTION_ID}${NC}" - -# Create channels for each contract -echo -e "${BLUE}Creating IBC channels for contracts...${NC}" - -# Channel for voting module -VOTING_CHANNEL=$(hermes create channel \ - --a-chain "$COSMOS_HUB_CHAIN_ID" \ - --a-connection "$CONNECTION_ID" \ - --a-port "wasm.$VOTING_ADDR" \ - --b-port "did" \ - --order unordered \ - --version "identity-dao-1" | grep -oP 'channel-\d+' | head -1) - -echo -e "${GREEN}✓ Created voting channel: ${VOTING_CHANNEL}${NC}" - -# Channel for proposals module -PROPOSALS_CHANNEL=$(hermes create channel \ - --a-chain "$COSMOS_HUB_CHAIN_ID" \ - --a-connection "$CONNECTION_ID" \ - --a-port "wasm.$PROPOSALS_ADDR" \ - --b-port "dwn" \ - --order unordered \ - --version "identity-dao-1" | grep -oP 'channel-\d+' | head -1) - -echo -e "${GREEN}✓ Created proposals channel: ${PROPOSALS_CHANNEL}${NC}" - -# Start the relayer -echo -e "${BLUE}Starting IBC relayer...${NC}" - -hermes start & -RELAYER_PID=$! - -echo -e "${GREEN}✓ IBC relayer started with PID: ${RELAYER_PID}${NC}" - -# Save deployment information -DEPLOYMENT_FILE="cosmos-hub-deployment.json" -cat >"$DEPLOYMENT_FILE" < /dev/null; then - log_error "snrd is not installed. Please run 'make install'" - exit 1 - fi - - if ! command -v jq &> /dev/null; then - log_error "jq is not installed. Please install jq" - exit 1 - fi - - log_info "All dependencies satisfied" -} - -# Build contracts -build_contracts() { - log_info "Building Identity DAO contracts..." - - cd "$(dirname "$0")/.." - - # Build with optimizer - docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/workspace-optimizer:0.13.0 - - # Move artifacts - mkdir -p artifacts - mv artifacts/*.wasm artifacts/ 2>/dev/null || true - - log_info "Contracts built successfully" -} - -# Store contract code -store_contract() { - local wasm_file=$1 - local contract_name=$2 - - log_info "Storing $contract_name contract..." - - if [ ! -f "$wasm_file" ]; then - log_error "Contract file not found: $wasm_file" - exit 1 - fi - - local tx_result=$(snrd tx wasm store "$wasm_file" \ - --from "$DEPLOYER" \ - --chain-id "$CHAIN_ID" \ - --node "$NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas-adjustment "$GAS_ADJUSTMENT" \ - --keyring-backend "$KEYRING" \ - --output json \ - --yes) - - local tx_hash=$(echo "$tx_result" | jq -r .txhash) - - # Wait for transaction - sleep 6 - - # Get code ID from events - local code_id=$(snrd query tx "$tx_hash" \ - --node "$NODE" \ - --output json | jq -r '.events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') - - if [ -z "$code_id" ]; then - log_error "Failed to get code ID for $contract_name" - exit 1 - fi - - log_info "$contract_name stored with code ID: $code_id" - echo "$code_id" -} - -# Instantiate contract -instantiate_contract() { - local code_id=$1 - local init_msg=$2 - local label=$3 - local admin=${4:-$DEPLOYER} - - log_info "Instantiating contract: $label" - - local tx_result=$(snrd tx wasm instantiate "$code_id" "$init_msg" \ - --from "$DEPLOYER" \ - --label "$label" \ - --admin "$admin" \ - --chain-id "$CHAIN_ID" \ - --node "$NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas-adjustment "$GAS_ADJUSTMENT" \ - --keyring-backend "$KEYRING" \ - --output json \ - --yes) - - local tx_hash=$(echo "$tx_result" | jq -r .txhash) - - # Wait for transaction - sleep 6 - - # Get contract address from events - local contract_addr=$(snrd query tx "$tx_hash" \ - --node "$NODE" \ - --output json | jq -r '.events[] | select(.type=="instantiate") | .attributes[] | select(.key=="_contract_address") | .value') - - if [ -z "$contract_addr" ]; then - log_error "Failed to get contract address for $label" - exit 1 - fi - - log_info "$label instantiated at: $contract_addr" - echo "$contract_addr" -} - -# Main deployment flow -main() { - log_info "Starting Identity DAO deployment..." - - # Check dependencies - check_dependencies - - # Build contracts if artifacts don't exist - if [ ! -d "$CONTRACTS_DIR" ] || [ -z "$(ls -A $CONTRACTS_DIR/*.wasm 2>/dev/null)" ]; then - build_contracts - else - log_info "Using existing contract artifacts" - fi - - # Store contract codes - log_info "Storing contract codes on chain..." - - CORE_CODE_ID=$(store_contract "$CORE_WASM" "Identity DAO Core") - VOTING_CODE_ID=$(store_contract "$VOTING_WASM" "DID-Based Voting") - PROPOSALS_CODE_ID=$(store_contract "$PROPOSALS_WASM" "Identity Proposals") - PRE_PROPOSE_CODE_ID=$(store_contract "$PRE_PROPOSE_WASM" "Pre-Propose Identity") - - # Save code IDs - cat > "${CONTRACTS_DIR}/code_ids.json" < "${CONTRACTS_DIR}/addresses.json" < /dev/null; then - log_error "Multisig account not found. Please create it first:" - echo "gaiad keys add ${MULTISIG_NAME} --multisig key1,key2,key3 --multisig-threshold ${REQUIRED_SIGNATURES}" - exit 1 - fi - - MULTISIG_ADDR=$(gaiad keys show "${MULTISIG_NAME}" -a ${KEYRING}) - log_info "Multisig address: ${MULTISIG_ADDR}" - - # Check multisig balance - BALANCE=$(gaiad query bank balances "${MULTISIG_ADDR}" \ - --node "${NODE}" \ - --output json | jq -r '.balances[] | select(.denom=="uatom") | .amount') - - BALANCE_ATOM=$((BALANCE / 1000000)) - - if [ "$BALANCE_ATOM" -lt "$MIN_BALANCE_ATOM" ]; then - log_error "Insufficient balance: ${BALANCE_ATOM} ATOM (required: ${MIN_BALANCE_ATOM} ATOM)" - exit 1 - fi - - log_info "Multisig balance: ${BALANCE_ATOM} ATOM" -} - -# Verify contracts -verify_contracts() { - log_info "Verifying contract checksums..." - - if [ ! -f "${CONTRACTS_DIR}/checksums.txt" ]; then - log_error "Checksums file not found" - exit 1 - fi - - # Verify each contract - cd "${CONTRACTS_DIR}" - - if command -v sha256sum &> /dev/null; then - sha256sum -c checksums.txt - else - shasum -a 256 -c checksums.txt - fi - - if [ $? -eq 0 ]; then - log_info "All contract checksums verified" - else - log_error "Contract checksum verification failed" - exit 1 - fi - - cd - > /dev/null -} - -# Backup current state -create_backup() { - log_info "Creating deployment backup..." - - BACKUP_DIR="backups/mainnet_$(date +%Y%m%d_%H%M%S)" - mkdir -p "${BACKUP_DIR}" - - # Copy contracts - cp -r "${CONTRACTS_DIR}" "${BACKUP_DIR}/" - - # Save deployment configuration - cat > "${BACKUP_DIR}/deployment_config.json" << EOF -{ - "chain_id": "${CHAIN_ID}", - "node": "${NODE}", - "multisig_addr": "${MULTISIG_ADDR}", - "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")", - "contracts": { - "core": "${CORE_WASM}", - "voting": "${VOTING_WASM}", - "proposals": "${PROPOSALS_WASM}", - "pre_propose": "${PRE_PROPOSE_WASM}" - }, - "config": { - "proposal_deposit": "${PROPOSAL_DEPOSIT}", - "voting_period": ${VOTING_PERIOD}, - "quorum": "${QUORUM}", - "threshold": "${THRESHOLD}" - } -} -EOF - - log_info "Backup created at ${BACKUP_DIR}" -} - -# Generate multisig transaction -generate_multisig_tx() { - local msg=$1 - local output_file=$2 - local description=$3 - - log_info "Generating multisig transaction: ${description}" - - # Generate unsigned transaction - gaiad tx wasm $msg \ - --from "${MULTISIG_NAME}" \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - --generate-only > "${output_file}" - - log_info "Unsigned transaction saved to ${output_file}" -} - -# Upload contract with multisig -upload_contract_multisig() { - local wasm_file=$1 - local contract_name=$2 - - log_info "Preparing ${contract_name} upload..." - - # Generate store transaction - TX_FILE="tx_store_${contract_name}.json" - - generate_multisig_tx \ - "store ${wasm_file}" \ - "${TX_FILE}" \ - "Store ${contract_name}" - - log_info "${contract_name} upload transaction prepared" - log_warning "Requires multisig signatures before broadcasting" - - echo "${TX_FILE}" -} - -# Main deployment flow -main() { - log_critical "Starting Identity DAO MAINNET deployment..." - - # Pre-deployment checks - pre_deployment_checks - - # Check multisig setup - check_multisig - - # Verify contracts - verify_contracts - - # Create backup - create_backup - - # Prepare upload transactions - log_info "Preparing contract upload transactions..." - - CORE_TX=$(upload_contract_multisig "${CORE_WASM}" "Identity DAO Core") - VOTING_TX=$(upload_contract_multisig "${VOTING_WASM}" "DID Voting") - PROPOSALS_TX=$(upload_contract_multisig "${PROPOSALS_WASM}" "Proposals") - PRE_PROPOSE_TX=$(upload_contract_multisig "${PRE_PROPOSE_WASM}" "Pre-Propose") - - # Generate instantiation messages - log_info "Generating instantiation messages..." - - CORE_INIT_MSG='{ - "name": "Sonr Identity DAO", - "description": "Decentralized Identity Governance on Cosmos Hub", - "voting_config": { - "threshold": "'${THRESHOLD}'", - "quorum": "'${QUORUM}'", - "voting_period": '${VOTING_PERIOD}', - "proposal_deposit": "'${PROPOSAL_DEPOSIT}'" - }, - "admin": "'${MULTISIG_ADDR}'", - "enable_did_integration": true - }' - - echo "$CORE_INIT_MSG" > init_core.json - - # Save deployment instructions - cat > MAINNET_DEPLOYMENT_INSTRUCTIONS.md << EOF -# Cosmos Hub Mainnet Deployment Instructions - -## Prerequisites -- Multisig address: ${MULTISIG_ADDR} -- Required signatures: ${REQUIRED_SIGNATURES} of ${MULTISIG_THRESHOLD} -- Chain ID: ${CHAIN_ID} - -## Step 1: Sign Upload Transactions - -Each signer must sign the upload transactions: - -\`\`\`bash -# Sign Core contract upload -gaiad tx sign ${CORE_TX} --from --chain-id ${CHAIN_ID} ${KEYRING} > signed_core_.json - -# Sign Voting contract upload -gaiad tx sign ${VOTING_TX} --from --chain-id ${CHAIN_ID} ${KEYRING} > signed_voting_.json - -# Sign Proposals contract upload -gaiad tx sign ${PROPOSALS_TX} --from --chain-id ${CHAIN_ID} ${KEYRING} > signed_proposals_.json - -# Sign Pre-Propose contract upload -gaiad tx sign ${PRE_PROPOSE_TX} --from --chain-id ${CHAIN_ID} ${KEYRING} > signed_pre_propose_.json -\`\`\` - -## Step 2: Combine Signatures - -\`\`\`bash -# Combine Core signatures -gaiad tx multisign ${CORE_TX} ${MULTISIG_NAME} signed_core_*.json --chain-id ${CHAIN_ID} ${KEYRING} > tx_core_signed.json - -# Combine Voting signatures -gaiad tx multisign ${VOTING_TX} ${MULTISIG_NAME} signed_voting_*.json --chain-id ${CHAIN_ID} ${KEYRING} > tx_voting_signed.json - -# Combine Proposals signatures -gaiad tx multisign ${PROPOSALS_TX} ${MULTISIG_NAME} signed_proposals_*.json --chain-id ${CHAIN_ID} ${KEYRING} > tx_proposals_signed.json - -# Combine Pre-Propose signatures -gaiad tx multisign ${PRE_PROPOSE_TX} ${MULTISIG_NAME} signed_pre_propose_*.json --chain-id ${CHAIN_ID} ${KEYRING} > tx_pre_propose_signed.json -\`\`\` - -## Step 3: Broadcast Transactions - -\`\`\`bash -# Broadcast uploads (one at a time) -gaiad tx broadcast tx_core_signed.json --node ${NODE} -# Wait for confirmation and note CODE_ID - -gaiad tx broadcast tx_voting_signed.json --node ${NODE} -# Wait for confirmation and note CODE_ID - -gaiad tx broadcast tx_proposals_signed.json --node ${NODE} -# Wait for confirmation and note CODE_ID - -gaiad tx broadcast tx_pre_propose_signed.json --node ${NODE} -# Wait for confirmation and note CODE_ID -\`\`\` - -## Step 4: Instantiate Contracts - -After obtaining code IDs, instantiate each contract following the same multisig process. - -## Step 5: Verify Deployment - -Run verification script: -\`\`\`bash -./scripts/verify_deployment.sh -\`\`\` - -## Security Checklist - -- [ ] All signers have verified contract checksums -- [ ] Multisig threshold is correctly configured -- [ ] Admin keys are securely stored -- [ ] Backup of deployment configuration created -- [ ] IBC channels will be established post-deployment -- [ ] Emergency procedures documented - -## Emergency Contacts - -- Technical Lead: [Contact] -- Security Team: [Contact] -- Multisig Signers: [List] - ---- -Generated: $(date) -EOF - - log_info "✅ Mainnet deployment preparation complete!" - log_info "" - log_critical "=== IMPORTANT NEXT STEPS ===" - echo "1. Review MAINNET_DEPLOYMENT_INSTRUCTIONS.md" - echo "2. Coordinate with multisig signers" - echo "3. Execute deployment following the instructions" - echo "4. Verify deployment using verify_deployment.sh" - echo "5. Establish IBC channels to Sonr mainnet" - echo "" - log_warning "All unsigned transactions saved to current directory" - log_warning "DO NOT share private keys or signed transactions insecurely" -} - -# Run main deployment -main "$@" \ No newline at end of file diff --git a/contracts/DAO/scripts/deploy_testnet.sh b/contracts/DAO/scripts/deploy_testnet.sh deleted file mode 100644 index f0d7f1fec..000000000 --- a/contracts/DAO/scripts/deploy_testnet.sh +++ /dev/null @@ -1,357 +0,0 @@ -#!/bin/bash - -# Deploy Identity DAO Contracts to Cosmos Hub Testnet -# This script handles the deployment of all DAO contracts and IBC setup - -set -e - -# Configuration -CHAIN_ID="theta-testnet-001" # Cosmos Hub testnet chain ID -NODE="https://rpc.sentry-01.theta-testnet.polypore.xyz" -GAS_PRICES="0.025uatom" -GAS_AUTO="--gas auto --gas-adjustment 1.3" -KEYRING="--keyring-backend test" - -# Contract paths -CONTRACTS_DIR="$(dirname "$0")/../target/wasm32-unknown-unknown/release" -CORE_WASM="${CONTRACTS_DIR}/identity_dao_core.wasm" -VOTING_WASM="${CONTRACTS_DIR}/identity_dao_voting.wasm" -PROPOSALS_WASM="${CONTRACTS_DIR}/identity_dao_proposals.wasm" -PRE_PROPOSE_WASM="${CONTRACTS_DIR}/identity_dao_pre_propose.wasm" - -# Sonr chain configuration for IBC -SONR_CHAIN_ID="sonrtest_1-1" -SONR_NODE="http://localhost:26657" -IBC_VERSION="ics20-1" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Helper functions -log_info() { - echo -e "${GREEN}[INFO]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -log_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -# Check if gaiad is installed -check_gaiad() { - if ! command -v gaiad &> /dev/null; then - log_error "gaiad is not installed. Please install Cosmos Hub client." - exit 1 - fi - log_info "Found gaiad: $(gaiad version)" -} - -# Check if contracts are built -check_contracts() { - log_info "Checking for compiled contracts..." - - if [ ! -f "$CORE_WASM" ]; then - log_error "Core contract not found at $CORE_WASM" - log_info "Building contracts..." - cd "$(dirname "$0")/.." - cargo build --release --target wasm32-unknown-unknown - fi - - log_info "All contracts found" -} - -# Optimize contracts for deployment -optimize_contracts() { - log_info "Optimizing contracts for deployment..." - - # Use CosmWasm optimizer - docker run --rm -v "$(pwd)":/code \ - --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ - --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/optimizer:0.16.0 - - log_info "Contract optimization complete" -} - -# Upload contract to chain -upload_contract() { - local wasm_file=$1 - local contract_name=$2 - - log_info "Uploading ${contract_name} contract..." - - TX_HASH=$(gaiad tx wasm store "${wasm_file}" \ - --from deployer \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - --broadcast-mode sync \ - --output json \ - -y | jq -r '.txhash') - - log_info "Transaction submitted: ${TX_HASH}" - sleep 6 - - # Get code ID from transaction - CODE_ID=$(gaiad query tx "${TX_HASH}" \ - --node "${NODE}" \ - --output json | jq -r '.logs[0].events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') - - log_info "${contract_name} uploaded with code ID: ${CODE_ID}" - echo "${CODE_ID}" -} - -# Instantiate contract -instantiate_contract() { - local code_id=$1 - local init_msg=$2 - local label=$3 - local admin=$4 - - log_info "Instantiating ${label}..." - - TX_HASH=$(gaiad tx wasm instantiate "${code_id}" "${init_msg}" \ - --from deployer \ - --label "${label}" \ - --admin "${admin}" \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - --broadcast-mode sync \ - --output json \ - -y | jq -r '.txhash') - - log_info "Transaction submitted: ${TX_HASH}" - sleep 6 - - # Get contract address from transaction - CONTRACT_ADDR=$(gaiad query tx "${TX_HASH}" \ - --node "${NODE}" \ - --output json | jq -r '.logs[0].events[] | select(.type=="instantiate") | .attributes[] | select(.key=="_contract_address") | .value') - - log_info "${label} instantiated at: ${CONTRACT_ADDR}" - echo "${CONTRACT_ADDR}" -} - -# Setup IBC channel -setup_ibc_channel() { - local contract_addr=$1 - local port=$2 - - log_info "Setting up IBC channel for ${port}..." - - # Create client for Sonr chain - gaiad tx ibc client create \ - --chain-id "${CHAIN_ID}" \ - --from deployer \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - sleep 6 - - # Create connection - gaiad tx ibc connection open-init \ - --chain-id "${CHAIN_ID}" \ - --from deployer \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - sleep 6 - - # Create channel - gaiad tx ibc channel open-init \ - --port "${port}" \ - --version "${IBC_VERSION}" \ - --chain-id "${CHAIN_ID}" \ - --from deployer \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - log_info "IBC channel setup initiated for ${port}" -} - -# Main deployment flow -main() { - log_info "Starting Identity DAO deployment to Cosmos Hub testnet..." - - # Prerequisites - check_gaiad - check_contracts - - # Get deployer address - DEPLOYER_ADDR=$(gaiad keys show deployer -a ${KEYRING}) - log_info "Deployer address: ${DEPLOYER_ADDR}" - - # Check balance - BALANCE=$(gaiad query bank balances "${DEPLOYER_ADDR}" \ - --node "${NODE}" \ - --output json | jq -r '.balances[] | select(.denom=="uatom") | .amount') - - if [ -z "$BALANCE" ] || [ "$BALANCE" -eq "0" ]; then - log_error "Deployer has no ATOM tokens. Please fund the account." - log_info "Visit https://discord.com/channels/669268347736686612/953641721746206780 for testnet faucet" - exit 1 - fi - - log_info "Deployer balance: ${BALANCE} uatom" - - # Optimize contracts - optimize_contracts - - # Upload contracts - log_info "Uploading contracts to chain..." - CORE_CODE_ID=$(upload_contract "${CONTRACTS_DIR}/identity_dao_core-optimized.wasm" "Identity DAO Core") - VOTING_CODE_ID=$(upload_contract "${CONTRACTS_DIR}/identity_dao_voting-optimized.wasm" "DID Voting") - PROPOSALS_CODE_ID=$(upload_contract "${CONTRACTS_DIR}/identity_dao_proposals-optimized.wasm" "Proposals") - PRE_PROPOSE_CODE_ID=$(upload_contract "${CONTRACTS_DIR}/identity_dao_pre_propose-optimized.wasm" "Pre-Propose") - - # Save code IDs - echo "CORE_CODE_ID=${CORE_CODE_ID}" > deployment_ids.env - echo "VOTING_CODE_ID=${VOTING_CODE_ID}" >> deployment_ids.env - echo "PROPOSALS_CODE_ID=${PROPOSALS_CODE_ID}" >> deployment_ids.env - echo "PRE_PROPOSE_CODE_ID=${PRE_PROPOSE_CODE_ID}" >> deployment_ids.env - - # Instantiate Core contract - CORE_INIT_MSG='{ - "name": "Sonr Identity DAO", - "description": "Decentralized Identity Governance on Cosmos Hub", - "voting_config": { - "threshold": "0.51", - "quorum": "0.1", - "voting_period": 604800, - "proposal_deposit": "1000000" - }, - "admin": "'${DEPLOYER_ADDR}'", - "enable_did_integration": true - }' - - CORE_ADDR=$(instantiate_contract "${CORE_CODE_ID}" "${CORE_INIT_MSG}" "sonr-identity-dao-core" "${DEPLOYER_ADDR}") - echo "CORE_ADDR=${CORE_ADDR}" >> deployment_ids.env - - # Instantiate Voting contract - VOTING_INIT_MSG='{ - "dao_core": "'${CORE_ADDR}'", - "min_verification_level": 1, - "use_reputation_weight": true - }' - - VOTING_ADDR=$(instantiate_contract "${VOTING_CODE_ID}" "${VOTING_INIT_MSG}" "sonr-did-voting" "${CORE_ADDR}") - echo "VOTING_ADDR=${VOTING_ADDR}" >> deployment_ids.env - - # Instantiate Proposals contract - PROPOSALS_INIT_MSG='{ - "dao_core": "'${CORE_ADDR}'", - "voting_module": "'${VOTING_ADDR}'", - "pre_propose_module": null, - "proposal_deposit": "1000000", - "max_voting_period": 604800 - }' - - PROPOSALS_ADDR=$(instantiate_contract "${PROPOSALS_CODE_ID}" "${PROPOSALS_INIT_MSG}" "sonr-proposals" "${CORE_ADDR}") - echo "PROPOSALS_ADDR=${PROPOSALS_ADDR}" >> deployment_ids.env - - # Instantiate Pre-Propose contract - PRE_PROPOSE_INIT_MSG='{ - "dao_core": "'${CORE_ADDR}'", - "proposal_module": "'${PROPOSALS_ADDR}'", - "require_verified_did": true, - "min_reputation_score": 10, - "deposit_amount": "1000000", - "deposit_denom": "uatom" - }' - - PRE_PROPOSE_ADDR=$(instantiate_contract "${PRE_PROPOSE_CODE_ID}" "${PRE_PROPOSE_INIT_MSG}" "sonr-pre-propose" "${CORE_ADDR}") - echo "PRE_PROPOSE_ADDR=${PRE_PROPOSE_ADDR}" >> deployment_ids.env - - # Register modules with Core - log_info "Registering modules with Core contract..." - - REGISTER_VOTING_MSG='{"register_module":{"module_type":"voting","module_address":"'${VOTING_ADDR}'"}}' - gaiad tx wasm execute "${CORE_ADDR}" "${REGISTER_VOTING_MSG}" \ - --from deployer \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - sleep 6 - - REGISTER_PROPOSALS_MSG='{"register_module":{"module_type":"proposal","module_address":"'${PROPOSALS_ADDR}'"}}' - gaiad tx wasm execute "${CORE_ADDR}" "${REGISTER_PROPOSALS_MSG}" \ - --from deployer \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - sleep 6 - - REGISTER_PRE_PROPOSE_MSG='{"register_module":{"module_type":"pre_propose","module_address":"'${PRE_PROPOSE_ADDR}'"}}' - gaiad tx wasm execute "${CORE_ADDR}" "${REGISTER_PRE_PROPOSE_MSG}" \ - --from deployer \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - sleep 6 - - # Setup IBC channels for Sonr integration - log_info "Setting up IBC channels for Sonr integration..." - setup_ibc_channel "${VOTING_ADDR}" "wasm.${VOTING_ADDR}" - - # Update Pre-Propose module in Proposals contract - UPDATE_PRE_PROPOSE_MSG='{"update_pre_propose_module":{"module":"'${PRE_PROPOSE_ADDR}'"}}' - gaiad tx wasm execute "${PROPOSALS_ADDR}" "${UPDATE_PRE_PROPOSE_MSG}" \ - --from deployer \ - --chain-id "${CHAIN_ID}" \ - --node "${NODE}" \ - --gas-prices "${GAS_PRICES}" \ - ${GAS_AUTO} \ - ${KEYRING} \ - -y - - log_info "✅ Deployment complete!" - log_info "Deployment details saved to deployment_ids.env" - - # Display summary - echo "" - log_info "=== Deployment Summary ===" - echo "Core Contract: ${CORE_ADDR}" - echo "Voting Contract: ${VOTING_ADDR}" - echo "Proposals Contract: ${PROPOSALS_ADDR}" - echo "Pre-Propose Contract: ${PRE_PROPOSE_ADDR}" - echo "" - log_info "Next steps:" - echo "1. Verify contract deployment: ./scripts/verify_deployment.sh" - echo "2. Test IBC connectivity: ./scripts/test_ibc.sh" - echo "3. Create first proposal: ./scripts/create_proposal.sh" -} - -# Run main deployment -main "$@" \ No newline at end of file diff --git a/contracts/DAO/scripts/migrate.sh b/contracts/DAO/scripts/migrate.sh deleted file mode 100644 index 9cf314056..000000000 --- a/contracts/DAO/scripts/migrate.sh +++ /dev/null @@ -1,221 +0,0 @@ -#!/bin/bash -# Identity DAO Migration Script -# Migrates Identity DAO contracts to new versions - -set -e - -# Configuration -CHAIN_ID="${CHAIN_ID:-sonrtest_1-1}" -NODE="${NODE:-http://localhost:26657}" -KEYRING="${KEYRING:-test}" -ADMIN="${ADMIN:-deployer}" -GAS_PRICES="${GAS_PRICES:-0.025usnr}" -GAS_ADJUSTMENT="${GAS_ADJUSTMENT:-1.5}" - -# Contract paths -CONTRACTS_DIR="$(dirname "$0")/../artifacts" -ADDRESSES_FILE="${CONTRACTS_DIR}/addresses.json" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Helper functions -log_info() { - echo -e "${GREEN}[INFO]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -log_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -# Check dependencies -check_dependencies() { - log_info "Checking dependencies..." - - if ! command -v snrd &> /dev/null; then - log_error "snrd is not installed. Please run 'make install'" - exit 1 - fi - - if ! command -v jq &> /dev/null; then - log_error "jq is not installed. Please install jq" - exit 1 - fi - - if [ ! -f "$ADDRESSES_FILE" ]; then - log_error "Contract addresses file not found. Please deploy first." - exit 1 - fi - - log_info "All dependencies satisfied" -} - -# Store new contract code -store_new_code() { - local wasm_file=$1 - local contract_name=$2 - - log_info "Storing new $contract_name contract code..." - - if [ ! -f "$wasm_file" ]; then - log_error "Contract file not found: $wasm_file" - exit 1 - fi - - local tx_result=$(snrd tx wasm store "$wasm_file" \ - --from "$ADMIN" \ - --chain-id "$CHAIN_ID" \ - --node "$NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas-adjustment "$GAS_ADJUSTMENT" \ - --keyring-backend "$KEYRING" \ - --output json \ - --yes) - - local tx_hash=$(echo "$tx_result" | jq -r .txhash) - - # Wait for transaction - sleep 6 - - # Get code ID from events - local code_id=$(snrd query tx "$tx_hash" \ - --node "$NODE" \ - --output json | jq -r '.events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value') - - if [ -z "$code_id" ]; then - log_error "Failed to get code ID for $contract_name" - exit 1 - fi - - log_info "$contract_name new code stored with ID: $code_id" - echo "$code_id" -} - -# Migrate contract -migrate_contract() { - local contract_addr=$1 - local new_code_id=$2 - local migrate_msg=$3 - local contract_name=$4 - - log_info "Migrating $contract_name contract..." - - local tx_result=$(snrd tx wasm migrate "$contract_addr" "$new_code_id" "$migrate_msg" \ - --from "$ADMIN" \ - --chain-id "$CHAIN_ID" \ - --node "$NODE" \ - --gas-prices "$GAS_PRICES" \ - --gas-adjustment "$GAS_ADJUSTMENT" \ - --keyring-backend "$KEYRING" \ - --output json \ - --yes) - - local tx_hash=$(echo "$tx_result" | jq -r .txhash) - - # Wait for transaction - sleep 6 - - # Check migration success - local tx_query=$(snrd query tx "$tx_hash" \ - --node "$NODE" \ - --output json) - - local code=$(echo "$tx_query" | jq -r .code) - - if [ "$code" != "0" ]; then - log_error "Migration failed for $contract_name" - echo "$tx_query" | jq -r .raw_log - exit 1 - fi - - log_info "$contract_name migrated successfully" -} - -# Main migration flow -main() { - local MODULE=$1 - - log_info "Starting Identity DAO migration..." - - # Check dependencies - check_dependencies - - # Load contract addresses - CORE_ADDR=$(jq -r .core "$ADDRESSES_FILE") - VOTING_ADDR=$(jq -r .voting "$ADDRESSES_FILE") - PROPOSALS_ADDR=$(jq -r .proposals "$ADDRESSES_FILE") - PRE_PROPOSE_ADDR=$(jq -r .pre_propose "$ADDRESSES_FILE") - - log_info "Loaded contract addresses from deployment" - - # Migrate specific module or all - case "$MODULE" in - core) - log_info "Migrating Core Module..." - NEW_CODE_ID=$(store_new_code "${CONTRACTS_DIR}/identity_dao_core.wasm" "Core") - MIGRATE_MSG='{"update_version":{}}' - migrate_contract "$CORE_ADDR" "$NEW_CODE_ID" "$MIGRATE_MSG" "Core" - ;; - voting) - log_info "Migrating Voting Module..." - NEW_CODE_ID=$(store_new_code "${CONTRACTS_DIR}/identity_dao_voting.wasm" "Voting") - MIGRATE_MSG='{"update_version":{}}' - migrate_contract "$VOTING_ADDR" "$NEW_CODE_ID" "$MIGRATE_MSG" "Voting" - ;; - proposals) - log_info "Migrating Proposals Module..." - NEW_CODE_ID=$(store_new_code "${CONTRACTS_DIR}/identity_dao_proposals.wasm" "Proposals") - MIGRATE_MSG='{"update_version":{}}' - migrate_contract "$PROPOSALS_ADDR" "$NEW_CODE_ID" "$MIGRATE_MSG" "Proposals" - ;; - pre-propose) - log_info "Migrating Pre-Propose Module..." - NEW_CODE_ID=$(store_new_code "${CONTRACTS_DIR}/identity_dao_pre_propose.wasm" "Pre-Propose") - MIGRATE_MSG='{"update_version":{}}' - migrate_contract "$PRE_PROPOSE_ADDR" "$NEW_CODE_ID" "$MIGRATE_MSG" "Pre-Propose" - ;; - all) - log_info "Migrating all modules..." - - # Store all new codes first - CORE_NEW_CODE=$(store_new_code "${CONTRACTS_DIR}/identity_dao_core.wasm" "Core") - VOTING_NEW_CODE=$(store_new_code "${CONTRACTS_DIR}/identity_dao_voting.wasm" "Voting") - PROPOSALS_NEW_CODE=$(store_new_code "${CONTRACTS_DIR}/identity_dao_proposals.wasm" "Proposals") - PRE_PROPOSE_NEW_CODE=$(store_new_code "${CONTRACTS_DIR}/identity_dao_pre_propose.wasm" "Pre-Propose") - - # Migrate in order - MIGRATE_MSG='{"update_version":{}}' - migrate_contract "$CORE_ADDR" "$CORE_NEW_CODE" "$MIGRATE_MSG" "Core" - migrate_contract "$VOTING_ADDR" "$VOTING_NEW_CODE" "$MIGRATE_MSG" "Voting" - migrate_contract "$PRE_PROPOSE_ADDR" "$PRE_PROPOSE_NEW_CODE" "$MIGRATE_MSG" "Pre-Propose" - migrate_contract "$PROPOSALS_ADDR" "$PROPOSALS_NEW_CODE" "$MIGRATE_MSG" "Proposals" - ;; - *) - log_error "Invalid module: $MODULE" - log_info "Usage: $0 [core|voting|proposals|pre-propose|all]" - exit 1 - ;; - esac - - # Save migration info - cat > "${CONTRACTS_DIR}/migration_$(date +%Y%m%d_%H%M%S).json" < /dev/null; then - log_error "Hermes relayer not found. Installing..." - - # Install Hermes based on OS - if [[ "$OSTYPE" == "darwin"* ]]; then - brew install hermes - else - # Linux installation - curl -L https://github.com/informalsystems/hermes/releases/download/v1.8.0/hermes-v1.8.0-x86_64-unknown-linux-gnu.tar.gz | tar xz - sudo mv hermes /usr/local/bin/ - fi - fi - - log_info "Found Hermes: $(hermes version)" -} - -# Initialize Hermes configuration -init_hermes_config() { - log_info "Initializing Hermes configuration..." - - mkdir -p "${RELAYER_HOME}" - - cat > "${RELAYER_HOME}/config.toml" << EOF -[global] -log_level = 'info' - -[mode] - -[mode.clients] -enabled = true -refresh = true -misbehaviour = true - -[mode.connections] -enabled = true - -[mode.channels] -enabled = true - -[mode.packets] -enabled = true -clear_interval = 100 -clear_on_start = true -tx_confirmation = true - -[rest] -enabled = true -host = '127.0.0.1' -port = 3000 - -[telemetry] -enabled = false -host = '127.0.0.1' -port = 3001 - -# Cosmos Hub testnet configuration -[[chains]] -id = '${HUB_CHAIN_ID}' -type = 'CosmosSdk' -rpc_addr = '${HUB_RPC}' -grpc_addr = '${HUB_GRPC}' -event_source = { mode = 'push', url = '${HUB_RPC/https/wss}/websocket', batch_delay = '500ms' } -rpc_timeout = '10s' -account_prefix = '${HUB_PREFIX}' -key_name = 'hub-relayer' -store_prefix = 'ibc' -gas_price = { price = 0.025, denom = '${HUB_DENOM}' } -max_gas = 6000000 -default_gas = 1000000 -gas_multiplier = 1.2 -max_msg_num = 30 -max_tx_size = 2097152 -clock_drift = '5s' -max_block_time = '30s' -memo_prefix = 'Identity DAO IBC' -trusting_period = '14days' -trust_threshold = { numerator = '1', denominator = '3' } - -[chains.packet_filter] -policy = 'allow' -list = [ - ['wasm*', '*'], # Allow all CosmWasm IBC traffic -] - -# Sonr testnet configuration -[[chains]] -id = '${SONR_CHAIN_ID}' -type = 'CosmosSdk' -rpc_addr = '${SONR_RPC}' -grpc_addr = '${SONR_GRPC}' -event_source = { mode = 'push', url = '${SONR_RPC/http/ws}/websocket', batch_delay = '500ms' } -rpc_timeout = '10s' -account_prefix = '${SONR_PREFIX}' -key_name = 'sonr-relayer' -store_prefix = 'ibc' -gas_price = { price = 0.025, denom = '${SONR_DENOM}' } -max_gas = 6000000 -default_gas = 1000000 -gas_multiplier = 1.2 -max_msg_num = 30 -max_tx_size = 2097152 -clock_drift = '5s' -max_block_time = '30s' -memo_prefix = 'Identity DAO IBC' -trusting_period = '14days' -trust_threshold = { numerator = '1', denominator = '3' } - -[chains.packet_filter] -policy = 'allow' -list = [ - ['transfer', 'channel-*'], - ['wasm*', '*'], -] -EOF - - log_info "Hermes config created at ${RELAYER_HOME}/config.toml" -} - -# Add relayer keys -add_relayer_keys() { - log_info "Adding relayer keys..." - - # Add Cosmos Hub key - log_info "Adding Cosmos Hub relayer key..." - hermes keys add \ - --chain "${HUB_CHAIN_ID}" \ - --mnemonic-file hub-relayer.mnemonic \ - --key-name hub-relayer - - # Add Sonr key - log_info "Adding Sonr relayer key..." - hermes keys add \ - --chain "${SONR_CHAIN_ID}" \ - --mnemonic-file sonr-relayer.mnemonic \ - --key-name sonr-relayer -} - -# Create IBC clients -create_clients() { - log_info "Creating IBC clients..." - - # Create client on Cosmos Hub for Sonr - log_info "Creating Sonr client on Cosmos Hub..." - hermes create client \ - --host-chain "${HUB_CHAIN_ID}" \ - --reference-chain "${SONR_CHAIN_ID}" - - # Create client on Sonr for Cosmos Hub - log_info "Creating Cosmos Hub client on Sonr..." - hermes create client \ - --host-chain "${SONR_CHAIN_ID}" \ - --reference-chain "${HUB_CHAIN_ID}" -} - -# Create IBC connection -create_connection() { - log_info "Creating IBC connection..." - - hermes create connection \ - --a-chain "${HUB_CHAIN_ID}" \ - --b-chain "${SONR_CHAIN_ID}" -} - -# Create IBC channels for contracts -create_channels() { - log_info "Creating IBC channels for Identity DAO contracts..." - - # Load deployed contract addresses - if [ -f "deployment_ids.env" ]; then - source deployment_ids.env - else - log_error "deployment_ids.env not found. Please deploy contracts first." - exit 1 - fi - - # Channel for Voting contract to query x/did module - log_info "Creating channel for Voting contract..." - hermes create channel \ - --a-chain "${HUB_CHAIN_ID}" \ - --a-port "wasm.${VOTING_ADDR}" \ - --b-port "did" \ - --order unordered \ - --version "did-ibc-v1" - - # Channel for Proposals contract - log_info "Creating channel for Proposals contract..." - hermes create channel \ - --a-chain "${HUB_CHAIN_ID}" \ - --a-port "wasm.${PROPOSALS_ADDR}" \ - --b-port "dwn" \ - --order unordered \ - --version "dwn-ibc-v1" - - # Standard transfer channel for treasury operations - log_info "Creating transfer channel..." - hermes create channel \ - --a-chain "${HUB_CHAIN_ID}" \ - --a-port "transfer" \ - --b-port "transfer" \ - --order unordered \ - --version "${IBC_VERSION}" -} - -# Start relayer -start_relayer() { - log_info "Starting Hermes relayer..." - - # Start in background - hermes start & - RELAYER_PID=$! - - log_info "Relayer started with PID: ${RELAYER_PID}" - echo "${RELAYER_PID}" > relayer.pid - - # Give it time to establish connections - sleep 10 - - # Check if relayer is running - if ps -p ${RELAYER_PID} > /dev/null; then - log_info "Relayer is running successfully" - else - log_error "Relayer failed to start" - exit 1 - fi -} - -# Query IBC channels -query_channels() { - log_info "Querying established IBC channels..." - - # Query channels on Cosmos Hub - log_info "Channels on Cosmos Hub:" - hermes query channels --chain "${HUB_CHAIN_ID}" - - # Query channels on Sonr - log_info "Channels on Sonr:" - hermes query channels --chain "${SONR_CHAIN_ID}" -} - -# Test IBC connectivity -test_ibc() { - log_info "Testing IBC connectivity..." - - # Test transfer channel - log_info "Testing transfer channel..." - - # Get channel IDs - TRANSFER_CHANNEL=$(hermes query channels --chain "${HUB_CHAIN_ID}" | grep transfer | head -1 | awk '{print $1}') - - if [ -n "$TRANSFER_CHANNEL" ]; then - log_info "Transfer channel: ${TRANSFER_CHANNEL}" - - # Send test transfer - gaiad tx ibc-transfer transfer \ - transfer "${TRANSFER_CHANNEL}" \ - sonr1test_address \ - 1000uatom \ - --from hub-relayer \ - --chain-id "${HUB_CHAIN_ID}" \ - --node "${HUB_RPC}" \ - --gas-prices "${HUB_GAS_PRICES}" \ - --packet-timeout-height 0-1000 \ - -y - - log_info "Test transfer sent" - else - log_warning "No transfer channel found" - fi -} - -# Monitor IBC packets -monitor_packets() { - log_info "Monitoring IBC packet flow..." - - hermes query packet pending \ - --chain "${HUB_CHAIN_ID}" \ - --port transfer \ - --channel "${TRANSFER_CHANNEL}" -} - -# Main IBC setup flow -main() { - log_info "Starting IBC setup for Identity DAO..." - - # Check requirements - check_hermes - - # Initialize configuration - init_hermes_config - - # Check if keys exist or need to be created - if [ ! -f "hub-relayer.mnemonic" ] || [ ! -f "sonr-relayer.mnemonic" ]; then - log_error "Relayer mnemonics not found. Please create:" - log_info "1. hub-relayer.mnemonic - Funded account on Cosmos Hub testnet" - log_info "2. sonr-relayer.mnemonic - Funded account on Sonr testnet" - exit 1 - fi - - # Add keys - add_relayer_keys - - # Create IBC infrastructure - create_clients - create_connection - create_channels - - # Start relayer - start_relayer - - # Query established channels - query_channels - - # Test connectivity - test_ibc - - # Monitor packets - monitor_packets - - log_info "✅ IBC setup complete!" - log_info "" - log_info "=== IBC Summary ===" - log_info "Relayer PID: $(cat relayer.pid)" - log_info "Config: ${RELAYER_HOME}/config.toml" - log_info "" - log_info "Next steps:" - log_info "1. Monitor relayer logs: hermes start" - log_info "2. Query channels: hermes query channels --chain ${HUB_CHAIN_ID}" - log_info "3. Test cross-chain queries: ./scripts/test_did_query.sh" -} - -# Run main IBC setup -main "$@" \ No newline at end of file diff --git a/contracts/DAO/scripts/test-ibc-integration.sh b/contracts/DAO/scripts/test-ibc-integration.sh deleted file mode 100755 index 3c1df64aa..000000000 --- a/contracts/DAO/scripts/test-ibc-integration.sh +++ /dev/null @@ -1,245 +0,0 @@ -#!/bin/bash - -# Test script for Identity DAO IBC Integration -# Validates cross-chain DID verification between Cosmos Hub and Sonr - -set -e - -# Configuration -DEPLOYMENT_FILE="${1:-cosmos-hub-deployment.json}" -TEST_DID="did:sonr:test123" -TEST_ADDRESS="cosmos1test..." - -# Colors -RED='\033[0;31m' -GREEN='\033[0;32m' -BLUE='\033[0;34m' -YELLOW='\033[1;33m' -NC='\033[0m' - -echo -e "${BLUE}========================================${NC}" -echo -e "${BLUE}Identity DAO IBC Integration Tests${NC}" -echo -e "${BLUE}========================================${NC}" - -# Load deployment info -if [ ! -f "$DEPLOYMENT_FILE" ]; then - echo -e "${RED}Error: Deployment file not found: $DEPLOYMENT_FILE${NC}" - exit 1 -fi - -# Extract contract addresses -VOTING_ADDR=$(jq -r '.contracts.voting.address' "$DEPLOYMENT_FILE") -PROPOSALS_ADDR=$(jq -r '.contracts.proposals.address' "$DEPLOYMENT_FILE") -VOTING_CHANNEL=$(jq -r '.contracts.voting.ibc_channel' "$DEPLOYMENT_FILE") -CHAIN_ID=$(jq -r '.chain_id' "$DEPLOYMENT_FILE") - -echo "Using contracts from deployment:" -echo " Voting: $VOTING_ADDR (Channel: $VOTING_CHANNEL)" -echo " Proposals: $PROPOSALS_ADDR" -echo "" - -# Function to run test -run_test() { - local test_name=$1 - local test_cmd=$2 - - echo -ne "${YELLOW}Testing: ${test_name}...${NC}" - - if eval "$test_cmd" > /dev/null 2>&1; then - echo -e " ${GREEN}✓${NC}" - return 0 - else - echo -e " ${RED}✗${NC}" - return 1 - fi -} - -# Test 1: Check IBC channel status -echo -e "${BLUE}1. Checking IBC Channel Status${NC}" - -CHANNEL_STATUS=$(hermes query channel end \ - --chain "$CHAIN_ID" \ - --port "wasm.$VOTING_ADDR" \ - --channel "$VOTING_CHANNEL" \ - 2>/dev/null | jq -r '.state') - -if [ "$CHANNEL_STATUS" = "Open" ]; then - echo -e "${GREEN}✓ Channel is OPEN${NC}" -else - echo -e "${RED}✗ Channel status: $CHANNEL_STATUS${NC}" - exit 1 -fi - -# Test 2: Query Sonr chain for DIDs -echo -e "${BLUE}2. Querying Sonr DIDs via IBC${NC}" - -# Send IBC packet to query DID -QUERY_MSG='{ - "send_did_query": { - "did": "'$TEST_DID'", - "channel": "'$VOTING_CHANNEL'" - } -}' - -TX_HASH=$(gaiad tx wasm execute "$VOTING_ADDR" "$QUERY_MSG" \ - --from deployer \ - --chain-id "$CHAIN_ID" \ - --gas-prices 0.025uatom \ - --gas auto \ - --gas-adjustment 1.5 \ - --yes \ - --output json 2>/dev/null | jq -r '.txhash') - -echo "Query transaction: $TX_HASH" -sleep 6 - -# Check if packet was acknowledged -PACKET_ACK=$(hermes query packet acks \ - --chain "$CHAIN_ID" \ - --port "wasm.$VOTING_ADDR" \ - --channel "$VOTING_CHANNEL" \ - 2>/dev/null | jq -r '.acks | length') - -if [ "$PACKET_ACK" -gt 0 ]; then - echo -e "${GREEN}✓ IBC packet acknowledged${NC}" -else - echo -e "${YELLOW}⚠ No acknowledgment yet (may be pending)${NC}" -fi - -# Test 3: Update voter with DID verification -echo -e "${BLUE}3. Testing Voter Update with DID${NC}" - -UPDATE_MSG='{ - "update_voter": { - "did": "'$TEST_DID'", - "address": "'$TEST_ADDRESS'" - } -}' - -UPDATE_TX=$(gaiad tx wasm execute "$VOTING_ADDR" "$UPDATE_MSG" \ - --from deployer \ - --chain-id "$CHAIN_ID" \ - --gas-prices 0.025uatom \ - --gas auto \ - --gas-adjustment 1.5 \ - --yes \ - --output json 2>/dev/null | jq -r '.txhash') - -echo "Update transaction: $UPDATE_TX" -sleep 6 - -# Query voter info -VOTER_QUERY='{ - "voter_info": { - "did": "'$TEST_DID'" - } -}' - -VOTER_INFO=$(gaiad query wasm contract-state smart "$VOTING_ADDR" "$VOTER_QUERY" \ - --output json 2>/dev/null | jq -r '.data') - -if [ "$VOTER_INFO" != "null" ]; then - echo -e "${GREEN}✓ Voter registered successfully${NC}" - echo "Voter info: $VOTER_INFO" -else - echo -e "${RED}✗ Voter not found${NC}" -fi - -# Test 4: Create proposal through IBC -echo -e "${BLUE}4. Testing Proposal Creation${NC}" - -PROPOSAL_MSG='{ - "propose": { - "title": "Test IBC Proposal", - "description": "Testing cross-chain governance", - "msgs": [], - "proposer_did": "'$TEST_DID'" - } -}' - -PROPOSAL_TX=$(gaiad tx wasm execute "$PROPOSALS_ADDR" "$PROPOSAL_MSG" \ - --from deployer \ - --chain-id "$CHAIN_ID" \ - --gas-prices 0.025uatom \ - --gas auto \ - --gas-adjustment 1.5 \ - --yes \ - --output json 2>/dev/null | jq -r '.txhash') - -echo "Proposal transaction: $PROPOSAL_TX" -sleep 6 - -# Query proposals -PROPOSALS_QUERY='{"list_proposals": {"limit": 10}}' - -PROPOSALS=$(gaiad query wasm contract-state smart "$PROPOSALS_ADDR" "$PROPOSALS_QUERY" \ - --output json 2>/dev/null | jq -r '.data.proposals | length') - -if [ "$PROPOSALS" -gt 0 ]; then - echo -e "${GREEN}✓ Proposal created successfully${NC}" - echo "Total proposals: $PROPOSALS" -else - echo -e "${RED}✗ No proposals found${NC}" -fi - -# Test 5: Check relayer metrics -echo -e "${BLUE}5. Checking Relayer Health${NC}" - -RELAYER_STATUS=$(hermes health-check 2>/dev/null | grep -c "OK" || true) - -if [ "$RELAYER_STATUS" -gt 0 ]; then - echo -e "${GREEN}✓ Relayer is healthy${NC}" -else - echo -e "${YELLOW}⚠ Relayer may need attention${NC}" -fi - -# Test 6: Packet flow statistics -echo -e "${BLUE}6. IBC Packet Statistics${NC}" - -echo "Channel: $VOTING_CHANNEL" - -# Get packet commitments -PENDING_PACKETS=$(hermes query packet commitments \ - --chain "$CHAIN_ID" \ - --port "wasm.$VOTING_ADDR" \ - --channel "$VOTING_CHANNEL" \ - 2>/dev/null | jq -r '.commitments | length') - -echo "Pending packets: $PENDING_PACKETS" - -# Get packet acknowledgments -TOTAL_ACKS=$(hermes query packet acks \ - --chain "$CHAIN_ID" \ - --port "wasm.$VOTING_ADDR" \ - --channel "$VOTING_CHANNEL" \ - 2>/dev/null | jq -r '.acks | length') - -echo "Total acknowledgments: $TOTAL_ACKS" - -# Summary -echo "" -echo -e "${BLUE}========================================${NC}" -echo -e "${BLUE}Test Summary${NC}" -echo -e "${BLUE}========================================${NC}" - -TESTS_PASSED=0 -TESTS_TOTAL=6 - -[ "$CHANNEL_STATUS" = "Open" ] && ((TESTS_PASSED++)) -[ "$PACKET_ACK" -gt 0 ] && ((TESTS_PASSED++)) -[ "$VOTER_INFO" != "null" ] && ((TESTS_PASSED++)) -[ "$PROPOSALS" -gt 0 ] && ((TESTS_PASSED++)) -[ "$RELAYER_STATUS" -gt 0 ] && ((TESTS_PASSED++)) -[ "$PENDING_PACKETS" -eq 0 ] && ((TESTS_PASSED++)) - -if [ "$TESTS_PASSED" -eq "$TESTS_TOTAL" ]; then - echo -e "${GREEN}✓ All tests passed! ($TESTS_PASSED/$TESTS_TOTAL)${NC}" -else - echo -e "${YELLOW}⚠ Some tests failed ($TESTS_PASSED/$TESTS_TOTAL)${NC}" -fi - -echo "" -echo "Next steps:" -echo "1. Monitor packet relay: hermes query packet pending --chain $CHAIN_ID" -echo "2. Check channel balance: hermes query channel balance --chain $CHAIN_ID" -echo "3. View relayer logs: hermes start --log-level debug" \ No newline at end of file diff --git a/contracts/DAO/scripts/testnet-config.json b/contracts/DAO/scripts/testnet-config.json deleted file mode 100644 index 9a626640d..000000000 --- a/contracts/DAO/scripts/testnet-config.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "cosmos_hub_testnet": { - "chain_id": "theta-testnet-001", - "rpc_endpoints": [ - "https://rpc.sentry-01.theta-testnet.polypore.xyz", - "https://rpc.sentry-02.theta-testnet.polypore.xyz" - ], - "grpc_endpoints": [ - "grpc.sentry-01.theta-testnet.polypore.xyz:9090", - "grpc.sentry-02.theta-testnet.polypore.xyz:9090" - ], - "explorer": "https://explorer.theta-testnet.polypore.xyz", - "faucet": "https://discord.com/channels/669268347736686612/953697793476821092" - }, - "sonr_testnet": { - "chain_id": "sonrtest_1-1", - "rpc_endpoints": [ - "http://localhost:26657", - "https://testnet-rpc.sonr.io" - ], - "grpc_endpoints": [ - "localhost:9090", - "testnet-grpc.sonr.io:443" - ] - }, - "ibc_config": { - "connection_version": "1", - "channel_version": "identity-dao-1", - "packet_timeout": "10m", - "ports": { - "voting": "wasm.identity_dao_voting", - "proposals": "wasm.identity_dao_proposals", - "core": "wasm.identity_dao_core" - }, - "sonr_ports": { - "did": "did", - "dwn": "dwn", - "svc": "svc" - } - }, - "deployment_params": { - "gas_prices": { - "cosmos_hub": "0.025uatom", - "sonr": "0.025usnr" - }, - "gas_adjustment": 1.5, - "deposit_amount": "1000000", - "min_verification_level": 1, - "voting_periods": { - "min_seconds": 86400, - "max_seconds": 604800 - }, - "pass_threshold": { - "percentage": "0.5" - } - }, - "relayer_config": { - "type": "hermes", - "version": "1.7.0", - "clear_interval": 100, - "packet_timeout": "10m", - "trusting_period": "14days", - "trust_threshold": { - "numerator": 2, - "denominator": 3 - } - } -} \ No newline at end of file diff --git a/contracts/DAO/scripts/verify_deployment.sh b/contracts/DAO/scripts/verify_deployment.sh deleted file mode 100644 index c96493069..000000000 --- a/contracts/DAO/scripts/verify_deployment.sh +++ /dev/null @@ -1,356 +0,0 @@ -#!/bin/bash - -# Verify Identity DAO deployment and IBC connectivity -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# Helper functions -log_info() { - echo -e "${GREEN}[INFO]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -log_success() { - echo -e "${GREEN}[✓]${NC} $1" -} - -log_fail() { - echo -e "${RED}[✗]${NC} $1" -} - -# Configuration -CHAIN_ID="theta-testnet-001" -NODE="https://rpc.sentry-01.theta-testnet.polypore.xyz" - -# Load deployment addresses -load_deployment() { - if [ -f "deployment_ids.env" ]; then - source deployment_ids.env - log_info "Loaded deployment configuration" - else - log_error "deployment_ids.env not found. Please deploy contracts first." - exit 1 - fi -} - -# Verify contract deployment -verify_contract() { - local addr=$1 - local name=$2 - - log_info "Verifying ${name}..." - - # Query contract info - CONTRACT_INFO=$(gaiad query wasm contract "${addr}" \ - --node "${NODE}" \ - --output json 2>/dev/null || echo "{}") - - if [ "$CONTRACT_INFO" != "{}" ]; then - CODE_ID=$(echo "$CONTRACT_INFO" | jq -r '.contract_info.code_id') - CREATOR=$(echo "$CONTRACT_INFO" | jq -r '.contract_info.creator') - ADMIN=$(echo "$CONTRACT_INFO" | jq -r '.contract_info.admin') - - log_success "${name} deployed at ${addr}" - echo " Code ID: ${CODE_ID}" - echo " Creator: ${CREATOR}" - echo " Admin: ${ADMIN}" - return 0 - else - log_fail "${name} not found at ${addr}" - return 1 - fi -} - -# Query contract state -query_contract_state() { - local addr=$1 - local query=$2 - local name=$3 - - log_info "Querying ${name} state..." - - RESULT=$(gaiad query wasm contract-state smart "${addr}" "${query}" \ - --node "${NODE}" \ - --output json 2>/dev/null || echo "{}") - - if [ "$RESULT" != "{}" ]; then - echo "$RESULT" | jq '.' - return 0 - else - log_error "Failed to query ${name}" - return 1 - fi -} - -# Test Core contract -test_core_contract() { - log_info "Testing Core contract functionality..." - - # Query config - CONFIG_QUERY='{"get_config":{}}' - if query_contract_state "${CORE_ADDR}" "${CONFIG_QUERY}" "Core Config"; then - log_success "Core config query successful" - fi - - # Query modules - MODULES_QUERY='{"get_modules":{}}' - if query_contract_state "${CORE_ADDR}" "${MODULES_QUERY}" "Core Modules"; then - log_success "Core modules query successful" - fi - - # Query treasury - TREASURY_QUERY='{"get_treasury":{}}' - if query_contract_state "${CORE_ADDR}" "${TREASURY_QUERY}" "Core Treasury"; then - log_success "Core treasury query successful" - fi -} - -# Test Voting contract -test_voting_contract() { - log_info "Testing Voting contract functionality..." - - # Query total voting power - POWER_QUERY='{"get_total_power":{}}' - if query_contract_state "${VOTING_ADDR}" "${POWER_QUERY}" "Total Voting Power"; then - log_success "Voting power query successful" - fi - - # Query voters list - VOTERS_QUERY='{"list_voters":{"limit":10}}' - if query_contract_state "${VOTING_ADDR}" "${VOTERS_QUERY}" "Voters List"; then - log_success "Voters list query successful" - fi -} - -# Test Proposals contract -test_proposals_contract() { - log_info "Testing Proposals contract functionality..." - - # Query proposal count - COUNT_QUERY='{"get_proposal_count":{}}' - if query_contract_state "${PROPOSALS_ADDR}" "${COUNT_QUERY}" "Proposal Count"; then - log_success "Proposal count query successful" - fi - - # Query proposals list - LIST_QUERY='{"list_proposals":{"limit":10}}' - if query_contract_state "${PROPOSALS_ADDR}" "${LIST_QUERY}" "Proposals List"; then - log_success "Proposals list query successful" - fi -} - -# Test Pre-Propose contract -test_pre_propose_contract() { - log_info "Testing Pre-Propose contract functionality..." - - # Query config - CONFIG_QUERY='{"get_config":{}}' - if query_contract_state "${PRE_PROPOSE_ADDR}" "${CONFIG_QUERY}" "Pre-Propose Config"; then - log_success "Pre-propose config query successful" - fi - - # Query deposit info - DEPOSIT_QUERY='{"get_deposit_info":{}}' - if query_contract_state "${PRE_PROPOSE_ADDR}" "${DEPOSIT_QUERY}" "Deposit Info"; then - log_success "Deposit info query successful" - fi -} - -# Check IBC channels -check_ibc_channels() { - log_info "Checking IBC channels..." - - # Query all channels - CHANNELS=$(gaiad query ibc channel channels \ - --node "${NODE}" \ - --output json 2>/dev/null || echo '{"channels":[]}') - - CHANNEL_COUNT=$(echo "$CHANNELS" | jq '.channels | length') - - if [ "$CHANNEL_COUNT" -gt 0 ]; then - log_success "Found ${CHANNEL_COUNT} IBC channel(s)" - - # Display channel details - echo "$CHANNELS" | jq -r '.channels[] | " Channel \(.channel_id): \(.state) (\(.port_id))"' - else - log_fail "No IBC channels found" - fi -} - -# Check IBC clients -check_ibc_clients() { - log_info "Checking IBC clients..." - - # Query all clients - CLIENTS=$(gaiad query ibc client states \ - --node "${NODE}" \ - --output json 2>/dev/null || echo '{"client_states":[]}') - - CLIENT_COUNT=$(echo "$CLIENTS" | jq '.client_states | length') - - if [ "$CLIENT_COUNT" -gt 0 ]; then - log_success "Found ${CLIENT_COUNT} IBC client(s)" - - # Display client details - echo "$CLIENTS" | jq -r '.client_states[] | " Client \(.client_id): \(.client_state.chain_id)"' - else - log_fail "No IBC clients found" - fi -} - -# Test cross-chain query -test_cross_chain_query() { - log_info "Testing cross-chain DID query..." - - # Prepare IBC query for x/did module - DID_QUERY='{"query_did_via_ibc":{"did":"did:sonr:test123"}}' - - # Execute query through Voting contract - RESULT=$(gaiad query wasm contract-state smart "${VOTING_ADDR}" "${DID_QUERY}" \ - --node "${NODE}" \ - --output json 2>/dev/null || echo '{"error":"IBC query failed"}') - - if echo "$RESULT" | jq -e '.error' > /dev/null; then - log_fail "Cross-chain query failed" - echo "$RESULT" | jq '.' - else - log_success "Cross-chain query successful" - echo "$RESULT" | jq '.' - fi -} - -# Generate deployment report -generate_report() { - log_info "Generating deployment report..." - - REPORT_FILE="deployment_report_$(date +%Y%m%d_%H%M%S).md" - - cat > "$REPORT_FILE" << EOF -# Identity DAO Deployment Report - -**Date:** $(date) -**Chain:** Cosmos Hub Testnet (${CHAIN_ID}) -**Node:** ${NODE} - -## Deployed Contracts - -| Contract | Address | Code ID | Status | -|----------|---------|---------|--------| -| Core | ${CORE_ADDR} | ${CORE_CODE_ID} | ✓ | -| Voting | ${VOTING_ADDR} | ${VOTING_CODE_ID} | ✓ | -| Proposals | ${PROPOSALS_ADDR} | ${PROPOSALS_CODE_ID} | ✓ | -| Pre-Propose | ${PRE_PROPOSE_ADDR} | ${PRE_PROPOSE_CODE_ID} | ✓ | - -## IBC Configuration - -- Clients: ${CLIENT_COUNT} -- Channels: ${CHANNEL_COUNT} -- Relayer Status: $([ -f "relayer.pid" ] && echo "Running (PID: $(cat relayer.pid))" || echo "Not running") - -## Test Results - -- Core Contract: ✓ -- Voting Contract: ✓ -- Proposals Contract: ✓ -- Pre-Propose Contract: ✓ -- IBC Connectivity: $([ "$CHANNEL_COUNT" -gt 0 ] && echo "✓" || echo "✗") - -## Next Steps - -1. Fund DAO treasury -2. Register initial DID voters -3. Create first governance proposal -4. Monitor IBC packet flow - -## Commands - -\`\`\`bash -# Query DAO config -gaiad query wasm contract-state smart ${CORE_ADDR} '{"get_config":{}}' --node ${NODE} - -# Query voting power -gaiad query wasm contract-state smart ${VOTING_ADDR} '{"get_total_power":{}}' --node ${NODE} - -# List proposals -gaiad query wasm contract-state smart ${PROPOSALS_ADDR} '{"list_proposals":{"limit":10}}' --node ${NODE} -\`\`\` - ---- -Generated by verify_deployment.sh -EOF - - log_success "Report saved to ${REPORT_FILE}" -} - -# Main verification flow -main() { - log_info "Starting Identity DAO deployment verification..." - - # Load deployment configuration - load_deployment - - # Verify all contracts - CONTRACTS_OK=true - verify_contract "${CORE_ADDR}" "Core Contract" || CONTRACTS_OK=false - verify_contract "${VOTING_ADDR}" "Voting Contract" || CONTRACTS_OK=false - verify_contract "${PROPOSALS_ADDR}" "Proposals Contract" || CONTRACTS_OK=false - verify_contract "${PRE_PROPOSE_ADDR}" "Pre-Propose Contract" || CONTRACTS_OK=false - - if [ "$CONTRACTS_OK" = false ]; then - log_error "Some contracts are not deployed correctly" - exit 1 - fi - - echo "" - - # Test contract functionality - test_core_contract - echo "" - test_voting_contract - echo "" - test_proposals_contract - echo "" - test_pre_propose_contract - echo "" - - # Check IBC setup - check_ibc_clients - echo "" - check_ibc_channels - echo "" - - # Test cross-chain functionality - test_cross_chain_query - echo "" - - # Generate report - generate_report - - log_info "✅ Verification complete!" - log_info "" - log_info "=== Summary ===" - if [ "$CONTRACTS_OK" = true ]; then - log_success "All contracts deployed successfully" - fi - - if [ "$CHANNEL_COUNT" -gt 0 ]; then - log_success "IBC channels established" - else - log_fail "IBC channels not yet established" - fi - - log_info "" - log_info "View detailed report: cat ${REPORT_FILE}" -} - -# Run main verification -main "$@" \ No newline at end of file diff --git a/contracts/DAO/tests/e2e/identity_dao_test.go.template b/contracts/DAO/tests/e2e/identity_dao_test.go.template deleted file mode 100644 index fca557c54..000000000 --- a/contracts/DAO/tests/e2e/identity_dao_test.go.template +++ /dev/null @@ -1,515 +0,0 @@ -package e2e - -import ( - "encoding/json" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - // Note: These would be imported from actual test helpers - // For now, we'll define mock functions inline -) - -// IdentityDAOTestSuite tests end-to-end Identity DAO functionality -type IdentityDAOTestSuite struct { - suite.Suite - - // app *app.App // Would be initialized with actual app - ctx sdk.Context - deployer sdk.AccAddress - voter1 sdk.AccAddress - voter2 sdk.AccAddress - voter3 sdk.AccAddress - - // Contract addresses - coreAddr sdk.AccAddress - votingAddr sdk.AccAddress - proposalsAddr sdk.AccAddress - preProposeAddr sdk.AccAddress - - // Code IDs - coreCodeID uint64 - votingCodeID uint64 - proposalsCodeID uint64 - preProposeCodeID uint64 -} - -// SetupSuite runs once before all tests -func (suite *IdentityDAOTestSuite) SetupSuite() { - // Note: In production, these would initialize actual test app - // For now, we provide the structure for the tests - - // Initialize test app - // suite.app = helpers.SetupTestApp() - // suite.ctx = suite.app.NewContext(false, sdk.BlockHeader{ - // Height: 1, - // Time: time.Now(), - // }) - - // Create test accounts - // suite.deployer = helpers.CreateTestAccount(suite.app, suite.ctx, "deployer", sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(1000000000)))) - // suite.voter1 = helpers.CreateTestAccount(suite.app, suite.ctx, "voter1", sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(10000000)))) - // suite.voter2 = helpers.CreateTestAccount(suite.app, suite.ctx, "voter2", sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(10000000)))) - // suite.voter3 = helpers.CreateTestAccount(suite.app, suite.ctx, "voter3", sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(10000000)))) - - // Store contract codes - // suite.storeContracts() - - // Deploy contracts - // suite.deployContracts() -} - -// storeContracts stores all contract codes -func (suite *IdentityDAOTestSuite) storeContracts() { - // wasmKeeper := suite.app.WasmKeeper - - // Load contract bytecode (would be from compiled .wasm files) - // coreWasm := helpers.LoadContractCode("../../artifacts/identity_dao_core.wasm") - // votingWasm := helpers.LoadContractCode("../../artifacts/identity_dao_voting.wasm") - // proposalsWasm := helpers.LoadContractCode("../../artifacts/identity_dao_proposals.wasm") - // preProposeWasm := helpers.LoadContractCode("../../artifacts/identity_dao_pre_propose.wasm") - - // Store codes - // var err error - // suite.coreCodeID, err = wasmKeeper.StoreCode(suite.ctx, suite.deployer, coreWasm) - // suite.Require().NoError(err) - - // suite.votingCodeID, err = wasmKeeper.StoreCode(suite.ctx, suite.deployer, votingWasm) - // suite.Require().NoError(err) - - // suite.proposalsCodeID, err = wasmKeeper.StoreCode(suite.ctx, suite.deployer, proposalsWasm) - // suite.Require().NoError(err) - - // suite.preProposeCodeID, err = wasmKeeper.StoreCode(suite.ctx, suite.deployer, preProposeWasm) - // suite.Require().NoError(err) -} - -// deployContracts instantiates all contracts -func (suite *IdentityDAOTestSuite) deployContracts() { - wasmKeeper := suite.app.WasmKeeper - - // Deploy Core Module - coreInitMsg := map[string]any{ - "admin": suite.deployer.String(), - "dao_name": "Test Identity DAO", - "dao_uri": "https://test.dao", - "voting_module": nil, - "proposal_modules": []string{}, - } - - coreInitBytes, err := json.Marshal(coreInitMsg) - suite.Require().NoError(err) - - suite.coreAddr, _, err = wasmKeeper.InstantiateContract( - suite.ctx, - suite.coreCodeID, - suite.deployer, - suite.deployer, - coreInitBytes, - "identity-dao-core", - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // Deploy Voting Module - votingInitMsg := map[string]any{ - "dao_address": suite.coreAddr.String(), - "min_verification_level": 1, - "voting_period": 604800, - "quorum_percentage": 20, - "threshold_percentage": 51, - } - - votingInitBytes, err := json.Marshal(votingInitMsg) - suite.Require().NoError(err) - - suite.votingAddr, _, err = wasmKeeper.InstantiateContract( - suite.ctx, - suite.votingCodeID, - suite.deployer, - suite.coreAddr, - votingInitBytes, - "did-voting", - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // Deploy Pre-Propose Module - preProposeInitMsg := map[string]any{ - "proposal_module": nil, - "min_verification_status": "Basic", - "deposit_amount": "1000000", - "deposit_denom": "usnr", - } - - preProposeInitBytes, err := json.Marshal(preProposeInitMsg) - suite.Require().NoError(err) - - suite.preProposeAddr, _, err = wasmKeeper.InstantiateContract( - suite.ctx, - suite.preProposeCodeID, - suite.deployer, - suite.coreAddr, - preProposeInitBytes, - "pre-propose-identity", - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // Deploy Proposals Module - proposalsInitMsg := map[string]any{ - "dao_address": suite.coreAddr.String(), - "voting_module": suite.votingAddr.String(), - "pre_propose_module": suite.preProposeAddr.String(), - "proposal_duration": 604800, - "min_verification_level": 1, - } - - proposalsInitBytes, err := json.Marshal(proposalsInitMsg) - suite.Require().NoError(err) - - suite.proposalsAddr, _, err = wasmKeeper.InstantiateContract( - suite.ctx, - suite.proposalsCodeID, - suite.deployer, - suite.coreAddr, - proposalsInitBytes, - "identity-proposals", - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // Update Core Module with voting and proposal modules - updateMsg := map[string]any{ - "update_config": map[string]any{ - "voting_module": suite.votingAddr.String(), - "proposal_modules": []string{suite.proposalsAddr.String()}, - }, - } - - updateBytes, err := json.Marshal(updateMsg) - suite.Require().NoError(err) - - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.coreAddr, - suite.deployer, - updateBytes, - sdk.NewCoins(), - ) - suite.Require().NoError(err) -} - -// TestProposalLifecycle tests the complete proposal workflow -func (suite *IdentityDAOTestSuite) TestProposalLifecycle() { - wasmKeeper := suite.app.WasmKeeper - - // 1. Submit proposal through pre-propose module - submitMsg := map[string]any{ - "submit_proposal": map[string]any{ - "title": "Test Proposal", - "description": "This is a test proposal", - "msgs": []map[string]any{ - { - "bank": map[string]any{ - "send": map[string]any{ - "to_address": suite.voter1.String(), - "amount": []map[string]any{ - { - "denom": "usnr", - "amount": "100000", - }, - }, - }, - }, - }, - }, - }, - } - - submitBytes, err := json.Marshal(submitMsg) - suite.Require().NoError(err) - - // Submit with deposit - deposit := sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(1000000))) - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.preProposeAddr, - suite.voter1, - submitBytes, - deposit, - ) - suite.Require().NoError(err) - - // 2. Query pending proposals - queryMsg := map[string]any{ - "pending_proposals": map[string]any{}, - } - - queryBytes, err := json.Marshal(queryMsg) - suite.Require().NoError(err) - - result, err := wasmKeeper.QuerySmart(suite.ctx, suite.preProposeAddr, queryBytes) - suite.Require().NoError(err) - - var pendingResp map[string]any - err = json.Unmarshal(result, &pendingResp) - suite.Require().NoError(err) - - proposals := pendingResp["proposals"].([]any) - suite.Require().Len(proposals, 1, "Should have one pending proposal") - - // 3. Approve proposal (move to voting) - approveMsg := map[string]any{ - "approve_proposal": map[string]any{ - "proposal_id": 1, - }, - } - - approveBytes, err := json.Marshal(approveMsg) - suite.Require().NoError(err) - - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.preProposeAddr, - suite.deployer, // Admin approves - approveBytes, - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // 4. Vote on proposal - voteMsg := map[string]any{ - "vote": map[string]any{ - "proposal_id": 1, - "vote": "yes", - }, - } - - voteBytes, err := json.Marshal(voteMsg) - suite.Require().NoError(err) - - // Multiple voters vote - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.votingAddr, - suite.voter1, - voteBytes, - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.votingAddr, - suite.voter2, - voteBytes, - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // 5. Query proposal status - statusQuery := map[string]any{ - "proposal": map[string]any{ - "proposal_id": 1, - }, - } - - statusBytes, err := json.Marshal(statusQuery) - suite.Require().NoError(err) - - statusResult, err := wasmKeeper.QuerySmart(suite.ctx, suite.proposalsAddr, statusBytes) - suite.Require().NoError(err) - - var statusResp map[string]any - err = json.Unmarshal(statusResult, &statusResp) - suite.Require().NoError(err) - - // Verify proposal status - suite.Equal("open", statusResp["status"], "Proposal should be open for voting") - - // 6. Execute proposal after voting period - // Fast-forward time - suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(7 * 24 * time.Hour)) - - executeMsg := map[string]any{ - "execute": map[string]any{ - "proposal_id": 1, - }, - } - - executeBytes, err := json.Marshal(executeMsg) - suite.Require().NoError(err) - - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.proposalsAddr, - suite.deployer, - executeBytes, - sdk.NewCoins(), - ) - suite.Require().NoError(err) - - // Verify execution - statusResult, err = wasmKeeper.QuerySmart(suite.ctx, suite.proposalsAddr, statusBytes) - suite.Require().NoError(err) - - err = json.Unmarshal(statusResult, &statusResp) - suite.Require().NoError(err) - - suite.Equal("executed", statusResp["status"], "Proposal should be executed") -} - -// TestDIDVerification tests DID-based voting power -func (suite *IdentityDAOTestSuite) TestDIDVerification() { - wasmKeeper := suite.app.WasmKeeper - - // Query voting power for voter with DID - queryMsg := map[string]any{ - "voting_power": map[string]any{ - "address": suite.voter1.String(), - }, - } - - queryBytes, err := json.Marshal(queryMsg) - suite.Require().NoError(err) - - result, err := wasmKeeper.QuerySmart(suite.ctx, suite.votingAddr, queryBytes) - suite.Require().NoError(err) - - var powerResp map[string]any - err = json.Unmarshal(result, &powerResp) - suite.Require().NoError(err) - - // Verify voting power based on verification level - power := powerResp["power"].(string) - suite.NotEqual("0", power, "Verified DID should have voting power") -} - -// TestTreasuryManagement tests DAO treasury operations -func (suite *IdentityDAOTestSuite) TestTreasuryManagement() { - wasmKeeper := suite.app.WasmKeeper - bankKeeper := suite.app.BankKeeper - - // Send funds to DAO treasury - treasuryFunds := sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(50000000))) - err := bankKeeper.SendCoins(suite.ctx, suite.deployer, suite.coreAddr, treasuryFunds) - suite.Require().NoError(err) - - // Query treasury balance - balance := bankKeeper.GetBalance(suite.ctx, suite.coreAddr, "usnr") - suite.Equal(treasuryFunds[0], balance, "Treasury should have the sent funds") - - // Create treasury spend proposal - spendMsg := map[string]any{ - "submit_proposal": map[string]any{ - "title": "Treasury Spend", - "description": "Spend from treasury", - "msgs": []map[string]any{ - { - "bank": map[string]any{ - "send": map[string]any{ - "from_address": suite.coreAddr.String(), - "to_address": suite.voter2.String(), - "amount": []map[string]any{ - { - "denom": "usnr", - "amount": "1000000", - }, - }, - }, - }, - }, - }, - }, - } - - spendBytes, err := json.Marshal(spendMsg) - suite.Require().NoError(err) - - deposit := sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(1000000))) - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.preProposeAddr, - suite.voter1, - spendBytes, - deposit, - ) - suite.Require().NoError(err) - - // Verify treasury spend requires proper authorization - // This would go through the full proposal workflow -} - -// TestAttestationGovernance tests identity attestation proposals -func (suite *IdentityDAOTestSuite) TestAttestationGovernance() { - wasmKeeper := suite.app.WasmKeeper - - // Create attestation policy change proposal - attestMsg := map[string]any{ - "submit_proposal": map[string]any{ - "title": "Update Attestation Policy", - "description": "Change attestation requirements", - "msgs": []map[string]any{ - { - "custom": map[string]any{ - "update_attestation_policy": map[string]any{ - "min_attestations": 2, - "valid_types": []string{"identity", "reputation"}, - }, - }, - }, - }, - }, - } - - attestBytes, err := json.Marshal(attestMsg) - suite.Require().NoError(err) - - deposit := sdk.NewCoins(sdk.NewCoin("usnr", sdk.NewInt(1000000))) - _, err = wasmKeeper.ExecuteContract( - suite.ctx, - suite.preProposeAddr, - suite.voter3, // Must have high verification level - attestBytes, - deposit, - ) - // This might fail if voter3 doesn't have sufficient verification - // suite.Require().Error(err, "Should require higher verification for attestation proposals") -} - -// TestWyomingDAOCompliance tests Wyoming DAO legal compliance -func (suite *IdentityDAOTestSuite) TestWyomingDAOCompliance() { - wasmKeeper := suite.app.WasmKeeper - - // Query DAO configuration - configQuery := map[string]any{ - "config": map[string]any{}, - } - - configBytes, err := json.Marshal(configQuery) - suite.Require().NoError(err) - - result, err := wasmKeeper.QuerySmart(suite.ctx, suite.coreAddr, configBytes) - suite.Require().NoError(err) - - var config map[string]any - err = json.Unmarshal(result, &config) - suite.Require().NoError(err) - - // Verify Wyoming DAO requirements - suite.NotEmpty(config["dao_name"], "DAO must have a name") - suite.NotEmpty(config["dao_uri"], "DAO must have a URI") - suite.NotEmpty(config["admin"], "DAO must have an admin") - - // Verify voting mechanism exists - suite.NotEmpty(config["voting_module"], "DAO must have voting module") - suite.NotEmpty(config["proposal_modules"], "DAO must have proposal modules") -} - -// TestSuite runs the test suite -func TestIdentityDAO(t *testing.T) { - suite.Run(t, new(IdentityDAOTestSuite)) -} diff --git a/contracts/DAO/tests/integration/did_integration_test.rs b/contracts/DAO/tests/integration/did_integration_test.rs deleted file mode 100644 index 299f788f7..000000000 --- a/contracts/DAO/tests/integration/did_integration_test.rs +++ /dev/null @@ -1,421 +0,0 @@ -#[cfg(test)] -mod did_integration_tests { - use cosmwasm_std::{ - testing::{mock_dependencies_with_balance, mock_env, mock_info, MockApi, MockQuerier, MockStorage}, - from_json, to_json_binary, Addr, Binary, Coin, ContractResult, Deps, DepsMut, Empty, Env, - MessageInfo, Response, StdError, StdResult, Uint128, WasmMsg, CosmosMsg, - QueryRequest, SystemResult, - }; - use cosmwasm_std::testing::MockQuerierCustomHandlerResult; - - use identity_dao_shared::{ - CoreInstantiateMsg, CoreExecuteMsg, CoreQueryMsg, - VotingInstantiateMsg, VotingExecuteMsg, VotingQueryMsg, - ProposalInstantiateMsg, ProposalExecuteMsg, ProposalQueryMsg, - PreProposeInstantiateMsg, PreProposeExecuteMsg, PreProposeQueryMsg, - VotingConfig, ProposalStatus, Vote, DaoConfigResponse, - VotingPowerResponse, ProposalResponse, IdentityVoter, VerificationStatus, - bindings::{SonrQuery, DIDDocumentResponse, VerificationResponse}, - }; - - struct IntegrationTestSetup { - core_addr: Addr, - voting_addr: Addr, - proposal_addr: Addr, - pre_propose_addr: Addr, - } - - /// Setup all DAO contracts with proper module registration - fn setup_dao_contracts() -> (MockStorage, MockApi, MockQuerier, IntegrationTestSetup) { - let mut storage = MockStorage::default(); - let api = MockApi::default(); - let mut querier = MockQuerier::new(&[]); - - // Setup custom query handler for DID module queries - querier.update_wasm(|query| -> MockQuerierCustomHandlerResult { - match query { - cosmwasm_std::WasmQuery::Smart { contract_addr, msg } => { - // Handle DID module queries - if let Ok(sonr_query) = from_json::(msg) { - match sonr_query { - SonrQuery::GetDIDDocument { did } => { - let response = DIDDocumentResponse { - did: did.clone(), - controller: format!("{}_controller", did), - verification_methods: vec![], - authentication: vec![], - assertion_method: vec![], - capability_invocation: vec![], - capability_delegation: vec![], - service_endpoints: vec![], - }; - return SystemResult::Ok(ContractResult::Ok(to_json_binary(&response).unwrap())); - }, - SonrQuery::VerifyDIDController { did, controller } => { - let response = VerificationResponse { - is_valid: controller == format!("{}_controller", did), - error: None, - }; - return SystemResult::Ok(ContractResult::Ok(to_json_binary(&response).unwrap())); - }, - } - } - SystemResult::Ok(ContractResult::Err("Not a DID query".to_string())) - }, - _ => SystemResult::Ok(ContractResult::Err("Unsupported query".to_string())), - } - }); - - // Contract addresses - let core_addr = Addr::unchecked("dao_core"); - let voting_addr = Addr::unchecked("dao_voting"); - let proposal_addr = Addr::unchecked("dao_proposal"); - let pre_propose_addr = Addr::unchecked("dao_pre_propose"); - - let setup = IntegrationTestSetup { - core_addr: core_addr.clone(), - voting_addr: voting_addr.clone(), - proposal_addr: proposal_addr.clone(), - pre_propose_addr: pre_propose_addr.clone(), - }; - - (storage, api, querier, setup) - } - - #[test] - fn test_full_dao_initialization_with_did() { - let (mut storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - let creator = mock_info("creator", &[]); - - // 1. Initialize Core Module - let core_msg = CoreInstantiateMsg { - name: "Identity DAO".to_string(), - description: "A DAO for identity management".to_string(), - voting_config: VotingConfig { - threshold: cosmwasm_std::Decimal::percent(51), - quorum: cosmwasm_std::Decimal::percent(10), - voting_period: 86400, - proposal_deposit: Uint128::from(1000000u128), - }, - admin: Some("admin".to_string()), - enable_did_integration: true, - }; - - // Simulate core instantiation - // In real integration test, this would be done via instantiate_contract - - // 2. Initialize Voting Module with DID integration - let voting_msg = VotingInstantiateMsg { - dao_core: setup.core_addr.to_string(), - min_verification_level: 1, - use_reputation_weight: true, - }; - - // 3. Initialize Proposal Module - let proposal_msg = ProposalInstantiateMsg { - dao_core: setup.core_addr.to_string(), - voting_module: setup.voting_addr.to_string(), - pre_propose_module: Some(setup.pre_propose_addr.to_string()), - proposal_deposit: Uint128::from(1000000u128), - max_voting_period: 604800, // 7 days - }; - - // 4. Initialize Pre-Propose Module with DID gating - let pre_propose_msg = PreProposeInstantiateMsg { - dao_core: setup.core_addr.to_string(), - proposal_module: setup.proposal_addr.to_string(), - require_verified_did: true, - min_reputation_score: 10, - deposit_amount: Uint128::from(1000000u128), - deposit_denom: "usnr".to_string(), - }; - - // Verify all modules are properly configured - assert_eq!(voting_msg.dao_core, setup.core_addr.to_string()); - assert_eq!(proposal_msg.voting_module, setup.voting_addr.to_string()); - assert_eq!(pre_propose_msg.proposal_module, setup.proposal_addr.to_string()); - } - - #[test] - fn test_did_voter_registration_and_verification() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Register a voter with DID - let did = "did:sonr:alice123"; - let alice_addr = "alice_address"; - - let register_msg = VotingExecuteMsg::UpdateVoter { - did: did.to_string(), - address: alice_addr.to_string(), - }; - - // Simulate DID verification through stargate query - let verification_query = SonrQuery::VerifyDIDController { - did: did.to_string(), - controller: format!("{}_controller", did), - }; - - // Query would return verification status - let deps = mock_dependencies_with_balance(&[]); - let query_result: StdResult = to_json_binary(&VerificationResponse { - is_valid: true, - error: None, - }); - - assert!(query_result.is_ok()); - } - - #[test] - fn test_did_gated_proposal_creation() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Setup verified DID holder - let proposer_did = "did:sonr:proposer456"; - let proposer_addr = "proposer_address"; - - // Create proposal through pre-propose module - let proposal_msg = PreProposeExecuteMsg::ProposeWithDID { - did: proposer_did.to_string(), - title: "Upgrade Protocol".to_string(), - description: "Proposal to upgrade the protocol to v2".to_string(), - msgs: vec![], - }; - - // Verify DID before allowing proposal - let verification_query = SonrQuery::GetDIDDocument { - did: proposer_did.to_string(), - }; - - // Check that proposal creation requires verified DID - let deps = mock_dependencies_with_balance(&[]); - let did_response = DIDDocumentResponse { - did: proposer_did.to_string(), - controller: format!("{}_controller", proposer_did), - verification_methods: vec![], - authentication: vec![], - assertion_method: vec![], - capability_invocation: vec![], - capability_delegation: vec![], - service_endpoints: vec![], - }; - - let query_result: StdResult = to_json_binary(&did_response); - assert!(query_result.is_ok()); - } - - #[test] - fn test_voting_with_did_based_power() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Setup multiple voters with different verification levels - let voters = vec![ - ("did:sonr:voter1", "voter1_addr", 100u32), // High reputation - ("did:sonr:voter2", "voter2_addr", 50u32), // Medium reputation - ("did:sonr:voter3", "voter3_addr", 10u32), // Low reputation - ]; - - for (did, addr, reputation) in voters.iter() { - // Register voter - let register_msg = VotingExecuteMsg::UpdateVoter { - did: did.to_string(), - address: addr.to_string(), - }; - - // Voting power should be weighted by reputation - let expected_power = calculate_did_voting_power(*reputation); - - // Query voting power - let query_msg = VotingQueryMsg::GetVotingPower { - address: addr.to_string(), - }; - - // Verify power calculation - assert!(expected_power > Uint128::zero()); - if *reputation > 50 { - assert!(expected_power > Uint128::from(1u128)); - } - } - } - - #[test] - fn test_cross_module_proposal_execution() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Create proposal with multiple actions - let proposal_msgs = vec![ - CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: "target_contract".to_string(), - msg: to_json_binary(&"action1").unwrap(), - funds: vec![], - }), - CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: "target_contract".to_string(), - msg: to_json_binary(&"action2").unwrap(), - funds: vec![], - }), - ]; - - // Proposal creation through pre-propose - let create_proposal = ProposalExecuteMsg::CreateProposal { - title: "Multi-action Proposal".to_string(), - description: "Execute multiple actions".to_string(), - msgs: proposal_msgs.clone(), - proposer: "proposer_addr".to_string(), - }; - - // Simulate voting to pass proposal - let vote_msg = VotingExecuteMsg::Vote { - proposal_id: 1, - vote: Vote::Yes, - }; - - // Execute proposal through core - let execute_msg = CoreExecuteMsg::ExecuteProposal { - proposal_id: 1, - }; - - // Verify all messages are executed - assert_eq!(proposal_msgs.len(), 2); - } - - #[test] - fn test_ibc_did_verification() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Setup IBC channel for DID verification - let ibc_channel = "channel-0"; - let sonr_chain_did = "did:sonr:ibc_user789"; - - // Query DID from Sonr chain via IBC - let ibc_query = SonrQuery::GetDIDDocument { - did: sonr_chain_did.to_string(), - }; - - // Simulate IBC response - let ibc_response = DIDDocumentResponse { - did: sonr_chain_did.to_string(), - controller: "cosmos1abc...".to_string(), - verification_methods: vec!["key1".to_string()], - authentication: vec!["auth1".to_string()], - assertion_method: vec![], - capability_invocation: vec![], - capability_delegation: vec![], - service_endpoints: vec![], - }; - - // Verify cross-chain DID - assert_eq!(ibc_response.did, sonr_chain_did); - assert!(!ibc_response.verification_methods.is_empty()); - } - - #[test] - fn test_reputation_based_quorum() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Setup voters with varying reputation - let high_rep_voters = 2; - let low_rep_voters = 10; - - // High reputation voters should have more weight - let high_rep_power = Uint128::from(10u128); - let low_rep_power = Uint128::from(1u128); - - let total_power = high_rep_power - .checked_mul(Uint128::from(high_rep_voters as u128)) - .unwrap() - .checked_add(low_rep_power.checked_mul(Uint128::from(low_rep_voters as u128)).unwrap()) - .unwrap(); - - // Calculate quorum (10% of total power) - let quorum_threshold = total_power.multiply_ratio(10u128, 100u128); - - // Verify that 2 high-rep voters can meet quorum - let high_rep_voting_power = high_rep_power - .checked_mul(Uint128::from(high_rep_voters as u128)) - .unwrap(); - - assert!(high_rep_voting_power >= quorum_threshold); - } - - #[test] - fn test_treasury_management_with_did_auth() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Only verified DID holders can propose treasury withdrawals - let treasury_manager_did = "did:sonr:treasurer"; - - // Create treasury withdrawal proposal - let withdrawal_msg = CoreExecuteMsg::WithdrawFromTreasury { - recipient: "recipient_addr".to_string(), - amount: Uint128::from(1000000u128), - denom: "usnr".to_string(), - }; - - // Verify proposer has sufficient reputation - let min_reputation_for_treasury = 50u32; - - // Query proposer's reputation - let verification_query = SonrQuery::GetDIDDocument { - did: treasury_manager_did.to_string(), - }; - - // Simulate reputation check - let has_sufficient_reputation = true; // Would be fetched from DID module - assert!(has_sufficient_reputation); - } - - #[test] - fn test_emergency_pause_with_did_multisig() { - let (storage, api, querier, setup) = setup_dao_contracts(); - let env = mock_env(); - - // Emergency actions require multiple DID signatures - let emergency_signers = vec![ - "did:sonr:emergency1", - "did:sonr:emergency2", - "did:sonr:emergency3", - ]; - - // Each signer must be verified - for signer_did in emergency_signers.iter() { - let verification = SonrQuery::VerifyDIDController { - did: signer_did.to_string(), - controller: format!("{}_controller", signer_did), - }; - - // All signers must be valid - let response = VerificationResponse { - is_valid: true, - error: None, - }; - - assert!(response.is_valid); - } - - // Require 2/3 signatures for emergency action - let required_signatures = 2; - let collected_signatures = 3; - - assert!(collected_signatures >= required_signatures); - } - - // Helper function to calculate DID-based voting power - fn calculate_did_voting_power(reputation_score: u32) -> Uint128 { - let base_power = Uint128::from(1u128); - if reputation_score > 0 { - // Formula: base_power * (1 + reputation_score / 100) - let multiplier = Uint128::from((100 + reputation_score) as u128); - base_power.multiply_ratio(multiplier, 100u128) - } else { - base_power - } - } -} \ No newline at end of file diff --git a/contracts/wSNR/.env.example b/contracts/wSNR/.env.example deleted file mode 100644 index 59ec69d23..000000000 --- a/contracts/wSNR/.env.example +++ /dev/null @@ -1,15 +0,0 @@ -# Sonr EVM Configuration -# Local development (uses localchain_9000-1) -SONR_RPC_URL=http://localhost:8545 - -# Testnet (when available, uses sonr-testnet-1) -SONR_TESTNET_RPC_URL=http://localhost:8545 - -# Private key for deployment (DO NOT COMMIT REAL KEYS) -PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 - -# Block explorer API key for contract verification -ETHERSCAN_API_KEY= - -# Alchemy API key (optional, for Ethereum testnet comparison) -ALCHEMY_API_KEY= diff --git a/contracts/wSNR/.gitignore b/contracts/wSNR/.gitignore deleted file mode 100644 index f9d2bc54b..000000000 --- a/contracts/wSNR/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -# Foundry files -cache/ -out/ -broadcast/ - -# Environment -.env -.env.local - -# Dependencies -lib/ - -# Coverage -lcov.info -coverage/ - -# OS -.DS_Store -.claude* diff --git a/contracts/wSNR/DEPLOY.md b/contracts/wSNR/DEPLOY.md deleted file mode 100644 index 6fbf13919..000000000 --- a/contracts/wSNR/DEPLOY.md +++ /dev/null @@ -1,153 +0,0 @@ -# WSNR Deployment Scripts - -This directory contains multiple deployment scripts for the WSNR (Wrapped SNR) smart contract. - -## Prerequisites - -1. **Compile the contract first**: - - ```bash - cd contracts - forge build - ``` - -2. **Set up environment variables**: - - ```bash - cd contracts - cp .env.example .env - # Edit .env and add your PRIVATE_KEY - ``` - -3. **Ensure your Sonr node is running** with EVM enabled on `http://localhost:8545` - -## Deployment Options - -### Option 1: Foundry Script (Recommended) - -The most robust option using Foundry's native scripting: - -```bash -# Deploy to local Sonr node -./scripts/deploy-wsnr.sh - -# Deploy to testnet -./scripts/deploy-wsnr.sh sonr-testnet -``` - -Features: - -- Automatic chain detection -- Balance checking -- Contract verification -- Deployment info saved to `contracts/deployments/` - -### Option 2: Simple Node.js Script - -Requires Node.js and ethers.js: - -```bash -# Install dependencies (if not already installed) -npm install ethers - -# Deploy -node scripts/deploy-wsnr-simple.js [rpc-url] - -# Example with custom RPC -node scripts/deploy-wsnr-simple.js http://192.168.1.100:8545 -``` - -### Option 3: Python Script - -Requires Python 3 and web3.py: - -```bash -# Install dependencies (if not already installed) -pip3 install web3 eth-account - -# Deploy -python3 scripts/deploy-wsnr.py [rpc-url] - -# Example with custom RPC -python3 scripts/deploy-wsnr.py http://192.168.1.100:8545 -``` - -### Option 4: Direct Foundry Command - -For advanced users who want to customize deployment: - -```bash -cd contracts -forge script script/DeployWSNR.s.sol:DeployWSNR \ - --rpc-url http://localhost:8545 \ - --broadcast \ - --private-key $PRIVATE_KEY -``` - -## Post-Deployment - -After deployment, you'll receive: - -- Contract address -- Transaction hash -- Block number -- Deployment info saved to `contracts/deployments/{chainId}-WSNR.json` - -### Interacting with the Contract - -**Using cast (Foundry)**: - -```bash -# Deposit SNR to get WSNR -cast send "deposit()" --value 1ether --rpc-url http://localhost:8545 --private-key $PRIVATE_KEY - -# Check WSNR balance -cast call "balanceOf(address)" --rpc-url http://localhost:8545 - -# Withdraw SNR -cast send "withdraw(uint256)" 1000000000000000000 --rpc-url http://localhost:8545 --private-key $PRIVATE_KEY -``` - -**Using web3 console**: - -```javascript -// Connect to contract -const wsnr = new web3.eth.Contract(abi, contractAddress); - -// Deposit -await wsnr.methods - .deposit() - .send({ from: account, value: web3.utils.toWei("1", "ether") }); - -// Check balance -const balance = await wsnr.methods.balanceOf(account).call(); - -// Withdraw -await wsnr.methods - .withdraw(web3.utils.toWei("1", "ether")) - .send({ from: account }); -``` - -## Troubleshooting - -### Cannot connect to node - -- Ensure Sonr node is running: `make sh-testnet` or `docker-compose up sonr-node` -- Check if EVM is enabled with JSON-RPC on port 8545 -- Try `curl http://localhost:8545` to test connectivity - -### Insufficient balance - -- Fund your deployer address with SNR tokens -- Check balance: `cast balance --rpc-url http://localhost:8545` - -### Contract not compiled - -- Run `cd contracts && forge build` first -- Ensure you have Foundry installed: `curl -L https://foundry.paradigm.xyz | bash` - -### Transaction fails - -- Check gas prices and limits -- Ensure your account has enough SNR for gas -- Check if the network is synced diff --git a/contracts/wSNR/Makefile b/contracts/wSNR/Makefile deleted file mode 100644 index c2e67aee5..000000000 --- a/contracts/wSNR/Makefile +++ /dev/null @@ -1,105 +0,0 @@ -# Foundry Makefile for Sonr Smart Contracts - -# Load environment variables --include .env - -# Default network -NETWORK ?= sonr - -# Contract verification -VERIFIER ?= etherscan -VERIFIER_URL ?= https://api.etherscan.io/api - -.PHONY: help -help: ## Display this help message - @gum log --level info "Sonr Smart Contracts - Foundry Commands" - @gum log --level info "" - @awk 'BEGIN {FS = ":.*##"; printf "Usage:\n make \033[36m\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST) - -.PHONY: install -install: ## Install Foundry and dependencies - curl -L https://foundry.paradigm.xyz | bash - foundryup - forge install OpenZeppelin/openzeppelin-contracts@v5.0.0 --no-commit - -.PHONY: build -build: ## Build contracts - forge build - -.PHONY: test -test: ## Run tests - forge test -vvv - -.PHONY: test-gas -test-gas: ## Run tests with gas reporting - forge test -vvv --gas-report - -.PHONY: coverage -coverage: ## Generate test coverage report - forge coverage - -.PHONY: format -format: ## Format Solidity code - forge fmt - -.PHONY: lint -lint: ## Lint Solidity code - forge fmt --check - -.PHONY: snapshot -snapshot: ## Create gas snapshot - forge snapshot - -.PHONY: clean -clean: ## Clean build artifacts - forge clean - -# Deployment commands -.PHONY: deploy-wsnr -deploy-wsnr: ## Deploy WSNR contract - @gum log --level info "Deploying WSNR to $(NETWORK)..." - forge script script/DeployWSNR.s.sol:DeployWSNR \ - --rpc-url $(NETWORK) \ - --broadcast \ - --verify \ - -vvvv - -.PHONY: deploy-local -deploy-local: ## Deploy to local Sonr node - @gum log --level info "Deploying to local Sonr node..." - @cd .. && ./scripts/deploy-wsnr.sh sonr - -.PHONY: deploy-testnet -deploy-testnet: ## Deploy to Sonr testnet - @gum log --level info "Deploying to Sonr testnet..." - @cd .. && ./scripts/deploy-wsnr.sh sonr-testnet - -.PHONY: deploy -deploy: deploy-local ## Default deployment (alias for deploy-local) - -# Interaction commands -.PHONY: console -console: ## Start Foundry console - forge console --rpc-url $(NETWORK) - -.PHONY: verify -verify: ## Verify contract on Etherscan - forge verify-contract \ - --chain-id $(shell cast chain-id --rpc-url $(NETWORK)) \ - --etherscan-api-key $(ETHERSCAN_API_KEY) \ - --verifier $(VERIFIER) \ - $(CONTRACT_ADDRESS) \ - $(CONTRACT_NAME) - -# Development helpers -.PHONY: anvil -anvil: ## Start local Anvil node - anvil --chain-id 31337 - -.PHONY: cast-balance -cast-balance: ## Check ETH balance of an address - @cast balance $(ADDRESS) --rpc-url $(NETWORK) - -.PHONY: cast-send -cast-send: ## Send a transaction - @cast send $(TO) --value $(VALUE) --rpc-url $(NETWORK) --private-key $(PRIVATE_KEY) \ No newline at end of file diff --git a/contracts/wSNR/README.md b/contracts/wSNR/README.md deleted file mode 100644 index 1b54bcc0c..000000000 --- a/contracts/wSNR/README.md +++ /dev/null @@ -1,122 +0,0 @@ -# Sonr Smart Contracts - -This directory contains the smart contracts for the Sonr blockchain, including the WSNR (Wrapped SNR) ERC-20 token contract. - -## Setup - -### Prerequisites - -1. Install Foundry: - -```bash -curl -L https://foundry.paradigm.xyz | bash -foundryup -``` - -2. Install dependencies: - -```bash -make install -``` - -3. Copy environment variables: - -```bash -cp .env.example .env -``` - -4. Configure your `.env` file with appropriate values - -## Development - -### Build contracts: - -```bash -make build -``` - -### Run tests: - -```bash -make test -``` - -### Run tests with gas reporting: - -```bash -make test-gas -``` - -### Generate coverage report: - -```bash -make coverage -``` - -### Format code: - -```bash -make format -``` - -### Deploy to local Sonr network: - -```bash -make deploy-local -``` - -### Deploy to Sonr testnet: - -```bash -make deploy-testnet -``` - -### Clean build artifacts: - -```bash -make clean -``` - -### Start local Anvil node (for testing): - -```bash -make anvil -``` - -## Project Structure - -``` -contracts/ -├── src/ # Contract source files -├── test/ # Test files -├── script/ # Deployment scripts -├── lib/ # Dependencies (gitignored) -├── foundry.toml # Foundry configuration -└── Makefile # Build commands -``` - -## Testing on Sonr Native EVM - -Start the local testnet with EVM enabled: - -```bash -# From project root -docker-compose -f docker-compose.dev.yml up -d sonr-node -``` - -The EVM JSON-RPC endpoint will be available at: - -- HTTP: http://localhost:8545 -- WebSocket: ws://localhost:8546 - -## Foundry Commands - -For a full list of available commands: - -```bash -make help -``` - -## Contract Addresses - -- WSNR: TBD (after deployment) diff --git a/contracts/wSNR/build.sh b/contracts/wSNR/build.sh deleted file mode 100755 index 25ceaca7e..000000000 --- a/contracts/wSNR/build.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -set -e - -echo "🔧 Setting up Foundry environment..." - -# Source foundry if installed via foundryup -if [ -f "$HOME/.foundry/bin/forge" ]; then - export PATH="$HOME/.foundry/bin:$PATH" -fi - -# Check if forge is available -if ! command -v forge &>/dev/null; then - echo "❌ Forge not found in PATH. Please ensure Foundry is installed:" - echo " curl -L https://foundry.paradigm.xyz | bash" - echo " foundryup" - echo "" - echo "Then run: source ~/.bashrc or source ~/.zshrc" - exit 1 -fi - -echo "✅ Forge found at: $(which forge)" -echo "📦 Installing OpenZeppelin contracts..." - -# Install OpenZeppelin if not already installed -if [ ! -d "lib/openzeppelin-contracts" ]; then - forge install OpenZeppelin/openzeppelin-contracts@v5.0.0 --no-commit -else - echo "✅ OpenZeppelin already installed" -fi - -echo "🏗️ Building contracts..." -forge build - -echo "✅ Build complete!" diff --git a/contracts/wSNR/foundry.toml b/contracts/wSNR/foundry.toml deleted file mode 100644 index 702b944dd..000000000 --- a/contracts/wSNR/foundry.toml +++ /dev/null @@ -1,25 +0,0 @@ -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -solc = "0.8.20" -optimizer = true -optimizer_runs = 200 - -# Network configurations -[rpc_endpoints] -sonr = "${SONR_RPC_URL}" -sonr_testnet = "${SONR_TESTNET_RPC_URL}" -sepolia = "https://eth-sepolia.g.alchemy.com/v2/${ALCHEMY_API_KEY}" - -[etherscan] -sonr = { key = "${ETHERSCAN_API_KEY}" } - -# Testing configuration -[fuzz] -runs = 256 - -[invariant] -runs = 256 -depth = 128 -fail_on_revert = false diff --git a/contracts/wSNR/script/DeployWSNR.s.sol b/contracts/wSNR/script/DeployWSNR.s.sol deleted file mode 100644 index 861371a49..000000000 --- a/contracts/wSNR/script/DeployWSNR.s.sol +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {Script, console2} from "forge-std/Script.sol"; -import {WSNR} from "../src/WSNR.sol"; - -contract DeployWSNR is Script { - function run() external returns (WSNR) { - // Get deployer private key from environment - uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY"); - - // Get chain ID for logging - uint256 chainId = block.chainid; - - console2.log("Deploying WSNR to chain ID:", chainId); - console2.log("Deployer address:", vm.addr(deployerPrivateKey)); - console2.log("Deployer balance:", vm.addr(deployerPrivateKey).balance); - - // Start broadcasting transactions - vm.startBroadcast(deployerPrivateKey); - - // Deploy WSNR contract - WSNR wsnr = new WSNR(); - - console2.log("WSNR deployed at:", address(wsnr)); - console2.log("Contract name:", wsnr.name()); - console2.log("Contract symbol:", wsnr.symbol()); - console2.log("Contract decimals:", wsnr.decimals()); - - vm.stopBroadcast(); - - // Write deployment info to file for reference - string memory deploymentInfo = string( - abi.encodePacked( - "{\n", - ' "contractName": "WSNR",\n', - ' "address": "', vm.toString(address(wsnr)), '",\n', - ' "chainId": ', vm.toString(chainId), ',\n', - ' "deployer": "', vm.toString(vm.addr(deployerPrivateKey)), '",\n', - ' "deploymentBlock": ', vm.toString(block.number), ',\n', - ' "timestamp": ', vm.toString(block.timestamp), '\n', - "}" - ) - ); - - // Save deployment info - vm.writeFile( - string(abi.encodePacked("deployments/", vm.toString(chainId), "-WSNR.json")), - deploymentInfo - ); - - return wsnr; - } -} \ No newline at end of file diff --git a/contracts/wSNR/src/WSNR.sol b/contracts/wSNR/src/WSNR.sol deleted file mode 100644 index 06f9d14cb..000000000 --- a/contracts/wSNR/src/WSNR.sol +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {ERC20} from "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; -import {ReentrancyGuard} from "openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol"; -import {IWSNR} from "./interfaces/IWSNR.sol"; - -/** - * @title WSNR - Wrapped SNR - * @notice ERC20 wrapper for native SNR tokens - * @dev Implements a 1:1 wrapping mechanism for SNR tokens with deposit/withdraw functionality - */ -contract WSNR is IWSNR, ERC20, ReentrancyGuard { - /** - * @notice Initializes the WSNR token contract - * @dev Sets token name as "Wrapped SNR" and symbol as "WSNR" - */ - constructor() ERC20("Wrapped SNR", "WSNR") {} - - /** - * @notice Fallback function to handle direct SNR transfers - * @dev Automatically wraps sent SNR into WSNR tokens - */ - receive() external payable { - deposit(); - } - - /** - * @notice Deposit native SNR and receive WSNR tokens - * @dev Mints WSNR tokens equal to the amount of SNR sent - */ - function deposit() public payable override nonReentrant { - require(msg.value > 0, "WSNR: deposit amount must be greater than 0"); - - _mint(msg.sender, msg.value); - - emit Deposit(msg.sender, msg.value); - } - - /** - * @notice Deposit native SNR to a specific address - * @param to Address to receive the WSNR tokens - * @dev Allows depositing on behalf of another address - */ - function depositTo(address to) public payable override nonReentrant { - require(msg.value > 0, "WSNR: deposit amount must be greater than 0"); - require(to != address(0), "WSNR: cannot deposit to zero address"); - - _mint(to, msg.value); - - emit Deposit(to, msg.value); - } - - /** - * @notice Withdraw native SNR by burning WSNR tokens - * @param amount Amount of WSNR to burn and SNR to receive - * @dev Burns WSNR tokens and sends equivalent native SNR - */ - function withdraw(uint256 amount) public override { - withdrawTo(msg.sender, amount); - } - - /** - * @notice Withdraw native SNR to a specific address - * @param to Address to receive the native SNR - * @param amount Amount of WSNR to burn - * @dev Allows withdrawing to a different address - */ - function withdrawTo(address to, uint256 amount) public override nonReentrant { - require(amount > 0, "WSNR: withdrawal amount must be greater than 0"); - require(to != address(0), "WSNR: cannot withdraw to zero address"); - require(balanceOf(msg.sender) >= amount, "WSNR: insufficient balance"); - - _burn(msg.sender, amount); - - (bool success,) = to.call{value: amount}(""); - require(success, "WSNR: SNR transfer failed"); - - emit Withdrawal(to, amount); - } - - /** - * @notice Get the total amount of SNR locked in the contract - * @return The balance of native SNR held by the contract - */ - function getReserve() public view returns (uint256) { - return address(this).balance; - } - - /** - * @notice Verify that total supply equals contract balance - * @dev This should always return true for proper 1:1 backing - * @return Whether the contract is properly collateralized - */ - function isFullyCollateralized() public view returns (bool) { - return totalSupply() == address(this).balance; - } -} diff --git a/contracts/wSNR/src/interfaces/IWSNR.sol b/contracts/wSNR/src/interfaces/IWSNR.sol deleted file mode 100644 index e69915a66..000000000 --- a/contracts/wSNR/src/interfaces/IWSNR.sol +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; - -/** - * @title IWSNR - * @notice Interface for Wrapped SNR (WSNR) token contract - * @dev Extends ERC20 with deposit and withdraw functionality for wrapping native SNR tokens - */ -interface IWSNR is IERC20 { - /** - * @notice Emitted when native SNR is deposited and WSNR is minted - * @param from Address that deposited SNR - * @param amount Amount of SNR deposited (and WSNR minted) - */ - event Deposit(address indexed from, uint256 amount); - - /** - * @notice Emitted when WSNR is burned and native SNR is withdrawn - * @param to Address that received SNR - * @param amount Amount of WSNR burned (and SNR withdrawn) - */ - event Withdrawal(address indexed to, uint256 amount); - - /** - * @notice Deposit native SNR and receive WSNR tokens - * @dev Mints WSNR tokens equal to the amount of SNR sent - */ - function deposit() external payable; - - /** - * @notice Withdraw native SNR by burning WSNR tokens - * @param amount Amount of WSNR to burn and SNR to receive - * @dev Burns WSNR tokens and sends equivalent native SNR - */ - function withdraw(uint256 amount) external; - - /** - * @notice Deposit native SNR to a specific address - * @param to Address to receive the WSNR tokens - * @dev Allows depositing on behalf of another address - */ - function depositTo(address to) external payable; - - /** - * @notice Withdraw native SNR to a specific address - * @param to Address to receive the native SNR - * @param amount Amount of WSNR to burn - * @dev Allows withdrawing to a different address - */ - function withdrawTo(address to, uint256 amount) external; -} \ No newline at end of file diff --git a/contracts/wSNR/test/WSNR.t.sol b/contracts/wSNR/test/WSNR.t.sol deleted file mode 100644 index b7480f87c..000000000 --- a/contracts/wSNR/test/WSNR.t.sol +++ /dev/null @@ -1,371 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import {Test, console2} from "forge-std/Test.sol"; -import {WSNR} from "../src/WSNR.sol"; -import {ReentrancyGuard} from "openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol"; - -contract WSNRTest is Test { - WSNR public wsnr; - address public alice = address(0x1); - address public bob = address(0x2); - address public charlie = address(0x3); - - event Deposit(address indexed from, uint256 amount); - event Withdrawal(address indexed to, uint256 amount); - event Transfer(address indexed from, address indexed to, uint256 value); - event Approval(address indexed owner, address indexed spender, uint256 value); - - function setUp() public { - wsnr = new WSNR(); - - // Fund test accounts - vm.deal(alice, 100 ether); - vm.deal(bob, 100 ether); - vm.deal(charlie, 100 ether); - } - - function testInitialState() public { - assertEq(wsnr.name(), "Wrapped SNR"); - assertEq(wsnr.symbol(), "WSNR"); - assertEq(wsnr.decimals(), 18); - assertEq(wsnr.totalSupply(), 0); - assertEq(wsnr.getReserve(), 0); - assertTrue(wsnr.isFullyCollateralized()); - } - - function testDeposit() public { - uint256 depositAmount = 10 ether; - - vm.startPrank(alice); - - // Test deposit event - vm.expectEmit(true, false, false, true); - emit Deposit(alice, depositAmount); - - // Deposit SNR - wsnr.deposit{value: depositAmount}(); - - // Check balances - assertEq(wsnr.balanceOf(alice), depositAmount); - assertEq(wsnr.totalSupply(), depositAmount); - assertEq(wsnr.getReserve(), depositAmount); - assertEq(address(wsnr).balance, depositAmount); - assertTrue(wsnr.isFullyCollateralized()); - - vm.stopPrank(); - } - - function testDepositZeroAmount() public { - vm.startPrank(alice); - vm.expectRevert("WSNR: deposit amount must be greater than 0"); - wsnr.deposit{value: 0}(); - vm.stopPrank(); - } - - function testDepositTo() public { - uint256 depositAmount = 5 ether; - - vm.startPrank(alice); - - // Test deposit event - vm.expectEmit(true, false, false, true); - emit Deposit(bob, depositAmount); - - // Deposit SNR to bob's account - wsnr.depositTo{value: depositAmount}(bob); - - // Check balances - assertEq(wsnr.balanceOf(alice), 0); - assertEq(wsnr.balanceOf(bob), depositAmount); - assertEq(wsnr.totalSupply(), depositAmount); - assertEq(address(wsnr).balance, depositAmount); - - vm.stopPrank(); - } - - function testDepositToZeroAddress() public { - vm.startPrank(alice); - vm.expectRevert("WSNR: cannot deposit to zero address"); - wsnr.depositTo{value: 1 ether}(address(0)); - vm.stopPrank(); - } - - function testReceiveFallback() public { - uint256 depositAmount = 3 ether; - - vm.startPrank(alice); - - // Test deposit event through fallback - vm.expectEmit(true, false, false, true); - emit Deposit(alice, depositAmount); - - // Send SNR directly to contract - (bool success,) = address(wsnr).call{value: depositAmount}(""); - assertTrue(success); - - // Check balances - assertEq(wsnr.balanceOf(alice), depositAmount); - assertEq(wsnr.totalSupply(), depositAmount); - - vm.stopPrank(); - } - - function testWithdraw() public { - uint256 depositAmount = 10 ether; - uint256 withdrawAmount = 6 ether; - - vm.startPrank(alice); - - // First deposit - wsnr.deposit{value: depositAmount}(); - uint256 aliceBalanceBefore = alice.balance; - - // Test withdrawal event - vm.expectEmit(true, false, false, true); - emit Withdrawal(alice, withdrawAmount); - - // Withdraw - wsnr.withdraw(withdrawAmount); - - // Check balances - assertEq(wsnr.balanceOf(alice), depositAmount - withdrawAmount); - assertEq(wsnr.totalSupply(), depositAmount - withdrawAmount); - assertEq(address(wsnr).balance, depositAmount - withdrawAmount); - assertEq(alice.balance, aliceBalanceBefore + withdrawAmount); - assertTrue(wsnr.isFullyCollateralized()); - - vm.stopPrank(); - } - - function testWithdrawAll() public { - uint256 depositAmount = 10 ether; - - vm.startPrank(alice); - - // Deposit and withdraw all - wsnr.deposit{value: depositAmount}(); - uint256 aliceBalanceBefore = alice.balance; - - wsnr.withdraw(depositAmount); - - // Check everything is back to zero - assertEq(wsnr.balanceOf(alice), 0); - assertEq(wsnr.totalSupply(), 0); - assertEq(address(wsnr).balance, 0); - assertEq(alice.balance, aliceBalanceBefore + depositAmount); - - vm.stopPrank(); - } - - function testWithdrawZeroAmount() public { - vm.startPrank(alice); - wsnr.deposit{value: 1 ether}(); - - vm.expectRevert("WSNR: withdrawal amount must be greater than 0"); - wsnr.withdraw(0); - vm.stopPrank(); - } - - function testWithdrawInsufficientBalance() public { - vm.startPrank(alice); - wsnr.deposit{value: 5 ether}(); - - vm.expectRevert("WSNR: insufficient balance"); - wsnr.withdraw(10 ether); - vm.stopPrank(); - } - - function testWithdrawTo() public { - uint256 depositAmount = 10 ether; - uint256 withdrawAmount = 4 ether; - - vm.startPrank(alice); - - // Deposit from alice - wsnr.deposit{value: depositAmount}(); - uint256 bobBalanceBefore = bob.balance; - - // Test withdrawal event - vm.expectEmit(true, false, false, true); - emit Withdrawal(bob, withdrawAmount); - - // Withdraw to bob - wsnr.withdrawTo(bob, withdrawAmount); - - // Check balances - assertEq(wsnr.balanceOf(alice), depositAmount - withdrawAmount); - assertEq(bob.balance, bobBalanceBefore + withdrawAmount); - - vm.stopPrank(); - } - - function testWithdrawToZeroAddress() public { - vm.startPrank(alice); - wsnr.deposit{value: 1 ether}(); - - vm.expectRevert("WSNR: cannot withdraw to zero address"); - wsnr.withdrawTo(address(0), 1 ether); - vm.stopPrank(); - } - - function testERC20Transfer() public { - uint256 depositAmount = 10 ether; - uint256 transferAmount = 3 ether; - - vm.startPrank(alice); - wsnr.deposit{value: depositAmount}(); - - // Test transfer event - vm.expectEmit(true, true, false, true); - emit Transfer(alice, bob, transferAmount); - - // Transfer WSNR tokens - assertTrue(wsnr.transfer(bob, transferAmount)); - - // Check balances - assertEq(wsnr.balanceOf(alice), depositAmount - transferAmount); - assertEq(wsnr.balanceOf(bob), transferAmount); - assertEq(wsnr.totalSupply(), depositAmount); // Total supply unchanged - - vm.stopPrank(); - } - - function testERC20Approve() public { - uint256 depositAmount = 10 ether; - uint256 approveAmount = 5 ether; - - vm.startPrank(alice); - wsnr.deposit{value: depositAmount}(); - - // Test approval event - vm.expectEmit(true, true, false, true); - emit Approval(alice, bob, approveAmount); - - // Approve bob to spend alice's WSNR - assertTrue(wsnr.approve(bob, approveAmount)); - assertEq(wsnr.allowance(alice, bob), approveAmount); - - vm.stopPrank(); - } - - function testERC20TransferFrom() public { - uint256 depositAmount = 10 ether; - uint256 approveAmount = 6 ether; - uint256 transferAmount = 4 ether; - - // Alice deposits and approves bob - vm.startPrank(alice); - wsnr.deposit{value: depositAmount}(); - wsnr.approve(bob, approveAmount); - vm.stopPrank(); - - // Bob transfers from alice to charlie - vm.startPrank(bob); - - // Test transfer event - vm.expectEmit(true, true, false, true); - emit Transfer(alice, charlie, transferAmount); - - assertTrue(wsnr.transferFrom(alice, charlie, transferAmount)); - vm.stopPrank(); - - // Check balances and allowance - assertEq(wsnr.balanceOf(alice), depositAmount - transferAmount); - assertEq(wsnr.balanceOf(charlie), transferAmount); - assertEq(wsnr.allowance(alice, bob), approveAmount - transferAmount); - } - - function testMultipleUsersDepositWithdraw() public { - // Multiple users deposit - vm.prank(alice); - wsnr.deposit{value: 5 ether}(); - - vm.prank(bob); - wsnr.deposit{value: 3 ether}(); - - vm.prank(charlie); - wsnr.deposit{value: 2 ether}(); - - // Check total supply and reserves - assertEq(wsnr.totalSupply(), 10 ether); - assertEq(wsnr.getReserve(), 10 ether); - assertTrue(wsnr.isFullyCollateralized()); - - // Users withdraw - vm.prank(alice); - wsnr.withdraw(2 ether); - - vm.prank(bob); - wsnr.withdraw(1 ether); - - // Check final state - assertEq(wsnr.totalSupply(), 7 ether); - assertEq(wsnr.getReserve(), 7 ether); - assertEq(wsnr.balanceOf(alice), 3 ether); - assertEq(wsnr.balanceOf(bob), 2 ether); - assertEq(wsnr.balanceOf(charlie), 2 ether); - assertTrue(wsnr.isFullyCollateralized()); - } - - // Fuzz testing - function testFuzzDeposit(uint256 amount) public { - vm.assume(amount > 0 && amount <= 100 ether); - - vm.deal(alice, amount); - vm.prank(alice); - wsnr.deposit{value: amount}(); - - assertEq(wsnr.balanceOf(alice), amount); - assertEq(wsnr.totalSupply(), amount); - assertEq(address(wsnr).balance, amount); - } - - function testFuzzWithdraw(uint256 depositAmount, uint256 withdrawAmount) public { - vm.assume(depositAmount > 0 && depositAmount <= 100 ether); - vm.assume(withdrawAmount > 0 && withdrawAmount <= depositAmount); - - vm.deal(alice, depositAmount); - vm.startPrank(alice); - - wsnr.deposit{value: depositAmount}(); - wsnr.withdraw(withdrawAmount); - - assertEq(wsnr.balanceOf(alice), depositAmount - withdrawAmount); - assertEq(address(wsnr).balance, depositAmount - withdrawAmount); - - vm.stopPrank(); - } - - function testReentrancyProtection() public { - ReentrantAttacker attacker = new ReentrantAttacker(wsnr); - vm.deal(address(attacker), 10 ether); - - // The reentrancy guard prevents the second withdraw, which causes - // the ETH transfer to fail, resulting in "SNR transfer failed" error - vm.expectRevert("WSNR: SNR transfer failed"); - attacker.attack{value: 2 ether}(); - } -} - -// Reentrancy test helper contract -contract ReentrantAttacker { - WSNR public wsnr; - uint256 public attackCount; - - constructor(WSNR _wsnr) { - wsnr = _wsnr; - } - - receive() external payable { - attackCount++; - if (attackCount < 2 && address(wsnr).balance >= 1 ether) { - wsnr.withdraw(1 ether); - } - } - - function attack() external payable { - wsnr.deposit{value: msg.value}(); - wsnr.withdraw(1 ether); - } -} \ No newline at end of file diff --git a/crypto/Makefile b/crypto/Makefile deleted file mode 100644 index b47083e56..000000000 --- a/crypto/Makefile +++ /dev/null @@ -1,283 +0,0 @@ -# Crypto Module Makefile -# Provides targets for testing all cryptographic packages individually - -.PHONY: all test test-verbose clean help -.PHONY: test-accumulator test-bulletproof test-core test-daed test-dkg test-ecies -.PHONY: test-internal test-keys test-mpc test-ot test-paillier test-sharing -.PHONY: test-signatures test-subtle test-tecdsa test-ted25519 test-zkp -.PHONY: test-core-curves test-core-native test-dkg-frost test-dkg-gennaro test-dkg-gennaro2p -.PHONY: test-ot-base test-ot-extension test-sharing-v1 test-signatures-bbs test-signatures-bls -.PHONY: test-signatures-common test-signatures-schnorr test-tecdsa-dklsv1 test-ted25519-frost -.PHONY: test-ted25519-ted25519 test-zkp-schnorr -.PHONY: bench bench-verbose coverage coverage-html - -# Default target -all: test - -tidy: - @go mod tidy - @go mod download - -# Test all packages -test: tidy - @gum log --level info "Running tests for all crypto packages..." - @go test ./... -v - -# Test all packages with verbose output -test-verbose: tidy - @gum log --level info "Running verbose tests for all crypto packages..." - @go test ./... -v -count=1 - -# Help target -help: - @gum log --level info "Crypto Module Makefile" - @gum log --level info "" - @gum log --level info "Available targets:" - @gum log --level info " all - Run all tests (default)" - @gum log --level info " test - Run all tests" - @gum log --level info " test-verbose - Run all tests with verbose output" - @gum log --level info "" - @gum log --level info "Individual package tests:" - @gum log --level info " test-accumulator - Test accumulator package" - @gum log --level info " test-bulletproof - Test bulletproof package" - @gum log --level info " test-core - Test core package" - @gum log --level info " test-daed - Test daed package" - @gum log --level info " test-dkg - Test dkg package" - @gum log --level info " test-ecies - Test ecies package" - @gum log --level info " test-internal - Test internal package" - @gum log --level info " test-keys - Test keys package" - @gum log --level info " test-mpc - Test mpc package" - @gum log --level info " test-ot - Test ot package" - @gum log --level info " test-paillier - Test paillier package" - @gum log --level info " test-sharing - Test sharing package" - @gum log --level info " test-signatures - Test signatures package" - @gum log --level info " test-subtle - Test subtle package" - @gum log --level info " test-tecdsa - Test tecdsa package" - @gum log --level info " test-ted25519 - Test ted25519 package" - @gum log --level info " test-zkp - Test zkp package" - @gum log --level info "" - @gum log --level info "Subpackage tests:" - @gum log --level info " test-core-curves - Test core/curves package" - @gum log --level info " test-core-native - Test core/curves/native package" - @gum log --level info " test-dkg-frost - Test dkg/frost package" - @gum log --level info " test-dkg-gennaro - Test dkg/gennaro package" - @gum log --level info " test-dkg-gennaro2p - Test dkg/gennaro2p package" - @gum log --level info " test-ot-base - Test ot/base package" - @gum log --level info " test-ot-extension - Test ot/extension package" - @gum log --level info " test-sharing-v1 - Test sharing/v1 package" - @gum log --level info " test-signatures-bbs - Test signatures/bbs package" - @gum log --level info " test-signatures-bls - Test signatures/bls package" - @gum log --level info " test-signatures-common - Test signatures/common package" - @gum log --level info " test-signatures-schnorr - Test signatures/schnorr package" - @gum log --level info " test-tecdsa-dklsv1 - Test tecdsa/dklsv1 package" - @gum log --level info " test-ted25519-frost - Test ted25519/frost package" - @gum log --level info " test-ted25519-ted25519 - Test ted25519/ted25519 package" - @gum log --level info " test-zkp-schnorr - Test zkp/schnorr package" - @gum log --level info "" - @gum log --level info "Performance and coverage:" - @gum log --level info " bench - Run benchmarks" - @gum log --level info " bench-verbose - Run benchmarks with verbose output" - @gum log --level info " coverage - Generate test coverage report" - @gum log --level info " coverage-html - Generate HTML test coverage report" - -# Top-level package tests -test-accumulator: - @gum log --level info "Testing accumulator package..." - @go test ./accumulator -v - -test-bulletproof: - @gum log --level info "Testing bulletproof package..." - @go test ./bulletproof -v - -test-core: - @gum log --level info "Testing core package..." - @go test ./core -v - -test-daed: - @gum log --level info "Testing daed package..." - @go test ./daed -v - -test-dkg: - @gum log --level info "Testing dkg package..." - @go test ./dkg/... -v - -test-ecies: - @gum log --level info "Testing ecies package..." - @go test ./ecies -v - -test-internal: - @gum log --level info "Testing internal package..." - @go test ./internal -v - -test-keys: - @gum log --level info "Testing keys package..." - @go test ./keys -v - -test-mpc: - @gum log --level info "Testing mpc package..." - @go test ./mpc -v - -test-ot: - @gum log --level info "Testing ot package..." - @go test ./ot/... -v - -test-paillier: - @gum log --level info "Testing paillier package..." - @go test ./paillier -v - -test-sharing: - @gum log --level info "Testing sharing package..." - @go test ./sharing/... -v - -test-signatures: - @gum log --level info "Testing signatures package..." - @go test ./signatures/... -v - -test-subtle: - @gum log --level info "Testing subtle package..." - @go test ./subtle -v - -test-tecdsa: - @gum log --level info "Testing tecdsa package..." - @go test ./tecdsa/... -v - -test-ted25519: - @gum log --level info "Testing ted25519 package..." - @go test ./ted25519/... -v - - -test-zkp: - @gum log --level info "Testing zkp package..." - @go test ./zkp/... -v - -# Subpackage tests -test-core-curves: - @gum log --level info "Testing core/curves package..." - @go test ./core/curves -v - -test-core-native: - @gum log --level info "Testing core/curves/native package..." - @go test ./core/curves/native/... -v - -test-dkg-frost: - @gum log --level info "Testing dkg/frost package..." - @go test ./dkg/frost -v - -test-dkg-gennaro: - @gum log --level info "Testing dkg/gennaro package..." - @go test ./dkg/gennaro -v - -test-dkg-gennaro2p: - @gum log --level info "Testing dkg/gennaro2p package..." - @go test ./dkg/gennaro2p -v - -test-ot-base: - @gum log --level info "Testing ot/base package..." - @go test ./ot/base/... -v - -test-ot-extension: - @gum log --level info "Testing ot/extension package..." - @go test ./ot/extension/... -v - -test-sharing-v1: - @gum log --level info "Testing sharing/v1 package..." - @go test ./sharing/v1 -v - -test-signatures-bbs: - @gum log --level info "Testing signatures/bbs package..." - @go test ./signatures/bbs -v - -test-signatures-bls: - @gum log --level info "Testing signatures/bls package..." - @go test ./signatures/bls/... -v - -test-signatures-common: - @gum log --level info "Testing signatures/common package..." - @go test ./signatures/common -v - -test-signatures-schnorr: - @gum log --level info "Testing signatures/schnorr package..." - @go test ./signatures/schnorr/... -v - -test-tecdsa-dklsv1: - @gum log --level info "Testing tecdsa/dklsv1 package..." - @go test ./tecdsa/dklsv1/... -v - -test-ted25519-frost: - @gum log --level info "Testing ted25519/frost package..." - @go test ./ted25519/frost -v - -test-ted25519-ted25519: - @gum log --level info "Testing ted25519/ted25519 package..." - @go test ./ted25519/ted25519 -v - -test-zkp-schnorr: - @gum log --level info "Testing zkp/schnorr package..." - @go test ./zkp/schnorr -v - -# Performance testing -bench: - @gum log --level info "Running benchmarks for all packages..." - @go test ./... -bench=. -run=^$ - -bench-verbose: - @gum log --level info "Running verbose benchmarks for all packages..." - @go test ./... -bench=. -benchmem -run=^$ -v - -# Coverage testing -coverage: - @gum log --level info "Generating test coverage report..." - @go test ./... -coverprofile=coverage.out - @go tool cover -func=coverage.out - -coverage-html: - @gum log --level info "Generating HTML test coverage report..." - @go test ./... -coverprofile=coverage.out - @go tool cover -html=coverage.out -o coverage.html - @gum log --level info "Coverage report generated: coverage.html" - -# Build verification -build: - @gum log --level info "Building all packages to verify compilation..." - @go build ./... - -# Module maintenance -mod-tidy: - @gum log --level info "Tidying go.mod..." - @go mod tidy - -mod-verify: - @gum log --level info "Verifying go.mod..." - @go mod verify - -mod-download: - @gum log --level info "Downloading dependencies..." - @go mod download - -# Security scanning (if staticcheck is available) -lint: - @gum log --level info "Running static analysis..." - @if command -v staticcheck >/dev/null 2>&1; then \ - staticcheck ./...; \ - else \ - gum log --level warn "staticcheck not installed. Install with: go install honnef.co/go/tools/cmd/staticcheck@latest"; \ - go vet ./...; \ - fi - -# Format code -fmt: - @gum log --level info "Formatting code..." - @go fmt ./... - -# Check for formatting issues -fmt-check: - @gum log --level info "Checking code formatting..." - @test -z "$$(go fmt ./...)" - -# Run all quality checks -check: fmt-check lint test - @gum log --level info "✅ All quality checks passed!" - -# Development workflow -dev: clean mod-tidy fmt lint test - @gum log --level info "✅ Development workflow completed successfully!" diff --git a/crypto/README.md b/crypto/README.md deleted file mode 100644 index d38a9e6aa..000000000 --- a/crypto/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Sonr Crypto - -Sonr Crypto is a collection of cryptographic primitives that are used by Sonr. - -## Packages - -- [Accumulator](./accumulator): Accumulator is a cryptographic accumulator that allows for efficient verification of large sets of data. -- [Bulletproof](./bulletproof): Bulletproof is a zero-knowledge proof system that allows for efficient verification of large sets of data. -- [Core](./core): Core is a collection of cryptographic primitives that are used by Sonr. -- [Daed](./daed): Daed is a distributed key generation protocol that allows for efficient verification of large sets of data. -- [Dkg](./dkg): Dkg is a distributed key generation protocol that allows for efficient verification of large sets of data. -- [Ecies](./ecies): Ecies is a symmetric encryption algorithm that allows for efficient verification of large sets of data. -- [Keys](./keys): Keys is a collection of cryptographic primitives that are used by Sonr. -- [Mpc](./mpc): Mpc is a collection of cryptographic primitives that are used by Sonr. -- [Ot](./ot): Ot is a collection of cryptographic primitives that are used by Sonr. -- [Paillier](./paillier): Paillier is a cryptographic algorithm that allows for efficient verification of large sets of data. -- [Sharing](./sharing): Sharing is a collection of cryptographic primitives that are used by Sonr. -- [Signatures](./signatures): Signatures is a collection of cryptographic primitives that are used by Sonr. -- [Subtle](./subtle): Subtle is a collection of cryptographic primitives that are used by Sonr. -- [Tecdsa](./tecdsa): Tecdsa is a collection of cryptographic primitives that are used by Sonr. -- [Ted25519](./ted25519): Ted25519 is a collection of cryptographic primitives that are used by Sonr. -- [Ucan](./ucan): Ucan is a collection of cryptographic primitives that are used by Sonr. -- [Zkp](./zkp): Zkp is a collection of cryptographic primitives that are used by Sonr. - -## License - -This project is licensed under the [Apache 2.0 License](./LICENSE). diff --git a/crypto/accumulator/accumulator.go b/crypto/accumulator/accumulator.go deleted file mode 100644 index 4043d69a1..000000000 --- a/crypto/accumulator/accumulator.go +++ /dev/null @@ -1,179 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package accumulator implements the cryptographic accumulator as described in https://eprint.iacr.org/2020/777.pdf -// It also implements the zero knowledge proof of knowledge protocol -// described in section 7 of the paper. -// Note: the paper only describes for non-membership witness case, but we don't -// use non-membership witness. We only implement the membership witness case. -package accumulator - -import ( - "fmt" - - "git.sr.ht/~sircmpwn/go-bare" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type structMarshal struct { - Curve string `bare:"curve"` - Value []byte `bare:"value"` -} - -type Element curves.Scalar - -// Coefficient is a point -type Coefficient curves.Point - -// Accumulator is a point -type Accumulator struct { - value curves.Point -} - -// New creates a new accumulator. -func (acc *Accumulator) New(curve *curves.PairingCurve) (*Accumulator, error) { - // If we need to support non-membership witness, we need to implement Accumulator Initialization - // as described in section 6 of - // for now we don't need non-membership witness - - // i.e., it computes V0 = prod(y + α) * P, y ∈ Y_V0, P is a generator of G1. Since we do not use non-membership witness - // we just set the initial accumulator a G1 generator. - acc.value = curve.Scalar.Point().Generator() - return acc, nil -} - -// WithElements initializes a new accumulator prefilled with entries -// Each member is assumed to be hashed -// V = prod(y + α) * V0, for all y∈ Y_V -func (acc *Accumulator) WithElements( - curve *curves.PairingCurve, - key *SecretKey, - m []Element, -) (*Accumulator, error) { - _, err := acc.New(curve) - if err != nil { - return nil, err - } - y, err := key.BatchAdditions(m) - if err != nil { - return nil, err - } - acc.value = acc.value.Mul(y) - return acc, nil -} - -// AddElements accumulates a set of elements into the accumulator. -func (acc *Accumulator) AddElements(key *SecretKey, m []Element) (*Accumulator, error) { - if acc.value == nil || key.value == nil { - return nil, fmt.Errorf("accumulator and secret key should not be nil") - } - y, err := key.BatchAdditions(m) - if err != nil { - return nil, err - } - acc.value = acc.value.Mul(y) - return acc, nil -} - -// Add accumulates a single element into the accumulator -// V' = (y + alpha) * V -func (acc *Accumulator) Add(key *SecretKey, e Element) (*Accumulator, error) { - if acc.value == nil || acc.value.IsIdentity() || key.value == nil || e == nil { - return nil, fmt.Errorf("accumulator, secret key and element should not be nil") - } - y := e.Add(key.value) // y + alpha - acc.value = acc.value.Mul(y) - return acc, nil -} - -// Remove removes a single element from accumulator if it exists -// V' = 1/(y+alpha) * V -func (acc *Accumulator) Remove(key *SecretKey, e Element) (*Accumulator, error) { - if acc.value == nil || acc.value.IsIdentity() || key.value == nil || e == nil { - return nil, fmt.Errorf("accumulator, secret key and element should not be nil") - } - y := e.Add(key.value) // y + alpha - y, err := y.Invert() // 1/(y+alpha) - if err != nil { - return nil, err - } - acc.value = acc.value.Mul(y) - return acc, nil -} - -// Update performs a batch addition and deletion as described on page 7, section 3 in -// https://eprint.iacr.org/2020/777.pdf -func (acc *Accumulator) Update( - key *SecretKey, - additions []Element, - deletions []Element, -) (*Accumulator, []Coefficient, error) { - if acc.value == nil || acc.value.IsIdentity() || key.value == nil { - return nil, nil, fmt.Errorf("accumulator and secret key should not be nil") - } - - // Compute dA(-alpha) = prod(y + alpha), y in the set of A ⊆ ACC-Y_V - a, err := key.BatchAdditions(additions) - if err != nil { - return nil, nil, err - } - - // Compute dD(-alpha) = 1/prod(y + alpha), y in the set of D ⊆ Y_V - d, err := key.BatchDeletions(deletions) - if err != nil { - return nil, nil, err - } - - // dA(-alpha)/dD(-alpha) - div := a.Mul(d) - newAcc := acc.value.Mul(div) - - // build an array of coefficients - elements, err := key.CreateCoefficients(additions, deletions) - if err != nil { - return nil, nil, err - } - - coefficients := make([]Coefficient, len(elements)) - for i := range elements { - coefficients[i] = acc.value.Mul(elements[i]) - } - acc.value = newAcc - return acc, coefficients, nil -} - -// MarshalBinary converts Accumulator to bytes -func (acc Accumulator) MarshalBinary() ([]byte, error) { - if acc.value == nil { - return nil, fmt.Errorf("accumulator cannot be nil") - } - tv := &structMarshal{ - Value: acc.value.ToAffineCompressed(), - Curve: acc.value.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary sets Accumulator from bytes -func (acc *Accumulator) UnmarshalBinary(data []byte) error { - tv := new(structMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - - value, err := curve.NewIdentityPoint().FromAffineCompressed(tv.Value) - if err != nil { - return err - } - acc.value = value - return nil -} diff --git a/crypto/accumulator/accumulator_test.go b/crypto/accumulator/accumulator_test.go deleted file mode 100644 index 1b326c01f..000000000 --- a/crypto/accumulator/accumulator_test.go +++ /dev/null @@ -1,221 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "encoding/hex" - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestNewAccumulator100(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc, err := new(Accumulator).New(curve) - require.NoError(t, err) - accBz, err := acc.MarshalBinary() - require.NoError(t, err) - fmt.Println(accBz) - fmt.Println(len(accBz)) - fmt.Println(hex.EncodeToString(accBz)) - fmt.Println(len(hex.EncodeToString(accBz))) - require.Equal(t, 60, len(accBz), "Marshalled accumulator should be 60 bytes") - require.Equal( - t, - 120, - len(hex.EncodeToString(accBz)), - "Hex-encoded accumulator should be 120 characters", - ) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) -} - -func TestNewAccumulator10K(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc, err := new(Accumulator).New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) -} - -func TestNewAccumulator10M(t *testing.T) { - // Initiating 10M values takes time - if testing.Short() { - t.Skip("skipping test in short mode.") - } - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc, err := new(Accumulator).New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) -} - -func TestWithElements(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, _ := new(SecretKey).New(curve, seed[:]) - element1 := curve.Scalar.Hash([]byte("value1")) - element2 := curve.Scalar.Hash([]byte("value2")) - elements := []Element{element1, element2} - newAcc, err := new(Accumulator).WithElements(curve, key, elements) - require.NoError(t, err) - require.NotNil(t, newAcc) - require.NotEqual( - t, - newAcc.value.ToAffineCompressed(), - curve.PointG1.Identity().ToAffineCompressed(), - ) - require.NotEqual( - t, - newAcc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) - - _, _ = newAcc.Remove(key, element1) - _, _ = newAcc.Remove(key, element2) - require.Equal( - t, - newAcc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) -} - -func TestAdd(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc := &Accumulator{curve.PointG1.Generator()} - _, _ = acc.New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - - element := curve.Scalar.Hash([]byte("value1")) - require.NoError(t, err) - require.NotNil(t, element) - _, _ = acc.Add(key, element) - require.NotEqual( - t, - acc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) -} - -func TestRemove(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc, err := new(Accumulator).New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) - - element := curve.Scalar.Hash([]byte("value1")) - require.NoError(t, err) - require.NotNil(t, element) - - // add element - _, _ = acc.Add(key, element) - require.NotEqual( - t, - acc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) - - // remove element - acc, err = acc.Remove(key, element) - require.NoError(t, err) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) -} - -func TestAddElements(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc := &Accumulator{curve.PointG1.Generator()} - _, _ = acc.New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) - - element1 := curve.Scalar.Hash([]byte("value1")) - element2 := curve.Scalar.Hash([]byte("value2")) - element3 := curve.Scalar.Hash([]byte("value3")) - elements := []Element{element1, element2, element3} - - acc, err = acc.AddElements(key, elements) - require.NoError(t, err) - require.NotEqual( - t, - acc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) -} - -func TestAccumulatorMarshal(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - point := curve.PointG1.Generator().Mul(curve.Scalar.New(2)) - data, err := Accumulator{point}.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, data) - // element cannot be empty - _, err = Accumulator{}.MarshalBinary() - require.Error(t, err) - - e := &Accumulator{curve.PointG1.Generator()} - _ = e.UnmarshalBinary(data) - require.True(t, e.value.Equal(point)) -} - -func TestUpdate(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, err := new(SecretKey).New(curve, seed[:]) - require.NoError(t, err) - require.NotNil(t, key) - acc, err := new(Accumulator).New(curve) - require.NoError(t, err) - require.NotNil(t, acc) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) - - element1 := curve.Scalar.Hash([]byte("value1")) - element2 := curve.Scalar.Hash([]byte("value2")) - element3 := curve.Scalar.Hash([]byte("value3")) - elements := []Element{element1, element2, element3} - - acc, _, err = acc.Update(key, elements, nil) - require.NoError(t, err) - require.NotEqual( - t, - acc.value.ToAffineCompressed(), - curve.PointG1.Generator().ToAffineCompressed(), - ) - - acc, _, err = acc.Update(key, nil, elements) - require.NoError(t, err) - require.Equal(t, acc.value.ToAffineCompressed(), curve.PointG1.Generator().ToAffineCompressed()) -} diff --git a/crypto/accumulator/key.go b/crypto/accumulator/key.go deleted file mode 100644 index 67a49e0c8..000000000 --- a/crypto/accumulator/key.go +++ /dev/null @@ -1,247 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "errors" - "fmt" - - "git.sr.ht/~sircmpwn/go-bare" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// SecretKey is the secret alpha only held by the accumulator manager. -type SecretKey struct { - value curves.Scalar -} - -// New creates a new secret key from the seed. -func (sk *SecretKey) New(curve *curves.PairingCurve, seed []byte) (*SecretKey, error) { - sk.value = curve.Scalar.Hash(seed) - return sk, nil -} - -// GetPublicKey creates a public key from SecretKey sk -func (sk SecretKey) GetPublicKey(curve *curves.PairingCurve) (*PublicKey, error) { - if sk.value == nil || curve == nil { - return nil, fmt.Errorf("curve and sk value cannot be nil") - } - value := curve.Scalar.Point().(curves.PairingPoint).OtherGroup().Generator().Mul(sk.value) - return &PublicKey{value.(curves.PairingPoint)}, nil -} - -// MarshalBinary converts SecretKey to bytes -func (sk SecretKey) MarshalBinary() ([]byte, error) { - if sk.value == nil { - return nil, fmt.Errorf("sk cannot be empty") - } - tv := &structMarshal{ - Value: sk.value.Bytes(), - Curve: sk.value.Point().CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary sets SecretKey from bytes -func (sk *SecretKey) UnmarshalBinary(data []byte) error { - tv := new(structMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - - value, err := curve.NewScalar().SetBytes(tv.Value) - if err != nil { - return err - } - sk.value = value - return nil -} - -// BatchAdditions computes product(y + sk) for y in additions and output the product -func (sk SecretKey) BatchAdditions(additions []Element) (Element, error) { - if sk.value == nil { - return nil, fmt.Errorf("secret key cannot be empty") - } - mul := sk.value.One() - for i := 0; i < len(additions); i++ { - if additions[i] == nil { - return nil, fmt.Errorf("some element in additions is nil") - } - // y + alpha - temp := additions[i].Add(sk.value) - // prod(y + alpha) - mul = mul.Mul(temp) - } - return mul, nil -} - -// BatchDeletions computes 1/product(y + sk) for y in deletions and output it -func (sk SecretKey) BatchDeletions(deletions []Element) (Element, error) { - v, err := sk.BatchAdditions(deletions) - if err != nil { - return nil, err - } - y, err := v.Invert() - if err != nil { - return nil, err - } - return y, nil -} - -// CreateCoefficients creates the Batch Polynomial coefficients -// See page 7 of https://eprint.iacr.org/2020/777.pdf -func (sk SecretKey) CreateCoefficients( - additions []Element, - deletions []Element, -) ([]Element, error) { - if sk.value == nil { - return nil, fmt.Errorf("secret key should not be nil") - } - - // vD(x) = ∑^{m}_{s=1}{ ∏ 1..s {yD_i + alpha}^-1 ∏ 1 ..s-1 {yD_j - x} - one := sk.value.One() - m1 := one.Neg() // m1 is -1 - vD := make(polynomial, 0, len(deletions)) - for s := 0; s < len(deletions); s++ { - // ∏ 1..s (yD_i + alpha)^-1 - c, err := sk.BatchDeletions(deletions[0 : s+1]) - if err != nil { - return nil, fmt.Errorf("error in sk batchDeletions") - } - poly := make(polynomial, 1, s+2) - poly[0] = one - - // ∏ 1..(s-1) (yD_j - x) - for j := 0; j < s; j++ { - t := make(polynomial, 2) - // yD_j - t[0] = deletions[j] - // -x - t[1] = m1 - - // polynomial multiplication (yD_1-x) * (yD_2 - x) ... - poly, err = poly.Mul(t) - if err != nil { - return nil, err - } - } - poly, err = poly.MulScalar(c) - if err != nil { - return nil, err - } - vD, err = vD.Add(poly) - if err != nil { - return nil, err - } - } - - // vD(x) * ∏ 1..n (yA_i + alpha) - bAdd, err := sk.BatchAdditions(additions) - if err != nil { - return nil, fmt.Errorf("error in sk batchAdditions") - } - vD, err = vD.MulScalar(bAdd) - if err != nil { - return nil, err - } - - // vA(x) = ∑^n_{s=1}{ ∏ 1..s-1 {yA_i + alpha} ∏ s+1..n {yA_j - x} } - vA := make(polynomial, 0, len(additions)) - for s := range additions { - // ∏ 1..s-1 {yA_i + alpha} - var c Element - if s == 0 { - c = one - } else { - c, err = sk.BatchAdditions(additions[0:s]) - if err != nil { - return nil, err - } - } - poly := make(polynomial, 1, s+2) - poly[0] = one - - // ∏ s+1..n {yA_j - x} - for j := s + 1; j < len(additions); j++ { - t := make(polynomial, 2) - t[0] = additions[j] - t[1] = m1 - - // polynomial multiplication (yA_1-x) * (yA_2 - x) ... - poly, err = poly.Mul(t) - if err != nil { - return nil, err - } - } - poly, err = poly.MulScalar(c) - if err != nil { - return nil, err - } - vA, err = vA.Add(poly) - if err != nil { - return nil, err - } - } - - // vA - vD - vA, err = vA.Sub(vD) - if err != nil { - return nil, err - } - result := make([]Element, len(vA)) - for i := 0; i < len(vA); i++ { - result[i] = vA[i] - } - return result, nil -} - -// PublicKey is the public key of accumulator, it should be sk * generator of G2 -type PublicKey struct { - value curves.PairingPoint -} - -// MarshalBinary converts PublicKey to bytes -func (pk PublicKey) MarshalBinary() ([]byte, error) { - if pk.value == nil { - return nil, fmt.Errorf("public key cannot be nil") - } - tv := &structMarshal{ - Value: pk.value.ToAffineCompressed(), - Curve: pk.value.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary sets PublicKey from bytes -func (pk *PublicKey) UnmarshalBinary(data []byte) error { - tv := new(structMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetPairingCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - - value, err := curve.NewScalar().Point().FromAffineCompressed(tv.Value) - if err != nil { - return err - } - var ok bool - pk.value, ok = value.(curves.PairingPoint) - if !ok { - return errors.New("can't convert to PairingPoint") - } - return nil -} diff --git a/crypto/accumulator/key_test.go b/crypto/accumulator/key_test.go deleted file mode 100644 index 07f1efc71..000000000 --- a/crypto/accumulator/key_test.go +++ /dev/null @@ -1,88 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestSecretKeyMarshal(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - data, err := SecretKey{curve.Scalar.One()}.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, data) - e := &SecretKey{curve.Scalar.New(2)} - err = e.UnmarshalBinary(data) - require.NoError(t, err) - require.Equal(t, e.value.Bytes(), curve.Scalar.One().Bytes()) - - // element cannot be empty - _, err = SecretKey{}.MarshalBinary() - require.Error(t, err) -} - -func TestPublicKeyMarshal(t *testing.T) { - // Actually test both toBytes() and from() - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk := &SecretKey{curve.Scalar.New(3)} - pk, _ := sk.GetPublicKey(curve) - pkBytes, err := pk.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, pkBytes) - - pk2 := &PublicKey{} - err = pk2.UnmarshalBinary(pkBytes) - require.NoError(t, err) - require.True(t, pk.value.Equal(pk2.value)) -} - -func TestBatch(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - sk, _ := new(SecretKey).New(curve, seed[:]) - element1 := curve.Scalar.Hash([]byte("value1")) - element2 := curve.Scalar.Hash([]byte("value2")) - elements := []Element{element1, element2} - - add, err := sk.BatchAdditions(elements) - require.NoError(t, err) - require.NotNil(t, add) - - del, err := sk.BatchDeletions(elements) - require.NoError(t, err) - require.NotNil(t, del) - - result := add.Mul(del) - require.Equal(t, result, curve.Scalar.One()) - - g1 := curve.PointG1.Generator() - acc := g1.Mul(add) - require.NotEqual(t, acc, g1) - acc = acc.Mul(del) - require.Equal(t, acc.ToAffineCompressed(), g1.ToAffineCompressed()) - - acc2 := g1.Mul(result) - require.True(t, acc2.Equal(g1)) -} - -func TestCoefficient(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - element1 := curve.Scalar.Hash([]byte("value1")) - element2 := curve.Scalar.Hash([]byte("value2")) - element3 := curve.Scalar.Hash([]byte("value3")) - element4 := curve.Scalar.Hash([]byte("value4")) - element5 := curve.Scalar.Hash([]byte("value5")) - elements := []Element{element1, element2, element3, element4, element5} - coefficients, err := sk.CreateCoefficients(elements[0:2], elements[2:5]) - require.NoError(t, err) - require.Equal(t, len(coefficients), 3) -} diff --git a/crypto/accumulator/lib.go b/crypto/accumulator/lib.go deleted file mode 100644 index 1c54380c4..000000000 --- a/crypto/accumulator/lib.go +++ /dev/null @@ -1,204 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "fmt" - "math" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// dad constructs two polynomials - dA(x) and dD(x) -// dA(y) = prod(y_A,t - y), t = 1...n -// dD(y) = prod(y_D,t - y), t = 1...n -func dad(values []Element, y Element) (Element, error) { - if values == nil || y == nil { - return nil, fmt.Errorf("curve, values or y should not be nil") - } - - for _, value := range values { - if value == nil { - return nil, fmt.Errorf("some element is nil") - } - } - - result := y.One() - if len(values) == 1 { - a := values[0] - result = a.Sub(y) - } else { - for i := range values { - temp := values[i].Sub(y) - result = result.Mul(temp) - } - } - return result, nil -} - -type polynomialPoint []curves.Point - -// evaluate evaluates a PolynomialG1 on input x. -func (p polynomialPoint) evaluate(x curves.Scalar) (curves.Point, error) { - if p == nil { - return nil, fmt.Errorf("p cannot be empty") - } - for i := 0; i < len(p); i++ { - if p[i] == nil { - return nil, fmt.Errorf("some coefficient in p is nil") - } - } - - pp := x - res := p[0] - for i := 1; i < len(p); i++ { - r := p[i].Mul(pp) - res = res.Add(r) - pp = pp.Mul(x) - } - return res, nil -} - -// Add adds two PolynomialG1 -func (p polynomialPoint) Add(rhs polynomialPoint) (polynomialPoint, error) { - maxLen := int(math.Max(float64(len(p)), float64(len(rhs)))) - - result := make(polynomialPoint, maxLen) - - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - result[i] = c.Add(c.Identity()) - } - - for i, c := range rhs { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - if result[i] == nil { - result[i] = c.Add(c.Identity()) - } else { - result[i] = result[i].Add(c) - } - } - return result, nil -} - -// Mul for PolynomialG1 computes rhs * p, p is a polynomial, rhs is a value -func (p polynomialPoint) Mul(rhs curves.Scalar) (polynomialPoint, error) { - result := make(polynomialPoint, len(p)) - - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - result[i] = c.Mul(rhs) - } - - return result, nil -} - -type polynomial []curves.Scalar - -// Add adds two polynomials -func (p polynomial) Add(rhs polynomial) (polynomial, error) { - maxLen := int(math.Max(float64(len(p)), float64(len(rhs)))) - result := make([]curves.Scalar, maxLen) - - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - result[i] = c.Clone() - } - - for i, c := range rhs { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - if result[i] == nil { - result[i] = c.Clone() - } else { - result[i] = result[i].Add(c) - } - } - - return result, nil -} - -// Sub computes p-rhs and returns -func (p polynomial) Sub(rhs polynomial) (polynomial, error) { - maxLen := int(math.Max(float64(len(p)), float64(len(rhs)))) - result := make([]curves.Scalar, maxLen) - - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - result[i] = c.Clone() - } - - for i, c := range rhs { - if c == nil { - return nil, fmt.Errorf("invalid coefficient at %d", i) - } - if result[i] == nil { - result[i] = c.Neg() - } else { - result[i] = result[i].Sub(c) - } - } - - return result, nil -} - -// Mul multiplies two polynomials - p * rhs -func (p polynomial) Mul(rhs polynomial) (polynomial, error) { - // Check for each coefficient that should not be nil - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("coefficient in p at %d is nil", i) - } - } - - for i, c := range rhs { - if c == nil { - return nil, fmt.Errorf("coefficient in rhs at %d is nil", i) - } - } - - m := len(p) - n := len(rhs) - - // Initialize the product polynomial - prod := make(polynomial, m+n-1) - for i := 0; i < len(prod); i++ { - prod[i] = p[0].Zero() - } - - // Multiply two polynomials term by term - for i, cp := range p { - for j, cr := range rhs { - temp := cp.Mul(cr) - prod[i+j] = prod[i+j].Add(temp) - } - } - return prod, nil -} - -// MulScalar computes p * rhs, where rhs is a scalar value -func (p polynomial) MulScalar(rhs curves.Scalar) (polynomial, error) { - result := make(polynomial, len(p)) - for i, c := range p { - if c == nil { - return nil, fmt.Errorf("coefficient at %d is nil", i) - } - result[i] = c.Mul(rhs) - } - return result, nil -} diff --git a/crypto/accumulator/lib_test.go b/crypto/accumulator/lib_test.go deleted file mode 100644 index 173b53a38..000000000 --- a/crypto/accumulator/lib_test.go +++ /dev/null @@ -1,404 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestEvaluatePolyG1(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - output1, err := poly.evaluate(curve.Scalar.New(1)) - require.NoError(t, err) - require.NotNil(t, output1) - result1 := curve.PointG1.Generator().Mul(curve.Scalar.New(6)) - require.Equal(t, output1.ToAffineCompressed(), result1.ToAffineCompressed()) - - output2, err := poly.evaluate(curve.Scalar.New(2)) - require.NoError(t, err) - require.NotNil(t, output2) - result2 := curve.PointG1.Generator().Mul(curve.Scalar.New(11)) - require.Equal(t, output2.ToAffineCompressed(), result2.ToAffineCompressed()) -} - -func TestEvaluatePolyG1Error(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomialPoint{ - nil, - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - _, err := poly.evaluate(curve.Scalar.New(1)) - require.Error(t, err) -} - -func TestAddAssignPolyG1(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - // Test polynomial with equal length - poly1 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - poly2 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - } - - output, err := poly1.Add(poly2) - require.NoError(t, err) - require.NotNil(t, output) - result := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(4)), - curve.PointG1.Generator().Mul(curve.Scalar.New(4)), - curve.PointG1.Generator().Mul(curve.Scalar.New(4)), - } - for i := 0; i < len(output); i++ { - require.Equal(t, output[i].ToAffineCompressed(), result[i].ToAffineCompressed()) - } - - // Test polynomials with unequal length - poly3 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - } - output2, err := poly1.Add(poly3) - require.NoError(t, err) - require.NotNil(t, output2) - result2 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(4)), - curve.PointG1.Generator().Mul(curve.Scalar.New(4)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - require.Equal(t, len(output2), len(result2)) - for i := 0; i < len(output2); i++ { - require.Equal(t, output2[i].ToAffineCompressed(), result2[i].ToAffineCompressed()) - } - - // Test polynomial with Capacity - poly4 := make(polynomialPoint, 0, 3) - poly5, err := poly4.Add(poly1) - require.NoError(t, err) - require.Equal(t, len(poly5), len(poly1)) - for i := 0; i < len(poly5); i++ { - require.Equal(t, poly5[i].ToAffineCompressed(), poly1[i].ToAffineCompressed()) - } -} - -func TestAddAssignPolyG1Error(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly1 := polynomialPoint{ - nil, - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - poly2 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - } - output, err := poly1.Add(poly2) - require.Error(t, err) - require.Nil(t, output) -} - -func TestMulAssignPolyG1(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - rhs := curve.Scalar.New(3) - output, err := poly.Mul(rhs) - require.NoError(t, err) - require.NotNil(t, output) - poly2 := polynomialPoint{ - curve.PointG1.Generator().Mul(curve.Scalar.New(9)), - curve.PointG1.Generator().Mul(curve.Scalar.New(6)), - curve.PointG1.Generator().Mul(curve.Scalar.New(3)), - } - for i := 0; i < len(poly2); i++ { - require.Equal(t, output[i].ToAffineCompressed(), poly2[i].ToAffineCompressed()) - } -} - -func TestMulAssignPolyG1Error(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomialPoint{ - nil, - curve.PointG1.Generator().Mul(curve.Scalar.New(2)), - curve.PointG1.Generator().Mul(curve.Scalar.New(1)), - } - rhs := curve.Scalar.New(3) - output, err := poly.Mul(rhs) - require.Error(t, err) - require.Nil(t, output) -} - -func TestPushPoly(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomial{ - curve.Scalar.New(3), - curve.Scalar.New(2), - curve.Scalar.New(1), - } - scalar := curve.Scalar.New(4) - result := append(poly, scalar) - require.Equal(t, result[3], scalar) - - // Push one more - scalar2 := curve.Scalar.New(5) - result2 := append(result, scalar2) - require.Equal(t, result2[4], scalar2) - - // Push to a new polynomial - newPoly := polynomial{} - newPoly = append(newPoly, scalar) - require.Equal(t, newPoly[0], scalar) - newPoly = append(newPoly, scalar2) - require.Equal(t, newPoly[1], scalar2) -} - -func TestAddAssignPoly(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - // Test polynomial with equal length - poly1 := polynomial{ - curve.Scalar.New(3), - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - - output, err := poly1.Add(poly2) - require.NoError(t, err) - require.NotNil(t, output) - result := []curves.Scalar{ - curve.Scalar.New(4), - curve.Scalar.New(4), - curve.Scalar.New(4), - } - for i := 0; i < len(output); i++ { - require.Equal(t, output[i], result[i]) - } - - // Test polynomials with unequal length - poly3 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - } - output2, err := poly1.Add(poly3) - require.NoError(t, err) - require.NotNil(t, output2) - result2 := []curves.Scalar{ - curve.Scalar.New(4), - curve.Scalar.New(4), - curve.Scalar.New(1), - } - require.Equal(t, len(output2), len(result2)) - for i := 0; i < len(output2); i++ { - require.Equal(t, output2[i], result2[i]) - } -} - -func TestAddAssignPolyError(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - // Test polynomial with equal length - poly1 := polynomial{ - nil, - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - - output, err := poly1.Add(poly2) - require.Error(t, err) - require.Nil(t, output) -} - -func TestSubAssignPoly(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - // Test polynomial with equal length - poly1 := polynomial{ - curve.Scalar.New(3), - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - - output, err := poly1.Sub(poly2) - require.NoError(t, err) - require.NotNil(t, output) - result := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(0), - curve.Scalar.New(-2), - } - for i := 0; i < len(output); i++ { - require.Equal(t, output[i].Bytes(), result[i].Bytes()) - } - - // Test polynomials with unequal length - poly3 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - curve.Scalar.New(4), - } - output2, err := poly1.Sub(poly3) - require.NoError(t, err) - require.NotNil(t, output2) - result2 := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(0), - curve.Scalar.New(-2), - curve.Scalar.New(-4), - } - require.Equal(t, len(output2), len(result2)) - for i := 0; i < len(output2); i++ { - require.Equal(t, output2[i].Bytes(), result2[i].Bytes()) - } -} - -func TestSubAssignPolyError(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly1 := polynomial{ - nil, - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - - output, err := poly1.Sub(poly2) - require.Error(t, err) - require.Nil(t, output) -} - -func TestMulAssignPoly(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - // Test polynomial with equal length - poly1 := polynomial{ - curve.Scalar.New(3), - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - - output, err := poly1.Mul(poly2) - require.NoError(t, err) - require.NotNil(t, output) - result := []curves.Scalar{ - curve.Scalar.New(3), - curve.Scalar.New(8), - curve.Scalar.New(14), - curve.Scalar.New(8), - curve.Scalar.New(3), - } - for i := 0; i < len(result); i++ { - require.Equal(t, output[i].Bytes(), result[i].Bytes()) - } - - // Test polynomials with unequal length - poly3 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - } - output2, err := poly1.Mul(poly3) - require.NoError(t, err) - require.NotNil(t, output2) - result2 := []curves.Scalar{ - curve.Scalar.New(3), - curve.Scalar.New(8), - curve.Scalar.New(5), - curve.Scalar.New(2), - } - require.Equal(t, len(output2), 4) - for i := 0; i < len(output2); i++ { - require.Equal(t, output2[i].Bytes(), result2[i].Bytes()) - } -} - -func TestMulAssignPolyError(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly1 := polynomial{ - nil, - curve.Scalar.New(2), - curve.Scalar.New(1), - } - poly2 := polynomial{ - curve.Scalar.New(1), - curve.Scalar.New(2), - curve.Scalar.New(3), - } - output, err := poly1.Mul(poly2) - require.Error(t, err) - require.Nil(t, output) -} - -func TestMulValueAssignPoly(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomial{ - curve.Scalar.New(3), - curve.Scalar.New(2), - curve.Scalar.New(1), - } - rhs := curve.Scalar.New(3) - output, err := poly.MulScalar(rhs) - require.NoError(t, err) - require.NotNil(t, output) - coefficients2 := []curves.Scalar{ - curve.Scalar.New(9), - curve.Scalar.New(6), - curve.Scalar.New(3), - } - for i := 0; i < len(coefficients2); i++ { - require.Equal(t, output[i].Bytes(), coefficients2[i].Bytes()) - } -} - -func TestMulValueAssignPolyError(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - poly := polynomial{ - nil, - curve.Scalar.New(2), - curve.Scalar.New(1), - } - rhs := curve.Scalar.New(3) - output, err := poly.MulScalar(rhs) - require.Error(t, err) - require.Nil(t, output) -} diff --git a/crypto/accumulator/proof.go b/crypto/accumulator/proof.go deleted file mode 100644 index 6854fb1e4..000000000 --- a/crypto/accumulator/proof.go +++ /dev/null @@ -1,527 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "bytes" - crand "crypto/rand" - "errors" - "fmt" - - "git.sr.ht/~sircmpwn/go-bare" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type proofParamsMarshal struct { - X []byte `bare:"x"` - Y []byte `bare:"y"` - Z []byte `bare:"z"` - Curve string `bare:"curve"` -} - -// ProofParams contains four distinct public generators of G1 - X, Y, Z -type ProofParams struct { - x, y, z curves.Point -} - -// New samples X, Y, Z, K -func (p *ProofParams) New( - curve *curves.PairingCurve, - pk *PublicKey, - entropy []byte, -) (*ProofParams, error) { - pkBytes, err := pk.MarshalBinary() - if err != nil { - return nil, err - } - prefix := bytes.Repeat([]byte{0xFF}, 32) - data := append(prefix, entropy...) - data = append(data, pkBytes...) - p.z = curve.Scalar.Point().Hash(data) - - data[0] = 0xFE - p.y = curve.Scalar.Point().Hash(data) - - data[0] = 0xFD - p.x = curve.Scalar.Point().Hash(data) - - return p, nil -} - -// MarshalBinary converts ProofParams to bytes -func (p *ProofParams) MarshalBinary() ([]byte, error) { - if p.x == nil || p.y == nil || p.z == nil { - return nil, fmt.Errorf("some value x, y, or z is nil") - } - tv := &proofParamsMarshal{ - X: p.x.ToAffineCompressed(), - Y: p.y.ToAffineCompressed(), - Z: p.z.ToAffineCompressed(), - Curve: p.x.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary converts bytes to ProofParams -func (p *ProofParams) UnmarshalBinary(data []byte) error { - if data == nil { - return fmt.Errorf("expected non-zero byte sequence") - } - tv := new(proofParamsMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - x, err := curve.NewIdentityPoint().FromAffineCompressed(tv.X) - if err != nil { - return err - } - y, err := curve.NewIdentityPoint().FromAffineCompressed(tv.Y) - if err != nil { - return err - } - z, err := curve.NewIdentityPoint().FromAffineCompressed(tv.Z) - if err != nil { - return err - } - p.x = x - p.y = y - p.z = z - return nil -} - -// MembershipProofCommitting contains value computed in Proof of knowledge and -// Blinding phases as described in section 7 of https://eprint.iacr.org/2020/777.pdf -type MembershipProofCommitting struct { - eC curves.Point - tSigma curves.Point - tRho curves.Point - deltaSigma curves.Scalar - deltaRho curves.Scalar - blindingFactor curves.Scalar - rSigma curves.Scalar - rRho curves.Scalar - rDeltaSigma curves.Scalar - rDeltaRho curves.Scalar - sigma curves.Scalar - rho curves.Scalar - capRSigma curves.Point - capRRho curves.Point - capRDeltaSigma curves.Point - capRDeltaRho curves.Point - capRE curves.Scalar - accumulator curves.Point - witnessValue curves.Scalar - xG1 curves.Point - yG1 curves.Point - zG1 curves.Point -} - -// New initiates values of MembershipProofCommitting -func (mpc *MembershipProofCommitting) New( - witness *MembershipWitness, - acc *Accumulator, - pp *ProofParams, - pk *PublicKey, -) (*MembershipProofCommitting, error) { - // Randomly select σ, ρ - sigma := witness.y.Random(crand.Reader) - rho := witness.y.Random(crand.Reader) - - // E_C = C + (σ + ρ)Z - t := sigma - t = t.Add(rho) - eC := pp.z - eC = eC.Mul(t) - eC = eC.Add(witness.c) - - // T_σ = σX - tSigma := pp.x - tSigma = tSigma.Mul(sigma) - - // T_ρ = ρY - tRho := pp.y - tRho = tRho.Mul(rho) - - // δ_σ = yσ - deltaSigma := witness.y - deltaSigma = deltaSigma.Mul(sigma) - - // δ_ρ = yρ - deltaRho := witness.y - deltaRho = deltaRho.Mul(rho) - - // Randomly pick r_σ,r_ρ,r_δσ,r_δρ - rY := witness.y.Random(crand.Reader) - rSigma := witness.y.Random(crand.Reader) - rRho := witness.y.Random(crand.Reader) - rDeltaSigma := witness.y.Random(crand.Reader) - rDeltaRho := witness.y.Random(crand.Reader) - - // R_σ = r_σ X - capRSigma := pp.x - capRSigma = capRSigma.Mul(rSigma) - - // R_ρ = ρY - capRRho := pp.y - capRRho = capRRho.Mul(rRho) - - // R_δσ = r_y T_σ - r_δσ X - negX := pp.x - negX = negX.Neg() - capRDeltaSigma := tSigma.Mul(rY) - capRDeltaSigma = capRDeltaSigma.Add(negX.Mul(rDeltaSigma)) - - // R_δρ = r_y T_ρ - r_δρ Y - negY := pp.y - negY = negY.Neg() - capRDeltaRho := tRho.Mul(rY) - capRDeltaRho = capRDeltaRho.Add(negY.Mul(rDeltaRho)) - - // P~ - g2 := pk.value.Generator() - - // -r_δσ - r_δρ - exp := rDeltaSigma - exp = exp.Add(rDeltaRho) - exp = exp.Neg() - - // -r_σ - r_ρ - exp2 := rSigma - exp2 = exp2.Add(rRho) - exp2 = exp2.Neg() - - // rY * eC - rYeC := eC.Mul(rY) - - // (-r_δσ - r_δρ)*Z - expZ := pp.z.Mul(exp) - - // (-r_σ - r_ρ)*Z - exp2Z := pp.z.Mul(exp2) - - // Prepare - rYeCPrep, ok := rYeC.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - g2Prep, ok := g2.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - expZPrep, ok := expZ.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - exp2ZPrep, ok := exp2Z.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - pkPrep := pk.value - - // Pairing - capRE := g2Prep.MultiPairing(rYeCPrep, g2Prep, expZPrep, g2Prep, exp2ZPrep, pkPrep) - - return &MembershipProofCommitting{ - eC, - tSigma, - tRho, - deltaSigma, - deltaRho, - rY, - rSigma, - rRho, - rDeltaSigma, - rDeltaRho, - sigma, - rho, - capRSigma, - capRRho, - capRDeltaSigma, - capRDeltaRho, - capRE, - acc.value, - witness.y, - pp.x, - pp.y, - pp.z, - }, nil -} - -// GetChallengeBytes returns bytes that need to be hashed for generating challenge. -// V || Ec || T_sigma || T_rho || R_E || R_sigma || R_rho || R_delta_sigma || R_delta_rho -func (mpc MembershipProofCommitting) GetChallengeBytes() []byte { - res := mpc.accumulator.ToAffineCompressed() - res = append(res, mpc.eC.ToAffineCompressed()...) - res = append(res, mpc.tSigma.ToAffineCompressed()...) - res = append(res, mpc.tRho.ToAffineCompressed()...) - res = append(res, mpc.capRE.Bytes()...) - res = append(res, mpc.capRSigma.ToAffineCompressed()...) - res = append(res, mpc.capRRho.ToAffineCompressed()...) - res = append(res, mpc.capRDeltaSigma.ToAffineCompressed()...) - res = append(res, mpc.capRDeltaRho.ToAffineCompressed()...) - return res -} - -// GenProof computes the s values for Fiat-Shamir and return the actual -// proof to be sent to the verifier given the challenge c. -func (mpc *MembershipProofCommitting) GenProof(c curves.Scalar) *MembershipProof { - // s_y = r_y + c*y - sY := schnorr(mpc.blindingFactor, mpc.witnessValue, c) - // s_σ = r_σ + c*σ - sSigma := schnorr(mpc.rSigma, mpc.sigma, c) - // s_ρ = r_ρ + c*ρ - sRho := schnorr(mpc.rRho, mpc.rho, c) - // s_δσ = rδσ + c*δ_σ - sDeltaSigma := schnorr(mpc.rDeltaSigma, mpc.deltaSigma, c) - // s_δρ = rδρ + c*δ_ρ - sDeltaRho := schnorr(mpc.rDeltaRho, mpc.deltaRho, c) - - return &MembershipProof{ - mpc.eC, - mpc.tSigma, - mpc.tRho, - sSigma, - sRho, - sDeltaSigma, - sDeltaRho, - sY, - } -} - -func schnorr(r, v, challenge curves.Scalar) curves.Scalar { - res := v - res = res.Mul(challenge) - res = res.Add(r) - return res -} - -type membershipProofMarshal struct { - EC []byte `bare:"e_c"` - TSigma []byte `bare:"t_sigma"` - TRho []byte `bare:"t_rho"` - SSigma []byte `bare:"s_sigma"` - SRho []byte `bare:"s_rho"` - SDeltaSigma []byte `bare:"s_delta_sigma"` - SDeltaRho []byte `bare:"s_delta_rho"` - SY []byte `bare:"s_y"` - Curve string `bare:"curve"` -} - -// MembershipProof contains values in the proof to be verified -type MembershipProof struct { - eC curves.Point - tSigma curves.Point - tRho curves.Point - sSigma curves.Scalar - sRho curves.Scalar - sDeltaSigma curves.Scalar - sDeltaRho curves.Scalar - sY curves.Scalar -} - -// Finalize computes values in the proof to be verified. -func (mp *MembershipProof) Finalize( - acc *Accumulator, - pp *ProofParams, - pk *PublicKey, - challenge curves.Scalar, -) (*MembershipProofFinal, error) { - // R_σ = s_δ X + c T_σ - negTSigma := mp.tSigma - negTSigma = negTSigma.Neg() - capRSigma := pp.x.Mul(mp.sSigma) - capRSigma = capRSigma.Add(negTSigma.Mul(challenge)) - - // R_ρ = s_ρ Y + c T_ρ - negTRho := mp.tRho - negTRho = negTRho.Neg() - capRRho := pp.y.Mul(mp.sRho) - capRRho = capRRho.Add(negTRho.Mul(challenge)) - - // R_δσ = s_y T_σ - s_δσ X - negX := pp.x - negX = negX.Neg() - capRDeltaSigma := mp.tSigma.Mul(mp.sY) - capRDeltaSigma = capRDeltaSigma.Add(negX.Mul(mp.sDeltaSigma)) - - // R_δρ = s_y T_ρ - s_δρ Y - negY := pp.y - negY = negY.Neg() - capRDeltaRho := mp.tRho.Mul(mp.sY) - capRDeltaRho = capRDeltaRho.Add(negY.Mul(mp.sDeltaRho)) - - // tildeP - g2 := pk.value.Generator() - - // Compute capRE, the pairing - // E_c * s_y - eCsY := mp.eC.Mul(mp.sY) - - // (-s_delta_sigma - s_delta_rho) * Z - exp := mp.sDeltaSigma - exp = exp.Add(mp.sDeltaRho) - exp = exp.Neg() - expZ := pp.z.Mul(exp) - - // (-c) * V - exp = challenge.Neg() - expV := acc.value.Mul(exp) - - // E_c * s_y + (-s_delta_sigma - s_delta_rho) * Z + (-c) * V - lhs := eCsY.Add(expZ).Add(expV) - - // (-s_sigma - s_rho) * Z - exp = mp.sSigma - exp = exp.Add(mp.sRho) - exp = exp.Neg() - expZ2 := pp.z.Mul(exp) - - // E_c * c - cEc := mp.eC.Mul(challenge) - - // (-s_sigma - s_rho) * Z + E_c * c - rhs := cEc.Add(expZ2) - - // Prepare - lhsPrep, ok := lhs.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - g2Prep, ok := g2.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - rhsPrep, ok := rhs.(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - pkPrep := pk.value - - // capRE - capRE := g2Prep.MultiPairing(lhsPrep, g2Prep, rhsPrep, pkPrep) - - return &MembershipProofFinal{ - acc.value, - mp.eC, - mp.tSigma, - mp.tRho, - capRE, - capRSigma, - capRRho, - capRDeltaSigma, - capRDeltaRho, - }, nil -} - -// MarshalBinary converts MembershipProof to bytes -func (mp MembershipProof) MarshalBinary() ([]byte, error) { - tv := &membershipProofMarshal{ - EC: mp.eC.ToAffineCompressed(), - TSigma: mp.tSigma.ToAffineCompressed(), - TRho: mp.tRho.ToAffineCompressed(), - SSigma: mp.sSigma.Bytes(), - SRho: mp.sRho.Bytes(), - SDeltaSigma: mp.sDeltaSigma.Bytes(), - SDeltaRho: mp.sDeltaRho.Bytes(), - SY: mp.sY.Bytes(), - Curve: mp.eC.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary converts bytes to MembershipProof -func (mp *MembershipProof) UnmarshalBinary(data []byte) error { - if data == nil { - return fmt.Errorf("expected non-zero byte sequence") - } - tv := new(membershipProofMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - eC, err := curve.NewIdentityPoint().FromAffineCompressed(tv.EC) - if err != nil { - return err - } - tSigma, err := curve.NewIdentityPoint().FromAffineCompressed(tv.TSigma) - if err != nil { - return err - } - tRho, err := curve.NewIdentityPoint().FromAffineCompressed(tv.TRho) - if err != nil { - return err - } - sSigma, err := curve.NewScalar().SetBytes(tv.SSigma) - if err != nil { - return err - } - sRho, err := curve.NewScalar().SetBytes(tv.SRho) - if err != nil { - return err - } - sDeltaSigma, err := curve.NewScalar().SetBytes(tv.SDeltaSigma) - if err != nil { - return err - } - sDeltaRho, err := curve.NewScalar().SetBytes(tv.SDeltaRho) - if err != nil { - return err - } - sY, err := curve.NewScalar().SetBytes(tv.SY) - if err != nil { - return err - } - - mp.eC = eC - mp.tSigma = tSigma - mp.tRho = tRho - mp.sSigma = sSigma - mp.sRho = sRho - mp.sDeltaSigma = sDeltaSigma - mp.sDeltaRho = sDeltaRho - mp.sY = sY - - return nil -} - -// MembershipProofFinal contains values that are input to Fiat-Shamir Heuristic -type MembershipProofFinal struct { - accumulator curves.Point - eC curves.Point - tSigma curves.Point - tRho curves.Point - capRE curves.Scalar - capRSigma curves.Point - capRRho curves.Point - capRDeltaSigma curves.Point - capRDeltaRho curves.Point -} - -// GetChallenge computes Fiat-Shamir Heuristic taking input values of MembershipProofFinal -func (m MembershipProofFinal) GetChallenge(curve *curves.PairingCurve) curves.Scalar { - res := m.accumulator.ToAffineCompressed() - res = append(res, m.eC.ToAffineCompressed()...) - res = append(res, m.tSigma.ToAffineCompressed()...) - res = append(res, m.tRho.ToAffineCompressed()...) - res = append(res, m.capRE.Bytes()...) - res = append(res, m.capRSigma.ToAffineCompressed()...) - res = append(res, m.capRRho.ToAffineCompressed()...) - res = append(res, m.capRDeltaSigma.ToAffineCompressed()...) - res = append(res, m.capRDeltaRho.ToAffineCompressed()...) - challenge := curve.Scalar.Hash(res) - return challenge -} diff --git a/crypto/accumulator/proof_test.go b/crypto/accumulator/proof_test.go deleted file mode 100644 index b2228d735..000000000 --- a/crypto/accumulator/proof_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestProofParamsMarshal(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - pk, _ := sk.GetPublicKey(curve) - - params, err := new(ProofParams).New(curve, pk, []byte("entropy")) - require.NoError(t, err) - require.NotNil(t, params.x) - require.NotNil(t, params.y) - require.NotNil(t, params.z) - - bytes, err := params.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, bytes) - - params2 := &ProofParams{ - curve.PointG1.Generator(), - curve.PointG1.Generator(), - curve.PointG1.Generator(), - } - err = params2.UnmarshalBinary(bytes) - require.NoError(t, err) - require.True(t, params.x.Equal(params2.x)) - require.True(t, params.y.Equal(params2.y)) - require.True(t, params.z.Equal(params2.z)) -} - -func TestMembershipProof(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - pk, _ := sk.GetPublicKey(curve) - - element1 := curve.Scalar.Hash([]byte("3")) - element2 := curve.Scalar.Hash([]byte("4")) - element3 := curve.Scalar.Hash([]byte("5")) - element4 := curve.Scalar.Hash([]byte("6")) - element5 := curve.Scalar.Hash([]byte("7")) - element6 := curve.Scalar.Hash([]byte("8")) - element7 := curve.Scalar.Hash([]byte("9")) - elements := []Element{element1, element2, element3, element4, element5, element6, element7} - - // Initiate a new accumulator - acc, err := new(Accumulator).WithElements(curve, sk, elements) - require.NoError(t, err) - require.NotNil(t, acc.value) - - // Initiate a new membership witness for value elements[3] - wit, err := new(MembershipWitness).New(elements[3], acc, sk) - require.NoError(t, err) - require.Equal(t, wit.y, elements[3]) - - // Create proof parameters, which contains randomly sampled G1 points X, Y, Z, K - params, err := new(ProofParams).New(curve, pk, []byte("entropy")) - require.NoError(t, err) - require.NotNil(t, params.x) - require.NotNil(t, params.y) - require.NotNil(t, params.z) - - mpc, err := new(MembershipProofCommitting).New(wit, acc, params, pk) - require.NoError(t, err) - testMPC(t, mpc) - - challenge := curve.Scalar.Hash(mpc.GetChallengeBytes()) - require.NotNil(t, challenge) - - proof := mpc.GenProof(challenge) - require.NotNil(t, proof) - testProof(t, proof) - - finalProof, err := proof.Finalize(acc, params, pk, challenge) - require.NoError(t, err) - require.NotNil(t, finalProof) - testFinalProof(t, finalProof) - - challenge2 := finalProof.GetChallenge(curve) - require.Equal(t, challenge, challenge2) - - // Check we can still have a valid proof even if accumulator and witness are updated - data1 := curve.Scalar.Hash([]byte("1")) - data2 := curve.Scalar.Hash([]byte("2")) - data3 := curve.Scalar.Hash([]byte("3")) - data4 := curve.Scalar.Hash([]byte("4")) - data5 := curve.Scalar.Hash([]byte("5")) - data := []Element{data1, data2, data3, data4, data5} - additions := data[0:2] - deletions := data[2:5] - _, coefficients, err := acc.Update(sk, additions, deletions) - require.NoError(t, err) - require.NotNil(t, coefficients) - - _, err = wit.BatchUpdate(additions, deletions, coefficients) - require.NoError(t, err) - - newParams, err := new(ProofParams).New(curve, pk, []byte("entropy")) - require.NoError(t, err) - require.NotNil(t, newParams.x) - require.NotNil(t, newParams.y) - require.NotNil(t, newParams.z) - - newMPC, err := new(MembershipProofCommitting).New(wit, acc, newParams, pk) - require.NoError(t, err) - testMPC(t, newMPC) - - challenge3 := curve.Scalar.Hash(newMPC.GetChallengeBytes()) - require.NotNil(t, challenge3) - - newProof := newMPC.GenProof(challenge3) - require.NotNil(t, newProof) - testProof(t, newProof) - - newFinalProof, err := newProof.Finalize(acc, newParams, pk, challenge3) - require.NoError(t, err) - require.NotNil(t, newFinalProof) - testFinalProof(t, newFinalProof) - - challenge4 := newFinalProof.GetChallenge(curve) - require.Equal(t, challenge3, challenge4) -} - -func testMPC(t *testing.T, mpc *MembershipProofCommitting) { - require.NotNil(t, mpc.eC) - require.NotNil(t, mpc.tSigma) - require.NotNil(t, mpc.tRho) - require.NotNil(t, mpc.deltaSigma) - require.NotNil(t, mpc.deltaRho) - require.NotNil(t, mpc.blindingFactor) - require.NotNil(t, mpc.rSigma) - require.NotNil(t, mpc.rRho) - require.NotNil(t, mpc.rDeltaSigma) - require.NotNil(t, mpc.rDeltaRho) - require.NotNil(t, mpc.sigma) - require.NotNil(t, mpc.rho) - require.NotNil(t, mpc.capRSigma) - require.NotNil(t, mpc.capRRho) - require.NotNil(t, mpc.capRDeltaSigma) - require.NotNil(t, mpc.capRDeltaRho) - require.NotNil(t, mpc.capRE) - require.NotNil(t, mpc.accumulator) - require.NotNil(t, mpc.witnessValue) - require.NotNil(t, mpc.xG1) - require.NotNil(t, mpc.yG1) - require.NotNil(t, mpc.zG1) -} - -func testProof(t *testing.T, proof *MembershipProof) { - require.NotNil(t, proof.eC) - require.NotNil(t, proof.tSigma) - require.NotNil(t, proof.tRho) - require.NotNil(t, proof.sSigma) - require.NotNil(t, proof.sRho) - require.NotNil(t, proof.sDeltaSigma) - require.NotNil(t, proof.sDeltaRho) - require.NotNil(t, proof.sY) -} - -func testFinalProof(t *testing.T, finalProof *MembershipProofFinal) { - require.NotNil(t, finalProof.accumulator) - require.NotNil(t, finalProof.eC) - require.NotNil(t, finalProof.tSigma) - require.NotNil(t, finalProof.tRho) - require.NotNil(t, finalProof.capRE) - require.NotNil(t, finalProof.capRSigma) - require.NotNil(t, finalProof.capRRho) - require.NotNil(t, finalProof.capRDeltaSigma) - require.NotNil(t, finalProof.capRDeltaRho) -} diff --git a/crypto/accumulator/witness.go b/crypto/accumulator/witness.go deleted file mode 100644 index 8d74183d7..000000000 --- a/crypto/accumulator/witness.go +++ /dev/null @@ -1,392 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "errors" - "fmt" - - "git.sr.ht/~sircmpwn/go-bare" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// MembershipWitness contains the witness c and the value y respect to the accumulator state. -type MembershipWitness struct { - c curves.Point - y curves.Scalar -} - -// New creates a new membership witness -func (mw *MembershipWitness) New( - y Element, - acc *Accumulator, - sk *SecretKey, -) (*MembershipWitness, error) { - if acc.value == nil || acc.value.IsIdentity() { - return nil, fmt.Errorf("value of accumulator should not be nil") - } - if sk.value == nil || sk.value.IsZero() { - return nil, fmt.Errorf("secret key should not be nil") - } - if y == nil || y.IsZero() { - return nil, fmt.Errorf("y should not be nil") - } - newAcc := &Accumulator{acc.value} - _, err := newAcc.Remove(sk, y) - if err != nil { - return nil, err - } - mw.c = newAcc.value - mw.y = y.Add(y.Zero()) - return mw, nil -} - -// Verify the MembershipWitness mw is a valid witness as per section 4 in -// -func (mw MembershipWitness) Verify(pk *PublicKey, acc *Accumulator) error { - if mw.c == nil || mw.y == nil || mw.c.IsIdentity() || mw.y.IsZero() { - return fmt.Errorf("c and y should not be nil") - } - - if pk.value == nil || pk.value.IsIdentity() { - return fmt.Errorf("invalid public key") - } - if acc.value == nil || acc.value.IsIdentity() { - return fmt.Errorf("accumulator value should not be nil") - } - - // Set -tildeP - g2, ok := pk.value.Generator().(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - - // y*tildeP + tildeQ, tildeP is a G2 generator. - p, ok := g2.Mul(mw.y).Add(pk.value).(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - - // Prepare - witness, ok := mw.c.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - v, ok := acc.value.Neg().(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - - // Check e(witness, y*tildeP + tildeQ) * e(-acc, tildeP) == Identity - result := p.MultiPairing(witness, p, v, g2) - if !result.IsOne() { - return fmt.Errorf("invalid result") - } - - return nil -} - -// ApplyDelta returns C' = dA(y)/dD(y)*C + 1/dD(y) * -// according to the witness update protocol described in section 4 of -// https://eprint.iacr.org/2020/777.pdf -func (mw *MembershipWitness) ApplyDelta(delta *Delta) (*MembershipWitness, error) { - if mw.c == nil || mw.y == nil || delta == nil { - return nil, fmt.Errorf("y, c or delta should not be nil") - } - - // C' = dA(y)/dD(y)*C + 1/dD(y) * - mw.c = mw.c.Mul(delta.d).Add(delta.p) - return mw, nil -} - -// BatchUpdate performs batch update as described in section 4 -func (mw *MembershipWitness) BatchUpdate( - additions []Element, - deletions []Element, - coefficients []Coefficient, -) (*MembershipWitness, error) { - delta, err := evaluateDelta(mw.y, additions, deletions, coefficients) - if err != nil { - return nil, err - } - mw, err = mw.ApplyDelta(delta) - if err != nil { - return nil, fmt.Errorf("applyDelta fails") - } - return mw, nil -} - -// MultiBatchUpdate performs multi-batch update using epoch as described in section 4.2 -func (mw *MembershipWitness) MultiBatchUpdate( - A [][]Element, - D [][]Element, - C [][]Coefficient, -) (*MembershipWitness, error) { - delta, err := evaluateDeltas(mw.y, A, D, C) - if err != nil { - return nil, fmt.Errorf("evaluateDeltas fails") - } - mw, err = mw.ApplyDelta(delta) - if err != nil { - return nil, err - } - return mw, nil -} - -// MarshalBinary converts a membership witness to bytes -func (mw MembershipWitness) MarshalBinary() ([]byte, error) { - if mw.c == nil || mw.y == nil { - return nil, fmt.Errorf("c and y value should not be nil") - } - - result := append(mw.c.ToAffineCompressed(), mw.y.Bytes()...) - tv := &structMarshal{ - Value: result, - Curve: mw.c.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary converts bytes into MembershipWitness -func (mw *MembershipWitness) UnmarshalBinary(data []byte) error { - if data == nil { - return fmt.Errorf("input data should not be nil") - } - tv := new(structMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - - ptLength := len(curve.Point.ToAffineCompressed()) - scLength := len(curve.Scalar.Bytes()) - expectedLength := ptLength + scLength - if len(tv.Value) != expectedLength { - return fmt.Errorf("invalid byte sequence") - } - cValue, err := curve.Point.FromAffineCompressed(tv.Value[:ptLength]) - if err != nil { - return err - } - yValue, err := curve.Scalar.SetBytes(tv.Value[ptLength:]) - if err != nil { - return err - } - mw.c = cValue - mw.y = yValue - return nil -} - -// Delta contains values d and p, where d should be the division dA(y)/dD(y) on some value y -// p should be equal to 1/dD * -type Delta struct { - d curves.Scalar - p curves.Point -} - -// MarshalBinary converts Delta into bytes -func (d *Delta) MarshalBinary() ([]byte, error) { - if d.d == nil || d.p == nil { - return nil, fmt.Errorf("d and p should not be nil") - } - var result []byte - result = append(result, d.p.ToAffineCompressed()...) - result = append(result, d.d.Bytes()...) - tv := &structMarshal{ - Value: result, - Curve: d.p.CurveName(), - } - return bare.Marshal(tv) -} - -// UnmarshalBinary converts data into Delta -func (d *Delta) UnmarshalBinary(data []byte) error { - if data == nil { - return fmt.Errorf("expected non-zero byte sequence") - } - - tv := new(structMarshal) - err := bare.Unmarshal(data, tv) - if err != nil { - return err - } - curve := curves.GetCurveByName(tv.Curve) - if curve == nil { - return fmt.Errorf("invalid curve") - } - - ptLength := len(curve.Point.ToAffineCompressed()) - scLength := len(curve.Scalar.Bytes()) - expectedLength := ptLength + scLength - if len(tv.Value) != expectedLength { - return fmt.Errorf("invalid byte sequence") - } - pValue, err := curve.NewIdentityPoint().FromAffineCompressed(tv.Value[:ptLength]) - if err != nil { - return err - } - dValue, err := curve.NewScalar().SetBytes(tv.Value[ptLength:]) - if err != nil { - return err - } - d.d = dValue - d.p = pValue - return nil -} - -// evaluateDeltas compute values used for membership witness batch update with epoch -// as described in section 4.2, page 11 of https://eprint.iacr.org/2020/777.pdf -func evaluateDeltas(y Element, A [][]Element, D [][]Element, C [][]Coefficient) (*Delta, error) { - if len(A) != len(D) || len(A) != len(C) { - return nil, fmt.Errorf("a, d, c should have same length") - } - - one := y.One() - size := len(A) - - // dA(x) = ∏ 1..n (yA_i - x) - aa := make([]curves.Scalar, 0) - // dD(x) = ∏ 1..m (yD_i - x) - dd := make([]curves.Scalar, 0) - - a := one - d := one - - // dA_{a->b}(y) = ∏ a..b dAs(y) - // dD_{a->b}(y) = ∏ a..b dDs(y) - for i := range size { - adds := A[i] - dels := D[i] - - // ta = dAs(y) - ta, err := dad(adds, y) - if err != nil { - return nil, fmt.Errorf("dad on additions fails") - } - // td = dDs(y) - td, err := dad(dels, y) - if err != nil { - return nil, fmt.Errorf("dad on deletions fails") - } - // ∏ a..b dAs(y) - a = a.Mul(ta) - // ∏ a..b dDs(y) - d = d.Mul(td) - - aa = append(aa, ta) - dd = append(dd, td) - } - - // If this fails, then this value was removed. - d, err := d.Invert() - if err != nil { - return nil, fmt.Errorf("no inverse exists") - } - - // - p := make(polynomialPoint, 0, size) - - // Ωi->j+1 = ∑ 1..t (dAt * dDt-1) · Ω - for i := 0; i < size; i++ { - // t = i+1 - // ∏^(t-1)_(h=i+1) - ddh := one - - // dDi→t−1 (y) - for h := 0; h < i; h++ { - ddh = ddh.Mul(dd[h]) - } - - // ∏^(j+1)_(k=t+1) - dak := one - // dAt->j(y) - for k := i + 1; k < size; k++ { - dak = dak.Mul(aa[k]) - } - - // dDi->t-1(y) * dAt->j(y) - dak = dak.Mul(ddh) - pp := make(polynomialPoint, len(C[i])) - for j := 0; j < len(pp); j++ { - pp[j] = C[i][j] - } - - // dDi->t-1(y) * dAt->j(y) · Ω - pp, err := pp.Mul(dak) - if err != nil { - return nil, fmt.Errorf("pp.Mul fails") - } - - p, err = p.Add(pp) - if err != nil { - return nil, fmt.Errorf("pp.Add fails") - } - } - // dAi->j(y)/dDi->j(y) - a = a.Mul(d) - - // Ωi->j(y) - v, err := p.evaluate(y) - if err != nil { - return nil, fmt.Errorf("p.evaluate fails") - } - - // (1/dDi->j(y)) * Ωi->j(y) - v = v.Mul(d) - - // return - return &Delta{d: a, p: v}, nil -} - -// evaluateDelta computes values used for membership witness batch update -// as described in section 4.1 of https://eprint.iacr.org/2020/777.pdf -func evaluateDelta( - y Element, - additions []Element, - deletions []Element, - coefficients []Coefficient, -) (*Delta, error) { - // dD(y) = ∏ 1..m (yD_i - y), d = 1/dD(y) - var err error - d, err := dad(deletions, y) - if err != nil { - return nil, fmt.Errorf("dad fails on deletions") - } - d, err = d.Invert() - if err != nil { - return nil, fmt.Errorf("no inverse exists") - } - - // dA(y) = ∏ 1..n (yA_i - y) - a, err := dad(additions, y) - if err != nil { - return nil, fmt.Errorf("dad fails on additions") - } - // dA(y)/dD(y) - a = a.Mul(d) - - // Create a PolynomialG1 from coefficients - p := make(polynomialPoint, len(coefficients)) - for i := range coefficients { - p[i] = coefficients[i] - } - - // - v, err := p.evaluate(y) - if err != nil { - return nil, fmt.Errorf("p.evaluate fails") - } - // 1/dD * - v = v.Mul(d) - - return &Delta{d: a, p: v}, nil -} diff --git a/crypto/accumulator/witness_test.go b/crypto/accumulator/witness_test.go deleted file mode 100644 index e21a51a72..000000000 --- a/crypto/accumulator/witness_test.go +++ /dev/null @@ -1,229 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package accumulator - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func Test_Membership_Witness_New(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - var seed [32]byte - key, _ := new(SecretKey).New(curve, seed[:]) - acc, _ := new(Accumulator).New(curve) - e := curve.Scalar.New(2) - mw, err := new(MembershipWitness).New(e, acc, key) - require.NoError(t, err) - require.NotNil(t, mw.c) - require.NotNil(t, mw.y) -} - -func Test_Membership_Witness_Marshal(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - mw := &MembershipWitness{ - curve.PointG1.Generator().Mul(curve.Scalar.New(10)), - curve.Scalar.New(15), - } - data, err := mw.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, data) - newMW := &MembershipWitness{} - err = newMW.UnmarshalBinary(data) - require.NoError(t, err) - require.True(t, mw.c.Equal(newMW.c)) - require.Equal(t, 0, mw.y.Cmp(newMW.y)) -} - -func Test_Membership(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - pk, _ := sk.GetPublicKey(curve) - - element1 := curve.Scalar.Hash([]byte("3")) - element2 := curve.Scalar.Hash([]byte("4")) - element3 := curve.Scalar.Hash([]byte("5")) - element4 := curve.Scalar.Hash([]byte("6")) - element5 := curve.Scalar.Hash([]byte("7")) - element6 := curve.Scalar.Hash([]byte("8")) - element7 := curve.Scalar.Hash([]byte("9")) - elements := []Element{element1, element2, element3, element4, element5, element6, element7} - - // nm_witness_max works as well if set to value larger than 0 for this test.x - acc, err := new(Accumulator).WithElements(curve, sk, elements) - require.NoError(t, err) - require.NotNil(t, acc.value) - require.False(t, acc.value.IsIdentity()) - require.True(t, acc.value.IsOnCurve()) - require.NotEqual(t, acc.value, curve.NewG1GeneratorPoint()) - - wit, err := new(MembershipWitness).New(elements[3], acc, sk) - require.NoError(t, err) - require.Equal(t, wit.y, elements[3]) - - err = wit.Verify(pk, acc) - require.NoError(t, err) - - // Test wrong cases, forge a wrong witness - wrongWit := MembershipWitness{ - curve.PointG1.Identity(), - curve.Scalar.One(), - } - err = wrongWit.Verify(pk, acc) - require.Error(t, err) - - // Test wrong cases, forge a wrong accumulator - wrongAcc := &Accumulator{ - curve.PointG1.Generator(), - } - err = wit.Verify(pk, wrongAcc) - require.Error(t, err) -} - -func Test_Membership_Batch_Update(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - pk, _ := sk.GetPublicKey(curve) - - element1 := curve.Scalar.Hash([]byte("3")) - element2 := curve.Scalar.Hash([]byte("4")) - element3 := curve.Scalar.Hash([]byte("5")) - element4 := curve.Scalar.Hash([]byte("6")) - element5 := curve.Scalar.Hash([]byte("7")) - element6 := curve.Scalar.Hash([]byte("8")) - element7 := curve.Scalar.Hash([]byte("9")) - elements := []Element{element1, element2, element3, element4, element5, element6, element7} - - // nm_witness_max works as well if set to value larger than 0 for this test. - acc, err := new(Accumulator).WithElements(curve, sk, elements) - require.NoError(t, err) - require.NotNil(t, acc.value) - - wit, err := new(MembershipWitness).New(elements[3], acc, sk) - require.NoError(t, err) - require.Equal(t, wit.y, elements[3]) - - err = wit.Verify(pk, acc) - require.Nil(t, err) - - data1 := curve.Scalar.Hash([]byte("1")) - data2 := curve.Scalar.Hash([]byte("2")) - data3 := curve.Scalar.Hash([]byte("3")) - data4 := curve.Scalar.Hash([]byte("4")) - data5 := curve.Scalar.Hash([]byte("5")) - data := []Element{data1, data2, data3, data4, data5} - additions := data[0:2] - deletions := data[2:5] - _, coefficients, err := acc.Update(sk, additions, deletions) - require.NoError(t, err) - require.NotNil(t, coefficients) - - _, err = wit.BatchUpdate(additions, deletions, coefficients) - require.NoError(t, err) - err = wit.Verify(pk, acc) - require.Nil(t, err) -} - -func Test_Membership_Multi_Batch_Update(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G1{}) - sk, _ := new(SecretKey).New(curve, []byte("1234567890")) - pk, _ := sk.GetPublicKey(curve) - - element1 := curve.Scalar.Hash([]byte("3")) - element2 := curve.Scalar.Hash([]byte("4")) - element3 := curve.Scalar.Hash([]byte("5")) - element4 := curve.Scalar.Hash([]byte("6")) - element5 := curve.Scalar.Hash([]byte("7")) - element6 := curve.Scalar.Hash([]byte("8")) - element7 := curve.Scalar.Hash([]byte("9")) - element8 := curve.Scalar.Hash([]byte("10")) - element9 := curve.Scalar.Hash([]byte("11")) - element10 := curve.Scalar.Hash([]byte("12")) - element11 := curve.Scalar.Hash([]byte("13")) - element12 := curve.Scalar.Hash([]byte("14")) - element13 := curve.Scalar.Hash([]byte("15")) - element14 := curve.Scalar.Hash([]byte("16")) - element15 := curve.Scalar.Hash([]byte("17")) - element16 := curve.Scalar.Hash([]byte("18")) - element17 := curve.Scalar.Hash([]byte("19")) - element18 := curve.Scalar.Hash([]byte("20")) - elements := []Element{ - element1, - element2, - element3, - element4, - element5, - element6, - element7, - element8, - element9, - element10, - element11, - element12, - element13, - element14, - element15, - element16, - element17, - element18, - } - acc, err := new(Accumulator).WithElements(curve, sk, elements) - require.NoError(t, err) - require.NotNil(t, acc.value) - - wit, err := new(MembershipWitness).New(elements[3], acc, sk) - require.NoError(t, err) - - err = wit.Verify(pk, acc) - require.Nil(t, err) - - data1 := curve.Scalar.Hash([]byte("1")) - data2 := curve.Scalar.Hash([]byte("2")) - data3 := curve.Scalar.Hash([]byte("3")) - data4 := curve.Scalar.Hash([]byte("4")) - data5 := curve.Scalar.Hash([]byte("5")) - data := []Element{data1, data2, data3, data4, data5} - adds1 := data[0:2] - dels1 := data[2:5] - _, coeffs1, err := acc.Update(sk, adds1, dels1) - require.NoError(t, err) - require.NotNil(t, coeffs1) - - dels2 := elements[8:10] - _, coeffs2, err := acc.Update(sk, []Element{}, dels2) - require.NoError(t, err) - require.NotNil(t, coeffs2) - - dels3 := elements[11:14] - _, coeffs3, err := acc.Update(sk, []Element{}, dels3) - require.NoError(t, err) - require.NotNil(t, coeffs3) - - a := make([][]Element, 3) - a[0] = adds1 - a[1] = []Element{} - a[2] = []Element{} - - d := make([][]Element, 3) - d[0] = dels1 - d[1] = dels2 - d[2] = dels3 - - c := make([][]Coefficient, 3) - c[0] = coeffs1 - c[1] = coeffs2 - c[2] = coeffs3 - - _, err = wit.MultiBatchUpdate(a, d, c) - require.NoError(t, err) - - err = wit.Verify(pk, acc) - require.Nil(t, err) -} diff --git a/crypto/aead/aes_gcm.go b/crypto/aead/aes_gcm.go deleted file mode 100644 index cf5119108..000000000 --- a/crypto/aead/aes_gcm.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package aead provides authenticated encryption with associated data (AEAD) implementations -// following NIST SP 800-38D standards for secure data encryption and integrity verification. -package aead - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "fmt" - "io" -) - -const ( - // NonceSize defines the standard 96-bit nonce size for optimal GCM performance - NonceSize = 12 - // TagSize defines the 128-bit authentication tag size for GCM - TagSize = 16 - // KeySize defines the AES-256 key size - KeySize = 32 -) - -// AESGCMCipher wraps AES-GCM operations with secure defaults -type AESGCMCipher struct { - gcm cipher.AEAD -} - -// NewAESGCM creates a new AES-GCM cipher with the provided 256-bit key -func NewAESGCM(key []byte) (*AESGCMCipher, error) { - if len(key) != KeySize { - return nil, fmt.Errorf("invalid key size: expected %d bytes, got %d", KeySize, len(key)) - } - - block, err := aes.NewCipher(key) - if err != nil { - return nil, fmt.Errorf("failed to create AES cipher: %w", err) - } - - gcm, err := cipher.NewGCM(block) - if err != nil { - return nil, fmt.Errorf("failed to create GCM mode: %w", err) - } - - return &AESGCMCipher{gcm: gcm}, nil -} - -// Encrypt encrypts plaintext with additional authenticated data (AAD) using AES-GCM -// Returns nonce + ciphertext + tag concatenated for easy storage -func (a *AESGCMCipher) Encrypt(plaintext, aad []byte) ([]byte, error) { - // Generate cryptographically secure random nonce - nonce, err := generateNonce() - if err != nil { - return nil, fmt.Errorf("failed to generate nonce: %w", err) - } - - // Encrypt with GCM (includes authentication tag) - ciphertext := a.gcm.Seal(nil, nonce, plaintext, aad) - - // Prepend nonce to ciphertext for transport - result := make([]byte, NonceSize+len(ciphertext)) - copy(result[:NonceSize], nonce) - copy(result[NonceSize:], ciphertext) - - return result, nil -} - -// Decrypt decrypts and authenticates ciphertext with AAD using AES-GCM -// Expects input format: nonce + ciphertext + tag -func (a *AESGCMCipher) Decrypt(data, aad []byte) ([]byte, error) { - if len(data) < NonceSize+TagSize { - return nil, fmt.Errorf("invalid ciphertext length: minimum %d bytes required", NonceSize+TagSize) - } - - // Extract nonce and ciphertext - nonce := data[:NonceSize] - ciphertext := data[NonceSize:] - - // Decrypt and verify authentication tag - plaintext, err := a.gcm.Open(nil, nonce, ciphertext, aad) - if err != nil { - return nil, fmt.Errorf("decryption and authentication failed: %w", err) - } - - return plaintext, nil -} - -// EncryptWithNonce encrypts plaintext using a provided nonce (for testing purposes) -// WARNING: Nonce reuse can compromise security. Use only for testing. -func (a *AESGCMCipher) EncryptWithNonce(plaintext, aad, nonce []byte) ([]byte, error) { - if len(nonce) != NonceSize { - return nil, fmt.Errorf("invalid nonce size: expected %d bytes, got %d", NonceSize, len(nonce)) - } - - // Encrypt with provided nonce - ciphertext := a.gcm.Seal(nil, nonce, plaintext, aad) - - // Prepend nonce to ciphertext - result := make([]byte, NonceSize+len(ciphertext)) - copy(result[:NonceSize], nonce) - copy(result[NonceSize:], ciphertext) - - return result, nil -} - -// generateNonce creates a cryptographically secure 96-bit nonce -func generateNonce() ([]byte, error) { - nonce := make([]byte, NonceSize) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return nil, fmt.Errorf("failed to read random bytes: %w", err) - } - return nonce, nil -} - -// GetNonceSize returns the nonce size used by this cipher -func (a *AESGCMCipher) GetNonceSize() int { - return NonceSize -} - -// GetTagSize returns the authentication tag size -func (a *AESGCMCipher) GetTagSize() int { - return TagSize -} diff --git a/crypto/aead/aes_gcm_test.go b/crypto/aead/aes_gcm_test.go deleted file mode 100644 index a80e6e197..000000000 --- a/crypto/aead/aes_gcm_test.go +++ /dev/null @@ -1,349 +0,0 @@ -package aead - -import ( - "crypto/rand" - "fmt" - "testing" -) - -func TestNewAESGCM(t *testing.T) { - tests := []struct { - name string - keySize int - wantErr bool - }{ - {"valid 256-bit key", 32, false}, - {"invalid 128-bit key", 16, true}, - {"invalid 192-bit key", 24, true}, - {"empty key", 0, true}, - {"oversized key", 64, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - key := make([]byte, tt.keySize) - _, err := rand.Read(key) - if err != nil { - t.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if (err != nil) != tt.wantErr { - t.Errorf("NewAESGCM() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if !tt.wantErr && cipher == nil { - t.Error("NewAESGCM() returned nil cipher without error") - } - }) - } -} - -func TestAESGCMEncryptDecrypt(t *testing.T) { - // Generate random 256-bit key - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - t.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - t.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - tests := []struct { - name string - plaintext []byte - aad []byte - }{ - {"empty plaintext", []byte{}, nil}, - {"small plaintext", []byte("hello"), nil}, - {"large plaintext", make([]byte, 1024), nil}, - {"with AAD", []byte("secret data"), []byte("additional auth data")}, - {"unicode plaintext", []byte("Hello, 世界! 🔐"), []byte("metadata")}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Fill large plaintext with test data - if len(tt.plaintext) == 1024 { - for i := range tt.plaintext { - tt.plaintext[i] = byte(i % 256) - } - } - - // Encrypt - ciphertext, err := cipher.Encrypt(tt.plaintext, tt.aad) - if err != nil { - t.Fatalf("Encrypt() error = %v", err) - } - - // Verify ciphertext structure - expectedLen := NonceSize + len(tt.plaintext) + TagSize - if len(ciphertext) != expectedLen { - t.Errorf("Unexpected ciphertext length: got %d, want %d", len(ciphertext), expectedLen) - } - - // Decrypt - decrypted, err := cipher.Decrypt(ciphertext, tt.aad) - if err != nil { - t.Fatalf("Decrypt() error = %v", err) - } - - // Verify plaintext matches - if string(decrypted) != string(tt.plaintext) { - t.Errorf("Decrypted text doesn't match original: got %q, want %q", string(decrypted), string(tt.plaintext)) - } - }) - } -} - -func TestAESGCMAuthenticationFailure(t *testing.T) { - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - t.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - t.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - plaintext := []byte("authenticated data") - aad := []byte("additional data") - - ciphertext, err := cipher.Encrypt(plaintext, aad) - if err != nil { - t.Fatalf("Encrypt() error = %v", err) - } - - tests := []struct { - name string - modifyFunc func([]byte) []byte - modifyAAD func([]byte) []byte - expectFailure bool - }{ - { - "tampered ciphertext", - func(data []byte) []byte { - if len(data) > NonceSize+5 { - data[NonceSize+5] ^= 0x01 // Flip one bit in ciphertext - } - return data - }, - nil, - true, - }, - { - "tampered nonce", - func(data []byte) []byte { - if len(data) > 5 { - data[5] ^= 0x01 // Flip one bit in nonce - } - return data - }, - nil, - true, - }, - { - "tampered AAD", - nil, - func(aad []byte) []byte { - modified := make([]byte, len(aad)) - copy(modified, aad) - if len(modified) > 0 { - modified[0] ^= 0x01 - } - return modified - }, - true, - }, - { - "valid decryption", - nil, - nil, - false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - testCiphertext := make([]byte, len(ciphertext)) - copy(testCiphertext, ciphertext) - testAAD := make([]byte, len(aad)) - copy(testAAD, aad) - - if tt.modifyFunc != nil { - testCiphertext = tt.modifyFunc(testCiphertext) - } - if tt.modifyAAD != nil { - testAAD = tt.modifyAAD(testAAD) - } - - _, err := cipher.Decrypt(testCiphertext, testAAD) - if tt.expectFailure && err == nil { - t.Error("Expected decryption to fail due to tampering, but it succeeded") - } - if !tt.expectFailure && err != nil { - t.Errorf("Expected decryption to succeed, but got error: %v", err) - } - }) - } -} - -func TestAESGCMWithNonce(t *testing.T) { - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - t.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - t.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - plaintext := []byte("test message") - nonce := make([]byte, NonceSize) - _, err = rand.Read(nonce) - if err != nil { - t.Fatalf("Failed to generate nonce: %v", err) - } - - // Test encryption with provided nonce - ciphertext, err := cipher.EncryptWithNonce(plaintext, nil, nonce) - if err != nil { - t.Fatalf("EncryptWithNonce() error = %v", err) - } - - // Verify nonce is properly prepended - if string(ciphertext[:NonceSize]) != string(nonce) { - t.Error("Nonce not properly prepended to ciphertext") - } - - // Test decryption works - decrypted, err := cipher.Decrypt(ciphertext, nil) - if err != nil { - t.Fatalf("Decrypt() error = %v", err) - } - - if string(decrypted) != string(plaintext) { - t.Errorf("Decrypted text doesn't match: got %q, want %q", string(decrypted), string(plaintext)) - } - - // Test invalid nonce size - invalidNonce := make([]byte, 8) - _, err = cipher.EncryptWithNonce(plaintext, nil, invalidNonce) - if err == nil { - t.Error("Expected error for invalid nonce size") - } -} - -func TestAESGCMInvalidCiphertext(t *testing.T) { - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - t.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - t.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - tests := []struct { - name string - ciphertext []byte - }{ - {"empty ciphertext", []byte{}}, - {"too short ciphertext", make([]byte, NonceSize)}, - {"minimal invalid", make([]byte, NonceSize+TagSize-1)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := cipher.Decrypt(tt.ciphertext, nil) - if err == nil { - t.Error("Expected error for invalid ciphertext length") - } - }) - } -} - -func BenchmarkAESGCMEncrypt(b *testing.B) { - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - b.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - b.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - sizes := []int{64, 512, 1024, 4096} - - for _, size := range sizes { - b.Run(fmt.Sprintf("%dB", size), func(b *testing.B) { - plaintext := make([]byte, size) - _, err := rand.Read(plaintext) - if err != nil { - b.Fatalf("Failed to generate test data: %v", err) - } - - b.ResetTimer() - b.SetBytes(int64(size)) - - for i := 0; i < b.N; i++ { - _, err := cipher.Encrypt(plaintext, nil) - if err != nil { - b.Fatalf("Encrypt error: %v", err) - } - } - }) - } -} - -func BenchmarkAESGCMDecrypt(b *testing.B) { - key := make([]byte, KeySize) - _, err := rand.Read(key) - if err != nil { - b.Fatalf("Failed to generate test key: %v", err) - } - - cipher, err := NewAESGCM(key) - if err != nil { - b.Fatalf("Failed to create AES-GCM cipher: %v", err) - } - - sizes := []int{64, 512, 1024, 4096} - - for _, size := range sizes { - b.Run(fmt.Sprintf("%dB", size), func(b *testing.B) { - plaintext := make([]byte, size) - _, err := rand.Read(plaintext) - if err != nil { - b.Fatalf("Failed to generate test data: %v", err) - } - - ciphertext, err := cipher.Encrypt(plaintext, nil) - if err != nil { - b.Fatalf("Failed to encrypt test data: %v", err) - } - - b.ResetTimer() - b.SetBytes(int64(size)) - - for i := 0; i < b.N; i++ { - _, err := cipher.Decrypt(ciphertext, nil) - if err != nil { - b.Fatalf("Decrypt error: %v", err) - } - } - }) - } -} diff --git a/crypto/argon2/kdf.go b/crypto/argon2/kdf.go deleted file mode 100644 index 1fcf5ad41..000000000 --- a/crypto/argon2/kdf.go +++ /dev/null @@ -1,213 +0,0 @@ -// Package argon2 provides secure key derivation using Argon2id -package argon2 - -import ( - "crypto/rand" - "crypto/subtle" - "encoding/base64" - "fmt" - "strings" - - "golang.org/x/crypto/argon2" -) - -// Config defines Argon2id parameters -type Config struct { - Time uint32 // Number of iterations - Memory uint32 // Memory in KB - Parallelism uint8 // Number of threads - SaltLength uint32 // Salt length in bytes - KeyLength uint32 // Output key length in bytes -} - -// DefaultConfig returns secure default parameters -func DefaultConfig() *Config { - return &Config{ - Time: 1, - Memory: 64 * 1024, // 64MB - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - } -} - -// LightConfig returns lighter parameters for testing -func LightConfig() *Config { - return &Config{ - Time: 1, - Memory: 16 * 1024, // 16MB - Parallelism: 2, - SaltLength: 16, - KeyLength: 32, - } -} - -// HighSecurityConfig returns high-security parameters -func HighSecurityConfig() *Config { - return &Config{ - Time: 3, - Memory: 128 * 1024, // 128MB - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - } -} - -// KDF implements Argon2id key derivation -type KDF struct { - config *Config -} - -// New creates a new Argon2id KDF with the given configuration -func New(config *Config) *KDF { - if config == nil { - config = DefaultConfig() - } - return &KDF{config: config} -} - -// DeriveKey derives a key from password and salt -func (k *KDF) DeriveKey(password []byte, salt []byte) []byte { - return argon2.IDKey( - password, - salt, - k.config.Time, - k.config.Memory, - k.config.Parallelism, - k.config.KeyLength, - ) -} - -// GenerateSalt generates a cryptographically secure salt -func (k *KDF) GenerateSalt() ([]byte, error) { - salt := make([]byte, k.config.SaltLength) - if _, err := rand.Read(salt); err != nil { - return nil, fmt.Errorf("failed to generate salt: %w", err) - } - return salt, nil -} - -// HashPassword generates a hash with embedded salt and parameters -func (k *KDF) HashPassword(password []byte) (string, error) { - salt, err := k.GenerateSalt() - if err != nil { - return "", err - } - - hash := k.DeriveKey(password, salt) - - // Encode in PHC format: $argon2id$v=19$m=65536,t=1,p=4$salt$hash - encodedSalt := base64.RawStdEncoding.EncodeToString(salt) - encodedHash := base64.RawStdEncoding.EncodeToString(hash) - - return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", - argon2.Version, - k.config.Memory, - k.config.Time, - k.config.Parallelism, - encodedSalt, - encodedHash, - ), nil -} - -// VerifyPassword verifies a password against a PHC-formatted hash -func VerifyPassword(password []byte, encodedHash string) (bool, error) { - params, salt, hash, err := decodeHash(encodedHash) - if err != nil { - return false, err - } - - kdf := &KDF{config: params} - derivedHash := kdf.DeriveKey(password, salt) - - // Constant-time comparison - return subtle.ConstantTimeCompare(hash, derivedHash) == 1, nil -} - -// decodeHash parses PHC-formatted Argon2id hash -func decodeHash(encodedHash string) (*Config, []byte, []byte, error) { - parts := strings.Split(encodedHash, "$") - if len(parts) != 6 { - return nil, nil, nil, fmt.Errorf("invalid hash format") - } - - if parts[1] != "argon2id" { - return nil, nil, nil, fmt.Errorf("unsupported algorithm: %s", parts[1]) - } - - var version int - _, err := fmt.Sscanf(parts[2], "v=%d", &version) - if err != nil { - return nil, nil, nil, fmt.Errorf("failed to parse version: %w", err) - } - - if version != argon2.Version { - return nil, nil, nil, fmt.Errorf("unsupported Argon2 version: %d", version) - } - - var memory, time uint32 - var parallelism uint8 - _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, ¶llelism) - if err != nil { - return nil, nil, nil, fmt.Errorf("failed to parse parameters: %w", err) - } - - salt, err := base64.RawStdEncoding.DecodeString(parts[4]) - if err != nil { - return nil, nil, nil, fmt.Errorf("failed to decode salt: %w", err) - } - - hash, err := base64.RawStdEncoding.DecodeString(parts[5]) - if err != nil { - return nil, nil, nil, fmt.Errorf("failed to decode hash: %w", err) - } - - config := &Config{ - Time: time, - Memory: memory, - Parallelism: parallelism, - SaltLength: uint32(len(salt)), - KeyLength: uint32(len(hash)), - } - - return config, salt, hash, nil -} - -// CompareHashes performs constant-time comparison of two hashes -func CompareHashes(hash1, hash2 []byte) bool { - return subtle.ConstantTimeCompare(hash1, hash2) == 1 -} - -// ValidateConfig validates Argon2id parameters -func ValidateConfig(config *Config) error { - if config.Time < 1 { - return fmt.Errorf("time must be at least 1") - } - if config.Memory < 8*1024 { - return fmt.Errorf("memory must be at least 8MB") - } - if config.Parallelism < 1 { - return fmt.Errorf("parallelism must be at least 1") - } - if config.SaltLength < 8 { - return fmt.Errorf("salt length must be at least 8 bytes") - } - if config.KeyLength < 16 { - return fmt.Errorf("key length must be at least 16 bytes") - } - return nil -} - -// EstimateTime estimates the time required for key derivation -func EstimateTime(config *Config, iterations int) string { - // This is a rough estimate - actual time depends on hardware - baseTime := float64(config.Time) * float64(config.Memory) / (64 * 1024) - totalTime := baseTime * float64(iterations) - - if totalTime < 1 { - return fmt.Sprintf("%.2f ms", totalTime*1000) - } else if totalTime < 60 { - return fmt.Sprintf("%.2f s", totalTime) - } - return fmt.Sprintf("%.2f min", totalTime/60) -} diff --git a/crypto/argon2/kdf_test.go b/crypto/argon2/kdf_test.go deleted file mode 100644 index 8dd41c7ca..000000000 --- a/crypto/argon2/kdf_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package argon2 - -import ( - "bytes" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestKDF_DeriveKey(t *testing.T) { - kdf := New(DefaultConfig()) - - password := []byte("test-password") - salt := []byte("salt-must-be-at-least-16-bytes!!") - - // Derive key - key := kdf.DeriveKey(password, salt) - assert.Len(t, key, int(kdf.config.KeyLength)) - - // Same inputs should produce same key - key2 := kdf.DeriveKey(password, salt) - assert.Equal(t, key, key2) - - // Different password should produce different key - key3 := kdf.DeriveKey([]byte("different"), salt) - assert.NotEqual(t, key, key3) - - // Different salt should produce different key - salt2 := []byte("different-salt-at-least-16-bytes") - key4 := kdf.DeriveKey(password, salt2) - assert.NotEqual(t, key, key4) -} - -func TestKDF_GenerateSalt(t *testing.T) { - kdf := New(DefaultConfig()) - - salt1, err := kdf.GenerateSalt() - require.NoError(t, err) - assert.Len(t, salt1, int(kdf.config.SaltLength)) - - // Should generate different salt each time - salt2, err := kdf.GenerateSalt() - require.NoError(t, err) - assert.NotEqual(t, salt1, salt2) -} - -func TestKDF_HashPassword(t *testing.T) { - kdf := New(DefaultConfig()) - password := []byte("MySecureP@ssw0rd") - - hash, err := kdf.HashPassword(password) - require.NoError(t, err) - - // Check format - assert.True(t, strings.HasPrefix(hash, "$argon2id$")) - parts := strings.Split(hash, "$") - assert.Len(t, parts, 6) - - // Verify password - valid, err := VerifyPassword(password, hash) - require.NoError(t, err) - assert.True(t, valid) - - // Wrong password should fail - valid, err = VerifyPassword([]byte("wrong"), hash) - require.NoError(t, err) - assert.False(t, valid) -} - -func TestVerifyPassword(t *testing.T) { - testCases := []struct { - name string - password string - hash string - valid bool - wantErr bool - }{ - { - name: "valid password", - password: "password123", - hash: "$argon2id$v=19$m=65536,t=1,p=4$c2FsdC1tdXN0LWJlLWF0LWxlYXN0LTE2LWJ5dGVzISE$+4smaTt/N7ivKLrqsPIbTplUxDBRMxTKCYOcXWTJOEI", - valid: true, - }, - { - name: "invalid password", - password: "wrongpassword", - hash: "$argon2id$v=19$m=65536,t=1,p=4$c2FsdC1tdXN0LWJlLWF0LWxlYXN0LTE2LWJ5dGVzISE$+4smaTt/N7ivKLrqsPIbTplUxDBRMxTKCYOcXWTJOEI", - valid: false, - }, - { - name: "invalid format", - password: "password", - hash: "invalid-hash-format", - wantErr: true, - }, - { - name: "wrong algorithm", - password: "password", - hash: "$bcrypt$v=19$m=65536,t=1,p=4$salt$hash", - wantErr: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - valid, err := VerifyPassword([]byte(tc.password), tc.hash) - if tc.wantErr { - assert.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, tc.valid, valid) - } - }) - } -} - -func TestConfigurations(t *testing.T) { - configs := map[string]*Config{ - "default": DefaultConfig(), - "light": LightConfig(), - "high": HighSecurityConfig(), - } - - for name, config := range configs { - t.Run(name, func(t *testing.T) { - err := ValidateConfig(config) - assert.NoError(t, err) - - kdf := New(config) - password := []byte("test-password") - - hash, err := kdf.HashPassword(password) - require.NoError(t, err) - - valid, err := VerifyPassword(password, hash) - require.NoError(t, err) - assert.True(t, valid) - }) - } -} - -func TestValidateConfig(t *testing.T) { - testCases := []struct { - name string - config *Config - wantErr bool - errMsg string - }{ - { - name: "valid config", - config: DefaultConfig(), - wantErr: false, - }, - { - name: "time too low", - config: &Config{ - Time: 0, - Memory: 64 * 1024, - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - }, - wantErr: true, - errMsg: "time must be at least 1", - }, - { - name: "memory too low", - config: &Config{ - Time: 1, - Memory: 4 * 1024, - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - }, - wantErr: true, - errMsg: "memory must be at least 8MB", - }, - { - name: "parallelism too low", - config: &Config{ - Time: 1, - Memory: 64 * 1024, - Parallelism: 0, - SaltLength: 32, - KeyLength: 32, - }, - wantErr: true, - errMsg: "parallelism must be at least 1", - }, - { - name: "salt too short", - config: &Config{ - Time: 1, - Memory: 64 * 1024, - Parallelism: 4, - SaltLength: 4, - KeyLength: 32, - }, - wantErr: true, - errMsg: "salt length must be at least 8 bytes", - }, - { - name: "key too short", - config: &Config{ - Time: 1, - Memory: 64 * 1024, - Parallelism: 4, - SaltLength: 32, - KeyLength: 8, - }, - wantErr: true, - errMsg: "key length must be at least 16 bytes", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateConfig(tc.config) - if tc.wantErr { - assert.Error(t, err) - assert.Contains(t, err.Error(), tc.errMsg) - } else { - assert.NoError(t, err) - } - }) - } -} - -func TestCompareHashes(t *testing.T) { - hash1 := []byte("hash1") - hash2 := []byte("hash1") - hash3 := []byte("hash2") - - assert.True(t, CompareHashes(hash1, hash2)) - assert.False(t, CompareHashes(hash1, hash3)) - assert.False(t, CompareHashes([]byte("short"), []byte("longer"))) -} - -func TestEstimateTime(t *testing.T) { - config := DefaultConfig() - - estimate := EstimateTime(config, 1) - assert.NotEmpty(t, estimate) - assert.True(t, strings.HasSuffix(estimate, "ms") || - strings.HasSuffix(estimate, "s") || - strings.HasSuffix(estimate, "min")) - - // Test different scales - estimate = EstimateTime(config, 100) - assert.NotEmpty(t, estimate) - - // High security config should take longer - highConfig := HighSecurityConfig() - highEstimate := EstimateTime(highConfig, 1) - assert.NotEmpty(t, highEstimate) -} - -func TestDecodeHash(t *testing.T) { - validHash := "$argon2id$v=19$m=65536,t=1,p=4$c2FsdA$aGFzaA" - - config, salt, hash, err := decodeHash(validHash) - require.NoError(t, err) - - assert.Equal(t, uint32(65536), config.Memory) - assert.Equal(t, uint32(1), config.Time) - assert.Equal(t, uint8(4), config.Parallelism) - assert.Equal(t, []byte("salt"), salt) - assert.Equal(t, []byte("hash"), hash) - - // Test invalid formats - invalidHashes := []string{ - "invalid", - "$bcrypt$v=19$m=65536,t=1,p=4$salt$hash", - "$argon2id$v=18$m=65536,t=1,p=4$salt$hash", // wrong version - "$argon2id$v=19$invalid$salt$hash", - "$argon2id$v=19$m=65536,t=1,p=4$!invalid!$hash", - } - - for _, h := range invalidHashes { - _, _, _, err := decodeHash(h) - assert.Error(t, err) - } -} - -func BenchmarkDeriveKey(b *testing.B) { - configs := map[string]*Config{ - "light": LightConfig(), - "default": DefaultConfig(), - "high": HighSecurityConfig(), - } - - password := []byte("benchmark-password") - salt := []byte("benchmark-salt-at-least-16-bytes") - - for name, config := range configs { - b.Run(name, func(b *testing.B) { - kdf := New(config) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = kdf.DeriveKey(password, salt) - } - }) - } -} - -func BenchmarkHashPassword(b *testing.B) { - kdf := New(LightConfig()) // Use light config for benchmarks - password := []byte("benchmark-password") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = kdf.HashPassword(password) - } -} - -func BenchmarkVerifyPassword(b *testing.B) { - kdf := New(LightConfig()) - password := []byte("benchmark-password") - hash, _ := kdf.HashPassword(password) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = VerifyPassword(password, hash) - } -} - -func TestConcurrentDerivation(t *testing.T) { - kdf := New(DefaultConfig()) - password := []byte("concurrent-test") - - // Generate multiple salts - salts := make([][]byte, 10) - for i := range salts { - salt, err := kdf.GenerateSalt() - require.NoError(t, err) - salts[i] = salt - } - - // Derive keys concurrently - results := make([][]byte, len(salts)) - done := make(chan int, len(salts)) - - for i, salt := range salts { - go func(idx int, s []byte) { - results[idx] = kdf.DeriveKey(password, s) - done <- idx - }(i, salt) - } - - // Wait for all goroutines - for i := 0; i < len(salts); i++ { - <-done - } - - // Verify all keys are different (different salts) - for i := 0; i < len(results)-1; i++ { - for j := i + 1; j < len(results); j++ { - assert.False(t, bytes.Equal(results[i], results[j])) - } - } -} - -func TestPerformanceBenchmark(t *testing.T) { - if testing.Short() { - t.Skip("Skipping performance benchmark in short mode") - } - - configs := []struct { - name string - config *Config - maxMs int64 - }{ - {"light", LightConfig(), 100}, - {"default", DefaultConfig(), 500}, - } - - password := []byte("perf-test") - - for _, tc := range configs { - t.Run(tc.name, func(t *testing.T) { - kdf := New(tc.config) - salt, _ := kdf.GenerateSalt() - - start := time.Now() - _ = kdf.DeriveKey(password, salt) - elapsed := time.Since(start).Milliseconds() - - t.Logf("%s config took %dms", tc.name, elapsed) - assert.Less(t, elapsed, tc.maxMs, - "derivation took too long: %dms > %dms", elapsed, tc.maxMs) - }) - } -} diff --git a/crypto/bulletproof/generators.go b/crypto/bulletproof/generators.go deleted file mode 100644 index 5246753a5..000000000 --- a/crypto/bulletproof/generators.go +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bulletproof - -import ( - "github.com/pkg/errors" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// generators contains a list of points to be used as generators for bulletproofs. -type generators []curves.Point - -// ippGenerators holds generators necessary for an Inner Product Proof -// It includes a single u generator, and a list of generators divided in half to G and H -// See lines 10 on pg 16 of https://eprint.iacr.org/2017/1066.pdf -type ippGenerators struct { - G generators - H generators -} - -// getGeneratorPoints generates generators using HashToCurve with Shake256(domain) as input -// lenVector is the length of the scalars used for the Inner Product Proof -// getGeneratorPoints will return 2*lenVector + 1 total points, split between a single u generator -// and G and H lists of vectors per the IPP specification -// See lines 10 on pg 16 of https://eprint.iacr.org/2017/1066.pdf -func getGeneratorPoints(lenVector int, domain []byte, curve curves.Curve) (*ippGenerators, error) { - shake := sha3.NewShake256() - _, err := shake.Write(domain) - if err != nil { - return nil, errors.Wrap(err, "getGeneratorPoints shake.Write") - } - numPoints := lenVector * 2 - points := make([]curves.Point, numPoints) - for i := 0; i < numPoints; i++ { - bytes := [64]byte{} - _, err := shake.Read(bytes[:]) - if err != nil { - return nil, errors.Wrap(err, "getGeneratorPoints shake.Read") - } - nextPoint := curve.Point.Hash(bytes[:]) - points[i] = nextPoint - } - // Get G and H by splitting points in half - G, H, err := splitPointVector(points) - if err != nil { - return nil, errors.Wrap(err, "getGeneratorPoints splitPointVector") - } - out := ippGenerators{G: G, H: H} - - return &out, nil -} diff --git a/crypto/bulletproof/generators_test.go b/crypto/bulletproof/generators_test.go deleted file mode 100644 index 8495c3eaa..000000000 --- a/crypto/bulletproof/generators_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package bulletproof - -import ( - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestGeneratorsHappyPath(t *testing.T) { - curve := curves.ED25519() - gs, err := getGeneratorPoints(10, []byte("test"), *curve) - gsConcatenated := concatIPPGenerators(*gs) - require.NoError(t, err) - require.Len(t, gs.G, 10) - require.Len(t, gs.H, 10) - require.True(t, noDuplicates(gsConcatenated)) -} - -func TestGeneratorsUniquePerDomain(t *testing.T) { - curve := curves.ED25519() - gs1, err := getGeneratorPoints(10, []byte("test"), *curve) - gs1Concatenated := concatIPPGenerators(*gs1) - require.NoError(t, err) - gs2, err := getGeneratorPoints(10, []byte("test2"), *curve) - gs2Concatenated := concatIPPGenerators(*gs2) - require.NoError(t, err) - require.True(t, areDisjoint(gs1Concatenated, gs2Concatenated)) -} - -func noDuplicates(gs generators) bool { - seen := map[[32]byte]bool{} - for _, G := range gs { - value := sha3.Sum256(G.ToAffineCompressed()) - if seen[value] { - return false - } - seen[value] = true - } - return true -} - -func areDisjoint(gs1, gs2 generators) bool { - for _, g1 := range gs1 { - for _, g2 := range gs2 { - if g1.Equal(g2) { - return false - } - } - } - return true -} - -func concatIPPGenerators(ippGens ippGenerators) generators { - var out generators - out = append(out, ippGens.G...) - out = append(out, ippGens.H...) - return out -} diff --git a/crypto/bulletproof/helpers.go b/crypto/bulletproof/helpers.go deleted file mode 100644 index 323da4f09..000000000 --- a/crypto/bulletproof/helpers.go +++ /dev/null @@ -1,181 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bulletproof - -import ( - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// innerProduct takes two lists of scalars (a, b) and performs the dot product returning a single scalar. -func innerProduct(a, b []curves.Scalar) (curves.Scalar, error) { - if len(a) != len(b) { - return nil, errors.New("length of scalar vectors must be the same") - } - if len(a) < 1 { - return nil, errors.New("length of vectors must be at least one") - } - // Get a new scalar of value zero of the same curve as input arguments - innerProduct := a[0].Zero() - for i, aElem := range a { - bElem := b[i] - // innerProduct = aElem*bElem + innerProduct - innerProduct = aElem.MulAdd(bElem, innerProduct) - } - - return innerProduct, nil -} - -// splitPointVector takes a vector of points, splits it in half returning each half. -func splitPointVector(points []curves.Point) ([]curves.Point, []curves.Point, error) { - if len(points) < 1 { - return nil, nil, errors.New("length of points must be at least one") - } - if len(points)&0x01 != 0 { - return nil, nil, errors.New("length of points must be even") - } - nPrime := len(points) >> 1 - firstHalf := points[:nPrime] - secondHalf := points[nPrime:] - return firstHalf, secondHalf, nil -} - -// splitScalarVector takes a vector of scalars, splits it in half returning each half. -func splitScalarVector(scalars []curves.Scalar) ([]curves.Scalar, []curves.Scalar, error) { - if len(scalars) < 1 { - return nil, nil, errors.New("length of scalars must be at least one") - } - if len(scalars)&0x01 != 0 { - return nil, nil, errors.New("length of scalars must be even") - } - nPrime := len(scalars) >> 1 - firstHalf := scalars[:nPrime] - secondHalf := scalars[nPrime:] - return firstHalf, secondHalf, nil -} - -// multiplyScalarToPointVector takes a single scalar and a list of points, multiplies each point by scalar. -func multiplyScalarToPointVector(x curves.Scalar, g []curves.Point) []curves.Point { - products := make([]curves.Point, len(g)) - for i, gElem := range g { - product := gElem.Mul(x) - products[i] = product - } - - return products -} - -// multiplyScalarToScalarVector takes a single scalar (x) and a list of scalars (a), multiplies each scalar in the vector by the scalar. -func multiplyScalarToScalarVector(x curves.Scalar, a []curves.Scalar) []curves.Scalar { - products := make([]curves.Scalar, len(a)) - for i, aElem := range a { - product := aElem.Mul(x) - products[i] = product - } - - return products -} - -// multiplyPairwisePointVectors takes two lists of points (g, h) and performs a pairwise multiplication returning a list of points. -func multiplyPairwisePointVectors(g, h []curves.Point) ([]curves.Point, error) { - if len(g) != len(h) { - return nil, errors.New("length of point vectors must be the same") - } - product := make([]curves.Point, len(g)) - for i, gElem := range g { - product[i] = gElem.Add(h[i]) - } - - return product, nil -} - -// multiplyPairwiseScalarVectors takes two lists of points (a, b) and performs a pairwise multiplication returning a list of scalars. -func multiplyPairwiseScalarVectors(a, b []curves.Scalar) ([]curves.Scalar, error) { - if len(a) != len(b) { - return nil, errors.New("length of point vectors must be the same") - } - product := make([]curves.Scalar, len(a)) - for i, aElem := range a { - product[i] = aElem.Mul(b[i]) - } - - return product, nil -} - -// addPairwiseScalarVectors takes two lists of scalars (a, b) and performs a pairwise addition returning a list of scalars. -func addPairwiseScalarVectors(a, b []curves.Scalar) ([]curves.Scalar, error) { - if len(a) != len(b) { - return nil, errors.New("length of scalar vectors must be the same") - } - sum := make([]curves.Scalar, len(a)) - for i, aElem := range a { - sum[i] = aElem.Add(b[i]) - } - - return sum, nil -} - -// subtractPairwiseScalarVectors takes two lists of scalars (a, b) and performs a pairwise subtraction returning a list of scalars. -func subtractPairwiseScalarVectors(a, b []curves.Scalar) ([]curves.Scalar, error) { - if len(a) != len(b) { - return nil, errors.New("length of scalar vectors must be the same") - } - diff := make([]curves.Scalar, len(a)) - for i, aElem := range a { - diff[i] = aElem.Sub(b[i]) - } - return diff, nil -} - -// invertScalars takes a list of scalars then returns a list with each element inverted. -func invertScalars(xs []curves.Scalar) ([]curves.Scalar, error) { - xinvs := make([]curves.Scalar, len(xs)) - for i, x := range xs { - xinv, err := x.Invert() - if err != nil { - return nil, errors.Wrap(err, "bulletproof helpers invertx") - } - xinvs[i] = xinv - } - - return xinvs, nil -} - -// isPowerOfTwo returns whether a number i is a power of two or not. -func isPowerOfTwo(i int) bool { - return i&(i-1) == 0 -} - -// get2nVector returns a scalar vector 2^n such that [1, 2, 4, ... 2^(n-1)] -// See k^n and 2^n definitions on pg 12 of https://eprint.iacr.org/2017/1066.pdf -func get2nVector(length int, curve curves.Curve) []curves.Scalar { - vector2n := make([]curves.Scalar, length) - vector2n[0] = curve.Scalar.One() - for i := 1; i < length; i++ { - vector2n[i] = vector2n[i-1].Double() - } - return vector2n -} - -func get1nVector(length int, curve curves.Curve) []curves.Scalar { - vector1n := make([]curves.Scalar, length) - for i := 0; i < length; i++ { - vector1n[i] = curve.Scalar.One() - } - return vector1n -} - -func getknVector(k curves.Scalar, length int, curve curves.Curve) []curves.Scalar { - vectorkn := make([]curves.Scalar, length) - vectorkn[0] = curve.Scalar.One() - vectorkn[1] = k - for i := 2; i < length; i++ { - vectorkn[i] = vectorkn[i-1].Mul(k) - } - return vectorkn -} diff --git a/crypto/bulletproof/helpers_test.go b/crypto/bulletproof/helpers_test.go deleted file mode 100644 index 8ae037e67..000000000 --- a/crypto/bulletproof/helpers_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestInnerProductHappyPath(t *testing.T) { - curve := curves.ED25519() - a := randScalarVec(3, *curve) - b := randScalarVec(3, *curve) - _, err := innerProduct(a, b) - require.NoError(t, err) -} - -func TestInnerProductMismatchedLengths(t *testing.T) { - curve := curves.ED25519() - a := randScalarVec(3, *curve) - b := randScalarVec(4, *curve) - _, err := innerProduct(a, b) - require.Error(t, err) -} - -func TestInnerProductEmptyVector(t *testing.T) { - curve := curves.ED25519() - a := randScalarVec(0, *curve) - b := randScalarVec(0, *curve) - _, err := innerProduct(a, b) - require.Error(t, err) -} - -func TestInnerProductOut(t *testing.T) { - curve := curves.ED25519() - a := randScalarVec(2, *curve) - b := randScalarVec(2, *curve) - c, err := innerProduct(a, b) - require.NoError(t, err) - - // Calculate manually a0*b0 + a1*b1 - cPrime := a[0].Mul(b[0]).Add(a[1].Mul(b[1])) - require.Equal(t, c, cPrime) -} - -func TestSplitListofPointsHappyPath(t *testing.T) { - curve := curves.ED25519() - points := randPointVec(10, *curve) - firstHalf, secondHalf, err := splitPointVector(points) - require.NoError(t, err) - require.Len(t, firstHalf, 5) - require.Len(t, secondHalf, 5) -} - -func TestSplitListofPointsOddLength(t *testing.T) { - curve := curves.ED25519() - points := randPointVec(11, *curve) - _, _, err := splitPointVector(points) - require.Error(t, err) -} - -func TestSplitListofPointsZeroLength(t *testing.T) { - curve := curves.ED25519() - points := randPointVec(0, *curve) - _, _, err := splitPointVector(points) - require.Error(t, err) -} - -func randScalarVec(length int, curve curves.Curve) []curves.Scalar { - out := make([]curves.Scalar, length) - for i := 0; i < length; i++ { - out[i] = curve.Scalar.Random(crand.Reader) - } - return out -} - -func randPointVec(length int, curve curves.Curve) []curves.Point { - out := make([]curves.Point, length) - for i := 0; i < length; i++ { - out[i] = curve.Point.Random(crand.Reader) - } - return out -} diff --git a/crypto/bulletproof/ipp_prover.go b/crypto/bulletproof/ipp_prover.go deleted file mode 100644 index 3633d279c..000000000 --- a/crypto/bulletproof/ipp_prover.go +++ /dev/null @@ -1,415 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package bulletproof implements the zero knowledge protocol bulletproofs as defined in https://eprint.iacr.org/2017/1066.pdf -package bulletproof - -import ( - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// InnerProductProver is the struct used to create InnerProductProofs -// It specifies which curve to use and holds precomputed generators -// See NewInnerProductProver() for prover initialization. -type InnerProductProver struct { - curve curves.Curve - generators ippGenerators -} - -// InnerProductProof contains necessary output for the inner product proof -// a and b are the final input vectors of scalars, they should be of length 1 -// Ls and Rs are calculated per recursion of the IPP and are necessary for verification -// See section 3.1 on pg 15 of https://eprint.iacr.org/2017/1066.pdf -type InnerProductProof struct { - a, b curves.Scalar - capLs, capRs []curves.Point - curve *curves.Curve -} - -// ippRecursion is the same as IPP but tracks recursive a', b', g', h' and Ls and Rs -// It should only be used internally by InnerProductProver.Prove() -// See L35 on pg 16 of https://eprint.iacr.org/2017/1066.pdf -type ippRecursion struct { - a, b []curves.Scalar - c curves.Scalar - capLs, capRs []curves.Point - g, h []curves.Point - u, capP curves.Point - transcript *merlin.Transcript -} - -// NewInnerProductProver initializes a new prover -// It uses the specified domain to generate generators for vectors of at most maxVectorLength -// A prover can be used to construct inner product proofs for vectors of length less than or equal to maxVectorLength -// A prover is defined by an explicit curve. -func NewInnerProductProver( - maxVectorLength int, - domain []byte, - curve curves.Curve, -) (*InnerProductProver, error) { - generators, err := getGeneratorPoints(maxVectorLength, domain, curve) - if err != nil { - return nil, errors.Wrap(err, "ipp getGenerators") - } - return &InnerProductProver{curve: curve, generators: *generators}, nil -} - -// NewInnerProductProof initializes a new InnerProductProof for a specified curve -// This should be used in tandem with UnmarshalBinary() to convert a marshaled proof into the struct. -func NewInnerProductProof(curve *curves.Curve) *InnerProductProof { - var capLs, capRs []curves.Point - newProof := InnerProductProof{ - a: curve.NewScalar(), - b: curve.NewScalar(), - capLs: capLs, - capRs: capRs, - curve: curve, - } - return &newProof -} - -// rangeToIPP takes the output of a range proof and converts it into an inner product proof -// See section 4.2 on pg 20 -// The conversion specifies generators to use (g and hPrime), as well as the two vectors l, r of which the inner product is tHat -// Additionally, note that the P used for the IPP is in fact P*h^-mu from the range proof. -func (prover *InnerProductProver) rangeToIPP( - proofG, proofH []curves.Point, - l, r []curves.Scalar, - tHat curves.Scalar, - capPhmuinv, u curves.Point, - transcript *merlin.Transcript, -) (*InnerProductProof, error) { - // Note that P as a witness is only g^l * h^r - // P needs to be in the form of g^l * h^r * u^ - // Calculate the final P including the u^ term - utHat := u.Mul(tHat) - capP := capPhmuinv.Add(utHat) - - // Use params to prove inner product - recursionParams := &ippRecursion{ - a: l, - b: r, - capLs: []curves.Point{}, - capRs: []curves.Point{}, - c: tHat, - g: proofG, - h: proofH, - capP: capP, - u: u, - transcript: transcript, - } - - return prover.proveRecursive(recursionParams) -} - -// getP returns the initial P value given two scalars a,b and point u -// This method should only be used for testing -// See (3) on page 13 of https://eprint.iacr.org/2017/1066.pdf -func (prover *InnerProductProver) getP(a, b []curves.Scalar, u curves.Point) (curves.Point, error) { - // Vectors must have length power of two - if !isPowerOfTwo(len(a)) { - return nil, errors.New("ipp vector length must be power of two") - } - // Generator vectors must be same length - if len(prover.generators.G) != len(prover.generators.H) { - return nil, errors.New("ipp generator lengths of g and h must be equal") - } - // Inner product requires len(a) == len(b) else error is returned - c, err := innerProduct(a, b) - if err != nil { - return nil, errors.Wrap(err, "ipp getInnerProduct") - } - - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := prover.generators.G[0:len(a)] - proofH := prover.generators.H[0:len(b)] - - // initial P = g^a * h^b * u^(a dot b) (See (3) on page 13 of https://eprint.iacr.org/2017/1066.pdf) - ga := prover.curve.NewGeneratorPoint().SumOfProducts(proofG, a) - hb := prover.curve.NewGeneratorPoint().SumOfProducts(proofH, b) - uadotb := u.Mul(c) - capP := ga.Add(hb).Add(uadotb) - - return capP, nil -} - -// Prove executes the prover protocol on pg 16 of https://eprint.iacr.org/2017/1066.pdf -// It generates an inner product proof for vectors a and b, using u to blind the inner product in P -// A transcript is used for the Fiat Shamir heuristic. -func (prover *InnerProductProver) Prove( - a, b []curves.Scalar, - u curves.Point, - transcript *merlin.Transcript, -) (*InnerProductProof, error) { - // Vectors must have length power of two - if !isPowerOfTwo(len(a)) { - return nil, errors.New("ipp vector length must be power of two") - } - // Generator vectors must be same length - if len(prover.generators.G) != len(prover.generators.H) { - return nil, errors.New("ipp generator lengths of g and h must be equal") - } - // Inner product requires len(a) == len(b) else error is returned - c, err := innerProduct(a, b) - if err != nil { - return nil, errors.Wrap(err, "ipp getInnerProduct") - } - - // Length of vectors must be less than the number of generators generated - if len(a) > len(prover.generators.G) { - return nil, errors.New("ipp vector length must be less than maxVectorLength") - } - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := prover.generators.G[0:len(a)] - proofH := prover.generators.H[0:len(b)] - - // initial P = g^a * h^b * u^(a dot b) (See (3) on page 13 of https://eprint.iacr.org/2017/1066.pdf) - ga := prover.curve.NewGeneratorPoint().SumOfProducts(proofG, a) - hb := prover.curve.NewGeneratorPoint().SumOfProducts(proofH, b) - uadotb := u.Mul(c) - capP := ga.Add(hb).Add(uadotb) - - recursionParams := &ippRecursion{ - a: a, - b: b, - capLs: []curves.Point{}, - capRs: []curves.Point{}, - c: c, - g: proofG, - h: proofH, - capP: capP, - u: u, - transcript: transcript, - } - return prover.proveRecursive(recursionParams) -} - -// proveRecursive executes the recursion on pg 16 of https://eprint.iacr.org/2017/1066.pdf -func (prover *InnerProductProver) proveRecursive( - recursionParams *ippRecursion, -) (*InnerProductProof, error) { - // length checks - if len(recursionParams.a) != len(recursionParams.b) { - return nil, errors.New("ipp proveRecursive a and b different lengths") - } - if len(recursionParams.g) != len(recursionParams.h) { - return nil, errors.New("ipp proveRecursive g and h different lengths") - } - if len(recursionParams.a) != len(recursionParams.g) { - return nil, errors.New("ipp proveRecursive scalar and point vectors different lengths") - } - // Base case (L14, pg16 of https://eprint.iacr.org/2017/1066.pdf) - if len(recursionParams.a) == 1 { - proof := &InnerProductProof{ - a: recursionParams.a[0], - b: recursionParams.b[0], - capLs: recursionParams.capLs, - capRs: recursionParams.capRs, - curve: &prover.curve, - } - return proof, nil - } - - // Split current state into low (first half) vs high (second half) vectors - aLo, aHi, err := splitScalarVector(recursionParams.a) - if err != nil { - return nil, errors.Wrap(err, "recursionParams splitScalarVector") - } - bLo, bHi, err := splitScalarVector(recursionParams.b) - if err != nil { - return nil, errors.Wrap(err, "recursionParams splitScalarVector") - } - gLo, gHi, err := splitPointVector(recursionParams.g) - if err != nil { - return nil, errors.Wrap(err, "recursionParams splitPointVector") - } - hLo, hHi, err := splitPointVector(recursionParams.h) - if err != nil { - return nil, errors.Wrap(err, "recursionParams splitPointVector") - } - - // c_l, c_r (L21,22, pg16 of https://eprint.iacr.org/2017/1066.pdf) - cL, err := innerProduct(aLo, bHi) - if err != nil { - return nil, errors.Wrap(err, "recursionParams innerProduct") - } - - cR, err := innerProduct(aHi, bLo) - if err != nil { - return nil, errors.Wrap(err, "recursionParams innerProduct") - } - - // L, R (L23,24, pg16 of https://eprint.iacr.org/2017/1066.pdf) - lga := prover.curve.Point.SumOfProducts(gHi, aLo) - lhb := prover.curve.Point.SumOfProducts(hLo, bHi) - ucL := recursionParams.u.Mul(cL) - capL := lga.Add(lhb).Add(ucL) - - rga := prover.curve.Point.SumOfProducts(gLo, aHi) - rhb := prover.curve.Point.SumOfProducts(hHi, bLo) - ucR := recursionParams.u.Mul(cR) - capR := rga.Add(rhb).Add(ucR) - - // Add L,R for verifier to use to calculate final g, h - newL := recursionParams.capLs - newL = append(newL, capL) - newR := recursionParams.capRs - newR = append(newR, capR) - - // Get x from L, R for non-interactive (See section 4.4 pg22 of https://eprint.iacr.org/2017/1066.pdf) - // Note this replaces the interactive model, i.e. L36-28 of pg16 of https://eprint.iacr.org/2017/1066.pdf - x, err := prover.calcx(capL, capR, recursionParams.transcript) - if err != nil { - return nil, errors.Wrap(err, "recursionParams calcx") - } - - // Calculate recursive inputs - xInv, err := x.Invert() - if err != nil { - return nil, errors.Wrap(err, "recursionParams x.Invert") - } - - // g', h' (L29,30, pg16 of https://eprint.iacr.org/2017/1066.pdf) - gLoxInverse := multiplyScalarToPointVector(xInv, gLo) - gHix := multiplyScalarToPointVector(x, gHi) - gPrime, err := multiplyPairwisePointVectors(gLoxInverse, gHix) - if err != nil { - return nil, errors.Wrap(err, "recursionParams multiplyPairwisePointVectors") - } - - hLox := multiplyScalarToPointVector(x, hLo) - hHixInv := multiplyScalarToPointVector(xInv, hHi) - hPrime, err := multiplyPairwisePointVectors(hLox, hHixInv) - if err != nil { - return nil, errors.Wrap(err, "recursionParams multiplyPairwisePointVectors") - } - - // P' (L31, pg16 of https://eprint.iacr.org/2017/1066.pdf) - xSquare := x.Square() - xInvSquare := xInv.Square() - LxSquare := capL.Mul(xSquare) - RxInvSquare := capR.Mul(xInvSquare) - PPrime := LxSquare.Add(recursionParams.capP).Add(RxInvSquare) - - // a', b' (L33, 34, pg16 of https://eprint.iacr.org/2017/1066.pdf) - aLox := multiplyScalarToScalarVector(x, aLo) - aHixIn := multiplyScalarToScalarVector(xInv, aHi) - aPrime, err := addPairwiseScalarVectors(aLox, aHixIn) - if err != nil { - return nil, errors.Wrap(err, "recursionParams addPairwiseScalarVectors") - } - - bLoxInv := multiplyScalarToScalarVector(xInv, bLo) - bHix := multiplyScalarToScalarVector(x, bHi) - bPrime, err := addPairwiseScalarVectors(bLoxInv, bHix) - if err != nil { - return nil, errors.Wrap(err, "recursionParams addPairwiseScalarVectors") - } - - // c' - cPrime, err := innerProduct(aPrime, bPrime) - if err != nil { - return nil, errors.Wrap(err, "recursionParams innerProduct") - } - - // Make recursive call (L35, pg16 of https://eprint.iacr.org/2017/1066.pdf) - recursiveIPP := &ippRecursion{ - a: aPrime, - b: bPrime, - capLs: newL, - capRs: newR, - c: cPrime, - g: gPrime, - h: hPrime, - capP: PPrime, - u: recursionParams.u, - transcript: recursionParams.transcript, - } - - out, err := prover.proveRecursive(recursiveIPP) - if err != nil { - return nil, errors.Wrap(err, "recursionParams proveRecursive") - } - return out, nil -} - -// calcx uses a merlin transcript for Fiat Shamir -// For each recursion, it takes the current state of the transcript and appends the newly calculated L and R values -// A new scalar is then read from the transcript -// See section 4.4 pg22 of https://eprint.iacr.org/2017/1066.pdf -func (prover *InnerProductProver) calcx( - capL, capR curves.Point, - transcript *merlin.Transcript, -) (curves.Scalar, error) { - // Add the newest capL and capR values to transcript - transcript.AppendMessage([]byte("addRecursiveL"), capL.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addRecursiveR"), capR.ToAffineUncompressed()) - // Read 64 bytes from, set to scalar - outBytes := transcript.ExtractBytes([]byte("getx"), 64) - x, err := prover.curve.NewScalar().SetBytesWide(outBytes) - if err != nil { - return nil, errors.Wrap(err, "calcx NewScalar SetBytesWide") - } - - return x, nil -} - -// MarshalBinary takes an inner product proof and marshals into bytes. -func (proof *InnerProductProof) MarshalBinary() []byte { - var out []byte - out = append(out, proof.a.Bytes()...) - out = append(out, proof.b.Bytes()...) - for i, capLElem := range proof.capLs { - capRElem := proof.capRs[i] - out = append(out, capLElem.ToAffineCompressed()...) - out = append(out, capRElem.ToAffineCompressed()...) - } - return out -} - -// UnmarshalBinary takes bytes of a marshaled proof and writes them into an inner product proof -// The inner product proof used should be from the output of NewInnerProductProof(). -func (proof *InnerProductProof) UnmarshalBinary(data []byte) error { - scalarLen := len(proof.curve.NewScalar().Bytes()) - pointLen := len(proof.curve.NewGeneratorPoint().ToAffineCompressed()) - ptr := 0 - // Get scalars - a, err := proof.curve.NewScalar().SetBytes(data[ptr : ptr+scalarLen]) - if err != nil { - return errors.New("innerProductProof UnmarshalBinary SetBytes") - } - proof.a = a - ptr += scalarLen - b, err := proof.curve.NewScalar().SetBytes(data[ptr : ptr+scalarLen]) - if err != nil { - return errors.New("innerProductProof UnmarshalBinary SetBytes") - } - proof.b = b - ptr += scalarLen - // Get points - var capLs, capRs []curves.Point //nolint:prealloc // pointer arithmetic makes it too unreadable. - for ptr < len(data) { - capLElem, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("innerProductProof UnmarshalBinary FromAffineCompressed") - } - capLs = append(capLs, capLElem) - ptr += pointLen - capRElem, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("innerProductProof UnmarshalBinary FromAffineCompressed") - } - capRs = append(capRs, capRElem) - ptr += pointLen - } - proof.capLs = capLs - proof.capRs = capRs - - return nil -} diff --git a/crypto/bulletproof/ipp_prover_test.go b/crypto/bulletproof/ipp_prover_test.go deleted file mode 100644 index 3a9762ba4..000000000 --- a/crypto/bulletproof/ipp_prover_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestIPPHappyPath(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(8, *curve) - b := randScalarVec(8, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(a, b, u, transcript) - require.NoError(t, err) - require.Equal(t, 3, len(proof.capLs)) - require.Equal(t, 3, len(proof.capRs)) -} - -func TestIPPMismatchedVectors(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(4, *curve) - b := randScalarVec(8, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - _, err = prover.Prove(a, b, u, transcript) - require.Error(t, err) -} - -func TestIPPNonPowerOfTwoLengthVectors(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(3, *curve) - b := randScalarVec(3, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - _, err = prover.Prove(a, b, u, transcript) - require.Error(t, err) -} - -func TestIPPZeroLengthVectors(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(0, *curve) - b := randScalarVec(0, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - _, err = prover.Prove(a, b, u, transcript) - require.Error(t, err) -} - -func TestIPPGreaterThanMaxLengthVectors(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(16, *curve) - b := randScalarVec(16, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - _, err = prover.Prove(a, b, u, transcript) - require.Error(t, err) -} - -func TestIPPMarshal(t *testing.T) { - curve := curves.ED25519() - prover, err := NewInnerProductProver(8, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(8, *curve) - b := randScalarVec(8, *curve) - u := curve.Point.Random(crand.Reader) - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(a, b, u, transcript) - require.NoError(t, err) - - proofMarshaled := proof.MarshalBinary() - proofPrime := NewInnerProductProof(curve) - err = proofPrime.UnmarshalBinary(proofMarshaled) - require.NoError(t, err) - require.Zero(t, proof.a.Cmp(proofPrime.a)) - require.Zero(t, proof.b.Cmp(proofPrime.b)) - for i, proofCapLElem := range proof.capLs { - proofPrimeCapLElem := proofPrime.capLs[i] - require.True(t, proofCapLElem.Equal(proofPrimeCapLElem)) - proofCapRElem := proof.capRs[i] - proofPrimeCapRElem := proofPrime.capRs[i] - require.True(t, proofCapRElem.Equal(proofPrimeCapRElem)) - } -} diff --git a/crypto/bulletproof/ipp_verifier.go b/crypto/bulletproof/ipp_verifier.go deleted file mode 100644 index 046c91e9f..000000000 --- a/crypto/bulletproof/ipp_verifier.go +++ /dev/null @@ -1,236 +0,0 @@ -package bulletproof - -import ( - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// InnerProductVerifier is the struct used to verify inner product proofs -// It specifies which curve to use and holds precomputed generators -// See NewInnerProductProver() for prover initialization. -type InnerProductVerifier struct { - curve curves.Curve - generators ippGenerators -} - -// NewInnerProductVerifier initializes a new verifier -// It uses the specified domain to generate generators for vectors of at most maxVectorLength -// A verifier can be used to verify inner product proofs for vectors of length less than or equal to maxVectorLength -// A verifier is defined by an explicit curve. -func NewInnerProductVerifier( - maxVectorLength int, - domain []byte, - curve curves.Curve, -) (*InnerProductVerifier, error) { - generators, err := getGeneratorPoints(maxVectorLength, domain, curve) - if err != nil { - return nil, errors.Wrap(err, "ipp getGenerators") - } - return &InnerProductVerifier{curve: curve, generators: *generators}, nil -} - -// Verify verifies the given proof inputs -// It implements the final comparison of section 3.1 on pg17 of https://eprint.iacr.org/2017/1066.pdf -func (verifier *InnerProductVerifier) Verify( - capP, u curves.Point, - proof *InnerProductProof, - transcript *merlin.Transcript, -) (bool, error) { - if len(proof.capLs) != len(proof.capRs) { - return false, errors.New("ipp capLs and capRs must be same length") - } - // Generator vectors must be same length - if len(verifier.generators.G) != len(verifier.generators.H) { - return false, errors.New("ipp generator lengths of g and h must be equal") - } - - // Get generators for each elem in a, b and one more for u - // len(Ls) = log n, therefore can just exponentiate - n := 1 << len(proof.capLs) - - // Length of vectors must be less than the number of generators generated - if n > len(verifier.generators.G) { - return false, errors.New("ipp vector length must be less than maxVectorLength") - } - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := verifier.generators.G[0:n] - proofH := verifier.generators.H[0:n] - - xs, err := getxs(transcript, proof.capLs, proof.capRs, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "verifier getxs") - } - s, err := verifier.getsNew(xs, n) - if err != nil { - return false, errors.Wrap(err, "verifier getss") - } - lhs, err := verifier.getLHS(u, proof, proofG, proofH, s) - if err != nil { - return false, errors.Wrap(err, "verify getLHS") - } - rhs, err := verifier.getRHS(capP, proof, xs) - if err != nil { - return false, errors.Wrap(err, "verify getRHS") - } - return lhs.Equal(rhs), nil -} - -// Verify verifies the given proof inputs -// It implements the final comparison of section 3.1 on pg17 of https://eprint.iacr.org/2017/1066.pdf -func (verifier *InnerProductVerifier) VerifyFromRangeProof( - proofG, proofH []curves.Point, - capPhmuinv, u curves.Point, - tHat curves.Scalar, - proof *InnerProductProof, - transcript *merlin.Transcript, -) (bool, error) { - // Get generators for each elem in a, b and one more for u - // len(Ls) = log n, therefore can just exponentiate - n := 1 << len(proof.capLs) - - xs, err := getxs(transcript, proof.capLs, proof.capRs, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "verifier getxs") - } - s, err := verifier.gets(xs, n) - if err != nil { - return false, errors.Wrap(err, "verifier getss") - } - lhs, err := verifier.getLHS(u, proof, proofG, proofH, s) - if err != nil { - return false, errors.Wrap(err, "verify getLHS") - } - utHat := u.Mul(tHat) - capP := capPhmuinv.Add(utHat) - rhs, err := verifier.getRHS(capP, proof, xs) - if err != nil { - return false, errors.Wrap(err, "verify getRHS") - } - return lhs.Equal(rhs), nil -} - -// getRHS gets the right hand side of the final comparison of section 3.1 on pg17. -func (*InnerProductVerifier) getRHS( - capP curves.Point, - proof *InnerProductProof, - xs []curves.Scalar, -) (curves.Point, error) { - product := capP - for j, Lj := range proof.capLs { - Rj := proof.capRs[j] - xj := xs[j] - xjSquare := xj.Square() - xjSquareInv, err := xjSquare.Invert() - if err != nil { - return nil, errors.Wrap(err, "verify invert") - } - LjxjSquare := Lj.Mul(xjSquare) - RjxjSquareInv := Rj.Mul(xjSquareInv) - product = product.Add(LjxjSquare).Add(RjxjSquareInv) - } - return product, nil -} - -// getLHS gets the left hand side of the final comparison of section 3.1 on pg17. -func (verifier *InnerProductVerifier) getLHS( - u curves.Point, - proof *InnerProductProof, - g, h []curves.Point, - s []curves.Scalar, -) (curves.Point, error) { - sInv, err := invertScalars(s) - if err != nil { - return nil, errors.Wrap(err, "verify invertScalars") - } - // g^(a*s) - as := multiplyScalarToScalarVector(proof.a, s) - gas := verifier.curve.Point.SumOfProducts(g, as) - // h^(b*s^-1) - bsInv := multiplyScalarToScalarVector(proof.b, sInv) - hbsInv := verifier.curve.Point.SumOfProducts(h, bsInv) - // u^a*b - ab := proof.a.Mul(proof.b) - uab := u.Mul(ab) - // g^(a*s) * h^(b*s^-1) * u^a*b - out := gas.Add(hbsInv).Add(uab) - - return out, nil -} - -// getxs calculates the x values from Ls and Rs -// Note that each x is read from the transcript, then the L and R at a certain index are written to the transcript -// This mirrors the reading of xs and writing of Ls and Rs in the prover. -func getxs( - transcript *merlin.Transcript, - capLs, capRs []curves.Point, - curve curves.Curve, -) ([]curves.Scalar, error) { - xs := make([]curves.Scalar, len(capLs)) - for i, capLi := range capLs { - capRi := capRs[i] - // Add the newest L and R values to transcript - transcript.AppendMessage([]byte("addRecursiveL"), capLi.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addRecursiveR"), capRi.ToAffineUncompressed()) - // Read 64 bytes from, set to scalar - outBytes := transcript.ExtractBytes([]byte("getx"), 64) - x, err := curve.NewScalar().SetBytesWide(outBytes) - if err != nil { - return nil, errors.Wrap(err, "calcx NewScalar SetBytesWide") - } - xs[i] = x - } - - return xs, nil -} - -// gets calculates the vector s of values used for verification -// See the second expression of section 3.1 on pg15 -// nolint -func (verifier *InnerProductVerifier) gets(xs []curves.Scalar, n int) ([]curves.Scalar, error) { - ss := make([]curves.Scalar, n) - for i := 0; i < n; i++ { - si := verifier.curve.Scalar.One() - for j, xj := range xs { - if i>>(len(xs)-j-1)&0x01 == 1 { - si = si.Mul(xj) - } else { - xjInverse, err := xj.Invert() - if err != nil { - return nil, errors.Wrap(err, "getss invert") - } - si = si.Mul(xjInverse) - } - } - ss[i] = si - } - - return ss, nil -} - -// getsNew calculates the vector s of values used for verification -// It provides analogous functionality as gets(), but uses a O(n) algorithm vs O(nlogn) -// The algorithm inverts all xs, then begins multiplying the inversion by the square of x elements to -// calculate all s values thus minimizing necessary inversions/ computation. -func (verifier *InnerProductVerifier) getsNew(xs []curves.Scalar, n int) ([]curves.Scalar, error) { - var err error - ss := make([]curves.Scalar, n) - // First element is all xs inverted mul'd - ss[0] = verifier.curve.Scalar.One() - for _, xj := range xs { - ss[0] = ss[0].Mul(xj) - } - ss[0], err = ss[0].Invert() - if err != nil { - return nil, errors.Wrap(err, "ipp gets inv ss0") - } - for j, xj := range xs { - xjSquared := xj.Square() - for i := 0; i < n; i += 1 << (len(xs) - j) { - ss[i+1<<(len(xs)-j-1)] = ss[i].Mul(xjSquared) - } - } - - return ss, nil -} diff --git a/crypto/bulletproof/ipp_verifier_test.go b/crypto/bulletproof/ipp_verifier_test.go deleted file mode 100644 index b386a6d30..000000000 --- a/crypto/bulletproof/ipp_verifier_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestIPPVerifyHappyPath(t *testing.T) { - curve := curves.ED25519() - vecLength := 256 - prover, err := NewInnerProductProver(vecLength, []byte("test"), *curve) - require.NoError(t, err) - a := randScalarVec(vecLength, *curve) - b := randScalarVec(vecLength, *curve) - u := curve.Point.Random(crand.Reader) - transcriptProver := merlin.NewTranscript("test") - proof, err := prover.Prove(a, b, u, transcriptProver) - require.NoError(t, err) - - verifier, err := NewInnerProductVerifier(vecLength, []byte("test"), *curve) - require.NoError(t, err) - capP, err := prover.getP(a, b, u) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - verified, err := verifier.Verify(capP, u, proof, transcriptVerifier) - require.NoError(t, err) - require.True(t, verified) -} - -func BenchmarkIPPVerification(bench *testing.B) { - curve := curves.ED25519() - vecLength := 1024 - prover, _ := NewInnerProductProver(vecLength, []byte("test"), *curve) - a := randScalarVec(vecLength, *curve) - b := randScalarVec(vecLength, *curve) - u := curve.Point.Random(crand.Reader) - transcriptProver := merlin.NewTranscript("test") - proof, _ := prover.Prove(a, b, u, transcriptProver) - - verifier, _ := NewInnerProductVerifier(vecLength, []byte("test"), *curve) - capP, _ := prover.getP(a, b, u) - transcriptVerifier := merlin.NewTranscript("test") - verified, _ := verifier.Verify(capP, u, proof, transcriptVerifier) - require.True(bench, verified) -} - -func TestIPPVerifyInvalidProof(t *testing.T) { - curve := curves.ED25519() - vecLength := 64 - prover, err := NewInnerProductProver(vecLength, []byte("test"), *curve) - require.NoError(t, err) - - a := randScalarVec(vecLength, *curve) - b := randScalarVec(vecLength, *curve) - u := curve.Point.Random(crand.Reader) - - aPrime := randScalarVec(64, *curve) - bPrime := randScalarVec(64, *curve) - uPrime := curve.Point.Random(crand.Reader) - transcriptProver := merlin.NewTranscript("test") - - proofPrime, err := prover.Prove(aPrime, bPrime, uPrime, transcriptProver) - require.NoError(t, err) - - verifier, err := NewInnerProductVerifier(vecLength, []byte("test"), *curve) - require.NoError(t, err) - capP, err := prover.getP(a, b, u) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - // Check for different capP, u from proof - verified, err := verifier.Verify(capP, u, proofPrime, transcriptVerifier) - require.NoError(t, err) - require.False(t, verified) -} diff --git a/crypto/bulletproof/range_batch_prover.go b/crypto/bulletproof/range_batch_prover.go deleted file mode 100644 index 82cd14343..000000000 --- a/crypto/bulletproof/range_batch_prover.go +++ /dev/null @@ -1,386 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// BatchProve proves that a list of scalars v are in the range n. -// It implements the aggregating logarithmic proofs defined on pg21. -// Instead of taking a single value and a single blinding factor, BatchProve takes in a list of values and list of -// blinding factors. -func (prover *RangeProver) BatchProve( - v, gamma []curves.Scalar, - n int, - proofGenerators RangeProofGenerators, - transcript *merlin.Transcript, -) (*RangeProof, error) { - // Define nm as the total bits required for secrets, calculated as number of secrets * n - m := len(v) - nm := n * m - // nm must be less than or equal to the number of generators generated - if nm > len(prover.generators.G) { - return nil, errors.New("ipp vector length must be less than or equal to maxVectorLength") - } - - // In case where nm is less than number of generators precomputed by prover, trim to length - proofG := prover.generators.G[0:nm] - proofH := prover.generators.H[0:nm] - - // Check that each elem in v is in range [0, 2^n] - for _, vi := range v { - checkedRange := checkRange(vi, n) - if checkedRange != nil { - return nil, checkedRange - } - } - - // L40 on pg19 - aL, err := getaLBatched(v, n, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - onenm := get1nVector(nm, prover.curve) - // L41 on pg19 - aR, err := subtractPairwiseScalarVectors(aL, onenm) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - alpha := prover.curve.Scalar.Random(crand.Reader) - // Calc A (L44, pg19) - halpha := proofGenerators.h.Mul(alpha) - gaL := prover.curve.Point.SumOfProducts(proofG, aL) - haR := prover.curve.Point.SumOfProducts(proofH, aR) - capA := halpha.Add(gaL).Add(haR) - - // L45, 46, pg19 - sL := getBlindingVector(nm, prover.curve) - sR := getBlindingVector(nm, prover.curve) - rho := prover.curve.Scalar.Random(crand.Reader) - - // Calc S (L47, pg19) - hrho := proofGenerators.h.Mul(rho) - gsL := prover.curve.Point.SumOfProducts(proofG, sL) - hsR := prover.curve.Point.SumOfProducts(proofH, sR) - capS := hrho.Add(gsL).Add(hsR) - - // Fiat Shamir for y,z (L49, pg19) - capV := getcapVBatched(v, gamma, proofGenerators.g, proofGenerators.h) - y, z, err := calcyzBatched(capV, capA, capS, transcript, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc t_1, t_2 - // See the l(X), r(X), equations on pg 21 - // Use l(X)'s and r(X)'s constant and linear terms to derive t_1 and t_2 - // (a_l - z*1^n) - zonenm := multiplyScalarToScalarVector(z, onenm) - constantTerml, err := subtractPairwiseScalarVectors(aL, zonenm) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - linearTerml := sL - - // zSum term, see equation 71 on pg21 - zSum := getSumTermrXBatched(z, n, len(v), prover.curve) - // a_r + z*1^nm - aRPluszonenm, err := addPairwiseScalarVectors(aR, zonenm) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - ynm := getknVector(y, nm, prover.curve) - hadamard, err := multiplyPairwiseScalarVectors(ynm, aRPluszonenm) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - constantTermr, err := addPairwiseScalarVectors(hadamard, zSum) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - linearTermr, err := multiplyPairwiseScalarVectors(ynm, sR) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // t_1 (as the linear coefficient) is the sum of the dot products of l(X)'s linear term dot r(X)'s constant term - // and r(X)'s linear term dot l(X)'s constant term - t1FirstTerm, err := innerProduct(linearTerml, constantTermr) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t1SecondTerm, err := innerProduct(linearTermr, constantTerml) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t1 := t1FirstTerm.Add(t1SecondTerm) - - // t_2 (as the quadratic coefficient) is the dot product of l(X)'s and r(X)'s linear terms - t2, err := innerProduct(linearTerml, linearTermr) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // L52, pg20 - tau1 := prover.curve.Scalar.Random(crand.Reader) - tau2 := prover.curve.Scalar.Random(crand.Reader) - - // T_1, T_2 (L53, pg20) - capT1 := proofGenerators.g.Mul(t1).Add(proofGenerators.h.Mul(tau1)) - capT2 := proofGenerators.g.Mul(t2).Add(proofGenerators.h.Mul(tau2)) - - // Fiat shamir for x (L55, pg20) - x, err := calcx(capT1, capT2, transcript, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc l - // Instead of using the expression in the line, evaluate l() at x - sLx := multiplyScalarToScalarVector(x, linearTerml) - l, err := addPairwiseScalarVectors(constantTerml, sLx) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc r - // Instead of using the expression in the line, evaluate r() at x - ynsRx := multiplyScalarToScalarVector(x, linearTermr) - r, err := addPairwiseScalarVectors(constantTermr, ynsRx) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc t hat - // For efficiency, instead of calculating the dot product, evaluate t() at x - zm := getknVector(z, m, prover.curve) - zsquarezm := multiplyScalarToScalarVector(z.Square(), zm) - sumv := prover.curve.Scalar.Zero() - for i := 0; i < m; i++ { - elem := zsquarezm[i].Mul(v[i]) - sumv = sumv.Add(elem) - } - - deltayzBatched, err := deltayzBatched(y, z, n, m, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t0 := sumv.Add(deltayzBatched) - tLinear := t1.Mul(x) - tQuadratic := t2.Mul(x.Square()) - tHat := t0.Add(tLinear).Add(tQuadratic) - - // Calc tau_x (L61, pg20) - tau2xsquare := tau2.Mul(x.Square()) - tau1x := tau1.Mul(x) - zsum := prover.curve.Scalar.Zero() - zExp := z.Clone() - for j := 1; j < m+1; j++ { - zExp = zExp.Mul(z) - zsum = zsum.Add(zExp.Mul(gamma[j-1])) - } - taux := tau2xsquare.Add(tau1x).Add(zsum) - - // Calc mu (L62, pg20) - mu := alpha.Add(rho.Mul(x)) - - // Calc IPP (See section 4.2) - hPrime, err := gethPrime(proofH, y, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // P is redefined in batched case, see bottom equation on pg21. - capPhmu := getPhmuBatched( - proofG, - hPrime, - proofGenerators.h, - capA, - capS, - x, - y, - z, - mu, - n, - m, - prover.curve, - ) - - wBytes := transcript.ExtractBytes([]byte("getw"), 64) - w, err := prover.curve.NewScalar().SetBytesWide(wBytes) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - ipp, err := prover.ippProver.rangeToIPP( - proofG, - hPrime, - l, - r, - tHat, - capPhmu, - proofGenerators.u.Mul(w), - transcript, - ) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - out := &RangeProof{ - capA: capA, - capS: capS, - capT1: capT1, - capT2: capT2, - taux: taux, - mu: mu, - tHat: tHat, - ipp: ipp, - curve: &prover.curve, - } - return out, nil -} - -// See final term of L71 on pg 21 -// Sigma_{j=1}^{m} z^{1+j} * (0^{(j-1)*n} || 2^{n} || 0^{(m-j)*n}). -func getSumTermrXBatched(z curves.Scalar, n, m int, curve curves.Curve) []curves.Scalar { - twoN := get2nVector(n, curve) - var out []curves.Scalar - // The final power should be one more than m - zExp := z.Clone() - for j := 0; j < m; j++ { - zExp = zExp.Mul(z) - elem := multiplyScalarToScalarVector(zExp, twoN) - out = append(out, elem...) - } - - return out -} - -func getcapVBatched(v, gamma []curves.Scalar, g, h curves.Point) []curves.Point { - out := make([]curves.Point, len(v)) - for i, vi := range v { - out[i] = getcapV(vi, gamma[i], g, h) - } - return out -} - -func getaLBatched(v []curves.Scalar, n int, curve curves.Curve) ([]curves.Scalar, error) { - var aL []curves.Scalar - for _, vi := range v { - aLi, err := getaL(vi, n, curve) - if err != nil { - return nil, err - } - aL = append(aL, aLi...) - } - return aL, nil -} - -func calcyzBatched( - capV []curves.Point, - capA, capS curves.Point, - transcript *merlin.Transcript, - curve curves.Curve, -) (curves.Scalar, curves.Scalar, error) { - // Add the A,S values to transcript - for _, capVi := range capV { - transcript.AppendMessage([]byte("addV"), capVi.ToAffineUncompressed()) - } - transcript.AppendMessage([]byte("addcapA"), capA.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addcapS"), capS.ToAffineUncompressed()) - // Read 64 bytes twice from, set to scalar for y and z - yBytes := transcript.ExtractBytes([]byte("gety"), 64) - y, err := curve.NewScalar().SetBytesWide(yBytes) - if err != nil { - return nil, nil, errors.Wrap(err, "calcyz NewScalar SetBytesWide") - } - zBytes := transcript.ExtractBytes([]byte("getz"), 64) - z, err := curve.NewScalar().SetBytesWide(zBytes) - if err != nil { - return nil, nil, errors.Wrap(err, "calcyz NewScalar SetBytesWide") - } - - return y, z, nil -} - -func deltayzBatched(y, z curves.Scalar, n, m int, curve curves.Curve) (curves.Scalar, error) { - // z - z^2 - zMinuszsquare := z.Sub(z.Square()) - // 1^(n*m) - onenm := get1nVector(n*m, curve) - // <1^nm, y^nm> - onenmdotynm, err := innerProduct(onenm, getknVector(y, n*m, curve)) - if err != nil { - return nil, errors.Wrap(err, "deltayz") - } - // (z - z^2)*<1^n, y^n> - termFirst := zMinuszsquare.Mul(onenmdotynm) - - // <1^n, 2^n> - onendottwon, err := innerProduct(get1nVector(n, curve), get2nVector(n, curve)) - if err != nil { - return nil, errors.Wrap(err, "deltayz") - } - - termSecond := curve.Scalar.Zero() - zExp := z.Square() - for j := 1; j < m+1; j++ { - zExp = zExp.Mul(z) - elem := zExp.Mul(onendottwon) - termSecond = termSecond.Add(elem) - } - - // (z - z^2)*<1^n, y^n> - z^3*<1^n, 2^n> - out := termFirst.Sub(termSecond) - - return out, nil -} - -// Bottom equation on pg21. -func getPhmuBatched( - proofG, proofHPrime []curves.Point, - h, capA, capS curves.Point, - x, y, z, mu curves.Scalar, - n, m int, - curve curves.Curve, -) curves.Point { - twoN := get2nVector(n, curve) - // h'^(z*y^n + z^2*2^n) - lastElem := curve.NewIdentityPoint() - zExp := z.Clone() - for j := 1; j < m+1; j++ { - // Get subvector of h - hSubvector := proofHPrime[(j-1)*n : j*n] - // z^(j+1) - zExp = zExp.Mul(z) - exp := multiplyScalarToScalarVector(zExp, twoN) - // Final elem - elem := curve.Point.SumOfProducts(hSubvector, exp) - lastElem = lastElem.Add(elem) - } - - zynm := multiplyScalarToScalarVector(z, getknVector(y, n*m, curve)) - hPrimezynm := curve.Point.SumOfProducts(proofHPrime, zynm) - lastElem = lastElem.Add(hPrimezynm) - - // S^x - capSx := capS.Mul(x) - - // g^-z --> -z*<1,g> - onenm := get1nVector(n*m, curve) - zNeg := z.Neg() - zinvonen := multiplyScalarToScalarVector(zNeg, onenm) - zgdotonen := curve.Point.SumOfProducts(proofG, zinvonen) - - // L66 on pg20 - P := capA.Add(capSx).Add(zgdotonen).Add(lastElem) - hmu := h.Mul(mu) - Phmu := P.Sub(hmu) - - return Phmu -} diff --git a/crypto/bulletproof/range_batch_prover_test.go b/crypto/bulletproof/range_batch_prover_test.go deleted file mode 100644 index 82ee031d9..000000000 --- a/crypto/bulletproof/range_batch_prover_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestRangeBatchProverHappyPath(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.Random(crand.Reader) - v2 := curve.Scalar.Random(crand.Reader) - v3 := curve.Scalar.Random(crand.Reader) - v4 := curve.Scalar.Random(crand.Reader) - v := []curves.Scalar{v1, v2, v3, v4} - - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - require.NotNil(t, proof) - require.Equal(t, 10, len(proof.ipp.capLs)) - require.Equal(t, 10, len(proof.ipp.capRs)) -} - -func TestGetaLBatched(t *testing.T) { - curve := curves.ED25519() - v1 := curve.Scalar.Random(crand.Reader) - v2 := curve.Scalar.Random(crand.Reader) - v3 := curve.Scalar.Random(crand.Reader) - v4 := curve.Scalar.Random(crand.Reader) - v := []curves.Scalar{v1, v2, v3, v4} - aL, err := getaLBatched(v, 256, *curve) - require.NoError(t, err) - twoN := get2nVector(256, *curve) - for i := 1; i < len(v)+1; i++ { - vec := aL[(i-1)*256 : i*256] - product, err := innerProduct(vec, twoN) - require.NoError(t, err) - require.Zero(t, product.Cmp(v[i-1])) - } -} - -func TestRangeBatchProverMarshal(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.Random(crand.Reader) - v2 := curve.Scalar.Random(crand.Reader) - v3 := curve.Scalar.Random(crand.Reader) - v4 := curve.Scalar.Random(crand.Reader) - v := []curves.Scalar{v1, v2, v3, v4} - - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - proofMarshaled := proof.MarshalBinary() - proofPrime := NewRangeProof(curve) - err = proofPrime.UnmarshalBinary(proofMarshaled) - require.NoError(t, err) - require.True(t, proof.capA.Equal(proofPrime.capA)) - require.True(t, proof.capS.Equal(proofPrime.capS)) - require.True(t, proof.capT1.Equal(proofPrime.capT1)) - require.True(t, proof.capT2.Equal(proofPrime.capT2)) - require.Zero(t, proof.taux.Cmp(proofPrime.taux)) - require.Zero(t, proof.mu.Cmp(proofPrime.mu)) - require.Zero(t, proof.tHat.Cmp(proofPrime.tHat)) -} diff --git a/crypto/bulletproof/range_batch_verifier.go b/crypto/bulletproof/range_batch_verifier.go deleted file mode 100644 index fbd0cee02..000000000 --- a/crypto/bulletproof/range_batch_verifier.go +++ /dev/null @@ -1,133 +0,0 @@ -package bulletproof - -import ( - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// VerifyBatched verifies a given batched range proof. -// It takes in a list of commitments to the secret values as capV instead of a single commitment to a single point -// when compared to the unbatched single range proof case. -func (verifier *RangeVerifier) VerifyBatched( - proof *RangeProof, - capV []curves.Point, - proofGenerators RangeProofGenerators, - n int, - transcript *merlin.Transcript, -) (bool, error) { - // Define nm as the total bits required for secrets, calculated as number of secrets * n - m := len(capV) - nm := n * m - // nm must be less than the number of generators generated - if nm > len(verifier.generators.G) { - return false, errors.New("ipp vector length must be less than maxVectorLength") - } - - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := verifier.generators.G[0:nm] - proofH := verifier.generators.H[0:nm] - - // Calc y,z,x from Fiat Shamir heuristic - y, z, err := calcyzBatched(capV, proof.capA, proof.capS, transcript, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - x, err := calcx(proof.capT1, proof.capT2, transcript, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - wBytes := transcript.ExtractBytes([]byte("getw"), 64) - w, err := verifier.curve.NewScalar().SetBytesWide(wBytes) - if err != nil { - return false, errors.Wrap(err, "rangeproof prove") - } - - // Calc delta(y,z), redefined for batched case on pg21 - deltayzBatched, err := deltayzBatched(y, z, n, m, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - // Check tHat: L65, pg20 - // See equation 72 on pg21 - tHatIsValid := verifier.checktHatBatched( - proof, - capV, - proofGenerators.g, - proofGenerators.h, - deltayzBatched, - x, - z, - m, - ) - if !tHatIsValid { - return false, errors.New("rangeproof verify tHat is invalid") - } - - // Verify IPP - hPrime, err := gethPrime(proofH, y, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - capPhmu := getPhmuBatched( - proofG, - hPrime, - proofGenerators.h, - proof.capA, - proof.capS, - x, - y, - z, - proof.mu, - n, - m, - verifier.curve, - ) - - ippVerified, err := verifier.ippVerifier.VerifyFromRangeProof( - proofG, - hPrime, - capPhmu, - proofGenerators.u.Mul(w), - proof.tHat, - proof.ipp, - transcript, - ) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - return ippVerified, nil -} - -// L65, pg20. -func (verifier *RangeVerifier) checktHatBatched( - proof *RangeProof, - capV []curves.Point, - g, h curves.Point, - deltayz, x, z curves.Scalar, - m int, -) bool { - // g^tHat * h^tau_x - gtHat := g.Mul(proof.tHat) - htaux := h.Mul(proof.taux) - lhs := gtHat.Add(htaux) - - // V^z^2 * g^delta(y,z) * Tau_1^x * Tau_2^x^2 - // g^delta(y,z) * V^(z^2*z^m) * Tau_1^x * Tau_2^x^2 - zm := getknVector(z, m, verifier.curve) - zsquarezm := multiplyScalarToScalarVector(z.Square(), zm) - capVzsquaretwom := verifier.curve.Point.SumOfProducts(capV, zsquarezm) - gdeltayz := g.Mul(deltayz) - capTau1x := proof.capT1.Mul(x) - capTau2xsquare := proof.capT2.Mul(x.Square()) - rhs := capVzsquaretwom.Add(gdeltayz).Add(capTau1x).Add(capTau2xsquare) - - // Compare lhs =? rhs - return lhs.Equal(rhs) -} diff --git a/crypto/bulletproof/range_batch_verifier_test.go b/crypto/bulletproof/range_batch_verifier_test.go deleted file mode 100644 index 3bfb44225..000000000 --- a/crypto/bulletproof/range_batch_verifier_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestRangeBatchVerifyHappyPath(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.Random(crand.Reader) - v2 := curve.Scalar.Random(crand.Reader) - v3 := curve.Scalar.Random(crand.Reader) - v4 := curve.Scalar.Random(crand.Reader) - v := []curves.Scalar{v1, v2, v3, v4} - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - verifier, err := NewRangeVerifier(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - capV := getcapVBatched(v, gamma, g, h) - verified, err := verifier.VerifyBatched(proof, capV, proofGenerators, n, transcriptVerifier) - require.NoError(t, err) - require.True(t, verified) -} - -func TestRangeBatchVerifyNotInRange(t *testing.T) { - curve := curves.ED25519() - n := 2 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.One() - v2 := curve.Scalar.Random(crand.Reader) - v3 := curve.Scalar.Random(crand.Reader) - v4 := curve.Scalar.Random(crand.Reader) - v := []curves.Scalar{v1, v2, v3, v4} - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - _, err = prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.Error(t, err) -} - -func TestRangeBatchVerifyNonRandom(t *testing.T) { - curve := curves.ED25519() - n := 2 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.One() - v2 := curve.Scalar.One() - v3 := curve.Scalar.One() - v4 := curve.Scalar.One() - v := []curves.Scalar{v1, v2, v3, v4} - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - verifier, err := NewRangeVerifier(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - capV := getcapVBatched(v, gamma, g, h) - verified, err := verifier.VerifyBatched(proof, capV, proofGenerators, n, transcriptVerifier) - require.NoError(t, err) - require.True(t, verified) -} - -func TestRangeBatchVerifyInvalid(t *testing.T) { - curve := curves.ED25519() - n := 2 - prover, err := NewRangeProver(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v1 := curve.Scalar.One() - v2 := curve.Scalar.One() - v3 := curve.Scalar.One() - v4 := curve.Scalar.One() - v := []curves.Scalar{v1, v2, v3, v4} - gamma1 := curve.Scalar.Random(crand.Reader) - gamma2 := curve.Scalar.Random(crand.Reader) - gamma3 := curve.Scalar.Random(crand.Reader) - gamma4 := curve.Scalar.Random(crand.Reader) - gamma := []curves.Scalar{gamma1, gamma2, gamma3, gamma4} - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.BatchProve(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - verifier, err := NewRangeVerifier(n*4, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - capV := getcapVBatched(v, gamma, g, h) - capV[0] = curve.Point.Random(crand.Reader) - verified, err := verifier.VerifyBatched(proof, capV, proofGenerators, n, transcriptVerifier) - require.Error(t, err) - require.False(t, verified) -} diff --git a/crypto/bulletproof/range_prover.go b/crypto/bulletproof/range_prover.go deleted file mode 100644 index 021b86f1c..000000000 --- a/crypto/bulletproof/range_prover.go +++ /dev/null @@ -1,514 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package bulletproof implements the zero knowledge protocol bulletproofs as defined in https://eprint.iacr.org/2017/1066.pdf -package bulletproof - -import ( - crand "crypto/rand" - "math/big" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// RangeProver is the struct used to create RangeProofs -// It specifies which curve to use and holds precomputed generators -// See NewRangeProver() for prover initialization. -type RangeProver struct { - curve curves.Curve - generators *ippGenerators - ippProver *InnerProductProver -} - -// RangeProof is the struct used to hold a range proof -// capA is a commitment to a_L and a_R using randomness alpha -// capS is a commitment to s_L and s_R using randomness rho -// capTau1,2 are commitments to t1,t2 respectively using randomness tau_1,2 -// tHat represents t(X) as defined on page 19 -// taux is the blinding factor for tHat -// ipp is the inner product proof used for compacting the transfer of l,r (See 4.2 on pg20). -type RangeProof struct { - capA, capS, capT1, capT2 curves.Point - taux, mu, tHat curves.Scalar - ipp *InnerProductProof - curve *curves.Curve -} - -type RangeProofGenerators struct { - g, h, u curves.Point -} - -// NewRangeProver initializes a new prover -// It uses the specified domain to generate generators for vectors of at most maxVectorLength -// A prover can be used to construct range proofs for vectors of length less than or equal to maxVectorLength -// A prover is defined by an explicit curve. -func NewRangeProver( - maxVectorLength int, - rangeDomain, ippDomain []byte, - curve curves.Curve, -) (*RangeProver, error) { - generators, err := getGeneratorPoints(maxVectorLength, rangeDomain, curve) - if err != nil { - return nil, errors.Wrap(err, "range NewRangeProver") - } - ippProver, err := NewInnerProductProver(maxVectorLength, ippDomain, curve) - if err != nil { - return nil, errors.Wrap(err, "range NewRangeProver") - } - return &RangeProver{curve: curve, generators: generators, ippProver: ippProver}, nil -} - -// NewRangeProof initializes a new RangeProof for a specified curve -// This should be used in tandem with UnmarshalBinary() to convert a marshaled proof into the struct. -func NewRangeProof(curve *curves.Curve) *RangeProof { - out := RangeProof{ - capA: nil, - capS: nil, - capT1: nil, - capT2: nil, - taux: nil, - mu: nil, - tHat: nil, - ipp: NewInnerProductProof(curve), - curve: curve, - } - - return &out -} - -// Prove uses the range prover to prove that some value v is within the range [0, 2^n] -// It implements the protocol defined on pgs 19,20 in https://eprint.iacr.org/2017/1066.pdf -// v is the value of which to prove the range -// n is the power that specifies the upper bound of the range, ie. 2^n -// gamma is a scalar used for as a blinding factor -// g, h, u are unique points used as generators for the blinding factor -// transcript is a merlin transcript to be used for the fiat shamir heuristic. -func (prover *RangeProver) Prove( - v, gamma curves.Scalar, - n int, - proofGenerators RangeProofGenerators, - transcript *merlin.Transcript, -) (*RangeProof, error) { - // n must be less than or equal to the number of generators generated - if n > len(prover.generators.G) { - return nil, errors.New("ipp vector length must be less than or equal to maxVectorLength") - } - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := prover.generators.G[0:n] - proofH := prover.generators.H[0:n] - - // Check that v is in range [0, 2^n] - if bigZero := big.NewInt(0); v.BigInt().Cmp(bigZero) == -1 { - return nil, errors.New("v is less than 0") - } - - bigTwo := big.NewInt(2) - if n < 0 { - return nil, errors.New("n cannot be less than 0") - } - bigN := big.NewInt(int64(n)) - var bigTwoToN big.Int - bigTwoToN.Exp(bigTwo, bigN, nil) - if v.BigInt().Cmp(&bigTwoToN) == 1 { - return nil, errors.New("v is greater than 2^n") - } - - // L40 on pg19 - aL, err := getaL(v, n, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - onen := get1nVector(n, prover.curve) - // L41 on pg19 - aR, err := subtractPairwiseScalarVectors(aL, onen) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - alpha := prover.curve.Scalar.Random(crand.Reader) - // Calc A (L44, pg19) - halpha := proofGenerators.h.Mul(alpha) - gaL := prover.curve.Point.SumOfProducts(proofG, aL) - haR := prover.curve.Point.SumOfProducts(proofH, aR) - capA := halpha.Add(gaL).Add(haR) - - // L45, 46, pg19 - sL := getBlindingVector(n, prover.curve) - sR := getBlindingVector(n, prover.curve) - rho := prover.curve.Scalar.Random(crand.Reader) - - // Calc S (L47, pg19) - hrho := proofGenerators.h.Mul(rho) - gsL := prover.curve.Point.SumOfProducts(proofG, sL) - hsR := prover.curve.Point.SumOfProducts(proofH, sR) - capS := hrho.Add(gsL).Add(hsR) - - // Fiat Shamir for y,z (L49, pg19) - capV := getcapV(v, gamma, proofGenerators.g, proofGenerators.h) - y, z, err := calcyz(capV, capA, capS, transcript, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc t_1, t_2 - // See the l(X), r(X), t(X) equations on pg 19 - // Use l(X)'s and r(X)'s constant and linear terms to derive t_1 and t_2 - // (a_l - z*1^n) - zonen := multiplyScalarToScalarVector(z, onen) - constantTerml, err := subtractPairwiseScalarVectors(aL, zonen) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - linearTerml := sL - - // z^2 * 2^N - twoN := get2nVector(n, prover.curve) - zSquareTwon := multiplyScalarToScalarVector(z.Square(), twoN) - // a_r + z*1^n - aRPluszonen, err := addPairwiseScalarVectors(aR, zonen) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - yn := getknVector(y, n, prover.curve) - hadamard, err := multiplyPairwiseScalarVectors(yn, aRPluszonen) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - constantTermr, err := addPairwiseScalarVectors(hadamard, zSquareTwon) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - linearTermr, err := multiplyPairwiseScalarVectors(yn, sR) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // t_1 (as the linear coefficient) is the sum of the dot products of l(X)'s linear term dot r(X)'s constant term - // and r(X)'s linear term dot l(X)'s constant term - t1FirstTerm, err := innerProduct(linearTerml, constantTermr) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t1SecondTerm, err := innerProduct(linearTermr, constantTerml) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t1 := t1FirstTerm.Add(t1SecondTerm) - - // t_2 (as the quadratic coefficient) is the dot product of l(X)'s and r(X)'s linear terms - t2, err := innerProduct(linearTerml, linearTermr) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // L52, pg20 - tau1 := prover.curve.Scalar.Random(crand.Reader) - tau2 := prover.curve.Scalar.Random(crand.Reader) - - // T_1, T_2 (L53, pg20) - capT1 := proofGenerators.g.Mul(t1).Add(proofGenerators.h.Mul(tau1)) - capT2 := proofGenerators.g.Mul(t2).Add(proofGenerators.h.Mul(tau2)) - - // Fiat shamir for x (L55, pg20) - x, err := calcx(capT1, capT2, transcript, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc l (L58, pg20) - // Instead of using the expression in the line, evaluate l() at x - sLx := multiplyScalarToScalarVector(x, linearTerml) - l, err := addPairwiseScalarVectors(constantTerml, sLx) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc r (L59, pg20) - // Instead of using the expression in the line, evaluate r() at x - ynsRx := multiplyScalarToScalarVector(x, linearTermr) - r, err := addPairwiseScalarVectors(constantTermr, ynsRx) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - // Calc t hat (L60, pg20) - // For efficiency, instead of calculating the dot product, evaluate t() at x - deltayz, err := deltayz(y, z, n, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - t0 := v.Mul(z.Square()).Add(deltayz) - tLinear := t1.Mul(x) - tQuadratic := t2.Mul(x.Square()) - tHat := t0.Add(tLinear).Add(tQuadratic) - - // Calc tau_x (L61, pg20) - tau2xsquare := tau2.Mul(x.Square()) - tau1x := tau1.Mul(x) - zsquaregamma := z.Square().Mul(gamma) - taux := tau2xsquare.Add(tau1x).Add(zsquaregamma) - - // Calc mu (L62, pg20) - mu := alpha.Add(rho.Mul(x)) - - // Calc IPP (See section 4.2) - hPrime, err := gethPrime(proofH, y, prover.curve) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - capPhmu, err := getPhmu( - proofG, - hPrime, - proofGenerators.h, - capA, - capS, - x, - y, - z, - mu, - n, - prover.curve, - ) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - wBytes := transcript.ExtractBytes([]byte("getw"), 64) - w, err := prover.curve.NewScalar().SetBytesWide(wBytes) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - ipp, err := prover.ippProver.rangeToIPP( - proofG, - hPrime, - l, - r, - tHat, - capPhmu, - proofGenerators.u.Mul(w), - transcript, - ) - if err != nil { - return nil, errors.Wrap(err, "rangeproof prove") - } - - out := &RangeProof{ - capA: capA, - capS: capS, - capT1: capT1, - capT2: capT2, - taux: taux, - mu: mu, - tHat: tHat, - ipp: ipp, - curve: &prover.curve, - } - return out, nil -} - -// MarshalBinary takes a range proof and marshals into bytes. -func (proof *RangeProof) MarshalBinary() []byte { - var out []byte - out = append(out, proof.capA.ToAffineCompressed()...) - out = append(out, proof.capS.ToAffineCompressed()...) - out = append(out, proof.capT1.ToAffineCompressed()...) - out = append(out, proof.capT2.ToAffineCompressed()...) - out = append(out, proof.taux.Bytes()...) - out = append(out, proof.mu.Bytes()...) - out = append(out, proof.tHat.Bytes()...) - out = append(out, proof.ipp.MarshalBinary()...) - - return out -} - -// UnmarshalBinary takes bytes of a marshaled proof and writes them into a range proof -// The range proof used should be from the output of NewRangeProof(). -func (proof *RangeProof) UnmarshalBinary(data []byte) error { - scalarLen := len(proof.curve.NewScalar().Bytes()) - pointLen := len(proof.curve.NewGeneratorPoint().ToAffineCompressed()) - ptr := 0 - // Get points - capA, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary FromAffineCompressed") - } - proof.capA = capA - ptr += pointLen - capS, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary FromAffineCompressed") - } - proof.capS = capS - ptr += pointLen - capT1, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary FromAffineCompressed") - } - proof.capT1 = capT1 - ptr += pointLen - capT2, err := proof.curve.Point.FromAffineCompressed(data[ptr : ptr+pointLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary FromAffineCompressed") - } - proof.capT2 = capT2 - ptr += pointLen - - // Get scalars - taux, err := proof.curve.NewScalar().SetBytes(data[ptr : ptr+scalarLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary SetBytes") - } - proof.taux = taux - ptr += scalarLen - mu, err := proof.curve.NewScalar().SetBytes(data[ptr : ptr+scalarLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary SetBytes") - } - proof.mu = mu - ptr += scalarLen - tHat, err := proof.curve.NewScalar().SetBytes(data[ptr : ptr+scalarLen]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary SetBytes") - } - proof.tHat = tHat - ptr += scalarLen - - // Get IPP - err = proof.ipp.UnmarshalBinary(data[ptr:]) - if err != nil { - return errors.New("rangeProof UnmarshalBinary") - } - - return nil -} - -// checkRange validates whether some scalar v is within the range [0, 2^n - 1] -// It will return an error if v is less than 0 or greater than 2^n - 1 -// Otherwise it will return nil. -func checkRange(v curves.Scalar, n int) error { - bigOne := big.NewInt(1) - if n < 0 { - return errors.New("n cannot be less than 0") - } - var bigTwoToN big.Int - bigTwoToN.Lsh(bigOne, uint(n)) - if v.BigInt().Cmp(&bigTwoToN) == 1 { - return errors.New("v is greater than 2^n") - } - - return nil -} - -// getBlindingVector returns a vector of scalars used as blinding factors for commitments. -func getBlindingVector(length int, curve curves.Curve) []curves.Scalar { - vec := make([]curves.Scalar, length) - for i := 0; i < length; i++ { - vec[i] = curve.Scalar.Random(crand.Reader) - } - return vec -} - -// getcapV returns a commitment to v using blinding factor gamma. -func getcapV(v, gamma curves.Scalar, g, h curves.Point) curves.Point { - return h.Mul(gamma).Add(g.Mul(v)) -} - -// getaL obtains the bit vector representation of v -// See the a_L definition towards the bottom of pg 17 of https://eprint.iacr.org/2017/1066.pdf -func getaL(v curves.Scalar, n int, curve curves.Curve) ([]curves.Scalar, error) { - var err error - - vBytes := v.Bytes() - zero := curve.Scalar.Zero() - one := curve.Scalar.One() - aL := make([]curves.Scalar, n) - for j := 0; j < len(aL); j++ { - aL[j] = zero - } - for i := 0; i < n; i++ { - ithBit := vBytes[i>>3] >> (i & 0x07) & 0x01 - aL[i], err = cmoveScalar(zero, one, int(ithBit), curve) - if err != nil { - return nil, errors.Wrap(err, "getaL") - } - } - - return aL, nil -} - -// cmoveScalar provides a constant time operation that returns x if which is 0 and returns y if which is 1. -func cmoveScalar(x, y curves.Scalar, which int, curve curves.Curve) (curves.Scalar, error) { - if which != 0 && which != 1 { - return nil, errors.New("cmoveScalar which must be 0 or 1") - } - mask := -byte(which) - xBytes := x.Bytes() - yBytes := y.Bytes() - for i, xByte := range xBytes { - xBytes[i] ^= (xByte ^ yBytes[i]) & mask - } - out, err := curve.NewScalar().SetBytes(xBytes) - if err != nil { - return nil, errors.Wrap(err, "cmoveScalar SetBytes") - } - - return out, nil -} - -// calcyz uses a merlin transcript for Fiat Shamir -// It takes the current state of the transcript and appends the newly calculated capA and capS values -// Two new scalars are then read from the transcript -// See section 4.4 pg22 of https://eprint.iacr.org/2017/1066.pdf -func calcyz( - capV, capA, capS curves.Point, - transcript *merlin.Transcript, - curve curves.Curve, -) (curves.Scalar, curves.Scalar, error) { - // Add the A,S values to transcript - transcript.AppendMessage([]byte("addV"), capV.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addcapA"), capA.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addcapS"), capS.ToAffineUncompressed()) - // Read 64 bytes twice from, set to scalar for y and z - yBytes := transcript.ExtractBytes([]byte("gety"), 64) - y, err := curve.NewScalar().SetBytesWide(yBytes) - if err != nil { - return nil, nil, errors.Wrap(err, "calcyz NewScalar SetBytesWide") - } - zBytes := transcript.ExtractBytes([]byte("getz"), 64) - z, err := curve.NewScalar().SetBytesWide(zBytes) - if err != nil { - return nil, nil, errors.Wrap(err, "calcyz NewScalar SetBytesWide") - } - - return y, z, nil -} - -// calcx uses a merlin transcript for Fiat Shamir -// It takes the current state of the transcript and appends the newly calculated capT1 and capT2 values -// A new scalar is then read from the transcript -// See section 4.4 pg22 of https://eprint.iacr.org/2017/1066.pdf -func calcx( - capT1, capT2 curves.Point, - transcript *merlin.Transcript, - curve curves.Curve, -) (curves.Scalar, error) { - // Add the Tau1,2 values to transcript - transcript.AppendMessage([]byte("addcapT1"), capT1.ToAffineUncompressed()) - transcript.AppendMessage([]byte("addcapT2"), capT2.ToAffineUncompressed()) - // Read 64 bytes from, set to scalar - outBytes := transcript.ExtractBytes([]byte("getx"), 64) - x, err := curve.NewScalar().SetBytesWide(outBytes) - if err != nil { - return nil, errors.Wrap(err, "calcx NewScalar SetBytesWide") - } - - return x, nil -} diff --git a/crypto/bulletproof/range_prover_test.go b/crypto/bulletproof/range_prover_test.go deleted file mode 100644 index 1ca4b083b..000000000 --- a/crypto/bulletproof/range_prover_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestRangeProverHappyPath(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v := curve.Scalar.Random(crand.Reader) - gamma := curve.Scalar.Random(crand.Reader) - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - require.NotNil(t, proof) - require.Equal(t, 8, len(proof.ipp.capLs)) - require.Equal(t, 8, len(proof.ipp.capRs)) -} - -func TestGetaL(t *testing.T) { - curve := curves.ED25519() - v := curve.Scalar.Random(crand.Reader) - aL, err := getaL(v, 256, *curve) - require.NoError(t, err) - twoN := get2nVector(256, *curve) - product, err := innerProduct(aL, twoN) - require.NoError(t, err) - require.Zero(t, product.Cmp(v)) -} - -func TestCmove(t *testing.T) { - curve := curves.ED25519() - two := curve.Scalar.One().Double() - four := two.Double() - out, err := cmoveScalar(two, four, 1, *curve) - require.NoError(t, err) - require.Zero(t, out.Cmp(four)) -} - -func TestRangeProverMarshal(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v := curve.Scalar.Random(crand.Reader) - gamma := curve.Scalar.Random(crand.Reader) - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - proofMarshaled := proof.MarshalBinary() - proofPrime := NewRangeProof(curve) - err = proofPrime.UnmarshalBinary(proofMarshaled) - require.NoError(t, err) - require.True(t, proof.capA.Equal(proofPrime.capA)) - require.True(t, proof.capS.Equal(proofPrime.capS)) - require.True(t, proof.capT1.Equal(proofPrime.capT1)) - require.True(t, proof.capT2.Equal(proofPrime.capT2)) - require.Zero(t, proof.taux.Cmp(proofPrime.taux)) - require.Zero(t, proof.mu.Cmp(proofPrime.mu)) - require.Zero(t, proof.tHat.Cmp(proofPrime.tHat)) -} diff --git a/crypto/bulletproof/range_verifier.go b/crypto/bulletproof/range_verifier.go deleted file mode 100644 index cda97b527..000000000 --- a/crypto/bulletproof/range_verifier.go +++ /dev/null @@ -1,235 +0,0 @@ -package bulletproof - -import ( - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// RangeVerifier is the struct used to verify RangeProofs -// It specifies which curve to use and holds precomputed generators -// See NewRangeVerifier() for verifier initialization. -type RangeVerifier struct { - curve curves.Curve - generators *ippGenerators - ippVerifier *InnerProductVerifier -} - -// NewRangeVerifier initializes a new verifier -// It uses the specified domain to generate generators for vectors of at most maxVectorLength -// A verifier can be used to verify range proofs for vectors of length less than or equal to maxVectorLength -// A verifier is defined by an explicit curve. -func NewRangeVerifier( - maxVectorLength int, - rangeDomain, ippDomain []byte, - curve curves.Curve, -) (*RangeVerifier, error) { - generators, err := getGeneratorPoints(maxVectorLength, rangeDomain, curve) - if err != nil { - return nil, errors.Wrap(err, "range NewRangeProver") - } - ippVerifier, err := NewInnerProductVerifier(maxVectorLength, ippDomain, curve) - if err != nil { - return nil, errors.Wrap(err, "range NewRangeProver") - } - return &RangeVerifier{curve: curve, generators: generators, ippVerifier: ippVerifier}, nil -} - -// Verify verifies the given range proof inputs -// It implements the checking of L65 on pg 20 -// It also verifies the dot product of using the inner product proof\ -// capV is a commitment to v using blinding factor gamma -// n is the power that specifies the upper bound of the range, ie. 2^n -// g, h, u are unique points used as generators for the blinding factor -// transcript is a merlin transcript to be used for the fiat shamir heuristic. -func (verifier *RangeVerifier) Verify( - proof *RangeProof, - capV curves.Point, - proofGenerators RangeProofGenerators, - n int, - transcript *merlin.Transcript, -) (bool, error) { - // Length of vectors must be less than the number of generators generated - if n > len(verifier.generators.G) { - return false, errors.New("ipp vector length must be less than maxVectorLength") - } - // In case where len(a) is less than number of generators precomputed by prover, trim to length - proofG := verifier.generators.G[0:n] - proofH := verifier.generators.H[0:n] - - // Calc y,z,x from Fiat Shamir heuristic - y, z, err := calcyz(capV, proof.capA, proof.capS, transcript, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - x, err := calcx(proof.capT1, proof.capT2, transcript, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - wBytes := transcript.ExtractBytes([]byte("getw"), 64) - w, err := verifier.curve.NewScalar().SetBytesWide(wBytes) - if err != nil { - return false, errors.Wrap(err, "rangeproof prove") - } - - // Calc delta(y,z) - deltayz, err := deltayz(y, z, n, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - // Check tHat: L65, pg20 - tHatIsValid := verifier.checktHat( - proof, - capV, - proofGenerators.g, - proofGenerators.h, - deltayz, - x, - z, - ) - if !tHatIsValid { - return false, errors.New("rangeproof verify tHat is invalid") - } - - // Verify IPP - hPrime, err := gethPrime(proofH, y, verifier.curve) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - capPhmu, err := getPhmu( - proofG, - hPrime, - proofGenerators.h, - proof.capA, - proof.capS, - x, - y, - z, - proof.mu, - n, - verifier.curve, - ) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - ippVerified, err := verifier.ippVerifier.VerifyFromRangeProof( - proofG, - hPrime, - capPhmu, - proofGenerators.u.Mul(w), - proof.tHat, - proof.ipp, - transcript, - ) - if err != nil { - return false, errors.Wrap(err, "rangeproof verify") - } - - return ippVerified, nil -} - -// L65, pg20. -func (*RangeVerifier) checktHat( - proof *RangeProof, - capV, g, h curves.Point, - deltayz, x, z curves.Scalar, -) bool { - // g^tHat * h^tau_x - gtHat := g.Mul(proof.tHat) - htaux := h.Mul(proof.taux) - lhs := gtHat.Add(htaux) - - // V^z^2 * g^delta(y,z) * Tau_1^x * Tau_2^x^2 - capVzsquare := capV.Mul(z.Square()) - gdeltayz := g.Mul(deltayz) - capTau1x := proof.capT1.Mul(x) - capTau2xsquare := proof.capT2.Mul(x.Square()) - rhs := capVzsquare.Add(gdeltayz).Add(capTau1x).Add(capTau2xsquare) - - // Compare lhs =? rhs - return lhs.Equal(rhs) -} - -// gethPrime calculates new h prime generators as defined in L64 on pg20. -func gethPrime(h []curves.Point, y curves.Scalar, curve curves.Curve) ([]curves.Point, error) { - hPrime := make([]curves.Point, len(h)) - yInv, err := y.Invert() - yInvn := getknVector(yInv, len(h), curve) - if err != nil { - return nil, errors.Wrap(err, "gethPrime") - } - for i, hElem := range h { - hPrime[i] = hElem.Mul(yInvn[i]) - } - return hPrime, nil -} - -// Obtain P used for IPP verification -// See L67 on pg20 -// Note P on L66 includes blinding factor hmu, this method removes that factor. -func getPhmu( - proofG, proofHPrime []curves.Point, - h, capA, capS curves.Point, - x, y, z, mu curves.Scalar, - n int, - curve curves.Curve, -) (curves.Point, error) { - // h'^(z*y^n + z^2*2^n) - zyn := multiplyScalarToScalarVector(z, getknVector(y, n, curve)) - zsquaretwon := multiplyScalarToScalarVector(z.Square(), get2nVector(n, curve)) - elemLastExponent, err := addPairwiseScalarVectors(zyn, zsquaretwon) - if err != nil { - return nil, errors.Wrap(err, "getPhmu") - } - lastElem := curve.Point.SumOfProducts(proofHPrime, elemLastExponent) - - // S^x - capSx := capS.Mul(x) - - // g^-z --> -z*<1,g> - onen := get1nVector(n, curve) - zNeg := z.Neg() - zinvonen := multiplyScalarToScalarVector(zNeg, onen) - zgdotonen := curve.Point.SumOfProducts(proofG, zinvonen) - - // L66 on pg20 - P := capA.Add(capSx).Add(zgdotonen).Add(lastElem) - hmu := h.Mul(mu) - Phmu := P.Sub(hmu) - - return Phmu, nil -} - -// Delta function for delta(y,z), See (39) on pg18. -func deltayz(y, z curves.Scalar, n int, curve curves.Curve) (curves.Scalar, error) { - // z - z^2 - zMinuszsquare := z.Sub(z.Square()) - // 1^n - onen := get1nVector(n, curve) - // <1^n, y^n> - onendotyn, err := innerProduct(onen, getknVector(y, n, curve)) - if err != nil { - return nil, errors.Wrap(err, "deltayz") - } - // (z - z^2)*<1^n, y^n> - termFirst := zMinuszsquare.Mul(onendotyn) - - // <1^n, 2^n> - onendottwon, err := innerProduct(onen, get2nVector(n, curve)) - if err != nil { - return nil, errors.Wrap(err, "deltayz") - } - // z^3*<1^n, 2^n> - termSecond := z.Cube().Mul(onendottwon) - - // (z - z^2)*<1^n, y^n> - z^3*<1^n, 2^n> - out := termFirst.Sub(termSecond) - - return out, nil -} diff --git a/crypto/bulletproof/range_verifier_test.go b/crypto/bulletproof/range_verifier_test.go deleted file mode 100644 index 8436b4228..000000000 --- a/crypto/bulletproof/range_verifier_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package bulletproof - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestRangeVerifyHappyPath(t *testing.T) { - curve := curves.ED25519() - n := 256 - prover, err := NewRangeProver(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v := curve.Scalar.Random(crand.Reader) - gamma := curve.Scalar.Random(crand.Reader) - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - verifier, err := NewRangeVerifier(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - capV := getcapV(v, gamma, g, h) - verified, err := verifier.Verify(proof, capV, proofGenerators, n, transcriptVerifier) - require.NoError(t, err) - require.True(t, verified) -} - -func TestRangeVerifyNotInRange(t *testing.T) { - curve := curves.ED25519() - n := 2 - prover, err := NewRangeProver(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v := curve.Scalar.Random(crand.Reader) - gamma := curve.Scalar.Random(crand.Reader) - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - _, err = prover.Prove(v, gamma, n, proofGenerators, transcript) - require.Error(t, err) -} - -func TestRangeVerifyNonRandom(t *testing.T) { - curve := curves.ED25519() - n := 2 - prover, err := NewRangeProver(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - v := curve.Scalar.One() - gamma := curve.Scalar.Random(crand.Reader) - g := curve.Point.Random(crand.Reader) - h := curve.Point.Random(crand.Reader) - u := curve.Point.Random(crand.Reader) - proofGenerators := RangeProofGenerators{ - g: g, - h: h, - u: u, - } - transcript := merlin.NewTranscript("test") - proof, err := prover.Prove(v, gamma, n, proofGenerators, transcript) - require.NoError(t, err) - - verifier, err := NewRangeVerifier(n, []byte("rangeDomain"), []byte("ippDomain"), *curve) - require.NoError(t, err) - transcriptVerifier := merlin.NewTranscript("test") - capV := getcapV(v, gamma, g, h) - verified, err := verifier.Verify(proof, capV, proofGenerators, n, transcriptVerifier) - require.NoError(t, err) - require.True(t, verified) -} diff --git a/crypto/core/README.md b/crypto/core/README.md deleted file mode 100755 index 8cc6599f1..000000000 --- a/crypto/core/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Core Package - -The core package contains a set of primitives, including but not limited to various -elliptic curves, hashes, and commitment schemes. These primitives are used internally -and can also be used independently on their own externally. diff --git a/crypto/core/commit.go b/crypto/core/commit.go deleted file mode 100755 index 6725e866e..000000000 --- a/crypto/core/commit.go +++ /dev/null @@ -1,123 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "crypto/hmac" - crand "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/json" - "fmt" - "hash" -) - -// Size of random values and hash outputs are determined by our hash function -const Size = sha256.Size - -type ( - // Commitment to a given message which can be later revealed. - // This is sent to and held by a verifier until the corresponding - // witness is provided. - Commitment []byte - - // Witness is sent to and opened by the verifier. This proves that - // committed message hasn't been altered by later information. - Witness struct { - Msg []byte - r [Size]byte - } - - // witnessJSON is used for un/marshaling. - witnessJSON struct { - Msg []byte - R [Size]byte - } -) - -// MarshalJSON encodes Witness in JSON -func (w Witness) MarshalJSON() ([]byte, error) { - return json.Marshal(witnessJSON{w.Msg, w.r}) -} - -// UnmarshalJSON decodes JSON into a Witness struct -func (w *Witness) UnmarshalJSON(data []byte) error { - witness := &witnessJSON{} - err := json.Unmarshal(data, witness) - if err != nil { - return err - } - w.Msg = witness.Msg - w.r = witness.R - return nil -} - -// Commit to a given message. Uses SHA256 as the hash function. -func Commit(msg []byte) (Commitment, *Witness, error) { - // Initialize our decommitment - d := Witness{msg, [Size]byte{}} - - // Generate a random nonce of the required length - n, err := crand.Read(d.r[:]) - // Ensure no errors retrieving nonce - if err != nil { - return nil, nil, err - } - - // Ensure we read all the bytes expected - if n != Size { - return nil, nil, fmt.Errorf( - "failed to read %v bytes from crypto/rand: received %v bytes", - Size, - n, - ) - } - // Compute the commitment: HMAC(Sha2, msg, key) - c, err := ComputeHMAC(sha256.New, msg, d.r[:]) - if err != nil { - return nil, nil, err - } - return c, &d, nil -} - -// Open a commitment and return true if the commitment/decommitment pair are valid. -// reference: spec.§2.4: Commitment Scheme -func Open(c Commitment, d Witness) (bool, error) { - // Ensure commitment is well-formed. - if len(c) != Size { - return false, fmt.Errorf("invalid commitment, wrong length. %v != %v", len(c), Size) - } - - // Re-compute the commitment: HMAC(Sha2, msg, key) - cʹ, err := ComputeHMAC(sha256.New, d.Msg, d.r[:]) - if err != nil { - return false, err - } - return subtle.ConstantTimeCompare(cʹ, c) == 1, nil -} - -// ComputeHMAC computes HMAC(hash_fn, msg, key) -// Takes in a hash function to use for HMAC -func ComputeHMAC(f func() hash.Hash, msg []byte, k []byte) ([]byte, error) { - if f == nil { - return nil, fmt.Errorf("hash function cannot be nil") - } - - mac := hmac.New(f, k) - w, err := mac.Write(msg) - - if w != len(msg) { - return nil, fmt.Errorf( - "bytes written to hash doesn't match expected: %v != %v", - w, - len(msg), - ) - } else if err != nil { - return nil, err - } - return mac.Sum(nil), nil -} diff --git a/crypto/core/commit_test.go b/crypto/core/commit_test.go deleted file mode 100755 index 72d3a8ad8..000000000 --- a/crypto/core/commit_test.go +++ /dev/null @@ -1,396 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -// An entry into our test table -type entry struct { - // Input - msg []byte - - // Result (actual, not expected) - commit Commitment - decommit *Witness - err error -} - -// Test inputs and placeholders for results that will be filled in -// during init() -var testResults = []entry{ - {[]byte("This is a test message"), nil, nil, nil}, - {[]byte("short msg"), nil, nil, nil}, - { - []byte( - "This input field is intentionally longer than the SHA256 block size to ensure that the entire message is processed", - ), - nil, nil, nil, - }, - { - []byte{ - 0xFB, - 0x1A, - 0x18, - 0x47, - 0x39, - 0x3C, - 0x9F, - 0x45, - 0x5F, - 0x29, - 0x4C, - 0x51, - 0x42, - 0x30, - 0xA6, - 0xB9, - }, - nil, nil, nil, - }, - // msg = \epsilon (empty string) - {[]byte{}, nil, nil, nil}, - // msg == nil - {nil, nil, nil, nil}, -} - -// Run our inputs through commit and record the outputs -func init() { - for i := range testResults { - entry := &testResults[i] - entry.commit, entry.decommit, entry.err = Commit(entry.msg) - } -} - -// Computing commitments should never produce errors -func TestCommitWithoutErrors(t *testing.T) { - for _, entry := range testResults { - if entry.err != nil { - t.Errorf("received Commit(%v): %v", entry.msg, entry.err) - } - } -} - -// Commitments should be 256b == 64B in length -func TestCommitmentsAreExpectedLength(t *testing.T) { - const expLen = 256 / 8 - for _, entry := range testResults { - if len(entry.commit) != expLen { - t.Errorf("commitment is not expected length: %v != %v", len(entry.commit), expLen) - } - } -} - -// Decommit cannot be nil -func TestCommmitProducesDecommit(t *testing.T) { - for _, entry := range testResults { - if entry.decommit == nil { - t.Errorf("decommit cannot be nil: Commit(%v)", entry.msg) - } - } -} - -// Decommit value should contain the same message -func TestCommmitProducesDecommitWithSameMessage(t *testing.T) { - for _, entry := range testResults { - if !bytes.Equal(entry.msg, entry.decommit.Msg) { - t.Errorf("decommit.msg != msg: %v != %v", entry.msg, entry.decommit.Msg) - } - } -} - -// Commitments should be unique -func TestCommmitProducesDistinctCommitments(t *testing.T) { - seen := make(map[[Size]byte]bool) - - // Check the pre-computed commitments for uniquness - for _, entry := range testResults { - - // Slices cannot be used as hash keys, so we need to copy into - // an array. Oh, go-lang. - var cee [Size]byte - copy(cee[:], entry.commit) - - // Ensure each commit is unique - if seen[cee] { - t.Errorf("duplicate commit found: %v", cee) - } - seen[cee] = true - } -} - -// Commitments should be unique even for the same message since the nonce is -// randomly selected -func TestCommmitDistinctCommitments(t *testing.T) { - seen := make(map[[Size]byte]bool) - msg := []byte("black lives matter") - const iterations = 1000 - - // Check the pre-computed commitments for uniquness - for i := 0; i < iterations; i++ { - // Compute a commitment - c, _, err := Commit(msg) - if err != nil { - t.Error(err) - } - - // Slices cannot be used as hash keys, so copy into an array - var cee [Size]byte - copy(cee[:], []byte(c)) - - // Ensure each commit is unique - if seen[cee] { - t.Errorf("duplicate commit found: %v", cee) - } - seen[cee] = true - } -} - -// Nonces must be 256b = 64B -func TestCommmitNonceIsExpectedLength(t *testing.T) { - const expLen = 256 / 8 - - // Check the pre-computed nonces - for _, entry := range testResults { - if len(entry.decommit.r) != expLen { - t.Errorf("nonce is not expected length: %v != %v", len(entry.decommit.r), expLen) - } - } -} - -// Randomly selected nonces will be unique with overwhelming probability -func TestCommmitProducesDistinctNonces(t *testing.T) { - seen := make(map[[Size]byte]bool) - msg := []byte("black lives matter") - const iterations = 1000 - - // Check the pre-computed commitments for uniquness - for i := 0; i < iterations; i++ { - // Compute a commitment - _, dee, err := Commit(msg) - if err != nil { - t.Error(err) - } - - // Ensure each nonce is unique - if seen[dee.r] { - t.Errorf("duplicate nonce found: %v", dee.r) - } - seen[dee.r] = true - } -} - -func TestOpenOnValidCommitments(t *testing.T) { - for _, entry := range testResults { - - // Open each commitment - ok, err := Open(entry.commit, *entry.decommit) - // There should be no error - if err != nil { - t.Error(err) - } - - // The commitments should verify - if !ok { - t.Errorf("commitment failed to open: %v", entry.msg) - } - } -} - -func TestOpenOnModifiedNonce(t *testing.T) { - for _, entry := range testResults { - dʹ := copyWitness(entry.decommit) - - // Modify the nonce - dʹ.r[0] ^= 0x40 - - // Open and check for failure - ok, err := Open(entry.commit, *dʹ) - assertFailedOpen(t, ok, err) - } -} - -func TestOpenOnZeroPrefixNonce(t *testing.T) { - for _, entry := range testResults { - dʹ := copyWitness(entry.decommit) - - // Modify the nonce - dʹ.r[0] = 0x00 - dʹ.r[1] = 0x00 - dʹ.r[2] = 0x00 - dʹ.r[3] = 0x00 - dʹ.r[4] = 0x00 - dʹ.r[5] = 0x00 - dʹ.r[6] = 0x00 - dʹ.r[7] = 0x00 - dʹ.r[8] = 0x00 - dʹ.r[9] = 0x00 - dʹ.r[10] = 0x00 - - // Open and check for failure - ok, err := Open(entry.commit, *dʹ) - assertFailedOpen(t, ok, err) - } -} - -// Makes a deep copy of a Witness -func copyWitness(d *Witness) *Witness { - msg := make([]byte, len(d.Msg)) - var r [Size]byte - - copy(msg, d.Msg) - copy(r[:], d.r[:]) - return &Witness{msg, r} -} - -// Asserts that err != nil, and ok == false. -func assertFailedOpen(t *testing.T, ok bool, err error) { - // There should be no error - if err != nil { - t.Error(err) - } - - // But the commitments should fail - if ok { - t.Error("commitment was verified but was expected to fail") - } -} - -// An unrelated message should fail on open -func TestOpenOnNewMessage(t *testing.T) { - for _, entry := range testResults { - dʹ := copyWitness(entry.decommit) - - // Use a distinct message - dʹ.Msg = []byte("no one expects the spanish inquisition") - - // Open and check for failure - ok, err := Open(entry.commit, *dʹ) - assertFailedOpen(t, ok, err) - } -} - -// An appended message should fail on open -func TestOpenOnAppendedMessage(t *testing.T) { - for _, entry := range testResults { - dʹ := copyWitness(entry.decommit) - - // Modify the message - dʹ.Msg = []byte("no one expects the spanish inquisition") - - // Open and check for failure - ok, err := Open(entry.commit, *dʹ) - assertFailedOpen(t, ok, err) - } -} - -// A modified message should fail on open -func TestOpenOnModifiedMessage(t *testing.T) { - for _, entry := range testResults { - // Skip the empty string message for this test case - if len(entry.msg) == 0 { - continue - } - - // Modify the message _in situ_ - dʹ := copyWitness(entry.decommit) - dʹ.Msg[1] ^= 0x99 - - // Open and check for failure - ok, err := Open(entry.commit, *dʹ) - assertFailedOpen(t, ok, err) - } -} - -// A modified commitment should fail on open -func TestOpenOnModifiedCommitment(t *testing.T) { - for _, entry := range testResults { - // Copy and then modify the commitment - cʹ := make([]byte, Size) - copy(cʹ[:], entry.commit) - cʹ[6] ^= 0x33 - - // Open and check for failure - ok, err := Open(cʹ, *entry.decommit) - assertFailedOpen(t, ok, err) - } -} - -// An empty decommit should fail to open -func TestOpenOnDefaultDecommitObject(t *testing.T) { - for _, entry := range testResults { - // Open and check for failure - ok, err := Open(entry.commit, Witness{}) - assertFailedOpen(t, ok, err) - } -} - -// A nil commit should return an error -func TestOpenOnNilCommitment(t *testing.T) { - _, err := Open(nil, Witness{}) - assertError(t, err) -} - -// Verifies that err != nil -func assertError(t *testing.T, err error) { - if err == nil { - t.Error("expected an error but received nil") - } -} - -// Ill-formed commitment should produce an error -func TestOpenOnLongCommitment(t *testing.T) { - tooLong := make([]byte, Size+1) - _, err := Open(tooLong, Witness{}) - assertError(t, err) -} - -// Ill-formed commitment should produce an error -func TestOpenOnShortCommitment(t *testing.T) { - tooShort := make([]byte, Size-1) - _, err := Open(tooShort, Witness{}) - assertError(t, err) -} - -// Tests that marshal-unmarshal is the identity function -func TestWitnessMarshalRoundTrip(t *testing.T) { - expected := &Witness{ - []byte("I'm the dude. So that's what you call me"), - [Size]byte{0xAC}, - } - - // Marhal and test - jsonBytes, err := json.Marshal(expected) - require.NoError(t, err) - require.NotNil(t, jsonBytes) - - // Unmarshal and test - actual := &Witness{} - require.NoError(t, json.Unmarshal(jsonBytes, actual)) - require.Equal(t, expected.Msg, actual.Msg) - require.Equal(t, expected.r, actual.r) -} - -// Tests that marshal-unmarshal is the identity function -func TestCommitmentMarshalRoundTrip(t *testing.T) { - expected := Commitment([]byte("That or uh his-dudeness or duder or el duderino.")) - - // Marhal and test - jsonBytes, err := json.Marshal(expected) - require.NoError(t, err) - require.NotNil(t, jsonBytes) - - // Unmarshal and test - actual := Commitment{} - require.NoError(t, json.Unmarshal(jsonBytes, &actual)) - require.Equal(t, []byte(expected), []byte(actual)) -} diff --git a/crypto/core/curves/bls12377_curve.go b/crypto/core/curves/bls12377_curve.go deleted file mode 100644 index 26e87e579..000000000 --- a/crypto/core/curves/bls12377_curve.go +++ /dev/null @@ -1,1226 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// NOTE that the bls curves are NOT constant time. There is an open issue to address it: https://github.com/sonr-eco/kryptology/issues/233 - -package curves - -import ( - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "fmt" - "io" - "math/big" - - bls12377 "github.com/consensys/gnark-crypto/ecc/bls12-377" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core" -) - -// See 'r' = https://eprint.iacr.org/2018/962.pdf Figure 16 -var ( - bls12377modulus = bhex("12ab655e9a2ca55660b44d1e5c37b00159aa76fed00000010a11800000000001") - g1Inf = bls12377.G1Affine{X: [6]uint64{}, Y: [6]uint64{}} - g2Inf = bls12377.G2Affine{ - X: bls12377.E2{A0: [6]uint64{}, A1: [6]uint64{}}, - Y: bls12377.E2{A0: [6]uint64{}, A1: [6]uint64{}}, - } -) - -type ScalarBls12377 struct { - value *big.Int - point Point -} - -type PointBls12377G1 struct { - value *bls12377.G1Affine -} - -type PointBls12377G2 struct { - value *bls12377.G2Affine -} - -type ScalarBls12377Gt struct { - value *bls12377.GT -} - -func (s *ScalarBls12377) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarBls12377) Hash(bytes []byte) Scalar { - xmd, err := expandMsgXmd(sha256.New(), bytes, []byte("BLS12377_XMD:SHA-256_SSWU_RO_"), 48) - if err != nil { - return nil - } - v := new(big.Int).SetBytes(xmd) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } -} - -func (s *ScalarBls12377) Zero() Scalar { - return &ScalarBls12377{ - value: big.NewInt(0), - point: s.point, - } -} - -func (s *ScalarBls12377) One() Scalar { - return &ScalarBls12377{ - value: big.NewInt(1), - point: s.point, - } -} - -func (s *ScalarBls12377) IsZero() bool { - return subtle.ConstantTimeCompare(s.value.Bytes(), []byte{}) == 1 -} - -func (s *ScalarBls12377) IsOne() bool { - return subtle.ConstantTimeCompare(s.value.Bytes(), []byte{1}) == 1 -} - -func (s *ScalarBls12377) IsOdd() bool { - return s.value.Bit(0) == 1 -} - -func (s *ScalarBls12377) IsEven() bool { - return s.value.Bit(0) == 0 -} - -func (s *ScalarBls12377) New(value int) Scalar { - v := big.NewInt(int64(value)) - if value < 0 { - v.Mod(v, bls12377modulus) - } - return &ScalarBls12377{ - value: v, - point: s.point, - } -} - -func (s *ScalarBls12377) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarBls12377) - if ok { - return s.value.Cmp(r.value) - } else { - return -2 - } -} - -func (s *ScalarBls12377) Square() Scalar { - return &ScalarBls12377{ - value: new(big.Int).Exp(s.value, big.NewInt(2), bls12377modulus), - point: s.point, - } -} - -func (s *ScalarBls12377) Double() Scalar { - v := new(big.Int).Add(s.value, s.value) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } -} - -func (s *ScalarBls12377) Invert() (Scalar, error) { - return &ScalarBls12377{ - value: new(big.Int).ModInverse(s.value, bls12377modulus), - point: s.point, - }, nil -} - -func (s *ScalarBls12377) Sqrt() (Scalar, error) { - return &ScalarBls12377{ - value: new(big.Int).ModSqrt(s.value, bls12377modulus), - point: s.point, - }, nil -} - -func (s *ScalarBls12377) Cube() Scalar { - return &ScalarBls12377{ - value: new(big.Int).Exp(s.value, big.NewInt(3), bls12377modulus), - point: s.point, - } -} - -func (s *ScalarBls12377) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377) - if ok { - v := new(big.Int).Add(s.value, r.value) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12377) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377) - if ok { - v := new(big.Int).Sub(s.value, r.value) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12377) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377) - if ok { - v := new(big.Int).Mul(s.value, r.value) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12377) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarBls12377) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377) - if ok { - v := new(big.Int).ModInverse(r.value, bls12377modulus) - v.Mul(v, s.value) - return &ScalarBls12377{ - value: v.Mod(v, bls12377modulus), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12377) Neg() Scalar { - z := new(big.Int).Neg(s.value) - return &ScalarBls12377{ - value: z.Mod(z, bls12377modulus), - point: s.point, - } -} - -func (s *ScalarBls12377) SetBigInt(v *big.Int) (Scalar, error) { - if v == nil { - return nil, fmt.Errorf("invalid value") - } - t := new(big.Int).Mod(v, bls12377modulus) - if t.Cmp(v) != 0 { - return nil, fmt.Errorf("invalid value") - } - return &ScalarBls12377{ - value: t, - point: s.point, - }, nil -} - -func (s *ScalarBls12377) BigInt() *big.Int { - return new(big.Int).Set(s.value) -} - -func (s *ScalarBls12377) Bytes() []byte { - var out [32]byte - return s.value.FillBytes(out[:]) -} - -func (s *ScalarBls12377) SetBytes(bytes []byte) (Scalar, error) { - value := new(big.Int).SetBytes(bytes) - t := new(big.Int).Mod(value, bls12377modulus) - if t.Cmp(value) != 0 { - return nil, fmt.Errorf("invalid byte sequence") - } - return &ScalarBls12377{ - value: t, - point: s.point, - }, nil -} - -func (s *ScalarBls12377) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) < 32 || len(bytes) > 128 { - return nil, fmt.Errorf("invalid byte sequence") - } - value := new(big.Int).SetBytes(bytes) - t := new(big.Int).Mod(value, bls12377modulus) - return &ScalarBls12377{ - value: t, - point: s.point, - }, nil -} - -func (s *ScalarBls12377) Point() Point { - return s.point.Identity() -} - -func (s *ScalarBls12377) Clone() Scalar { - return &ScalarBls12377{ - value: new(big.Int).Set(s.value), - point: s.point, - } -} - -func (s *ScalarBls12377) SetPoint(p Point) PairingScalar { - return &ScalarBls12377{ - value: new(big.Int).Set(s.value), - point: p, - } -} - -func (s *ScalarBls12377) Order() *big.Int { - return bls12377modulus -} - -func (s *ScalarBls12377) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarBls12377) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12377) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - s.point = ss.point - return nil -} - -func (s *ScalarBls12377) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarBls12377) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12377) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - s.point = ss.point - return nil -} - -func (s *ScalarBls12377) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarBls12377) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarBls12377) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (p *PointBls12377G1) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointBls12377G1) Hash(bytes []byte) Point { - domain := []byte("BLS12377G1_XMD:SHA-256_SVDW_RO_") - pt, err := bls12377.HashToG1(bytes, domain) - if err != nil { - return nil - } - return &PointBls12377G1{value: &pt} -} - -func (p *PointBls12377G1) Identity() Point { - t := bls12377.G1Affine{} - return &PointBls12377G1{ - value: t.Set(&g1Inf), - } -} - -func (p *PointBls12377G1) Generator() Point { - t := bls12377.G1Affine{} - _, _, g1Aff, _ := bls12377.Generators() - return &PointBls12377G1{ - value: t.Set(&g1Aff), - } -} - -func (p *PointBls12377G1) IsIdentity() bool { - return p.value.IsInfinity() -} - -func (p *PointBls12377G1) IsNegative() bool { - // According to https://github.com/zcash/librustzcash/blob/6e0364cd42a2b3d2b958a54771ef51a8db79dd29/pairing/src/bls12_381/README.md#serialization - // This bit represents the sign of the `y` coordinate which is what we want - - return (p.value.Bytes()[0]>>5)&1 == 1 -} - -func (p *PointBls12377G1) IsOnCurve() bool { - return p.value.IsOnCurve() -} - -func (p *PointBls12377G1) Double() Point { - t := &bls12377.G1Jac{} - t.FromAffine(p.value) - t.DoubleAssign() - value := bls12377.G1Affine{} - return &PointBls12377G1{value.FromJacobian(t)} -} - -func (p *PointBls12377G1) Scalar() Scalar { - return &ScalarBls12377{ - value: new(big.Int), - point: new(PointBls12377G1), - } -} - -func (p *PointBls12377G1) Neg() Point { - value := &bls12377.G1Affine{} - value.Neg(p.value) - return &PointBls12377G1{value} -} - -func (p *PointBls12377G1) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12377G1) - if ok { - value := &bls12377.G1Affine{} - return &PointBls12377G1{value.Add(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G1) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12377G1) - if ok { - value := &bls12377.G1Affine{} - return &PointBls12377G1{value.Sub(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G1) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarBls12377) - if ok { - value := &bls12377.G1Affine{} - return &PointBls12377G1{value.ScalarMultiplication(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G1) Equal(rhs Point) bool { - r, ok := rhs.(*PointBls12377G1) - if ok { - return p.value.Equal(r.value) - } else { - return false - } -} - -func (p *PointBls12377G1) Set(x, y *big.Int) (Point, error) { - if x.Cmp(core.Zero) == 0 && - y.Cmp(core.Zero) == 0 { - return p.Identity(), nil - } - var data [96]byte - x.FillBytes(data[:48]) - y.FillBytes(data[48:]) - value := &bls12377.G1Affine{} - _, err := value.SetBytes(data[:]) - if err != nil { - return nil, fmt.Errorf("invalid coordinates") - } - return &PointBls12377G1{value}, nil -} - -func (p *PointBls12377G1) ToAffineCompressed() []byte { - v := p.value.Bytes() - return v[:] -} - -func (p *PointBls12377G1) ToAffineUncompressed() []byte { - v := p.value.RawBytes() - return v[:] -} - -func (p *PointBls12377G1) FromAffineCompressed(bytes []byte) (Point, error) { - if len(bytes) != bls12377.SizeOfG1AffineCompressed { - return nil, fmt.Errorf("invalid point") - } - value := &bls12377.G1Affine{} - _, err := value.SetBytes(bytes) - if err != nil { - return nil, err - } - return &PointBls12377G1{value}, nil -} - -func (p *PointBls12377G1) FromAffineUncompressed(bytes []byte) (Point, error) { - if len(bytes) != bls12377.SizeOfG1AffineUncompressed { - return nil, fmt.Errorf("invalid point") - } - value := &bls12377.G1Affine{} - _, err := value.SetBytes(bytes) - if err != nil { - return nil, err - } - return &PointBls12377G1{value}, nil -} - -func (p *PointBls12377G1) CurveName() string { - return "BLS12377G1" -} - -func (p *PointBls12377G1) SumOfProducts(points []Point, scalars []Scalar) Point { - nScalars := make([]*big.Int, len(scalars)) - for i, sc := range scalars { - s, ok := sc.(*ScalarBls12377) - if !ok { - return nil - } - nScalars[i] = s.value - } - return sumOfProductsPippenger(points, nScalars) -} - -func (p *PointBls12377G1) OtherGroup() PairingPoint { - return new(PointBls12377G2).Identity().(PairingPoint) -} - -func (p *PointBls12377G1) Pairing(rhs PairingPoint) Scalar { - pt, ok := rhs.(*PointBls12377G2) - if !ok { - return nil - } - if !p.value.IsInSubGroup() || - !pt.value.IsInSubGroup() { - return nil - } - value := bls12377.GT{} - if p.value.IsInfinity() || pt.value.IsInfinity() { - return &ScalarBls12377Gt{&value} - } - value, err := bls12377.Pair([]bls12377.G1Affine{*p.value}, []bls12377.G2Affine{*pt.value}) - if err != nil { - return nil - } - - return &ScalarBls12377Gt{&value} -} - -func (p *PointBls12377G1) MultiPairing(points ...PairingPoint) Scalar { - return multiPairingBls12377(points...) -} - -func (p *PointBls12377G1) X() *big.Int { - b := p.value.RawBytes() - return new(big.Int).SetBytes(b[:48]) -} - -func (p *PointBls12377G1) Y() *big.Int { - b := p.value.RawBytes() - return new(big.Int).SetBytes(b[48:]) -} - -func (p *PointBls12377G1) Modulus() *big.Int { - return bls12377modulus -} - -func (p *PointBls12377G1) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointBls12377G1) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12377G1) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointBls12377G1) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointBls12377G1) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12377G1) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointBls12377G1) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointBls12377G1) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointBls12377G1) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} - -func (p *PointBls12377G2) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointBls12377G2) Hash(bytes []byte) Point { - domain := []byte("BLS12377G2_XMD:SHA-256_SVDW_RO_") - pt, err := bls12377.HashToG2(bytes, domain) - if err != nil { - return nil - } - return &PointBls12377G2{value: &pt} -} - -func (p *PointBls12377G2) Identity() Point { - t := bls12377.G2Affine{} - return &PointBls12377G2{ - value: t.Set(&g2Inf), - } -} - -func (p *PointBls12377G2) Generator() Point { - t := bls12377.G2Affine{} - _, _, _, g2Aff := bls12377.Generators() - return &PointBls12377G2{ - value: t.Set(&g2Aff), - } -} - -func (p *PointBls12377G2) IsIdentity() bool { - return p.value.IsInfinity() -} - -func (p *PointBls12377G2) IsNegative() bool { - // According to https://github.com/zcash/librustzcash/blob/6e0364cd42a2b3d2b958a54771ef51a8db79dd29/pairing/src/bls12_381/README.md#serialization - // This bit represents the sign of the `y` coordinate which is what we want - return (p.value.Bytes()[0]>>5)&1 == 1 -} - -func (p *PointBls12377G2) IsOnCurve() bool { - return p.value.IsOnCurve() -} - -func (p *PointBls12377G2) Double() Point { - t := &bls12377.G2Jac{} - t.FromAffine(p.value) - t.DoubleAssign() - value := bls12377.G2Affine{} - return &PointBls12377G2{value.FromJacobian(t)} -} - -func (p *PointBls12377G2) Scalar() Scalar { - return &ScalarBls12377{ - value: new(big.Int), - point: new(PointBls12377G2), - } -} - -func (p *PointBls12377G2) Neg() Point { - value := &bls12377.G2Affine{} - value.Neg(p.value) - return &PointBls12377G2{value} -} - -func (p *PointBls12377G2) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12377G2) - if ok { - value := &bls12377.G2Affine{} - return &PointBls12377G2{value.Add(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G2) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12377G2) - if ok { - value := &bls12377.G2Affine{} - return &PointBls12377G2{value.Sub(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G2) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarBls12377) - if ok { - value := &bls12377.G2Affine{} - return &PointBls12377G2{value.ScalarMultiplication(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointBls12377G2) Equal(rhs Point) bool { - r, ok := rhs.(*PointBls12377G2) - if ok { - return p.value.Equal(r.value) - } else { - return false - } -} - -func (p *PointBls12377G2) Set(x, y *big.Int) (Point, error) { - if x.Cmp(core.Zero) == 0 && - y.Cmp(core.Zero) == 0 { - return p.Identity(), nil - } - var data [192]byte - x.FillBytes(data[:96]) - y.FillBytes(data[96:]) - value := &bls12377.G2Affine{} - _, err := value.SetBytes(data[:]) - if err != nil { - return nil, fmt.Errorf("invalid coordinates") - } - return &PointBls12377G2{value}, nil -} - -func (p *PointBls12377G2) ToAffineCompressed() []byte { - v := p.value.Bytes() - return v[:] -} - -func (p *PointBls12377G2) ToAffineUncompressed() []byte { - v := p.value.RawBytes() - return v[:] -} - -func (p *PointBls12377G2) FromAffineCompressed(bytes []byte) (Point, error) { - if len(bytes) != bls12377.SizeOfG2AffineCompressed { - return nil, fmt.Errorf("invalid point") - } - value := &bls12377.G2Affine{} - _, err := value.SetBytes(bytes) - if err != nil { - return nil, err - } - return &PointBls12377G2{value}, nil -} - -func (p *PointBls12377G2) FromAffineUncompressed(bytes []byte) (Point, error) { - if len(bytes) != bls12377.SizeOfG2AffineUncompressed { - return nil, fmt.Errorf("invalid point") - } - value := &bls12377.G2Affine{} - _, err := value.SetBytes(bytes) - if err != nil { - return nil, err - } - return &PointBls12377G2{value}, nil -} - -func (p *PointBls12377G2) CurveName() string { - return "BLS12377G2" -} - -func (p *PointBls12377G2) SumOfProducts(points []Point, scalars []Scalar) Point { - nScalars := make([]*big.Int, len(scalars)) - for i, sc := range scalars { - s, ok := sc.(*ScalarBls12377) - if !ok { - return nil - } - nScalars[i] = s.value - } - return sumOfProductsPippenger(points, nScalars) -} - -func (p *PointBls12377G2) OtherGroup() PairingPoint { - return new(PointBls12377G1).Identity().(PairingPoint) -} - -func (p *PointBls12377G2) Pairing(rhs PairingPoint) Scalar { - pt, ok := rhs.(*PointBls12377G1) - if !ok { - return nil - } - if !p.value.IsInSubGroup() || - !pt.value.IsInSubGroup() { - return nil - } - value := bls12377.GT{} - if p.value.IsInfinity() || pt.value.IsInfinity() { - return &ScalarBls12377Gt{&value} - } - value, err := bls12377.Pair([]bls12377.G1Affine{*pt.value}, []bls12377.G2Affine{*p.value}) - if err != nil { - return nil - } - - return &ScalarBls12377Gt{&value} -} - -func (p *PointBls12377G2) MultiPairing(points ...PairingPoint) Scalar { - return multiPairingBls12377(points...) -} - -func (p *PointBls12377G2) X() *big.Int { - b := p.value.RawBytes() - return new(big.Int).SetBytes(b[:96]) -} - -func (p *PointBls12377G2) Y() *big.Int { - b := p.value.RawBytes() - return new(big.Int).SetBytes(b[96:]) -} - -func (p *PointBls12377G2) Modulus() *big.Int { - return bls12377modulus -} - -func (p *PointBls12377G2) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointBls12377G2) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12377G2) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointBls12377G2) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointBls12377G2) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12377G2) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointBls12377G2) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointBls12377G2) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointBls12377G2) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} - -func multiPairingBls12377(points ...PairingPoint) Scalar { - if len(points)%2 != 0 { - return nil - } - g1Arr := make([]bls12377.G1Affine, 0, len(points)/2) - g2Arr := make([]bls12377.G2Affine, 0, len(points)/2) - valid := true - for i := 0; i < len(points); i += 2 { - pt1, ok := points[i].(*PointBls12377G1) - valid = valid && ok - pt2, ok := points[i+1].(*PointBls12377G2) - valid = valid && ok - if valid { - valid = valid && pt1.value.IsInSubGroup() - valid = valid && pt2.value.IsInSubGroup() - } - if valid { - g1Arr = append(g1Arr, *pt1.value) - g2Arr = append(g2Arr, *pt2.value) - } - } - if !valid { - return nil - } - - value, err := bls12377.Pair(g1Arr, g2Arr) - if err != nil { - return nil - } - - return &ScalarBls12377Gt{&value} -} - -func (s *ScalarBls12377Gt) Random(reader io.Reader) Scalar { - const width = 48 - offset := 0 - var data [bls12377.SizeOfGT]byte - for i := 0; i < 12; i++ { - tv, err := rand.Int(reader, bls12377modulus) - if err != nil { - return nil - } - tv.FillBytes(data[offset*width : (offset+1)*width]) - offset++ - } - value := bls12377.GT{} - err := value.SetBytes(data[:]) - if err != nil { - return nil - } - return &ScalarBls12377Gt{&value} -} - -func (s *ScalarBls12377Gt) Hash(bytes []byte) Scalar { - reader := sha3.NewShake256() - n, err := reader.Write(bytes) - if err != nil { - return nil - } - if n != len(bytes) { - return nil - } - return s.Random(reader) -} - -func (s *ScalarBls12377Gt) Zero() Scalar { - var t [bls12377.SizeOfGT]byte - value := bls12377.GT{} - err := value.SetBytes(t[:]) - if err != nil { - return nil - } - return &ScalarBls12377Gt{&value} -} - -func (s *ScalarBls12377Gt) One() Scalar { - value := bls12377.GT{} - return &ScalarBls12377Gt{value.SetOne()} -} - -func (s *ScalarBls12377Gt) IsZero() bool { - r := byte(0) - b := s.value.Bytes() - for _, i := range b { - r |= i - } - return r == 0 -} - -func (s *ScalarBls12377Gt) IsOne() bool { - o := bls12377.GT{} - return s.value.Equal(o.SetOne()) -} - -func (s *ScalarBls12377Gt) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarBls12377Gt) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12377Gt) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarBls12377Gt) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarBls12377Gt) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12377Gt) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarBls12377Gt) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarBls12377Gt) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarBls12377Gt) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (s *ScalarBls12377Gt) IsOdd() bool { - data := s.value.Bytes() - return data[len(data)-1]&1 == 1 -} - -func (s *ScalarBls12377Gt) IsEven() bool { - data := s.value.Bytes() - return data[len(data)-1]&1 == 0 -} - -func (s *ScalarBls12377Gt) New(input int) Scalar { - var data [576]byte - data[3] = byte(input >> 24 & 0xFF) - data[2] = byte(input >> 16 & 0xFF) - data[1] = byte(input >> 8 & 0xFF) - data[0] = byte(input & 0xFF) - - value := bls12377.GT{} - err := value.SetBytes(data[:]) - if err != nil { - return nil - } - return &ScalarBls12377Gt{&value} -} - -func (s *ScalarBls12377Gt) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarBls12377Gt) - if ok && s.value.Equal(r.value) { - return 0 - } else { - return -2 - } -} - -func (s *ScalarBls12377Gt) Square() Scalar { - value := bls12377.GT{} - return &ScalarBls12377Gt{ - value.Square(s.value), - } -} - -func (s *ScalarBls12377Gt) Double() Scalar { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Add(s.value, s.value), - } -} - -func (s *ScalarBls12377Gt) Invert() (Scalar, error) { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Inverse(s.value), - }, nil -} - -func (s *ScalarBls12377Gt) Sqrt() (Scalar, error) { - // Not implemented - return nil, nil -} - -func (s *ScalarBls12377Gt) Cube() Scalar { - value := &bls12377.GT{} - value.Square(s.value) - value.Mul(value, s.value) - return &ScalarBls12377Gt{ - value, - } -} - -func (s *ScalarBls12377Gt) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377Gt) - if ok { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Add(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarBls12377Gt) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377Gt) - if ok { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Sub(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarBls12377Gt) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377Gt) - if ok { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Mul(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarBls12377Gt) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarBls12377Gt) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12377Gt) - if ok { - value := &bls12377.GT{} - value.Inverse(r.value) - value.Mul(value, s.value) - return &ScalarBls12377Gt{ - value, - } - } else { - return nil - } -} - -func (s *ScalarBls12377Gt) Neg() Scalar { - sValue := &bls12377.GT{} - sValue.SetOne() - value := &bls12377.GT{} - value.SetOne() - value.Sub(value, sValue) - return &ScalarBls12377Gt{ - value.Sub(value, s.value), - } -} - -func (s *ScalarBls12377Gt) SetBigInt(v *big.Int) (Scalar, error) { - var bytes [576]byte - v.FillBytes(bytes[:]) - return s.SetBytes(bytes[:]) -} - -func (s *ScalarBls12377Gt) BigInt() *big.Int { - b := s.value.Bytes() - return new(big.Int).SetBytes(b[:]) -} - -func (s *ScalarBls12377Gt) Point() Point { - p := &PointBls12377G1{} - return p.Identity() -} - -func (s *ScalarBls12377Gt) Bytes() []byte { - b := s.value.Bytes() - return b[:] -} - -func (s *ScalarBls12377Gt) SetBytes(bytes []byte) (Scalar, error) { - value := &bls12377.GT{} - err := value.SetBytes(bytes) - if err != nil { - return nil, err - } - return &ScalarBls12377Gt{value}, nil -} - -func (s *ScalarBls12377Gt) SetBytesWide(bytes []byte) (Scalar, error) { - l := len(bytes) - if l != 1152 { - return nil, fmt.Errorf("invalid byte sequence") - } - value := &bls12377.GT{} - err := value.SetBytes(bytes[:l/2]) - if err != nil { - return nil, err - } - value2 := &bls12377.GT{} - err = value2.SetBytes(bytes[l/2:]) - if err != nil { - return nil, err - } - value.Add(value, value2) - return &ScalarBls12377Gt{value}, nil -} - -func (s *ScalarBls12377Gt) Clone() Scalar { - value := &bls12377.GT{} - return &ScalarBls12377Gt{ - value.Set(s.value), - } -} diff --git a/crypto/core/curves/bls12381_curve.go b/crypto/core/curves/bls12381_curve.go deleted file mode 100644 index bbf8e5ba9..000000000 --- a/crypto/core/curves/bls12381_curve.go +++ /dev/null @@ -1,1131 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "fmt" - "io" - "math/big" - - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -var bls12381modulus = bhex( - "1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", -) - -type ScalarBls12381 struct { - Value *native.Field - point Point -} - -type PointBls12381G1 struct { - Value *bls12381.G1 -} - -type PointBls12381G2 struct { - Value *bls12381.G2 -} - -type ScalarBls12381Gt struct { - Value *bls12381.Gt -} - -func (s *ScalarBls12381) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarBls12381) Hash(bytes []byte) Scalar { - dst := []byte("BLS12381_XMD:SHA-256_SSWU_RO_") - xmd := native.ExpandMsgXmd(native.EllipticPointHasherSha256(), bytes, dst, 48) - var t [64]byte - copy(t[:48], internal.ReverseScalarBytes(xmd)) - - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().SetBytesWide(&t), - point: s.point, - } -} - -func (s *ScalarBls12381) Zero() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().SetZero(), - point: s.point, - } -} - -func (s *ScalarBls12381) One() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().SetOne(), - point: s.point, - } -} - -func (s *ScalarBls12381) IsZero() bool { - return s.Value.IsZero() == 1 -} - -func (s *ScalarBls12381) IsOne() bool { - return s.Value.IsOne() == 1 -} - -func (s *ScalarBls12381) IsOdd() bool { - bytes := s.Value.Bytes() - return bytes[0]&1 == 1 -} - -func (s *ScalarBls12381) IsEven() bool { - bytes := s.Value.Bytes() - return bytes[0]&1 == 0 -} - -func (s *ScalarBls12381) New(value int) Scalar { - t := bls12381.Bls12381FqNew() - v := big.NewInt(int64(value)) - if value < 0 { - v.Mod(v, t.Params.BiModulus) - } - return &ScalarBls12381{ - Value: t.SetBigInt(v), - point: s.point, - } -} - -func (s *ScalarBls12381) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarBls12381) - if ok { - return s.Value.Cmp(r.Value) - } else { - return -2 - } -} - -func (s *ScalarBls12381) Square() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Square(s.Value), - point: s.point, - } -} - -func (s *ScalarBls12381) Double() Scalar { - v := bls12381.Bls12381FqNew().Double(s.Value) - return &ScalarBls12381{ - Value: v, - point: s.point, - } -} - -func (s *ScalarBls12381) Invert() (Scalar, error) { - value, wasInverted := bls12381.Bls12381FqNew().Invert(s.Value) - if !wasInverted { - return nil, fmt.Errorf("inverse doesn't exist") - } - return &ScalarBls12381{ - Value: value, - point: s.point, - }, nil -} - -func (s *ScalarBls12381) Sqrt() (Scalar, error) { - value, wasSquare := bls12381.Bls12381FqNew().Sqrt(s.Value) - if !wasSquare { - return nil, fmt.Errorf("not a square") - } - return &ScalarBls12381{ - Value: value, - point: s.point, - }, nil -} - -func (s *ScalarBls12381) Cube() Scalar { - value := bls12381.Bls12381FqNew().Square(s.Value) - value.Mul(value, s.Value) - return &ScalarBls12381{ - Value: value, - point: s.point, - } -} - -func (s *ScalarBls12381) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381) - if ok { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Add(s.Value, r.Value), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12381) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381) - if ok { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Sub(s.Value, r.Value), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12381) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381) - if ok { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Mul(s.Value, r.Value), - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12381) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarBls12381) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381) - if ok { - v, wasInverted := bls12381.Bls12381FqNew().Invert(r.Value) - if !wasInverted { - return nil - } - v.Mul(v, s.Value) - return &ScalarBls12381{ - Value: v, - point: s.point, - } - } else { - return nil - } -} - -func (s *ScalarBls12381) Neg() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Neg(s.Value), - point: s.point, - } -} - -func (s *ScalarBls12381) SetBigInt(v *big.Int) (Scalar, error) { - if v == nil { - return nil, fmt.Errorf("invalid value") - } - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().SetBigInt(v), - point: s.point, - }, nil -} - -func (s *ScalarBls12381) BigInt() *big.Int { - return s.Value.BigInt() -} - -func (s *ScalarBls12381) Bytes() []byte { - t := s.Value.Bytes() - return internal.ReverseScalarBytes(t[:]) -} - -func (s *ScalarBls12381) SetBytes(bytes []byte) (Scalar, error) { - if len(bytes) != 32 { - return nil, fmt.Errorf("invalid length") - } - var seq [32]byte - copy(seq[:], internal.ReverseScalarBytes(bytes)) - value, err := bls12381.Bls12381FqNew().SetBytes(&seq) - if err != nil { - return nil, err - } - return &ScalarBls12381{ - value, s.point, - }, nil -} - -func (s *ScalarBls12381) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) != 64 { - return nil, fmt.Errorf("invalid length") - } - var seq [64]byte - copy(seq[:], bytes) - return &ScalarBls12381{ - bls12381.Bls12381FqNew().SetBytesWide(&seq), s.point, - }, nil -} - -func (s *ScalarBls12381) Point() Point { - return s.point.Identity() -} - -func (s *ScalarBls12381) Clone() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Set(s.Value), - point: s.point, - } -} - -func (s *ScalarBls12381) SetPoint(p Point) PairingScalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew().Set(s.Value), - point: p, - } -} - -func (s *ScalarBls12381) Order() *big.Int { - return s.Value.Params.BiModulus -} - -func (s *ScalarBls12381) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarBls12381) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12381) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.Value = ss.Value - s.point = ss.point - return nil -} - -func (s *ScalarBls12381) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarBls12381) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12381) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.Value = ss.Value - s.point = ss.point - return nil -} - -func (s *ScalarBls12381) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarBls12381) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarBls12381) - if !ok { - return fmt.Errorf("invalid type") - } - s.Value = S.Value - return nil -} - -func (p *PointBls12381G1) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointBls12381G1) Hash(bytes []byte) Point { - domain := []byte("BLS12381G1_XMD:SHA-256_SSWU_RO_") - pt := new(bls12381.G1).Hash(native.EllipticPointHasherSha256(), bytes, domain) - return &PointBls12381G1{Value: pt} -} - -func (p *PointBls12381G1) Identity() Point { - return &PointBls12381G1{ - Value: new(bls12381.G1).Identity(), - } -} - -func (p *PointBls12381G1) Generator() Point { - return &PointBls12381G1{ - Value: new(bls12381.G1).Generator(), - } -} - -func (p *PointBls12381G1) IsIdentity() bool { - return p.Value.IsIdentity() == 1 -} - -func (p *PointBls12381G1) IsNegative() bool { - // According to https://github.com/zcash/librustzcash/blob/6e0364cd42a2b3d2b958a54771ef51a8db79dd29/pairing/src/bls12_381/README.md#serialization - // This bit represents the sign of the `y` coordinate which is what we want - return (p.Value.ToCompressed()[0]>>5)&1 == 1 -} - -func (p *PointBls12381G1) IsOnCurve() bool { - return p.Value.IsOnCurve() == 1 -} - -func (p *PointBls12381G1) Double() Point { - return &PointBls12381G1{new(bls12381.G1).Double(p.Value)} -} - -func (p *PointBls12381G1) Scalar() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew(), - point: new(PointBls12381G1), - } -} - -func (p *PointBls12381G1) Neg() Point { - return &PointBls12381G1{new(bls12381.G1).Neg(p.Value)} -} - -func (p *PointBls12381G1) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12381G1) - if ok { - return &PointBls12381G1{new(bls12381.G1).Add(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G1) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12381G1) - if ok { - return &PointBls12381G1{new(bls12381.G1).Sub(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G1) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarBls12381) - if ok { - return &PointBls12381G1{new(bls12381.G1).Mul(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G1) Equal(rhs Point) bool { - r, ok := rhs.(*PointBls12381G1) - if ok { - return p.Value.Equal(r.Value) == 1 - } else { - return false - } -} - -func (p *PointBls12381G1) Set(x, y *big.Int) (Point, error) { - value, err := new(bls12381.G1).SetBigInt(x, y) - if err != nil { - return nil, fmt.Errorf("invalid coordinates") - } - return &PointBls12381G1{value}, nil -} - -func (p *PointBls12381G1) ToAffineCompressed() []byte { - out := p.Value.ToCompressed() - return out[:] -} - -func (p *PointBls12381G1) ToAffineUncompressed() []byte { - out := p.Value.ToUncompressed() - return out[:] -} - -func (p *PointBls12381G1) FromAffineCompressed(bytes []byte) (Point, error) { - var b [bls12381.FieldBytes]byte - copy(b[:], bytes) - value, err := new(bls12381.G1).FromCompressed(&b) - if err != nil { - return nil, err - } - return &PointBls12381G1{value}, nil -} - -func (p *PointBls12381G1) FromAffineUncompressed(bytes []byte) (Point, error) { - var b [96]byte - copy(b[:], bytes) - value, err := new(bls12381.G1).FromUncompressed(&b) - if err != nil { - return nil, err - } - return &PointBls12381G1{value}, nil -} - -func (p *PointBls12381G1) CurveName() string { - return "BLS12381G1" -} - -func (p *PointBls12381G1) SumOfProducts(points []Point, scalars []Scalar) Point { - nPoints := make([]*bls12381.G1, len(points)) - nScalars := make([]*native.Field, len(scalars)) - for i, pt := range points { - pp, ok := pt.(*PointBls12381G1) - if !ok { - return nil - } - nPoints[i] = pp.Value - } - for i, sc := range scalars { - s, ok := sc.(*ScalarBls12381) - if !ok { - return nil - } - nScalars[i] = s.Value - } - value, err := new(bls12381.G1).SumOfProducts(nPoints, nScalars) - if err != nil { - return nil - } - return &PointBls12381G1{value} -} - -func (p *PointBls12381G1) OtherGroup() PairingPoint { - return new(PointBls12381G2).Identity().(PairingPoint) -} - -func (p *PointBls12381G1) Pairing(rhs PairingPoint) Scalar { - pt, ok := rhs.(*PointBls12381G2) - if !ok { - return nil - } - e := new(bls12381.Engine) - e.AddPair(p.Value, pt.Value) - - value := e.Result() - - return &ScalarBls12381Gt{value} -} - -func (p *PointBls12381G1) MultiPairing(points ...PairingPoint) Scalar { - return multiPairing(points...) -} - -func (p *PointBls12381G1) X() *big.Int { - return p.Value.GetX().BigInt() -} - -func (p *PointBls12381G1) Y() *big.Int { - return p.Value.GetY().BigInt() -} - -func (p *PointBls12381G1) Modulus() *big.Int { - return bls12381modulus -} - -func (p *PointBls12381G1) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointBls12381G1) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12381G1) - if !ok { - return fmt.Errorf("invalid point") - } - p.Value = ppt.Value - return nil -} - -func (p *PointBls12381G1) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointBls12381G1) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12381G1) - if !ok { - return fmt.Errorf("invalid point") - } - p.Value = ppt.Value - return nil -} - -func (p *PointBls12381G1) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointBls12381G1) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointBls12381G1) - if !ok { - return fmt.Errorf("invalid type") - } - p.Value = P.Value - return nil -} - -func (p *PointBls12381G2) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointBls12381G2) Hash(bytes []byte) Point { - domain := []byte("BLS12381G2_XMD:SHA-256_SSWU_RO_") - pt := new(bls12381.G2).Hash(native.EllipticPointHasherSha256(), bytes, domain) - return &PointBls12381G2{Value: pt} -} - -func (p *PointBls12381G2) Identity() Point { - return &PointBls12381G2{ - Value: new(bls12381.G2).Identity(), - } -} - -func (p *PointBls12381G2) Generator() Point { - return &PointBls12381G2{ - Value: new(bls12381.G2).Generator(), - } -} - -func (p *PointBls12381G2) IsIdentity() bool { - return p.Value.IsIdentity() == 1 -} - -func (p *PointBls12381G2) IsNegative() bool { - // According to https://github.com/zcash/librustzcash/blob/6e0364cd42a2b3d2b958a54771ef51a8db79dd29/pairing/src/bls12_381/README.md#serialization - // This bit represents the sign of the `y` coordinate which is what we want - return (p.Value.ToCompressed()[0]>>5)&1 == 1 -} - -func (p *PointBls12381G2) IsOnCurve() bool { - return p.Value.IsOnCurve() == 1 -} - -func (p *PointBls12381G2) Double() Point { - return &PointBls12381G2{new(bls12381.G2).Double(p.Value)} -} - -func (p *PointBls12381G2) Scalar() Scalar { - return &ScalarBls12381{ - Value: bls12381.Bls12381FqNew(), - point: new(PointBls12381G2), - } -} - -func (p *PointBls12381G2) Neg() Point { - return &PointBls12381G2{new(bls12381.G2).Neg(p.Value)} -} - -func (p *PointBls12381G2) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12381G2) - if ok { - return &PointBls12381G2{new(bls12381.G2).Add(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G2) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointBls12381G2) - if ok { - return &PointBls12381G2{new(bls12381.G2).Sub(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G2) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarBls12381) - if ok { - return &PointBls12381G2{new(bls12381.G2).Mul(p.Value, r.Value)} - } else { - return nil - } -} - -func (p *PointBls12381G2) Equal(rhs Point) bool { - r, ok := rhs.(*PointBls12381G2) - if ok { - return p.Value.Equal(r.Value) == 1 - } else { - return false - } -} - -func (p *PointBls12381G2) Set(x, y *big.Int) (Point, error) { - value, err := new(bls12381.G2).SetBigInt(x, y) - if err != nil { - return nil, fmt.Errorf("invalid coordinates") - } - return &PointBls12381G2{value}, nil -} - -func (p *PointBls12381G2) ToAffineCompressed() []byte { - out := p.Value.ToCompressed() - return out[:] -} - -func (p *PointBls12381G2) ToAffineUncompressed() []byte { - out := p.Value.ToUncompressed() - return out[:] -} - -func (p *PointBls12381G2) FromAffineCompressed(bytes []byte) (Point, error) { - var b [bls12381.WideFieldBytes]byte - copy(b[:], bytes) - value, err := new(bls12381.G2).FromCompressed(&b) - if err != nil { - return nil, err - } - return &PointBls12381G2{value}, nil -} - -func (p *PointBls12381G2) FromAffineUncompressed(bytes []byte) (Point, error) { - var b [bls12381.DoubleWideFieldBytes]byte - copy(b[:], bytes) - value, err := new(bls12381.G2).FromUncompressed(&b) - if err != nil { - return nil, err - } - return &PointBls12381G2{value}, nil -} - -func (p *PointBls12381G2) CurveName() string { - return "BLS12381G2" -} - -func (p *PointBls12381G2) SumOfProducts(points []Point, scalars []Scalar) Point { - nPoints := make([]*bls12381.G2, len(points)) - nScalars := make([]*native.Field, len(scalars)) - for i, pt := range points { - pp, ok := pt.(*PointBls12381G2) - if !ok { - return nil - } - nPoints[i] = pp.Value - } - for i, sc := range scalars { - s, ok := sc.(*ScalarBls12381) - if !ok { - return nil - } - nScalars[i] = s.Value - } - value, err := new(bls12381.G2).SumOfProducts(nPoints, nScalars) - if err != nil { - return nil - } - return &PointBls12381G2{value} -} - -func (p *PointBls12381G2) OtherGroup() PairingPoint { - return new(PointBls12381G1).Identity().(PairingPoint) -} - -func (p *PointBls12381G2) Pairing(rhs PairingPoint) Scalar { - pt, ok := rhs.(*PointBls12381G1) - if !ok { - return nil - } - e := new(bls12381.Engine) - e.AddPair(pt.Value, p.Value) - - value := e.Result() - - return &ScalarBls12381Gt{value} -} - -func (p *PointBls12381G2) MultiPairing(points ...PairingPoint) Scalar { - return multiPairing(points...) -} - -func (p *PointBls12381G2) X() *big.Int { - x := p.Value.ToUncompressed() - return new(big.Int).SetBytes(x[:bls12381.WideFieldBytes]) -} - -func (p *PointBls12381G2) Y() *big.Int { - y := p.Value.ToUncompressed() - return new(big.Int).SetBytes(y[bls12381.WideFieldBytes:]) -} - -func (p *PointBls12381G2) Modulus() *big.Int { - return bls12381modulus -} - -func (p *PointBls12381G2) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointBls12381G2) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12381G2) - if !ok { - return fmt.Errorf("invalid point") - } - p.Value = ppt.Value - return nil -} - -func (p *PointBls12381G2) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointBls12381G2) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointBls12381G2) - if !ok { - return fmt.Errorf("invalid point") - } - p.Value = ppt.Value - return nil -} - -func (p *PointBls12381G2) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointBls12381G2) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointBls12381G2) - if !ok { - return fmt.Errorf("invalid type") - } - p.Value = P.Value - return nil -} - -func multiPairing(points ...PairingPoint) Scalar { - if len(points)%2 != 0 { - return nil - } - valid := true - eng := new(bls12381.Engine) - for i := 0; i < len(points); i += 2 { - pt1, ok := points[i].(*PointBls12381G1) - valid = valid && ok - pt2, ok := points[i+1].(*PointBls12381G2) - valid = valid && ok - if valid { - eng.AddPair(pt1.Value, pt2.Value) - } - } - if !valid { - return nil - } - - value := eng.Result() - return &ScalarBls12381Gt{value} -} - -func (s *ScalarBls12381Gt) Random(reader io.Reader) Scalar { - value, err := new(bls12381.Gt).Random(reader) - if err != nil { - return nil - } - return &ScalarBls12381Gt{value} -} - -func (s *ScalarBls12381Gt) Hash(bytes []byte) Scalar { - reader := sha3.NewShake256() - n, err := reader.Write(bytes) - if err != nil { - return nil - } - if n != len(bytes) { - return nil - } - return s.Random(reader) -} - -func (s *ScalarBls12381Gt) Zero() Scalar { - return &ScalarBls12381Gt{new(bls12381.Gt)} -} - -func (s *ScalarBls12381Gt) One() Scalar { - return &ScalarBls12381Gt{new(bls12381.Gt).SetOne()} -} - -func (s *ScalarBls12381Gt) IsZero() bool { - return s.Value.IsZero() == 1 -} - -func (s *ScalarBls12381Gt) IsOne() bool { - return s.Value.IsOne() == 1 -} - -func (s *ScalarBls12381Gt) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarBls12381Gt) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12381Gt) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.Value = ss.Value - return nil -} - -func (s *ScalarBls12381Gt) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarBls12381Gt) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarBls12381Gt) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.Value = ss.Value - return nil -} - -func (s *ScalarBls12381Gt) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarBls12381Gt) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarBls12381Gt) - if !ok { - return fmt.Errorf("invalid type") - } - s.Value = S.Value - return nil -} - -func (s *ScalarBls12381Gt) IsOdd() bool { - data := s.Value.Bytes() - return data[0]&1 == 1 -} - -func (s *ScalarBls12381Gt) IsEven() bool { - data := s.Value.Bytes() - return data[0]&1 == 0 -} - -func (s *ScalarBls12381Gt) New(input int) Scalar { - var data [bls12381.GtFieldBytes]byte - data[3] = byte(input >> 24 & 0xFF) - data[2] = byte(input >> 16 & 0xFF) - data[1] = byte(input >> 8 & 0xFF) - data[0] = byte(input & 0xFF) - - value, isCanonical := new(bls12381.Gt).SetBytes(&data) - if isCanonical != 1 { - return nil - } - return &ScalarBls12381Gt{value} -} - -func (s *ScalarBls12381Gt) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarBls12381Gt) - if ok && s.Value.Equal(r.Value) == 1 { - return 0 - } else { - return -2 - } -} - -func (s *ScalarBls12381Gt) Square() Scalar { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Square(s.Value), - } -} - -func (s *ScalarBls12381Gt) Double() Scalar { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Double(s.Value), - } -} - -func (s *ScalarBls12381Gt) Invert() (Scalar, error) { - value, wasInverted := new(bls12381.Gt).Invert(s.Value) - if wasInverted != 1 { - return nil, fmt.Errorf("not invertible") - } - return &ScalarBls12381Gt{ - value, - }, nil -} - -func (s *ScalarBls12381Gt) Sqrt() (Scalar, error) { - // Not implemented - return nil, nil -} - -func (s *ScalarBls12381Gt) Cube() Scalar { - value := new(bls12381.Gt).Square(s.Value) - value.Add(value, s.Value) - return &ScalarBls12381Gt{ - value, - } -} - -func (s *ScalarBls12381Gt) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381Gt) - if ok { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Add(s.Value, r.Value), - } - } else { - return nil - } -} - -func (s *ScalarBls12381Gt) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381Gt) - if ok { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Sub(s.Value, r.Value), - } - } else { - return nil - } -} - -func (s *ScalarBls12381Gt) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381Gt) - if ok { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Add(s.Value, r.Value), - } - } else { - return nil - } -} - -func (s *ScalarBls12381Gt) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarBls12381Gt) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarBls12381Gt) - if ok { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Sub(s.Value, r.Value), - } - } else { - return nil - } -} - -func (s *ScalarBls12381Gt) Neg() Scalar { - return &ScalarBls12381Gt{ - new(bls12381.Gt).Neg(s.Value), - } -} - -func (s *ScalarBls12381Gt) SetBigInt(v *big.Int) (Scalar, error) { - var bytes [bls12381.GtFieldBytes]byte - v.FillBytes(bytes[:]) - return s.SetBytes(bytes[:]) -} - -func (s *ScalarBls12381Gt) BigInt() *big.Int { - bytes := s.Value.Bytes() - return new(big.Int).SetBytes(bytes[:]) -} - -func (s *ScalarBls12381Gt) Point() Point { - return &PointBls12381G1{Value: new(bls12381.G1).Identity()} -} - -func (s *ScalarBls12381Gt) Bytes() []byte { - bytes := s.Value.Bytes() - return bytes[:] -} - -func (s *ScalarBls12381Gt) SetBytes(bytes []byte) (Scalar, error) { - var b [bls12381.GtFieldBytes]byte - copy(b[:], bytes) - ss, isCanonical := new(bls12381.Gt).SetBytes(&b) - if isCanonical == 0 { - return nil, fmt.Errorf("invalid bytes") - } - return &ScalarBls12381Gt{ss}, nil -} - -func (s *ScalarBls12381Gt) SetBytesWide(bytes []byte) (Scalar, error) { - l := len(bytes) - if l != bls12381.GtFieldBytes*2 { - return nil, fmt.Errorf("invalid byte sequence") - } - var b [bls12381.GtFieldBytes]byte - copy(b[:], bytes[:bls12381.GtFieldBytes]) - - value, isCanonical := new(bls12381.Gt).SetBytes(&b) - if isCanonical == 0 { - return nil, fmt.Errorf("invalid byte sequence") - } - copy(b[:], bytes[bls12381.GtFieldBytes:]) - value2, isCanonical := new(bls12381.Gt).SetBytes(&b) - if isCanonical == 0 { - return nil, fmt.Errorf("invalid byte sequence") - } - value.Add(value, value2) - return &ScalarBls12381Gt{value}, nil -} - -func (s *ScalarBls12381Gt) Clone() Scalar { - return &ScalarBls12381Gt{ - Value: new(bls12381.Gt).Set(s.Value), - } -} diff --git a/crypto/core/curves/curve.go b/crypto/core/curves/curve.go deleted file mode 100644 index 5770d8981..000000000 --- a/crypto/core/curves/curve.go +++ /dev/null @@ -1,863 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "io" - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -var ( - k256Initonce sync.Once - k256 Curve - - bls12381g1Initonce sync.Once - bls12381g1 Curve - - bls12381g2Initonce sync.Once - bls12381g2 Curve - - bls12377g1Initonce sync.Once - bls12377g1 Curve - - bls12377g2Initonce sync.Once - bls12377g2 Curve - - p256Initonce sync.Once - p256 Curve - - ed25519Initonce sync.Once - ed25519 Curve - - pallasInitonce sync.Once - pallas Curve -) - -const ( - K256Name = "secp256k1" - BLS12381G1Name = "BLS12381G1" - BLS12381G2Name = "BLS12381G2" - BLS12831Name = "BLS12831" - P256Name = "P-256" - ED25519Name = "ed25519" - PallasName = "pallas" - BLS12377G1Name = "BLS12377G1" - BLS12377G2Name = "BLS12377G2" - BLS12377Name = "BLS12377" -) - -const scalarBytes = 32 - -// Scalar represents an element of the scalar field \mathbb{F}_q -// of the elliptic curve construction. -type Scalar interface { - // Random returns a random scalar using the provided reader - // to retrieve bytes - Random(reader io.Reader) Scalar - // Hash the specific bytes in a manner to yield a - // uniformly distributed scalar - Hash(bytes []byte) Scalar - // Zero returns the additive identity element - Zero() Scalar - // One returns the multiplicative identity element - One() Scalar - // IsZero returns true if this element is the additive identity element - IsZero() bool - // IsOne returns true if this element is the multiplicative identity element - IsOne() bool - // IsOdd returns true if this element is odd - IsOdd() bool - // IsEven returns true if this element is even - IsEven() bool - // New returns an element with the value equal to `value` - New(value int) Scalar - // Cmp returns - // -2 if this element is in a different field than rhs - // -1 if this element is less than rhs - // 0 if this element is equal to rhs - // 1 if this element is greater than rhs - Cmp(rhs Scalar) int - // Square returns element*element - Square() Scalar - // Double returns element+element - Double() Scalar - // Invert returns element^-1 mod p - Invert() (Scalar, error) - // Sqrt computes the square root of this element if it exists. - Sqrt() (Scalar, error) - // Cube returns element*element*element - Cube() Scalar - // Add returns element+rhs - Add(rhs Scalar) Scalar - // Sub returns element-rhs - Sub(rhs Scalar) Scalar - // Mul returns element*rhs - Mul(rhs Scalar) Scalar - // MulAdd returns element * y + z mod p - MulAdd(y, z Scalar) Scalar - // Div returns element*rhs^-1 mod p - Div(rhs Scalar) Scalar - // Neg returns -element mod p - Neg() Scalar - // SetBigInt returns this element set to the value of v - SetBigInt(v *big.Int) (Scalar, error) - // BigInt returns this element as a big integer - BigInt() *big.Int - // Point returns the associated point for this scalar - Point() Point - // Bytes returns the canonical byte representation of this scalar - Bytes() []byte - // SetBytes creates a scalar from the canonical representation expecting the exact number of bytes needed to represent the scalar - SetBytes(bytes []byte) (Scalar, error) - // SetBytesWide creates a scalar expecting double the exact number of bytes needed to represent the scalar which is reduced by the modulus - SetBytesWide(bytes []byte) (Scalar, error) - // Clone returns a cloned Scalar of this value - Clone() Scalar -} - -type PairingScalar interface { - Scalar - SetPoint(p Point) PairingScalar -} - -func unmarshalScalar(input []byte) (*Curve, []byte, error) { - sep := byte(':') - i := 0 - for ; i < len(input); i++ { - if input[i] == sep { - break - } - } - name := string(input[:i]) - curve := GetCurveByName(name) - if curve == nil { - return nil, nil, fmt.Errorf("unrecognized curve") - } - return curve, input[i+1:], nil -} - -func scalarMarshalBinary(scalar Scalar) ([]byte, error) { - // All scalars are 32 bytes long - // The last 32 bytes are the actual value - // The first remaining bytes are the curve name - // separated by a colon - name := []byte(scalar.Point().CurveName()) - output := make([]byte, len(name)+1+scalarBytes) - copy(output[:len(name)], name) - output[len(name)] = byte(':') - copy(output[len(name)+1:], scalar.Bytes()) - return output, nil -} - -func scalarUnmarshalBinary(input []byte) (Scalar, error) { - // All scalars are 32 bytes long - // The first 32 bytes are the actual value - // The remaining bytes are the curve name - if len(input) < scalarBytes+1+len(P256Name) { - return nil, fmt.Errorf("invalid byte sequence") - } - sc, data, err := unmarshalScalar(input) - if err != nil { - return nil, err - } - return sc.Scalar.SetBytes(data) -} - -func scalarMarshalText(scalar Scalar) ([]byte, error) { - // All scalars are 32 bytes long - // For text encoding we put the curve name first for readability - // separated by a colon, then the hex encoding of the scalar - // which avoids the base64 weakness with strict mode or not - name := []byte(scalar.Point().CurveName()) - output := make([]byte, len(name)+1+scalarBytes*2) - copy(output[:len(name)], name) - output[len(name)] = byte(':') - _ = hex.Encode(output[len(name)+1:], scalar.Bytes()) - return output, nil -} - -func scalarUnmarshalText(input []byte) (Scalar, error) { - if len(input) < scalarBytes*2+len(P256Name)+1 { - return nil, fmt.Errorf("invalid byte sequence") - } - curve, data, err := unmarshalScalar(input) - if err != nil { - return nil, err - } - var t [scalarBytes]byte - _, err = hex.Decode(t[:], data) - if err != nil { - return nil, err - } - return curve.Scalar.SetBytes(t[:]) -} - -func scalarMarshalJson(scalar Scalar) ([]byte, error) { - m := make(map[string]string, 2) - m["type"] = scalar.Point().CurveName() - m["value"] = hex.EncodeToString(scalar.Bytes()) - return json.Marshal(m) -} - -func scalarUnmarshalJson(input []byte) (Scalar, error) { - var m map[string]string - - err := json.Unmarshal(input, &m) - if err != nil { - return nil, err - } - curve := GetCurveByName(m["type"]) - if curve == nil { - return nil, fmt.Errorf("invalid type") - } - s, err := hex.DecodeString(m["value"]) - if err != nil { - return nil, err - } - S, err := curve.Scalar.SetBytes(s) - if err != nil { - return nil, err - } - return S, nil -} - -// Point represents an elliptic curve point -type Point interface { - Random(reader io.Reader) Point - Hash(bytes []byte) Point - Identity() Point - Generator() Point - IsIdentity() bool - IsNegative() bool - IsOnCurve() bool - Double() Point - Scalar() Scalar - Neg() Point - Add(rhs Point) Point - Sub(rhs Point) Point - Mul(rhs Scalar) Point - Equal(rhs Point) bool - Set(x, y *big.Int) (Point, error) - ToAffineCompressed() []byte - ToAffineUncompressed() []byte - FromAffineCompressed(bytes []byte) (Point, error) - FromAffineUncompressed(bytes []byte) (Point, error) - CurveName() string - SumOfProducts(points []Point, scalars []Scalar) Point -} - -type PairingPoint interface { - Point - OtherGroup() PairingPoint - Pairing(rhs PairingPoint) Scalar - MultiPairing(...PairingPoint) Scalar -} - -func pointMarshalBinary(point Point) ([]byte, error) { - // Always stores points in compressed form - // The first bytes are the curve name - // separated by a colon followed by the compressed point - // bytes - t := point.ToAffineCompressed() - name := []byte(point.CurveName()) - output := make([]byte, len(name)+1+len(t)) - copy(output[:len(name)], name) - output[len(name)] = byte(':') - copy(output[len(output)-len(t):], t) - return output, nil -} - -func pointUnmarshalBinary(input []byte) (Point, error) { - if len(input) < scalarBytes+1+len(P256Name) { - return nil, fmt.Errorf("invalid byte sequence") - } - sep := byte(':') - i := 0 - for ; i < len(input); i++ { - if input[i] == sep { - break - } - } - name := string(input[:i]) - curve := GetCurveByName(name) - if curve == nil { - return nil, fmt.Errorf("unrecognized curve") - } - return curve.Point.FromAffineCompressed(input[i+1:]) -} - -func pointMarshalText(point Point) ([]byte, error) { - // Always stores points in compressed form - // The first bytes are the curve name - // separated by a colon followed by the compressed point - // bytes - t := point.ToAffineCompressed() - name := []byte(point.CurveName()) - output := make([]byte, len(name)+1+len(t)*2) - copy(output[:len(name)], name) - output[len(name)] = byte(':') - hex.Encode(output[len(output)-len(t)*2:], t) - return output, nil -} - -func pointUnmarshalText(input []byte) (Point, error) { - if len(input) < scalarBytes*2+1+len(P256Name) { - return nil, fmt.Errorf("invalid byte sequence") - } - sep := byte(':') - i := 0 - for ; i < len(input); i++ { - if input[i] == sep { - break - } - } - name := string(input[:i]) - curve := GetCurveByName(name) - if curve == nil { - return nil, fmt.Errorf("unrecognized curve") - } - buffer := make([]byte, (len(input)-i)/2) - _, err := hex.Decode(buffer, input[i+1:]) - if err != nil { - return nil, err - } - return curve.Point.FromAffineCompressed(buffer) -} - -func pointMarshalJSON(point Point) ([]byte, error) { - m := make(map[string]string, 2) - m["type"] = point.CurveName() - m["value"] = hex.EncodeToString(point.ToAffineCompressed()) - return json.Marshal(m) -} - -func pointUnmarshalJSON(input []byte) (Point, error) { - var m map[string]string - - err := json.Unmarshal(input, &m) - if err != nil { - return nil, err - } - curve := GetCurveByName(m["type"]) - if curve == nil { - return nil, fmt.Errorf("invalid type") - } - p, err := hex.DecodeString(m["value"]) - if err != nil { - return nil, err - } - P, err := curve.Point.FromAffineCompressed(p) - if err != nil { - return nil, err - } - return P, nil -} - -// Curve represents a named elliptic curve with a scalar field and point group -type Curve struct { - Scalar Scalar - Point Point - Name string -} - -func (c Curve) ScalarBaseMult(sc Scalar) Point { - return c.Point.Generator().Mul(sc) -} - -func (c Curve) NewGeneratorPoint() Point { - return c.Point.Generator() -} - -func (c Curve) NewIdentityPoint() Point { - return c.Point.Identity() -} - -func (c Curve) NewScalar() Scalar { - return c.Scalar.Zero() -} - -// ToEllipticCurve returns the equivalent of this curve as the go interface `elliptic.Curve` -func (c Curve) ToEllipticCurve() (elliptic.Curve, error) { - err := fmt.Errorf("can't convert %s", c.Name) - switch c.Name { - case K256Name: - return K256Curve(), nil - case BLS12381G1Name: - return nil, err - case BLS12381G2Name: - return nil, err - case BLS12831Name: - return nil, err - case P256Name: - return NistP256Curve(), nil - case ED25519Name: - return nil, err - case PallasName: - return nil, err - case BLS12377G1Name: - return nil, err - case BLS12377G2Name: - return nil, err - case BLS12377Name: - return nil, err - default: - return nil, err - } -} - -// PairingCurve represents a named elliptic curve -// that supports pairings -type PairingCurve struct { - Scalar PairingScalar - PointG1 PairingPoint - PointG2 PairingPoint - GT Scalar - Name string -} - -func (c PairingCurve) ScalarG1BaseMult(sc Scalar) PairingPoint { - return c.PointG1.Generator().Mul(sc).(PairingPoint) -} - -func (c PairingCurve) ScalarG2BaseMult(sc Scalar) PairingPoint { - return c.PointG2.Generator().Mul(sc).(PairingPoint) -} - -func (c PairingCurve) NewG1GeneratorPoint() PairingPoint { - return c.PointG1.Generator().(PairingPoint) -} - -func (c PairingCurve) NewG2GeneratorPoint() PairingPoint { - return c.PointG2.Generator().(PairingPoint) -} - -func (c PairingCurve) NewG1IdentityPoint() PairingPoint { - return c.PointG1.Identity().(PairingPoint) -} - -func (c PairingCurve) NewG2IdentityPoint() PairingPoint { - return c.PointG2.Identity().(PairingPoint) -} - -func (c PairingCurve) NewScalar() PairingScalar { - return c.Scalar.Zero().(PairingScalar) -} - -// GetCurveByName returns the correct `Curve` given the name -func GetCurveByName(name string) *Curve { - switch name { - case K256Name: - return K256() - case BLS12381G1Name: - return BLS12381G1() - case BLS12381G2Name: - return BLS12381G2() - case BLS12831Name: - return BLS12381G1() - case P256Name: - return P256() - case ED25519Name: - return ED25519() - case PallasName: - return PALLAS() - case BLS12377G1Name: - return BLS12377G1() - case BLS12377G2Name: - return BLS12377G2() - case BLS12377Name: - return BLS12377G1() - default: - return nil - } -} - -func GetPairingCurveByName(name string) *PairingCurve { - switch name { - case BLS12381G1Name: - return BLS12381(BLS12381G1().NewIdentityPoint()) - case BLS12381G2Name: - return BLS12381(BLS12381G2().NewIdentityPoint()) - case BLS12831Name: - return BLS12381(BLS12381G1().NewIdentityPoint()) - default: - return nil - } -} - -// BLS12381G1 returns the BLS12-381 curve with points in G1 -func BLS12381G1() *Curve { - bls12381g1Initonce.Do(bls12381g1Init) - return &bls12381g1 -} - -func bls12381g1Init() { - bls12381g1 = Curve{ - Scalar: &ScalarBls12381{ - Value: bls12381.Bls12381FqNew(), - point: new(PointBls12381G1), - }, - Point: new(PointBls12381G1).Identity(), - Name: BLS12381G1Name, - } -} - -// BLS12381G2 returns the BLS12-381 curve with points in G2 -func BLS12381G2() *Curve { - bls12381g2Initonce.Do(bls12381g2Init) - return &bls12381g2 -} - -func bls12381g2Init() { - bls12381g2 = Curve{ - Scalar: &ScalarBls12381{ - Value: bls12381.Bls12381FqNew(), - point: new(PointBls12381G2), - }, - Point: new(PointBls12381G2).Identity(), - Name: BLS12381G2Name, - } -} - -func BLS12381(preferredPoint Point) *PairingCurve { - return &PairingCurve{ - Scalar: &ScalarBls12381{ - Value: bls12381.Bls12381FqNew(), - point: preferredPoint, - }, - PointG1: &PointBls12381G1{ - Value: new(bls12381.G1).Identity(), - }, - PointG2: &PointBls12381G2{ - Value: new(bls12381.G2).Identity(), - }, - GT: &ScalarBls12381Gt{ - Value: new(bls12381.Gt).SetOne(), - }, - Name: BLS12831Name, - } -} - -// BLS12377G1 returns the BLS12-377 curve with points in G1 -func BLS12377G1() *Curve { - bls12377g1Initonce.Do(bls12377g1Init) - return &bls12377g1 -} - -func bls12377g1Init() { - bls12377g1 = Curve{ - Scalar: &ScalarBls12377{ - value: new(big.Int), - point: new(PointBls12377G1), - }, - Point: new(PointBls12377G1).Identity(), - Name: BLS12377G1Name, - } -} - -// BLS12377G2 returns the BLS12-377 curve with points in G2 -func BLS12377G2() *Curve { - bls12377g2Initonce.Do(bls12377g2Init) - return &bls12377g2 -} - -func bls12377g2Init() { - bls12377g2 = Curve{ - Scalar: &ScalarBls12377{ - value: new(big.Int), - point: new(PointBls12377G2), - }, - Point: new(PointBls12377G2).Identity(), - Name: BLS12377G2Name, - } -} - -// K256 returns the secp256k1 curve -func K256() *Curve { - k256Initonce.Do(k256Init) - return &k256 -} - -func k256Init() { - k256 = Curve{ - Scalar: new(ScalarK256).Zero(), - Point: new(PointK256).Identity(), - Name: K256Name, - } -} - -func P256() *Curve { - p256Initonce.Do(p256Init) - return &p256 -} - -func p256Init() { - p256 = Curve{ - Scalar: new(ScalarP256).Zero(), - Point: new(PointP256).Identity(), - Name: P256Name, - } -} - -func ED25519() *Curve { - ed25519Initonce.Do(ed25519Init) - return &ed25519 -} - -func ed25519Init() { - ed25519 = Curve{ - Scalar: new(ScalarEd25519).Zero(), - Point: new(PointEd25519).Identity(), - Name: ED25519Name, - } -} - -func PALLAS() *Curve { - pallasInitonce.Do(pallasInit) - return &pallas -} - -func pallasInit() { - pallas = Curve{ - Scalar: new(ScalarPallas).Zero(), - Point: new(PointPallas).Identity(), - Name: PallasName, - } -} - -// https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-11#appendix-G.2.1 -func osswu3mod4(u *big.Int, p *sswuParams) (x, y *big.Int) { - params := p.Params - field := NewField(p.Params.P) - - tv1 := field.NewElement(u) - tv1 = tv1.Mul(tv1) // tv1 = u^2 - tv3 := field.NewElement(p.Z).Mul(tv1) // tv3 = Z * tv1 - tv2 := tv3.Mul(tv3) // tv2 = tv3^2 - xd := tv2.Add(tv3) // xd = tv2 + tv3 - x1n := xd.Add(field.One()) // x1n = (xd + 1) - x1n = x1n.Mul(field.NewElement(p.B)) // x1n * B - aNeg := field.NewElement(p.A).Neg() - xd = xd.Mul(aNeg) // xd = -A * xd - - if xd.Value.Cmp(big.NewInt(0)) == 0 { - xd = field.NewElement(p.Z).Mul(field.NewElement(p.A)) // xd = Z * A - } - - tv2 = xd.Mul(xd) // tv2 = xd^2 - gxd := tv2.Mul(xd) // gxd = tv2 * xd - tv2 = tv2.Mul(field.NewElement(p.A)) // tv2 = A * tv2 - - gx1 := x1n.Mul(x1n) // gx1 = x1n^2 - gx1 = gx1.Add(tv2) // gx1 = gx1 + tv2 - gx1 = gx1.Mul(x1n) // gx1 = gx1 * x1n - tv2 = gxd.Mul(field.NewElement(p.B)) // tv2 = B * gxd - gx1 = gx1.Add(tv2) // gx1 = gx1 + tv2 - - tv4 := gxd.Mul(gxd) // tv4 = gxd^2 - tv2 = gx1.Mul(gxd) // tv2 = gx1 * gxd - tv4 = tv4.Mul(tv2) // tv4 = tv4 * tv2 - - y1 := tv4.Pow(field.NewElement(p.C1)) - y1 = y1.Mul(tv2) // y1 = y1 * tv2 - x2n := tv3.Mul(x1n) // x2n = tv3 * x1n - - y2 := y1.Mul(field.NewElement(p.C2)) // y2 = y1 * c2 - y2 = y2.Mul(tv1) // y2 = y2 * tv1 - y2 = y2.Mul(field.NewElement(u)) // y2 = y2 * u - - tv2 = y1.Mul(y1) // tv2 = y1^2 - - tv2 = tv2.Mul(gxd) // tv2 = tv2 * gxd - - e2 := tv2.Value.Cmp(gx1.Value) == 0 - - // If e2, x = x1, else x = x2 - if e2 { - x = x1n.Value - } else { - x = x2n.Value - } - // xn / xd - x.Mul(x, new(big.Int).ModInverse(xd.Value, params.P)) - x.Mod(x, params.P) - - // If e2, y = y1, else y = y2 - if e2 { - y = y1.Value - } else { - y = y2.Value - } - - uBytes := u.Bytes() - yBytes := y.Bytes() - - usign := uBytes[len(uBytes)-1] & 1 - ysign := yBytes[len(yBytes)-1] & 1 - - // Fix sign of y - if usign != ysign { - y.Neg(y) - y.Mod(y, params.P) - } - - return x, y -} - -func expandMsgXmd(h hash.Hash, msg, domain []byte, outLen int) ([]byte, error) { - if len(domain) > 255 { - return nil, fmt.Errorf("invalid domain length") - } - domainLen := uint8(len(domain)) - // DST_prime = DST || I2OSP(len(DST), 1) - // b_0 = H(Z_pad || msg || l_i_b_str || I2OSP(0, 1) || DST_prime) - _, _ = h.Write(make([]byte, h.BlockSize())) - _, _ = h.Write(msg) - _, _ = h.Write([]byte{uint8(outLen >> 8), uint8(outLen)}) - _, _ = h.Write([]byte{0}) - _, _ = h.Write(domain) - _, _ = h.Write([]byte{domainLen}) - b0 := h.Sum(nil) - - // b_1 = H(b_0 || I2OSP(1, 1) || DST_prime) - h.Reset() - _, _ = h.Write(b0) - _, _ = h.Write([]byte{1}) - _, _ = h.Write(domain) - _, _ = h.Write([]byte{domainLen}) - b1 := h.Sum(nil) - - // b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime) - ell := (outLen + h.Size() - 1) / h.Size() - bi := b1 - out := make([]byte, outLen) - for i := 1; i < ell; i++ { - h.Reset() - // b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime) - tmp := make([]byte, h.Size()) - for j := 0; j < h.Size(); j++ { - tmp[j] = b0[j] ^ bi[j] - } - _, _ = h.Write(tmp) - _, _ = h.Write([]byte{1 + uint8(i)}) - _, _ = h.Write(domain) - _, _ = h.Write([]byte{domainLen}) - - // b_1 || ... || b_(ell - 1) - copy(out[(i-1)*h.Size():i*h.Size()], bi[:]) - bi = h.Sum(nil) - } - // b_ell - copy(out[(ell-1)*h.Size():], bi[:]) - return out[:outLen], nil -} - -func bhex(s string) *big.Int { - r, _ := new(big.Int).SetString(s, 16) - return r -} - -type sswuParams struct { - Params *elliptic.CurveParams - C1, C2, A, B, Z *big.Int -} - -// sumOfProductsPippenger implements a version of Pippenger's algorithm. -// -// The algorithm works as follows: -// -// Let `n` be a number of point-scalar pairs. -// Let `w` be a window of bits (6..8, chosen based on `n`, see cost factor). -// -// 1. Prepare `2^(w-1) - 1` buckets with indices `[1..2^(w-1))` initialized with identity points. -// Bucket 0 is not needed as it would contain points multiplied by 0. -// 2. Convert scalars to a radix-`2^w` representation with signed digits in `[-2^w/2, 2^w/2]`. -// Note: only the last digit may equal `2^w/2`. -// 3. Starting with the last window, for each point `i=[0..n)` add it to a a bucket indexed by -// the point's scalar's value in the window. -// 4. Once all points in a window are sorted into buckets, add buckets by multiplying each -// by their index. Efficient way of doing it is to start with the last bucket and compute two sums: -// intermediate sum from the last to the first, and the full sum made of all intermediate sums. -// 5. Shift the resulting sum of buckets by `w` bits by using `w` doublings. -// 6. Add to the return value. -// 7. Repeat the loop. -// -// Approximate cost w/o wNAF optimizations (A = addition, D = doubling): -// -// ```ascii -// cost = (n*A + 2*(2^w/2)*A + w*D + A)*256/w -// -// | | | | | -// | | | | looping over 256/w windows -// | | | adding to the result -// sorting points | shifting the sum by w bits (to the next window, starting from last window) -// one by one | -// into buckets adding/subtracting all buckets -// multiplied by their indexes -// using a sum of intermediate sums -// -// ``` -// -// For large `n`, dominant factor is (n*256/w) additions. -// However, if `w` is too big and `n` is not too big, then `(2^w/2)*A` could dominate. -// Therefore, the optimal choice of `w` grows slowly as `n` grows. -// -// # For constant time we use a fixed window of 6 -// -// This algorithm is adapted from section 4 of . -// and https://cacr.uwaterloo.ca/techreports/2010/cacr2010-26.pdf -func sumOfProductsPippenger(points []Point, scalars []*big.Int) Point { - if len(points) != len(scalars) { - return nil - } - - const w = 6 - - bucketSize := (1 << w) - 1 - windows := make([]Point, 255/w+1) - for i := range windows { - windows[i] = points[0].Identity() - } - bucket := make([]Point, bucketSize) - - for j := 0; j < len(windows); j++ { - for i := 0; i < bucketSize; i++ { - bucket[i] = points[0].Identity() - } - - for i := 0; i < len(scalars); i++ { - index := bucketSize & int(new(big.Int).Rsh(scalars[i], uint(w*j)).Int64()) - if index != 0 { - bucket[index-1] = bucket[index-1].Add(points[i]) - } - } - - acc, sum := windows[j].Identity(), windows[j].Identity() - - for i := bucketSize - 1; i >= 0; i-- { - sum = sum.Add(bucket[i]) - acc = acc.Add(sum) - } - windows[j] = acc - } - - acc := windows[0].Identity() - for i := len(windows) - 1; i >= 0; i-- { - for j := 0; j < w; j++ { - acc = acc.Double() - } - acc = acc.Add(windows[i]) - } - return acc -} diff --git a/crypto/core/curves/curve_test.go b/crypto/core/curves/curve_test.go deleted file mode 100644 index 8b8ace3ce..000000000 --- a/crypto/core/curves/curve_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Package curves provides integration tests for elliptic curve support -package curves - -import ( - "crypto/elliptic" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core" -) - -// TestAdditionalCurveSupport tests the new curve support in hash.go -func TestAdditionalCurveSupport(t *testing.T) { - tests := []struct { - name string - curve elliptic.Curve - expectedSecurity int - expectedL int - }{ - { - name: "P-256", - curve: elliptic.P256(), - expectedSecurity: 128, - expectedL: 48, - }, - { - name: "P-384", - curve: elliptic.P384(), - expectedSecurity: 192, - expectedL: 72, - }, - { - name: "P-521", - curve: elliptic.P521(), - expectedSecurity: 256, - expectedL: 98, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Test Hash function with the curve - msg := []byte("test message for curve support") - result, err := core.Hash(msg, tt.curve) - - require.NoError(t, err, "Hash should succeed for %s", tt.name) - require.NotNil(t, result, "Hash result should not be nil for %s", tt.name) - - // Verify the result is a valid big integer - require.Greater(t, result.BitLen(), 0, "Hash result should have non-zero bit length") - }) - } -} - -// BenchmarkHashWithCurves benchmarks the hash function with different curves -func BenchmarkHashWithCurves(b *testing.B) { - curves := []struct { - name string - curve elliptic.Curve - }{ - {"P256", elliptic.P256()}, - {"P384", elliptic.P384()}, - {"P521", elliptic.P521()}, - } - - msg := []byte("benchmark message for hash function") - - for _, c := range curves { - b.Run(c.name, func(b *testing.B) { - for i := 0; i < b.N; i++ { - _, _ = core.Hash(msg, c.curve) - } - }) - } -} - -// TestBackwardCompatibility ensures old curves still work -func TestBackwardCompatibility(t *testing.T) { - // Test that P-256 still works as before - msg := []byte("backward compatibility test") - - result256, err := core.Hash(msg, elliptic.P256()) - require.NoError(t, err) - require.NotNil(t, result256) - - // Test with same message multiple times for consistency - for i := 0; i < 10; i++ { - result, err := core.Hash(msg, elliptic.P256()) - require.NoError(t, err) - require.Equal(t, result256.Cmp(result), 0, "Hash should be consistent") - } -} diff --git a/crypto/core/curves/ec_point.go b/crypto/core/curves/ec_point.go deleted file mode 100644 index 6ab9cbdbd..000000000 --- a/crypto/core/curves/ec_point.go +++ /dev/null @@ -1,251 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - "encoding/json" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core" - - "github.com/dustinxie/ecc" - "github.com/sonr-io/sonr/crypto/internal" -) - -var curveNameToID = map[string]byte{ - "secp256k1": 0, - "P-224": 1, - "P-256": 2, - "P-384": 3, - "P-521": 4, -} - -var curveIDToName = map[byte]func() elliptic.Curve{ - 0: ecc.P256k1, - 1: elliptic.P224, - 2: elliptic.P256, - 3: elliptic.P384, - 4: elliptic.P521, -} - -var curveMapper = map[string]func() elliptic.Curve{ - "secp256k1": ecc.P256k1, - "P-224": elliptic.P224, - "P-256": elliptic.P256, - "P-384": elliptic.P384, - "P-521": elliptic.P521, -} - -// EcPoint represents an elliptic curve Point -type EcPoint struct { - Curve elliptic.Curve - X, Y *big.Int -} - -// EcPointJSON encapsulates the data that is serialized to JSON -// used internally and not for external use. Public so other pieces -// can use for serialization -type EcPointJSON struct { - X *big.Int `json:"x"` - Y *big.Int `json:"y"` - CurveName string `json:"curve_name"` -} - -// MarshalJSON serializes EcPoint to JSON -func (a EcPoint) MarshalJSON() ([]byte, error) { - return json.Marshal(EcPointJSON{ - CurveName: a.Curve.Params().Name, - X: a.X, - Y: a.Y, - }) -} - -// UnmarshalJSON deserializes JSON to EcPoint -func (a *EcPoint) UnmarshalJSON(bytes []byte) error { - data := new(EcPointJSON) - err := json.Unmarshal(bytes, data) - if err != nil { - return err - } - if mapper, ok := curveMapper[data.CurveName]; ok { - a.Curve = mapper() - a.X = data.X - a.Y = data.Y - return nil - } - return fmt.Errorf("unknown curve deserialized") -} - -// MarshalBinary serializes EcPoint to binary -func (a *EcPoint) MarshalBinary() ([]byte, error) { - result := [65]byte{} - if code, ok := curveNameToID[a.Curve.Params().Name]; ok { - result[0] = code - a.X.FillBytes(result[1:33]) - a.Y.FillBytes(result[33:65]) - return result[:], nil - } - return nil, fmt.Errorf("unknown curve serialized") -} - -// UnmarshalBinary deserializes binary to EcPoint -func (a *EcPoint) UnmarshalBinary(data []byte) error { - if mapper, ok := curveIDToName[data[0]]; ok { - a.Curve = mapper() - a.X = new(big.Int).SetBytes(data[1:33]) - a.Y = new(big.Int).SetBytes(data[33:65]) - return nil - } - return fmt.Errorf("unknown curve deserialized") -} - -// IsValid checks if the point is valid -func (a EcPoint) IsValid() bool { - return a.IsOnCurve() || a.IsIdentity() -} - -// IsOnCurve checks if the point is on the curve -func (a EcPoint) IsOnCurve() bool { - return a.Curve.IsOnCurve(a.X, a.Y) -} - -// IsIdentity returns true if this Point is the Point at infinity -func (a EcPoint) IsIdentity() bool { - x := core.ConstantTimeEqByte(a.X, core.Zero) - y := core.ConstantTimeEqByte(a.Y, core.Zero) - return (x & y) == 1 -} - -// Equals return true if a and b have the same x,y coordinates -func (a EcPoint) Equals(b *EcPoint) bool { - if !sameCurve(&a, b) { - return false - } - x := core.ConstantTimeEqByte(a.X, b.X) - y := core.ConstantTimeEqByte(a.Y, b.Y) - return (x & y) == 1 -} - -// IsBasePoint returns true if this Point is curve's base Point -func (a EcPoint) IsBasePoint() bool { - p := a.Curve.Params() - x := core.ConstantTimeEqByte(a.X, p.Gx) - y := core.ConstantTimeEqByte(a.Y, p.Gy) - return (x & y) == 1 -} - -// reduceModN normalizes the Scalar to a positive element smaller than the base Point order. -func reduceModN(curve elliptic.Curve, k *big.Int) *big.Int { - return new(big.Int).Mod(k, curve.Params().N) -} - -// Add performs elliptic curve addition on two points -func (a *EcPoint) Add(b *EcPoint) (*EcPoint, error) { - if a == nil || b == nil { - return nil, internal.ErrNilArguments - } - if !sameCurve(a, b) { - return nil, internal.ErrPointsDistinctCurves - } - p := &EcPoint{Curve: a.Curve} - p.X, p.Y = a.Curve.Add(a.X, a.Y, b.X, b.Y) - if !p.IsValid() { - return nil, internal.ErrNotOnCurve - } - return p, nil -} - -// Neg returns the negation of a Weierstrass Point. -func (a *EcPoint) Neg() (*EcPoint, error) { - if a == nil { - return nil, internal.ErrNilArguments - } - p := &EcPoint{Curve: a.Curve, X: a.X, Y: new(big.Int).Sub(a.Curve.Params().P, a.Y)} - if !p.IsValid() { - return nil, internal.ErrNotOnCurve - } - return p, nil -} - -// ScalarMult multiplies this Point by a Scalar -func (a *EcPoint) ScalarMult(k *big.Int) (*EcPoint, error) { - if a == nil || k == nil { - return nil, fmt.Errorf("cannot multiply nil Point or element") - } - n := reduceModN(a.Curve, k) - p := new(EcPoint) - p.Curve = a.Curve - p.X, p.Y = a.Curve.ScalarMult(a.X, a.Y, n.Bytes()) - if !p.IsValid() { - return nil, fmt.Errorf("result not on the curve") - } - return p, nil -} - -// NewScalarBaseMult creates a Point from the base Point multiplied by a field element -func NewScalarBaseMult(curve elliptic.Curve, k *big.Int) (*EcPoint, error) { - if curve == nil || k == nil { - return nil, fmt.Errorf("nil parameters are not supported") - } - n := reduceModN(curve, k) - p := new(EcPoint) - p.Curve = curve - p.X, p.Y = curve.ScalarBaseMult(n.Bytes()) - if !p.IsValid() { - return nil, fmt.Errorf("result not on the curve") - } - return p, nil -} - -// Bytes returns the bytes represented by this Point with x || y -func (a EcPoint) Bytes() []byte { - fieldSize := internal.CalcFieldSize(a.Curve) - out := make([]byte, fieldSize*2) - - a.X.FillBytes(out[0:fieldSize]) - a.Y.FillBytes(out[fieldSize : fieldSize*2]) - return out -} - -// PointFromBytesUncompressed outputs uncompressed X || Y similar to -// https://www.secg.org/sec1-v1.99.dif.pdf section 2.2 and 2.3 -func PointFromBytesUncompressed(curve elliptic.Curve, b []byte) (*EcPoint, error) { - fieldSize := internal.CalcFieldSize(curve) - if len(b) != fieldSize*2 { - return nil, fmt.Errorf("invalid number of bytes") - } - p := &EcPoint{ - Curve: curve, - X: new(big.Int).SetBytes(b[:fieldSize]), - Y: new(big.Int).SetBytes(b[fieldSize:]), - } - if !p.IsValid() { - return nil, fmt.Errorf("invalid Point") - } - return p, nil -} - -// sameCurve determines if points a,b appear to be from the same curve -func sameCurve(a, b *EcPoint) bool { - if a == b { - return true - } - if a == nil || b == nil { - return false - } - aParams := a.Curve.Params() - bParams := b.Curve.Params() - return aParams.P.Cmp(bParams.P) == 0 && - aParams.N.Cmp(bParams.N) == 0 && - aParams.B.Cmp(bParams.B) == 0 && - aParams.BitSize == bParams.BitSize && - aParams.Gx.Cmp(bParams.Gx) == 0 && - aParams.Gy.Cmp(bParams.Gy) == 0 && - aParams.Name == bParams.Name -} diff --git a/crypto/core/curves/ec_point_test.go b/crypto/core/curves/ec_point_test.go deleted file mode 100644 index cc13c4ee7..000000000 --- a/crypto/core/curves/ec_point_test.go +++ /dev/null @@ -1,369 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "bytes" - "crypto/elliptic" - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core" - tt "github.com/sonr-io/sonr/crypto/internal" -) - -func TestIsIdentity(t *testing.T) { - // Should be Point at infinity - identity := &EcPoint{btcec.S256(), core.Zero, core.Zero} - require.True(t, identity.IsIdentity()) -} - -func TestNewScalarBaseMultZero(t *testing.T) { - // Should be Point at infinity - curve := btcec.S256() - num := big.NewInt(0) - p, err := NewScalarBaseMult(curve, num) - if err != nil { - t.Errorf("NewScalarBaseMult failed: %v", err) - } - if p == nil { - t.Errorf("NewScalarBaseMult failed when it should've succeeded.") - } -} - -func TestNewScalarBaseMultOne(t *testing.T) { - // Should be base Point - curve := btcec.S256() - num := big.NewInt(1) - p, err := NewScalarBaseMult(curve, num) - if err != nil { - t.Errorf("NewScalarBaseMult failed: %v", err) - } - if p == nil { - t.Errorf("NewScalarBaseMult failed when it should've succeeded.") - t.FailNow() - } - if !bytes.Equal(p.Bytes(), append(curve.Gx.Bytes(), curve.Gy.Bytes()...)) { - t.Errorf("NewScalarBaseMult should've returned the base Point.") - } -} - -func TestNewScalarBaseMultNeg(t *testing.T) { - curve := btcec.S256() - num := big.NewInt(-1) - p, err := NewScalarBaseMult(curve, num) - if err != nil { - t.Errorf("NewScalarBaseMult failed: %v", err) - } - if p == nil { - t.Errorf("NewScalarBaseMult failed when it should've succeeded.") - t.FailNow() - } - num.Mod(num, curve.N) - - e, err := NewScalarBaseMult(curve, num) - if err != nil { - t.Errorf("NewScalarBaseMult failed: %v", err) - } - if e == nil { - t.Errorf("NewScalarBaseMult failed when it should've succeeded.") - t.FailNow() - } - - if !bytes.Equal(p.Bytes(), e.Bytes()) { - t.Errorf("NewScalarBaseMult should've returned the %v, found: %v", e, p) - } -} - -func TestScalarMultZero(t *testing.T) { - // Should be Point at infinity - curve := btcec.S256() - p := &EcPoint{ - Curve: curve, - X: curve.Gx, - Y: curve.Gy, - } - num := big.NewInt(0) - q, err := p.ScalarMult(num) - if err != nil { - t.Errorf("ScalarMult failed: %v", err) - } - if q == nil { - t.Errorf("ScalarMult failed when it should've succeeded.") - t.FailNow() - } - if !q.IsIdentity() { - t.Errorf("ScalarMult should've returned the identity Point.") - } -} - -func TestScalarMultOne(t *testing.T) { - // Should be base Point - curve := btcec.S256() - p := &EcPoint{ - Curve: curve, - X: curve.Gx, - Y: curve.Gy, - } - num := big.NewInt(1) - q, err := p.ScalarMult(num) - if err != nil { - t.Errorf("ScalarMult failed: %v", err) - } - if q == nil { - t.Errorf("ScalarMult failed when it should've succeeded.") - t.FailNow() - } - if !bytes.Equal(q.Bytes(), append(curve.Gx.Bytes(), curve.Gy.Bytes()...)) { - t.Errorf("ScalarMult should've returned the base Point.") - } -} - -func TestScalarMultNeg(t *testing.T) { - curve := btcec.S256() - p := &EcPoint{ - Curve: curve, - X: curve.Gx, - Y: curve.Gy, - } - num := big.NewInt(-1) - q, err := p.ScalarMult(num) - if err != nil { - t.Errorf("ScalarMult failed: %v", err) - } - if q == nil { - t.Errorf("ScalarMult failed when it should've succeeded.") - } - num.Mod(num, curve.N) - - e, err := p.ScalarMult(num) - if err != nil { - t.Errorf("ScalarMult failed: %v", err) - } - if e == nil { - t.Errorf("ScalarMult failed when it should've succeeded.") - t.FailNow() - } - - if !bytes.Equal(q.Bytes(), e.Bytes()) { - t.Errorf("ScalarMult should've returned the %v, found: %v", e, p) - } -} - -func TestEcPointAddSimple(t *testing.T) { - curve := btcec.S256() - num := big.NewInt(1) - p1, _ := NewScalarBaseMult(curve, num) - - p2, _ := NewScalarBaseMult(curve, num) - p3, err := p1.Add(p2) - if err != nil { - t.Errorf("EcPoint.Add failed: %v", err) - } - num = big.NewInt(2) - - ep, _ := NewScalarBaseMult(curve, num) - - if !bytes.Equal(ep.Bytes(), p3.Bytes()) { - t.Errorf("EcPoint.Add failed: should equal %v, found: %v", ep, p3) - } -} - -func TestEcPointAddCommunicative(t *testing.T) { - curve := btcec.S256() - a, _ := core.Rand(curve.Params().N) - b, _ := core.Rand(curve.Params().N) - - p1, _ := NewScalarBaseMult(curve, a) - p2, _ := NewScalarBaseMult(curve, b) - p3, err := p1.Add(p2) - if err != nil { - t.Errorf("EcPoint.Add failed: %v", err) - } - p4, err := p2.Add(p1) - if err != nil { - t.Errorf("EcPoint.Add failed: %v", err) - } - if !bytes.Equal(p3.Bytes(), p4.Bytes()) { - t.Errorf("EcPoint.Add Communicative not valid") - } -} - -func TestEcPointAddNeg(t *testing.T) { - curve := btcec.S256() - num := big.NewInt(-1) - - p1, _ := NewScalarBaseMult(curve, num) - num.Abs(num) - - p2, _ := NewScalarBaseMult(curve, num) - - p3, err := p1.Add(p2) - if err != nil { - t.Errorf("EcPoint.Add failed: %v", err) - } - zero := make([]byte, 64) - if !bytes.Equal(zero, p3.Bytes()) { - t.Errorf("Expected value to be zero, found: %v", p3) - } -} - -func TestEcPointBytes(t *testing.T) { - curve := btcec.S256() - - point, err := NewScalarBaseMult(curve, big.NewInt(2)) - require.NoError(t, err) - data := point.Bytes() - point2, err := PointFromBytesUncompressed(curve, data) - require.NoError(t, err) - if point.X.Cmp(point2.X) != 0 && point.Y.Cmp(point2.Y) != 0 { - t.Errorf("Points are not equal. Expected %v, found %v", point, point2) - } - - curve2 := elliptic.P224() - p2, err := NewScalarBaseMult(curve2, big.NewInt(2)) - require.NoError(t, err) - dta := p2.Bytes() - point3, err := PointFromBytesUncompressed(curve2, dta) - require.NoError(t, err) - if p2.X.Cmp(point3.X) != 0 && p2.Y.Cmp(point3.Y) != 0 { - t.Errorf("Points are not equal. Expected %v, found %v", p2, point3) - } - - curve3 := elliptic.P521() - p3, err := NewScalarBaseMult(curve3, big.NewInt(2)) - require.NoError(t, err) - data = p3.Bytes() - point4, err := PointFromBytesUncompressed(curve3, data) - require.NoError(t, err) - if p3.X.Cmp(point4.X) != 0 && p3.Y.Cmp(point4.Y) != 0 { - t.Errorf("Points are not equal. Expected %v, found %v", p3, point4) - } -} - -func TestEcPointBytesDifferentCurves(t *testing.T) { - k256 := btcec.S256() - p224 := elliptic.P224() - p256 := elliptic.P256() - - kp, err := NewScalarBaseMult(k256, big.NewInt(1)) - require.NoError(t, err) - data := kp.Bytes() - _, err = PointFromBytesUncompressed(p224, data) - require.Error(t, err) - _, err = PointFromBytesUncompressed(p256, data) - require.Error(t, err) -} - -func TestEcPointBytesInvalidNumberBytes(t *testing.T) { - curve := btcec.S256() - - for i := 1; i < 64; i++ { - data := make([]byte, i) - _, err := PointFromBytesUncompressed(curve, data) - require.Error(t, err) - } - for i := 65; i < 128; i++ { - data := make([]byte, i) - _, err := PointFromBytesUncompressed(curve, data) - require.Error(t, err) - } -} - -func TestEcPointMultRandom(t *testing.T) { - curve := btcec.S256() - r, err := core.Rand(curve.N) - require.NoError(t, err) - pt, err := NewScalarBaseMult(curve, r) - require.NoError(t, err) - require.NotNil(t, pt) - data := pt.Bytes() - pt2, err := PointFromBytesUncompressed(curve, data) - require.NoError(t, err) - if pt.X.Cmp(pt2.X) != 0 || pt.Y.Cmp(pt2.Y) != 0 { - t.Errorf("Points are not equal. Expected: %v, found: %v", pt, pt2) - } -} - -func TestIsBasePoint(t *testing.T) { - k256 := btcec.S256() - p224 := elliptic.P224() - p256 := elliptic.P256() - - notG_p224, err := NewScalarBaseMult(p224, tt.B10("9876453120")) - require.NoError(t, err) - - tests := []struct { - name string - curve elliptic.Curve - x, y *big.Int - expected bool - }{ - {"k256-positive", k256, k256.Gx, k256.Gy, true}, - {"p224-positive", p224, p224.Params().Gx, p224.Params().Gy, true}, - {"p256-positive", p256, p256.Params().Gx, p256.Params().Gy, true}, - - {"p224-negative", p224, notG_p224.X, notG_p224.Y, false}, - {"p256-negative-wrong-curve", p256, notG_p224.X, notG_p224.Y, false}, - {"k256-negative-doubleGx", k256, k256.Gx, k256.Gx, false}, - {"k256-negative-doubleGy", k256, k256.Gy, k256.Gy, false}, - {"k256-negative-xy-swap", k256, k256.Gy, k256.Gx, false}, - {"k256-negative-oh-oh", k256, core.Zero, core.Zero, false}, - } - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := EcPoint{test.curve, test.x, test.y}.IsBasePoint() - require.Equal(t, test.expected, actual) - }) - } -} - -func TestEquals(t *testing.T) { - k256 := btcec.S256() - p224 := elliptic.P224() - p256 := elliptic.P256() - P_p224, _ := NewScalarBaseMult(p224, tt.B10("9876453120")) - P1_p224, _ := NewScalarBaseMult(p224, tt.B10("9876453120")) - - P_k256 := &EcPoint{k256, P_p224.X, P_p224.Y} - - id_p224 := &EcPoint{p224, core.Zero, core.Zero} - id_k256 := &EcPoint{k256, core.Zero, core.Zero} - id_p256 := &EcPoint{p256, core.Zero, core.Zero} - - tests := []struct { - name string - x, y *EcPoint - expected bool - }{ - {"p224 same pointer", P_p224, P_p224, true}, - {"p224 same Point", P_p224, P1_p224, true}, - {"p224 identity", id_p224, id_p224, true}, - {"p256 identity", id_p256, id_p256, true}, - {"k256 identity", id_k256, id_k256, true}, - - {"negative-same x different y", P_p224, &EcPoint{p224, P_p224.X, core.One}, false}, - {"negative-same y different x", P_p224, &EcPoint{p224, core.Two, P_k256.Y}, false}, - - {"negative-wrong curve", P_p224, P_k256, false}, - {"negative-wrong curve reversed", P_k256, P_p224, false}, - {"Point is not the identity", P_p224, id_p224, false}, - {"negative nil", P1_p224, nil, false}, - {"identities on wrong curve", id_p256, id_k256, false}, - } - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := test.x.Equals(test.y) - require.Equal(t, test.expected, actual) - }) - } -} diff --git a/crypto/core/curves/ec_scalar.go b/crypto/core/curves/ec_scalar.go deleted file mode 100644 index a3076c2d2..000000000 --- a/crypto/core/curves/ec_scalar.go +++ /dev/null @@ -1,353 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - crand "crypto/rand" - "crypto/sha512" - "fmt" - "io" - "math/big" - - "filippo.io/edwards25519" - "github.com/btcsuite/btcd/btcec/v2" - "github.com/bwesterb/go-ristretto" - - "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -type EcScalar interface { - Add(x, y *big.Int) *big.Int - Sub(x, y *big.Int) *big.Int - Neg(x *big.Int) *big.Int - Mul(x, y *big.Int) *big.Int - Hash(input []byte) *big.Int - Div(x, y *big.Int) *big.Int - Random() (*big.Int, error) - IsValid(x *big.Int) bool - Bytes(x *big.Int) []byte // fixed-length byte array -} - -type K256Scalar struct{} - -// Static interface assertion -var _ EcScalar = (*K256Scalar)(nil) - -// warning: the Euclidean alg which Mod uses is not constant-time. - -func NewK256Scalar() *K256Scalar { - return &K256Scalar{} -} - -func (k K256Scalar) Add(x, y *big.Int) *big.Int { - v := new(big.Int).Add(x, y) - v.Mod(v, btcec.S256().N) - return v -} - -func (k K256Scalar) Sub(x, y *big.Int) *big.Int { - v := new(big.Int).Sub(x, y) - v.Mod(v, btcec.S256().N) - return v -} - -func (k K256Scalar) Neg(x *big.Int) *big.Int { - v := new(big.Int).Sub(btcec.S256().N, x) - v.Mod(v, btcec.S256().N) - return v -} - -func (k K256Scalar) Mul(x, y *big.Int) *big.Int { - v := new(big.Int).Mul(x, y) - v.Mod(v, btcec.S256().N) - return v -} - -func (k K256Scalar) Div(x, y *big.Int) *big.Int { - t := new(big.Int).ModInverse(y, btcec.S256().N) - return k.Mul(x, t) -} - -func (k K256Scalar) Hash(input []byte) *big.Int { - return new(ScalarK256).Hash(input).BigInt() -} - -func (k K256Scalar) Random() (*big.Int, error) { - b := make([]byte, 48) - n, err := crand.Read(b) - if err != nil { - return nil, err - } - if n != 48 { - return nil, fmt.Errorf("insufficient bytes read") - } - v := new(big.Int).SetBytes(b) - v.Mod(v, btcec.S256().N) - return v, nil -} - -func (k K256Scalar) IsValid(x *big.Int) bool { - return core.In(x, btcec.S256().N) == nil -} - -func (k K256Scalar) Bytes(x *big.Int) []byte { - bytes := make([]byte, 32) - x.FillBytes(bytes) // big-endian; will left-pad. - return bytes -} - -type P256Scalar struct{} - -// Static interface assertion -var _ EcScalar = (*P256Scalar)(nil) - -func NewP256Scalar() *P256Scalar { - return &P256Scalar{} -} - -func (k P256Scalar) Add(x, y *big.Int) *big.Int { - v := new(big.Int).Add(x, y) - v.Mod(v, elliptic.P256().Params().N) - return v -} - -func (k P256Scalar) Sub(x, y *big.Int) *big.Int { - v := new(big.Int).Sub(x, y) - v.Mod(v, elliptic.P256().Params().N) - return v -} - -func (k P256Scalar) Neg(x *big.Int) *big.Int { - v := new(big.Int).Sub(elliptic.P256().Params().N, x) - v.Mod(v, elliptic.P256().Params().N) - return v -} - -func (k P256Scalar) Mul(x, y *big.Int) *big.Int { - v := new(big.Int).Mul(x, y) - v.Mod(v, elliptic.P256().Params().N) - return v -} - -func (k P256Scalar) Div(x, y *big.Int) *big.Int { - t := new(big.Int).ModInverse(y, elliptic.P256().Params().N) - return k.Mul(x, t) -} - -func (k P256Scalar) Hash(input []byte) *big.Int { - return new(ScalarP256).Hash(input).BigInt() -} - -func (k P256Scalar) Random() (*big.Int, error) { - b := make([]byte, 48) - n, err := crand.Read(b) - if err != nil { - return nil, err - } - if n != 48 { - return nil, fmt.Errorf("insufficient bytes read") - } - v := new(big.Int).SetBytes(b) - v.Mod(v, elliptic.P256().Params().N) - return v, nil -} - -func (k P256Scalar) IsValid(x *big.Int) bool { - return core.In(x, elliptic.P256().Params().N) == nil -} - -func (k P256Scalar) Bytes(x *big.Int) []byte { - bytes := make([]byte, 32) - x.FillBytes(bytes) // big-endian; will left-pad. - return bytes -} - -type Bls12381Scalar struct{} - -// Static interface assertion -var _ EcScalar = (*Bls12381Scalar)(nil) - -func NewBls12381Scalar() *Bls12381Scalar { - return &Bls12381Scalar{} -} - -func (k Bls12381Scalar) Add(x, y *big.Int) *big.Int { - a := bls12381.Bls12381FqNew().SetBigInt(x) - b := bls12381.Bls12381FqNew().SetBigInt(y) - return a.Add(a, b).BigInt() -} - -func (k Bls12381Scalar) Sub(x, y *big.Int) *big.Int { - a := bls12381.Bls12381FqNew().SetBigInt(x) - b := bls12381.Bls12381FqNew().SetBigInt(y) - return a.Sub(a, b).BigInt() -} - -func (k Bls12381Scalar) Neg(x *big.Int) *big.Int { - a := bls12381.Bls12381FqNew().SetBigInt(x) - return a.Neg(a).BigInt() -} - -func (k Bls12381Scalar) Mul(x, y *big.Int) *big.Int { - a := bls12381.Bls12381FqNew().SetBigInt(x) - b := bls12381.Bls12381FqNew().SetBigInt(y) - return a.Mul(a, b).BigInt() -} - -func (k Bls12381Scalar) Div(x, y *big.Int) *big.Int { - c := bls12381.Bls12381FqNew() - a := bls12381.Bls12381FqNew().SetBigInt(x) - b := bls12381.Bls12381FqNew().SetBigInt(y) - _, wasInverted := c.Invert(b) - c.Mul(a, c) - tt := map[bool]int{false: 0, true: 1} - return a.CMove(a, c, tt[wasInverted]).BigInt() -} - -func (k Bls12381Scalar) Hash(input []byte) *big.Int { - return new(ScalarBls12381).Hash(input).BigInt() -} - -func (k Bls12381Scalar) Random() (*big.Int, error) { - a := BLS12381G1().NewScalar().Random(crand.Reader) - if a == nil { - return nil, fmt.Errorf("invalid random value") - } - return a.BigInt(), nil -} - -func (k Bls12381Scalar) Bytes(x *big.Int) []byte { - bytes := make([]byte, 32) - x.FillBytes(bytes) // big-endian; will left-pad. - return bytes -} - -func (k Bls12381Scalar) IsValid(x *big.Int) bool { - a := bls12381.Bls12381FqNew().SetBigInt(x) - return a.BigInt().Cmp(x) == 0 -} - -// taken from https://datatracker.ietf.org/doc/html/rfc8032 -var ed25519N, _ = new( - big.Int, -).SetString("1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", 16) - -type Ed25519Scalar struct{} - -// Static interface assertion -var _ EcScalar = (*Ed25519Scalar)(nil) - -func NewEd25519Scalar() *Ed25519Scalar { - return &Ed25519Scalar{} -} - -func (k Ed25519Scalar) Add(x, y *big.Int) *big.Int { - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - b, err := internal.BigInt2Ed25519Scalar(y) - if err != nil { - panic(err) - } - a.Add(a, b) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(a.Bytes())) -} - -func (k Ed25519Scalar) Sub(x, y *big.Int) *big.Int { - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - b, err := internal.BigInt2Ed25519Scalar(y) - if err != nil { - panic(err) - } - a.Subtract(a, b) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(a.Bytes())) -} - -func (k Ed25519Scalar) Neg(x *big.Int) *big.Int { - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - a.Negate(a) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(a.Bytes())) -} - -func (k Ed25519Scalar) Mul(x, y *big.Int) *big.Int { - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - b, err := internal.BigInt2Ed25519Scalar(y) - if err != nil { - panic(err) - } - a.Multiply(a, b) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(a.Bytes())) -} - -func (k Ed25519Scalar) Div(x, y *big.Int) *big.Int { - b, err := internal.BigInt2Ed25519Scalar(y) - if err != nil { - panic(err) - } - b.Invert(b) - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - a.Multiply(a, b) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(a.Bytes())) -} - -func (k Ed25519Scalar) Hash(input []byte) *big.Int { - v := new(ristretto.Scalar).Derive(input) - var data [32]byte - v.BytesInto(&data) - return new(big.Int).SetBytes(internal.ReverseScalarBytes(data[:])) -} - -func (k Ed25519Scalar) Bytes(x *big.Int) []byte { - a, err := internal.BigInt2Ed25519Scalar(x) - if err != nil { - panic(err) - } - return internal.ReverseScalarBytes(a.Bytes()) -} - -func (k Ed25519Scalar) Random() (*big.Int, error) { - return k.RandomWithReader(crand.Reader) -} - -func (k Ed25519Scalar) RandomWithReader(r io.Reader) (*big.Int, error) { - b := make([]byte, 64) - n, err := r.Read(b) - if err != nil { - return nil, err - } - if n != 64 { - return nil, fmt.Errorf("insufficient bytes read") - } - digest := sha512.Sum512(b) - var hBytes [32]byte - copy(hBytes[:], digest[:]) - s, err := edwards25519.NewScalar().SetBytesWithClamping(hBytes[:]) - if err != nil { - return nil, err - } - return new(big.Int).SetBytes(internal.ReverseScalarBytes(s.Bytes())), nil -} - -func (k Ed25519Scalar) IsValid(x *big.Int) bool { - return x.Cmp(ed25519N) == -1 -} diff --git a/crypto/core/curves/ecdsa.go b/crypto/core/curves/ecdsa.go deleted file mode 100755 index 41e8759e1..000000000 --- a/crypto/core/curves/ecdsa.go +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/ecdsa" - "math/big" -) - -// EcdsaVerify runs a curve- or algorithm-specific ECDSA verification function on input -// an ECDSA public (verification) key, a message digest, and an ECDSA signature. -// It must return true if all the parameters are sane and the ECDSA signature is valid, -// and false otherwise -type EcdsaVerify func(pubKey *EcPoint, hash []byte, signature *EcdsaSignature) bool - -// EcdsaSignature represents a (composite) digital signature -type EcdsaSignature struct { - R *big.Int - S *big.Int - V int -} - -// Static type assertion -var _ EcdsaVerify = VerifyEcdsa - -// Verifies ECDSA signature using core types. -func VerifyEcdsa(pk *EcPoint, hash []byte, sig *EcdsaSignature) bool { - return ecdsa.Verify( - &ecdsa.PublicKey{ - Curve: pk.Curve, - X: pk.X, - Y: pk.Y, - }, - hash, sig.R, sig.S) -} diff --git a/crypto/core/curves/ed25519_curve.go b/crypto/core/curves/ed25519_curve.go deleted file mode 100644 index 443e0a6f4..000000000 --- a/crypto/core/curves/ed25519_curve.go +++ /dev/null @@ -1,864 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "bytes" - "crypto/sha512" - "crypto/subtle" - "fmt" - "io" - "math/big" - - "filippo.io/edwards25519" - "filippo.io/edwards25519/field" - "github.com/bwesterb/go-ristretto" - ed "github.com/bwesterb/go-ristretto/edwards25519" - - "github.com/sonr-io/sonr/crypto/internal" -) - -type ScalarEd25519 struct { - value *edwards25519.Scalar -} - -type PointEd25519 struct { - value *edwards25519.Point -} - -var scOne, _ = edwards25519.NewScalar(). - SetCanonicalBytes([]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) - -func (s *ScalarEd25519) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarEd25519) Hash(bytes []byte) Scalar { - v := new(ristretto.Scalar).Derive(bytes) - var data [32]byte - v.BytesInto(&data) - value, err := edwards25519.NewScalar().SetCanonicalBytes(data[:]) - if err != nil { - return nil - } - return &ScalarEd25519{value} -} - -func (s *ScalarEd25519) Zero() Scalar { - return &ScalarEd25519{ - value: edwards25519.NewScalar(), - } -} - -func (s *ScalarEd25519) One() Scalar { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Set(scOne), - } -} - -func (s *ScalarEd25519) IsZero() bool { - i := byte(0) - for _, b := range s.value.Bytes() { - i |= b - } - return i == 0 -} - -func (s *ScalarEd25519) IsOne() bool { - data := s.value.Bytes() - i := byte(0) - for j := 1; j < len(data); j++ { - i |= data[j] - } - return i == 0 && data[0] == 1 -} - -func (s *ScalarEd25519) IsOdd() bool { - return s.value.Bytes()[0]&1 == 1 -} - -func (s *ScalarEd25519) IsEven() bool { - return s.value.Bytes()[0]&1 == 0 -} - -func (s *ScalarEd25519) New(input int) Scalar { - var data [64]byte - i := input - if input < 0 { - i = -input - } - data[0] = byte(i) - data[1] = byte(i >> 8) - data[2] = byte(i >> 16) - data[3] = byte(i >> 24) - value, err := edwards25519.NewScalar().SetUniformBytes(data[:]) - if err != nil { - return nil - } - if input < 0 { - value.Negate(value) - } - - return &ScalarEd25519{ - value, - } -} - -func (s *ScalarEd25519) Cmp(rhs Scalar) int { - r := s.Sub(rhs) - if r != nil && r.IsZero() { - return 0 - } else { - return -2 - } -} - -func (s *ScalarEd25519) Square() Scalar { - value := edwards25519.NewScalar().Multiply(s.value, s.value) - return &ScalarEd25519{value} -} - -func (s *ScalarEd25519) Double() Scalar { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Add(s.value, s.value), - } -} - -func (s *ScalarEd25519) Invert() (Scalar, error) { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Invert(s.value), - }, nil -} - -func (s *ScalarEd25519) Sqrt() (Scalar, error) { - bi25519, _ := new( - big.Int, - ).SetString("1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", 16) - x := s.BigInt() - x.ModSqrt(x, bi25519) - return s.SetBigInt(x) -} - -func (s *ScalarEd25519) Cube() Scalar { - value := edwards25519.NewScalar().Multiply(s.value, s.value) - value.Multiply(value, s.value) - return &ScalarEd25519{value} -} - -func (s *ScalarEd25519) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarEd25519) - if ok { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Add(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarEd25519) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarEd25519) - if ok { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Subtract(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarEd25519) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarEd25519) - if ok { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Multiply(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarEd25519) MulAdd(y, z Scalar) Scalar { - yy, ok := y.(*ScalarEd25519) - if !ok { - return nil - } - zz, ok := z.(*ScalarEd25519) - if !ok { - return nil - } - return &ScalarEd25519{value: edwards25519.NewScalar().MultiplyAdd(s.value, yy.value, zz.value)} -} - -func (s *ScalarEd25519) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarEd25519) - if ok { - value := edwards25519.NewScalar().Invert(r.value) - value.Multiply(value, s.value) - return &ScalarEd25519{value} - } else { - return nil - } -} - -func (s *ScalarEd25519) Neg() Scalar { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Negate(s.value), - } -} - -func (s *ScalarEd25519) SetBigInt(x *big.Int) (Scalar, error) { - if x == nil { - return nil, fmt.Errorf("invalid value") - } - - bi25519, _ := new( - big.Int, - ).SetString("1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", 16) - var v big.Int - buf := v.Mod(x, bi25519).Bytes() - var rBuf [32]byte - for i := 0; i < len(buf) && i < 32; i++ { - rBuf[i] = buf[len(buf)-i-1] - } - value, err := edwards25519.NewScalar().SetCanonicalBytes(rBuf[:]) - if err != nil { - return nil, err - } - return &ScalarEd25519{value}, nil -} - -func (s *ScalarEd25519) BigInt() *big.Int { - var ret big.Int - buf := internal.ReverseScalarBytes(s.value.Bytes()) - return ret.SetBytes(buf) -} - -func (s *ScalarEd25519) Bytes() []byte { - return s.value.Bytes() -} - -// SetBytes takes input a 32-byte long array and returns a ed25519 scalar. -// The input must be 32-byte long and must be a reduced bytes. -func (s *ScalarEd25519) SetBytes(input []byte) (Scalar, error) { - if len(input) != 32 { - return nil, fmt.Errorf("invalid byte sequence") - } - value, err := edwards25519.NewScalar().SetCanonicalBytes(input) - if err != nil { - return nil, err - } - return &ScalarEd25519{value}, nil -} - -// SetBytesWide takes input a 64-byte long byte array, reduce it and return an ed25519 scalar. -// It uses SetUniformBytes of fillipo.io/edwards25519 - https://github.com/FiloSottile/edwards25519/blob/v1.0.0-rc.1/scalar.go#L85 -// If bytes is not of the right length, it returns nil and an error -func (s *ScalarEd25519) SetBytesWide(bytes []byte) (Scalar, error) { - value, err := edwards25519.NewScalar().SetUniformBytes(bytes) - if err != nil { - return nil, err - } - return &ScalarEd25519{value}, nil -} - -// SetBytesClamping uses SetBytesWithClamping of fillipo.io/edwards25519- https://github.com/FiloSottile/edwards25519/blob/v1.0.0-rc.1/scalar.go#L135 -// which applies the buffer pruning described in RFC 8032, Section 5.1.5 (also known as clamping) -// and sets bytes to the result. The input must be 32-byte long, and it is not modified. -// If bytes is not of the right length, SetBytesWithClamping returns nil and an error, and the receiver is unchanged. -func (s *ScalarEd25519) SetBytesClamping(bytes []byte) (Scalar, error) { - value, err := edwards25519.NewScalar().SetBytesWithClamping(bytes) - if err != nil { - return nil, err - } - return &ScalarEd25519{value}, nil -} - -// SetBytesCanonical uses SetCanonicalBytes of fillipo.io/edwards25519. -// https://github.com/FiloSottile/edwards25519/blob/v1.0.0-rc.1/scalar.go#L98 -// This function takes an input x and sets s = x, where x is a 32-byte little-endian -// encoding of s, then it returns the corresponding ed25519 scalar. If the input is -// not a canonical encoding of s, it returns nil and an error. -func (s *ScalarEd25519) SetBytesCanonical(bytes []byte) (Scalar, error) { - return s.SetBytes(bytes) -} - -func (s *ScalarEd25519) Point() Point { - return new(PointEd25519).Identity() -} - -func (s *ScalarEd25519) Clone() Scalar { - return &ScalarEd25519{ - value: edwards25519.NewScalar().Set(s.value), - } -} - -func (s *ScalarEd25519) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarEd25519) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarEd25519) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarEd25519) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarEd25519) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarEd25519) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarEd25519) GetEdwardsScalar() *edwards25519.Scalar { - return edwards25519.NewScalar().Set(s.value) -} - -func (s *ScalarEd25519) SetEdwardsScalar(sc *edwards25519.Scalar) *ScalarEd25519 { - return &ScalarEd25519{value: edwards25519.NewScalar().Set(sc)} -} - -func (s *ScalarEd25519) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarEd25519) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarEd25519) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (p *PointEd25519) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointEd25519) Hash(bytes []byte) Point { - /// Perform hashing to the group using the Elligator2 map - /// - /// See https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-11#section-6.7.1 - h := sha512.Sum512(bytes) - var res [32]byte - copy(res[:], h[:32]) - signBit := (res[31] & 0x80) >> 7 - - fe := new(ed.FieldElement).SetBytes(&res).BytesInto(&res) - m1 := elligatorEncode(fe) - - return toEdwards(m1, signBit) -} - -func (p *PointEd25519) Identity() Point { - return &PointEd25519{ - value: edwards25519.NewIdentityPoint(), - } -} - -func (p *PointEd25519) Generator() Point { - return &PointEd25519{ - value: edwards25519.NewGeneratorPoint(), - } -} - -func (p *PointEd25519) IsIdentity() bool { - return p.Equal(p.Identity()) -} - -func (p *PointEd25519) IsNegative() bool { - // Negative points don't really exist in ed25519 - return false -} - -func (p *PointEd25519) IsOnCurve() bool { - _, err := edwards25519.NewIdentityPoint().SetBytes(p.ToAffineCompressed()) - return err == nil -} - -func (p *PointEd25519) Double() Point { - return &PointEd25519{value: edwards25519.NewIdentityPoint().Add(p.value, p.value)} -} - -func (p *PointEd25519) Scalar() Scalar { - return new(ScalarEd25519).Zero() -} - -func (p *PointEd25519) Neg() Point { - return &PointEd25519{value: edwards25519.NewIdentityPoint().Negate(p.value)} -} - -func (p *PointEd25519) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointEd25519) - if ok { - return &PointEd25519{value: edwards25519.NewIdentityPoint().Add(p.value, r.value)} - } else { - return nil - } -} - -func (p *PointEd25519) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointEd25519) - if ok { - rTmp := edwards25519.NewIdentityPoint().Negate(r.value) - return &PointEd25519{value: edwards25519.NewIdentityPoint().Add(p.value, rTmp)} - } else { - return nil - } -} - -func (p *PointEd25519) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarEd25519) - if ok { - value := edwards25519.NewIdentityPoint().ScalarMult(r.value, p.value) - return &PointEd25519{value} - } else { - return nil - } -} - -// MangleScalarBitsAndMulByBasepointToProducePublicKey -// is a function for mangling the bits of a (formerly -// mathematically well-defined) "scalar" and multiplying it to produce a -// public key. -func (p *PointEd25519) MangleScalarBitsAndMulByBasepointToProducePublicKey( - rhs *ScalarEd25519, -) *PointEd25519 { - data := rhs.value.Bytes() - s, err := edwards25519.NewScalar().SetBytesWithClamping(data[:]) - if err != nil { - return nil - } - value := edwards25519.NewIdentityPoint().ScalarBaseMult(s) - return &PointEd25519{value} -} - -func (p *PointEd25519) Equal(rhs Point) bool { - r, ok := rhs.(*PointEd25519) - if ok { - // We would like to check that the point (X/Z, Y/Z) is equal to - // the point (X'/Z', Y'/Z') without converting into affine - // coordinates (x, y) and (x', y'), which requires two inversions. - // We have that X = xZ and X' = x'Z'. Thus, x = x' is equivalent to - // (xZ)Z' = (x'Z')Z, and similarly for the y-coordinate. - return p.value.Equal(r.value) == 1 - //lhs1 := new(ed.FieldElement).Mul(&p.value.X, &r.value.Z) - //rhs1 := new(ed.FieldElement).Mul(&r.value.X, &p.value.Z) - //lhs2 := new(ed.FieldElement).Mul(&p.value.Y, &r.value.Z) - //rhs2 := new(ed.FieldElement).Mul(&r.value.Y, &p.value.Z) - // - //return lhs1.Equals(rhs1) && lhs2.Equals(rhs2) - } else { - return false - } -} - -func (p *PointEd25519) Set(x, y *big.Int) (Point, error) { - // check is identity - xx := subtle.ConstantTimeCompare(x.Bytes(), []byte{}) - yy := subtle.ConstantTimeCompare(y.Bytes(), []byte{}) - if (xx | yy) == 1 { - return p.Identity(), nil - } - xElem := new(ed.FieldElement).SetBigInt(x) - yElem := new(ed.FieldElement).SetBigInt(y) - - var data [32]byte - var affine [64]byte - xElem.BytesInto(&data) - copy(affine[:32], data[:]) - yElem.BytesInto(&data) - copy(affine[32:], data[:]) - return p.FromAffineUncompressed(affine[:]) -} - -// sqrtRatio sets r to the non-negative square root of the ratio of u and v. -// -// If u/v is square, sqrtRatio returns r and 1. If u/v is not square, SqrtRatio -// sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00, -// and returns r and 0. -func sqrtRatio(u, v *ed.FieldElement) (r *ed.FieldElement, wasSquare bool) { - sqrtM1 := ed.FieldElement{ - 533094393274173, 2016890930128738, 18285341111199, - 134597186663265, 1486323764102114, - } - a := new(ed.FieldElement) - b := new(ed.FieldElement) - r = new(ed.FieldElement) - - // r = (u * v3) * (u * v7)^((p-5)/8) - v2 := a.Square(v) - uv3 := b.Mul(u, b.Mul(v2, v)) - uv7 := a.Mul(uv3, a.Square(v2)) - r.Mul(uv3, r.Exp22523(uv7)) - - check := a.Mul(v, a.Square(r)) // check = v * r^2 - - uNeg := b.Neg(u) - correctSignSqrt := check.Equals(u) - flippedSignSqrt := check.Equals(uNeg) - flippedSignSqrtI := check.Equals(uNeg.Mul(uNeg, &sqrtM1)) - - rPrime := b.Mul(r, &sqrtM1) // r_prime = SQRT_M1 * r - // r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r) - cselect(r, rPrime, r, flippedSignSqrt || flippedSignSqrtI) - - r.Abs(r) // Choose the nonnegative square root. - return r, correctSignSqrt || flippedSignSqrt -} - -// cselect sets v to a if cond == 1, and to b if cond == 0. -func cselect(v, a, b *ed.FieldElement, cond bool) *ed.FieldElement { - const mask64Bits uint64 = (1 << 64) - 1 - - m := uint64(0) - if cond { - m = mask64Bits - } - - v[0] = (m & a[0]) | (^m & b[0]) - v[1] = (m & a[1]) | (^m & b[1]) - v[2] = (m & a[2]) | (^m & b[2]) - v[3] = (m & a[3]) | (^m & b[3]) - v[4] = (m & a[4]) | (^m & b[4]) - return v -} - -func (p *PointEd25519) ToAffineCompressed() []byte { - return p.value.Bytes() -} - -func (p *PointEd25519) ToAffineUncompressed() []byte { - x, y, z, _ := p.value.ExtendedCoordinates() - recip := new(field.Element).Invert(z) - x.Multiply(x, recip) - y.Multiply(y, recip) - var out [64]byte - copy(out[:32], x.Bytes()) - copy(out[32:], y.Bytes()) - return out[:] -} - -func (p *PointEd25519) FromAffineCompressed(inBytes []byte) (Point, error) { - pt, err := edwards25519.NewIdentityPoint().SetBytes(inBytes) - if err != nil { - return nil, err - } - return &PointEd25519{value: pt}, nil -} - -func (p *PointEd25519) FromAffineUncompressed(inBytes []byte) (Point, error) { - if len(inBytes) != 64 { - return nil, fmt.Errorf("invalid byte sequence") - } - if bytes.Equal( - inBytes, - []byte{ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - }, - ) { - return &PointEd25519{value: edwards25519.NewIdentityPoint()}, nil - } - x, err := new(field.Element).SetBytes(inBytes[:32]) - if err != nil { - return nil, err - } - y, err := new(field.Element).SetBytes(inBytes[32:]) - if err != nil { - return nil, err - } - z := new(field.Element).One() - t := new(field.Element).Multiply(x, y) - value, err := edwards25519.NewIdentityPoint().SetExtendedCoordinates(x, y, z, t) - if err != nil { - return nil, err - } - return &PointEd25519{value}, nil -} - -func (p *PointEd25519) CurveName() string { - return ED25519Name -} - -func (p *PointEd25519) SumOfProducts(points []Point, scalars []Scalar) Point { - nScalars := make([]*edwards25519.Scalar, len(scalars)) - nPoints := make([]*edwards25519.Point, len(points)) - for i, sc := range scalars { - s, err := edwards25519.NewScalar().SetCanonicalBytes(sc.Bytes()) - if err != nil { - return nil - } - nScalars[i] = s - } - for i, pt := range points { - pp, ok := pt.(*PointEd25519) - if !ok { - return nil - } - nPoints[i] = pp.value - } - pt := edwards25519.NewIdentityPoint().MultiScalarMult(nScalars, nPoints) - return &PointEd25519{value: pt} -} - -func (p *PointEd25519) VarTimeDoubleScalarBaseMult(a Scalar, A Point, b Scalar) Point { - AA, ok := A.(*PointEd25519) - if !ok { - return nil - } - aa, ok := a.(*ScalarEd25519) - if !ok { - return nil - } - bb, ok := b.(*ScalarEd25519) - if !ok { - return nil - } - value := edwards25519.NewIdentityPoint(). - VarTimeDoubleScalarBaseMult(aa.value, AA.value, bb.value) - return &PointEd25519{value} -} - -func (p *PointEd25519) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointEd25519) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointEd25519) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointEd25519) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointEd25519) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointEd25519) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointEd25519) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointEd25519) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointEd25519) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} - -func (p *PointEd25519) GetEdwardsPoint() *edwards25519.Point { - return edwards25519.NewIdentityPoint().Set(p.value) -} - -func (p *PointEd25519) SetEdwardsPoint(pt *edwards25519.Point) *PointEd25519 { - return &PointEd25519{value: edwards25519.NewIdentityPoint().Set(pt)} -} - -// Attempt to convert to an `EdwardsPoint`, using the supplied -// choice of sign for the `EdwardsPoint`. -// - `sign`: a `u8` donating the desired sign of the resulting -// `EdwardsPoint`. `0` denotes positive and `1` negative. -func toEdwards(u *ed.FieldElement, sign byte) *PointEd25519 { - one := new(ed.FieldElement).SetOne() - // To decompress the Montgomery u coordinate to an - // `EdwardsPoint`, we apply the birational map to obtain the - // Edwards y coordinate, then do Edwards decompression. - // - // The birational map is y = (u-1)/(u+1). - // - // The exceptional points are the zeros of the denominator, - // i.e., u = -1. - // - // But when u = -1, v^2 = u*(u^2+486662*u+1) = 486660. - // - // Since this is nonsquare mod p, u = -1 corresponds to a point - // on the twist, not the curve, so we can reject it early. - if u.Equals(new(ed.FieldElement).Neg(one)) { - return nil - } - - // y = (u-1)/(u+1) - yLhs := new(ed.FieldElement).Sub(u, one) - yRhs := new(ed.FieldElement).Add(u, one) - yInv := new(ed.FieldElement).Inverse(yRhs) - y := new(ed.FieldElement).Mul(yLhs, yInv) - yBytes := y.Bytes() - yBytes[31] ^= sign << 7 - - pt, err := edwards25519.NewIdentityPoint().SetBytes(yBytes[:]) - if err != nil { - return nil - } - pt.MultByCofactor(pt) - return &PointEd25519{value: pt} -} - -// Perform the Elligator2 mapping to a Montgomery point encoded as a 32 byte value -// -// See -func elligatorEncode(r0 *ed.FieldElement) *ed.FieldElement { - montgomeryA := &ed.FieldElement{ - 486662, 0, 0, 0, 0, - } - // montgomeryANeg is equal to -486662. - montgomeryANeg := &ed.FieldElement{ - 2251799813198567, - 2251799813685247, - 2251799813685247, - 2251799813685247, - 2251799813685247, - } - t := new(ed.FieldElement) - one := new(ed.FieldElement).SetOne() - // 2r^2 - d1 := new(ed.FieldElement).Add(one, t.DoubledSquare(r0)) - // A/(1+2r^2) - d := new(ed.FieldElement).Mul(montgomeryANeg, t.Inverse(d1)) - dsq := new(ed.FieldElement).Square(d) - au := new(ed.FieldElement).Mul(montgomeryA, d) - - inner := new(ed.FieldElement).Add(dsq, au) - inner.Add(inner, one) - - // d^3 + Ad^2 + d - eps := new(ed.FieldElement).Mul(d, inner) - _, wasSquare := sqrtRatio(eps, one) - - zero := new(ed.FieldElement).SetZero() - aTemp := new(ed.FieldElement).SetZero() - // 0 or A if non-square - cselect(aTemp, zero, montgomeryA, wasSquare) - // d, or d+A if non-square - u := new(ed.FieldElement).Add(d, aTemp) - // d or -d-A if non-square - cselect(u, u, new(ed.FieldElement).Neg(u), wasSquare) - return u -} diff --git a/crypto/core/curves/ed25519_curve_test.go b/crypto/core/curves/ed25519_curve_test.go deleted file mode 100644 index 16238a00b..000000000 --- a/crypto/core/curves/ed25519_curve_test.go +++ /dev/null @@ -1,621 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - crand "crypto/rand" - "encoding/hex" - "math/big" - "testing" - - ed "filippo.io/edwards25519" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestScalarEd25519Random(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Scalar.Random(testRng()) - s, ok := sc.(*ScalarEd25519) - require.True(t, ok) - expected := toRSc("feaa6a9d6dda758da6145f7d411a3af9f8a120698e0093faa97085b384c3f00e") - require.Equal(t, s.value.Equal(expected), 1) - // Try 10 random values - for i := 0; i < 10; i++ { - sc := ed25519.Scalar.Random(crand.Reader) - _, ok := sc.(*ScalarEd25519) - require.True(t, ok) - require.True(t, !sc.IsZero()) - } -} - -func TestScalarEd25519Hash(t *testing.T) { - var b [32]byte - ed25519 := ED25519() - sc := ed25519.Scalar.Hash(b[:]) - s, ok := sc.(*ScalarEd25519) - require.True(t, ok) - expected := toRSc("9d574494a02d72f5ff311cf0fb844d0fdd6103b17255274e029bdeed7207d409") - require.Equal(t, s.value.Equal(expected), 1) -} - -func TestScalarEd25519Zero(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Scalar.Zero() - require.True(t, sc.IsZero()) - require.True(t, sc.IsEven()) -} - -func TestScalarEd25519One(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Scalar.One() - require.True(t, sc.IsOne()) - require.True(t, sc.IsOdd()) -} - -func TestScalarEd25519New(t *testing.T) { - ed25519 := ED25519() - three := ed25519.Scalar.New(3) - require.True(t, three.IsOdd()) - four := ed25519.Scalar.New(4) - require.True(t, four.IsEven()) - neg1 := ed25519.Scalar.New(-1) - require.True(t, neg1.IsEven()) - neg2 := ed25519.Scalar.New(-2) - require.True(t, neg2.IsOdd()) -} - -func TestScalarEd25519Square(t *testing.T) { - ed25519 := ED25519() - three := ed25519.Scalar.New(3) - nine := ed25519.Scalar.New(9) - require.Equal(t, three.Square().Cmp(nine), 0) -} - -func TestScalarEd25519Cube(t *testing.T) { - ed25519 := ED25519() - three := ed25519.Scalar.New(3) - twentySeven := ed25519.Scalar.New(27) - require.Equal(t, three.Cube().Cmp(twentySeven), 0) -} - -func TestScalarEd25519Double(t *testing.T) { - ed25519 := ED25519() - three := ed25519.Scalar.New(3) - six := ed25519.Scalar.New(6) - require.Equal(t, three.Double().Cmp(six), 0) -} - -func TestScalarEd25519Neg(t *testing.T) { - ed25519 := ED25519() - one := ed25519.Scalar.One() - neg1 := ed25519.Scalar.New(-1) - require.Equal(t, one.Neg().Cmp(neg1), 0) - lotsOfThrees := ed25519.Scalar.New(333333) - expected := ed25519.Scalar.New(-333333) - require.Equal(t, lotsOfThrees.Neg().Cmp(expected), 0) -} - -func TestScalarEd25519Invert(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - actual, _ := nine.Invert() - sa, _ := actual.(*ScalarEd25519) - expected := toRSc("c3d9c4db0516043013b1e1ce8637dc92e3388ee3388ee3388ee3388ee3388e03") - require.Equal(t, sa.value.Equal(expected), 1) -} - -func TestScalarEd25519Sqrt(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - actual, err := nine.Sqrt() - sa, _ := actual.(*ScalarEd25519) - expected := toRSc("03") - require.NoError(t, err) - require.Equal(t, sa.value.Equal(expected), 1) -} - -func TestScalarEd25519Add(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - six := ed25519.Scalar.New(6) - fifteen := nine.Add(six) - require.NotNil(t, fifteen) - expected := ed25519.Scalar.New(15) - require.Equal(t, expected.Cmp(fifteen), 0) - - upper := ed25519.Scalar.New(-3) - actual := upper.Add(nine) - require.NotNil(t, actual) - require.Equal(t, actual.Cmp(six), 0) -} - -func TestScalarEd25519Sub(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - six := ed25519.Scalar.New(6) - expected := ed25519.Scalar.New(-3) - - actual := six.Sub(nine) - require.Equal(t, expected.Cmp(actual), 0) - - actual = nine.Sub(six) - require.Equal(t, actual.Cmp(ed25519.Scalar.New(3)), 0) -} - -func TestScalarEd25519Mul(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - six := ed25519.Scalar.New(6) - actual := nine.Mul(six) - require.Equal(t, actual.Cmp(ed25519.Scalar.New(54)), 0) - - upper := ed25519.Scalar.New(-1) - require.Equal(t, upper.Mul(upper).Cmp(ed25519.Scalar.New(1)), 0) -} - -func TestScalarEd25519Div(t *testing.T) { - ed25519 := ED25519() - nine := ed25519.Scalar.New(9) - actual := nine.Div(nine) - require.Equal(t, actual.Cmp(ed25519.Scalar.New(1)), 0) - require.Equal(t, ed25519.Scalar.New(54).Div(nine).Cmp(ed25519.Scalar.New(6)), 0) -} - -func TestScalarEd25519Serialize(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Scalar.New(255) - sequence := sc.Bytes() - require.Equal(t, len(sequence), 32) - require.Equal( - t, - sequence, - []byte{ - 0xff, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - 0x0, - }, - ) - ret, err := ed25519.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - - // Try 10 random values - for i := 0; i < 10; i++ { - sc = ed25519.Scalar.Random(crand.Reader) - sequence = sc.Bytes() - require.Equal(t, len(sequence), 32) - ret, err = ed25519.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - } -} - -func TestScalarEd25519Nil(t *testing.T) { - ed25519 := ED25519() - one := ed25519.Scalar.New(1) - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, one.Div(nil)) - require.Nil(t, ed25519.Scalar.Random(nil)) - require.Equal(t, one.Cmp(nil), -2) - _, err := ed25519.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointEd25519Random(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Point.Random(testRng()) - s, ok := sc.(*PointEd25519) - require.True(t, ok) - expected := toRPt("6011540c6231421a70ced5f577432531f198d318facfaad6e52cc42fba6e6fc5") - require.True(t, s.Equal(&PointEd25519{expected})) - // Try 25 random values - for i := 0; i < 25; i++ { - sc := ed25519.Point.Random(crand.Reader) - _, ok := sc.(*PointEd25519) - require.True(t, ok) - require.True(t, !sc.IsIdentity()) - pBytes := sc.ToAffineCompressed() - _, err := ed.NewIdentityPoint().SetBytes(pBytes) - require.NoError(t, err) - } -} - -func TestPointEd25519Hash(t *testing.T) { - var b [32]byte - ed25519 := ED25519() - sc := ed25519.Point.Hash(b[:]) - s, ok := sc.(*PointEd25519) - require.True(t, ok) - expected := toRPt("b4d75c3bb03ca644ab6c6d2a955c911003d8cfa719415de93a6b85eeb0c8dd97") - require.True(t, s.Equal(&PointEd25519{expected})) - - // Fuzz test - for i := 0; i < 25; i++ { - _, _ = crand.Read(b[:]) - sc = ed25519.Point.Hash(b[:]) - require.NotNil(t, sc) - } -} - -func TestPointEd25519Identity(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Point.Identity() - require.True(t, sc.IsIdentity()) - require.Equal( - t, - sc.ToAffineCompressed(), - []byte{ - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - }, - ) -} - -func TestPointEd25519Generator(t *testing.T) { - ed25519 := ED25519() - sc := ed25519.Point.Generator() - s, ok := sc.(*PointEd25519) - require.True(t, ok) - require.Equal( - t, - s.ToAffineCompressed(), - []byte{ - 0x58, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - 0x66, - }, - ) -} - -func TestPointEd25519Set(t *testing.T) { - ed25519 := ED25519() - iden, err := ed25519.Point.Set(big.NewInt(0), big.NewInt(0)) - require.NoError(t, err) - require.True(t, iden.IsIdentity()) - xBytes, _ := hex.DecodeString( - "1ad5258f602d56c9b2a7259560c72c695cdcd6fd31e2a4c0fe536ecdd3366921", - ) - yBytes, _ := hex.DecodeString( - "5866666666666666666666666666666666666666666666666666666666666666", - ) - x := new(big.Int).SetBytes(internal.ReverseScalarBytes(xBytes)) - y := new(big.Int).SetBytes(internal.ReverseScalarBytes(yBytes)) - newPoint, err := ed25519.Point.Set(x, y) - require.NoError(t, err) - require.NotEqualf( - t, - iden, - newPoint, - "after setting valid x and y, the point should NOT be identity point", - ) - - emptyX := new(big.Int).SetBytes(internal.ReverseScalarBytes([]byte{})) - identityPoint, err := ed25519.Point.Set(emptyX, y) - require.NoError(t, err) - require.Equalf(t, iden, identityPoint, "When x is empty, the point will be identity") -} - -func TestPointEd25519Double(t *testing.T) { - ed25519 := ED25519() - g := ed25519.Point.Generator() - g2 := g.Double() - require.True(t, g2.Equal(g.Mul(ed25519.Scalar.New(2)))) - i := ed25519.Point.Identity() - require.True(t, i.Double().Equal(i)) -} - -func TestPointEd25519Neg(t *testing.T) { - ed25519 := ED25519() - g := ed25519.Point.Generator().Neg() - require.True(t, g.Neg().Equal(ed25519.Point.Generator())) - require.True(t, ed25519.Point.Identity().Neg().Equal(ed25519.Point.Identity())) -} - -func TestPointEd25519Add(t *testing.T) { - ed25519 := ED25519() - pt := ed25519.Point.Generator() - require.True(t, pt.Add(pt).Equal(pt.Double())) - require.True(t, pt.Mul(ed25519.Scalar.New(3)).Equal(pt.Add(pt).Add(pt))) -} - -func TestPointEd25519Sub(t *testing.T) { - ed25519 := ED25519() - g := ed25519.Point.Generator() - pt := ed25519.Point.Generator().Mul(ed25519.Scalar.New(4)) - require.True(t, pt.Sub(g).Sub(g).Sub(g).Equal(g)) - require.True(t, pt.Sub(g).Sub(g).Sub(g).Sub(g).IsIdentity()) -} - -func TestPointEd25519Mul(t *testing.T) { - ed25519 := ED25519() - g := ed25519.Point.Generator() - pt := ed25519.Point.Generator().Mul(ed25519.Scalar.New(4)) - require.True(t, g.Double().Double().Equal(pt)) -} - -func TestPointEd25519Serialize(t *testing.T) { - ed25519 := ED25519() - ss := ed25519.Scalar.Random(testRng()) - g := ed25519.Point.Generator() - - ppt := g.Mul(ss) - expectedC := []byte{ - 0x7f, - 0x5b, - 0xa, - 0xd9, - 0xb8, - 0xce, - 0xb7, - 0x7, - 0x4c, - 0x10, - 0xc8, - 0xb4, - 0x27, - 0xe8, - 0xd2, - 0x28, - 0x50, - 0x42, - 0x6c, - 0x0, - 0x8a, - 0x3, - 0x72, - 0x2b, - 0x7c, - 0x3c, - 0x37, - 0x6f, - 0xf8, - 0x8f, - 0x42, - 0x5d, - } - expectedU := []byte{ - 0x70, - 0xad, - 0x4, - 0xa1, - 0x6, - 0x8, - 0x9f, - 0x47, - 0xe1, - 0xe8, - 0x9b, - 0x9c, - 0x81, - 0x5a, - 0xfb, - 0xb9, - 0x85, - 0x6a, - 0x2c, - 0xa, - 0xbc, - 0xff, - 0xe, - 0xc6, - 0xa0, - 0xb0, - 0xac, - 0x75, - 0xc, - 0xd8, - 0x59, - 0x53, - 0x7f, - 0x5b, - 0xa, - 0xd9, - 0xb8, - 0xce, - 0xb7, - 0x7, - 0x4c, - 0x10, - 0xc8, - 0xb4, - 0x27, - 0xe8, - 0xd2, - 0x28, - 0x50, - 0x42, - 0x6c, - 0x0, - 0x8a, - 0x3, - 0x72, - 0x2b, - 0x7c, - 0x3c, - 0x37, - 0x6f, - 0xf8, - 0x8f, - 0x42, - 0x5d, - } - require.Equal(t, ppt.ToAffineCompressed(), expectedC) - require.Equal(t, ppt.ToAffineUncompressed(), expectedU) - retP, err := ppt.FromAffineCompressed(ppt.ToAffineCompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - retP, err = ppt.FromAffineUncompressed(ppt.ToAffineUncompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - - // smoke test - for i := 0; i < 25; i++ { - s := ed25519.Scalar.Random(crand.Reader) - pt := g.Mul(s) - cmprs := pt.ToAffineCompressed() - require.Equal(t, len(cmprs), 32) - retC, err := pt.FromAffineCompressed(cmprs) - require.NoError(t, err) - require.True(t, pt.Equal(retC)) - - un := pt.ToAffineUncompressed() - require.Equal(t, len(un), 64) - retU, err := pt.FromAffineUncompressed(un) - require.NoError(t, err) - require.True(t, pt.Equal(retU)) - } -} - -func TestPointEd25519Nil(t *testing.T) { - ed25519 := ED25519() - one := ed25519.Point.Generator() - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, ed25519.Scalar.Random(nil)) - require.False(t, one.Equal(nil)) - _, err := ed25519.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointEd25519SumOfProducts(t *testing.T) { - lhs := new(PointEd25519).Generator().Mul(new(ScalarEd25519).New(50)) - points := make([]Point, 5) - for i := range points { - points[i] = new(PointEd25519).Generator() - } - scalars := []Scalar{ - new(ScalarEd25519).New(8), - new(ScalarEd25519).New(9), - new(ScalarEd25519).New(10), - new(ScalarEd25519).New(11), - new(ScalarEd25519).New(12), - } - rhs := lhs.SumOfProducts(points, scalars) - require.NotNil(t, rhs) - require.True(t, lhs.Equal(rhs)) -} - -func TestPointEd25519VarTimeDoubleScalarBaseMult(t *testing.T) { - curve := ED25519() - h := curve.Point.Hash([]byte("TestPointEd25519VarTimeDoubleScalarBaseMult")) - a := curve.Scalar.New(23) - b := curve.Scalar.New(77) - H, ok := h.(*PointEd25519) - require.True(t, ok) - rhs := H.VarTimeDoubleScalarBaseMult(a, H, b) - lhs := h.Mul(a).Add(curve.Point.Generator().Mul(b)) - require.True(t, lhs.Equal(rhs)) -} - -func toRSc(hx string) *ed.Scalar { - e, _ := hex.DecodeString(hx) - var data [32]byte - copy(data[:], e) - value, _ := new(ed.Scalar).SetCanonicalBytes(data[:]) - return value -} - -func toRPt(hx string) *ed.Point { - e, _ := hex.DecodeString(hx) - var data [32]byte - copy(data[:], e) - pt, _ := new(PointEd25519).FromAffineCompressed(data[:]) - return pt.(*PointEd25519).value -} diff --git a/crypto/core/curves/field.go b/crypto/core/curves/field.go deleted file mode 100755 index 87ca0c22b..000000000 --- a/crypto/core/curves/field.go +++ /dev/null @@ -1,282 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package curves: Field implementation IS NOT constant time as it leverages math/big for big number operations. -package curves - -import ( - "crypto/rand" - "encoding/json" - "fmt" - "io" - "math/big" - "sync" -) - -var ( - ed25519SubGroupOrderOnce sync.Once - ed25519SubGroupOrder *big.Int -) - -// Field is a finite field. -type Field struct { - *big.Int -} - -// Element is a group element within a finite field. -type Element struct { - Modulus *Field `json:"modulus"` - Value *big.Int `json:"value"` -} - -// ElementJSON is used in JSON<>Element conversions. -// For years, big.Int hasn't properly supported JSON unmarshaling -// https://github.com/golang/go/issues/28154 -type ElementJSON struct { - Modulus string `json:"modulus"` - Value string `json:"value"` -} - -// Marshal Element to JSON -func (x *Element) MarshalJSON() ([]byte, error) { - return json.Marshal(ElementJSON{ - Modulus: x.Modulus.String(), - Value: x.Value.String(), - }) -} - -func (x *Element) UnmarshalJSON(bytes []byte) error { - var e ElementJSON - err := json.Unmarshal(bytes, &e) - if err != nil { - return err - } - // Convert the strings to big.Ints - modulus, ok := new(big.Int).SetString(e.Modulus, 10) - if !ok { - return fmt.Errorf("failed to unmarshal modulus string '%v' to big.Int", e.Modulus) - } - x.Modulus = &Field{modulus} - x.Value, ok = new(big.Int).SetString(e.Value, 10) - if !ok { - return fmt.Errorf("failed to unmarshal value string '%v' to big.Int", e.Value) - } - return nil -} - -// The probability of returning true for a randomly chosen -// non-prime is at most ¼ⁿ. 64 is a widely used standard -// that is more than sufficient. -const millerRabinRounds = 64 - -// New is a constructor for a Field. -func NewField(modulus *big.Int) *Field { - // For our purposes we never expect to be dealing with a non-prime field. This provides some protection against - // accidentally doing that. - if !modulus.ProbablyPrime(millerRabinRounds) { - panic(fmt.Sprintf("modulus: %x is not a prime", modulus)) - } - - return &Field{modulus} -} - -func newElement(field *Field, value *big.Int) *Element { - if !field.IsValid(value) { - panic(fmt.Sprintf("value: %x is not within field: %x", value, field)) - } - - return &Element{field, value} -} - -// IsValid returns whether or not the value is within [0, modulus) -func (f Field) IsValid(value *big.Int) bool { - // value < modulus && value >= 0 - return value.Cmp(f.Int) < 0 && value.Sign() >= 0 -} - -func (f Field) NewElement(value *big.Int) *Element { - return newElement(&f, value) -} - -func (f Field) Zero() *Element { - return newElement(&f, big.NewInt(0)) -} - -func (f Field) One() *Element { - return newElement(&f, big.NewInt(1)) -} - -func (f Field) RandomElement(r io.Reader) (*Element, error) { - if r == nil { - r = rand.Reader - } - var randInt *big.Int - var err error - // Ed25519 needs to do special handling - // in case the value is used in - // Scalar multiplications with points - if f.Int.Cmp(Ed25519Order()) == 0 { - scalar := NewEd25519Scalar() - randInt, err = scalar.RandomWithReader(r) - } else { - // Read a random integer within the field. This is defined as [0, max) so we don't need to - // explicitly check it is within the field. If it is not, NewElement will panic anyways. - randInt, err = rand.Int(r, f.Int) - } - if err != nil { - return nil, err - } - return newElement(&f, randInt), nil -} - -// ElementFromBytes initializes a new field element from big-endian bytes -func (f Field) ElementFromBytes(bytes []byte) *Element { - return newElement(&f, new(big.Int).SetBytes(bytes)) -} - -// ReducedElementFromBytes initializes a new field element from big-endian bytes and reduces it by -// the modulus of the field. -// -// WARNING: If this is used with cryptographic constructions which rely on a uniform distribution of -// values, this may introduce a bias to the value of the returned field element. This happens when -// the integer range of the provided bytes is not an integer multiple of the field order. -// -// Assume we are working in field which a modulus of 3 and the range of the uniform random bytes we -// provide as input is 5. Thus, the set of field elements is {0, 1, 2} and the set of integer values -// for the input bytes is: {0, 1, 2, 3, 4}. What is the distribution of the output values produced -// by this function? -// -// ReducedElementFromBytes(0) => 0 -// ReducedElementFromBytes(1) => 1 -// ReducedElementFromBytes(2) => 2 -// ReducedElementFromBytes(3) => 0 -// ReducedElementFromBytes(4) => 1 -// -// For a value space V and random value v, a uniform distribution is defined as P[V = v] = 1/|V| -// where |V| is to the order of the field. Using the results from above, we see that P[v = 0] = 2/5, -// P[v = 1] = 2/5, and P[v = 2] = 1/5. For a uniform distribution we would expect these to each be -// equal to 1/3. As they do not, this does not return uniform output for that example. -// -// To see why this is okay if the range is a multiple of the field order, change the input range to -// 6 and notice that now each output has a probability of 2/6 = 1/3, and the output is uniform. -func (f Field) ReducedElementFromBytes(bytes []byte) *Element { - value := new(big.Int).SetBytes(bytes) - value.Mod(value, f.Int) - return newElement(&f, value) -} - -func (x Element) Field() *Field { - return x.Modulus -} - -// Add returns the sum x+y -func (x Element) Add(y *Element) *Element { - x.validateFields(y) - - sum := new(big.Int).Add(x.Value, y.Value) - sum.Mod(sum, x.Modulus.Int) - return newElement(x.Modulus, sum) -} - -// Sub returns the difference x-y -func (x Element) Sub(y *Element) *Element { - x.validateFields(y) - - difference := new(big.Int).Sub(x.Value, y.Value) - difference.Mod(difference, x.Modulus.Int) - return newElement(x.Modulus, difference) -} - -// Neg returns the field negation -func (x Element) Neg() *Element { - z := new(big.Int).Neg(x.Value) - z.Mod(z, x.Modulus.Int) - return newElement(x.Modulus, z) -} - -// Mul returns the product x*y -func (x Element) Mul(y *Element) *Element { - x.validateFields(y) - - product := new(big.Int).Mul(x.Value, y.Value) - product.Mod(product, x.Modulus.Int) - return newElement(x.Modulus, product) -} - -// Div returns the quotient x/y -func (x Element) Div(y *Element) *Element { - x.validateFields(y) - - yInv := new(big.Int).ModInverse(y.Value, x.Modulus.Int) - quotient := new(big.Int).Mul(x.Value, yInv) - quotient.Mod(quotient, x.Modulus.Int) - return newElement(x.Modulus, quotient) -} - -// Pow computes x^y reduced by the modulus -func (x Element) Pow(y *Element) *Element { - x.validateFields(y) - - return newElement(x.Modulus, new(big.Int).Exp(x.Value, y.Value, x.Modulus.Int)) -} - -func (x Element) Invert() *Element { - return newElement(x.Modulus, new(big.Int).ModInverse(x.Value, x.Modulus.Int)) -} - -func (x Element) Sqrt() *Element { - return newElement(x.Modulus, new(big.Int).ModSqrt(x.Value, x.Modulus.Int)) -} - -// BigInt returns value as a big.Int -func (x Element) BigInt() *big.Int { - return x.Value -} - -// Bytes returns the value as bytes -func (x Element) Bytes() []byte { - return x.BigInt().Bytes() -} - -// IsEqual returns x == y -func (x Element) IsEqual(y *Element) bool { - if !x.isEqualFields(y) { - return false - } - - return x.Value.Cmp(y.Value) == 0 -} - -// Clone returns a new copy of the element -func (x Element) Clone() *Element { - return x.Modulus.ElementFromBytes(x.Bytes()) -} - -func (x Element) isEqualFields(y *Element) bool { - return x.Modulus.Int.Cmp(y.Modulus.Int) == 0 -} - -func (x Element) validateFields(y *Element) { - if !x.isEqualFields(y) { - panic("fields must match for valid binary operation") - } -} - -// SubgroupOrder returns the order of the Ed25519 base Point. -func Ed25519Order() *big.Int { - ed25519SubGroupOrderOnce.Do(func() { - order, ok := new(big.Int).SetString( - "1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", - 16, - ) - if !ok { - panic("invalid hex string provided. This should never happen as it is constant.") - } - ed25519SubGroupOrder = order - }) - - return ed25519SubGroupOrder -} diff --git a/crypto/core/curves/field_test.go b/crypto/core/curves/field_test.go deleted file mode 100755 index 5b2f32776..000000000 --- a/crypto/core/curves/field_test.go +++ /dev/null @@ -1,305 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "encoding/json" - "errors" - "fmt" - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -var ( - one = big.NewInt(1) - modulus, modulusOk = new(big.Int).SetString( - "1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", - 16, - ) - oneBelowModulus = zero().Sub(modulus, one) - oneAboveModulus = zero().Add(modulus, one) - field25519 = NewField(modulus) -) - -type buggedReader struct{} - -func (r buggedReader) Read(p []byte) (n int, err error) { - return 0, errors.New("EOF") -} - -func zero() *big.Int { - return new(big.Int) -} - -func assertElementZero(t *testing.T, e *Element) { - require.Equal(t, zero().Bytes(), e.Bytes()) -} - -type binaryOperation func(*Element) *Element - -func assertUnequalFieldsPanic(t *testing.T, b binaryOperation) { - altField := NewField(big.NewInt(23)) - altElement := altField.NewElement(one) - - require.PanicsWithValue( - t, - "fields must match for valid binary operation", - func() { b(altElement) }, - ) -} - -func TestFieldModulus(t *testing.T) { - require.True(t, modulusOk) -} - -func TestNewField(t *testing.T) { - require.PanicsWithValue( - t, - fmt.Sprintf("modulus: %x is not a prime", oneBelowModulus), - func() { NewField(oneBelowModulus) }, - ) - require.NotPanics( - t, - func() { NewField(modulus) }, - ) -} - -func TestNewElement(t *testing.T) { - require.PanicsWithValue( - t, - fmt.Sprintf("value: %x is not within field: %x", modulus, field25519.Int), - func() { newElement(field25519, modulus) }, - ) - require.NotPanics( - t, - func() { newElement(field25519, oneBelowModulus) }, - ) -} - -func TestElementIsValid(t *testing.T) { - require.False(t, field25519.IsValid(zero().Neg(one))) - require.False(t, field25519.IsValid(modulus)) - require.False(t, field25519.IsValid(oneAboveModulus)) - require.True(t, field25519.IsValid(oneBelowModulus)) -} - -func TestFieldNewElement(t *testing.T) { - element := field25519.NewElement(oneBelowModulus) - - require.Equal(t, oneBelowModulus, element.Value) - require.Equal(t, field25519, element.Field()) -} - -func TestZeroElement(t *testing.T) { - require.Equal(t, zero(), field25519.Zero().Value) - require.Equal(t, field25519, field25519.Zero().Field()) -} - -func TestOneElement(t *testing.T) { - require.Equal(t, field25519.One().Value, one) - require.Equal(t, field25519.One().Field(), field25519) -} - -func TestRandomElement(t *testing.T) { - randomElement1, err := field25519.RandomElement(nil) - require.NoError(t, err) - randomElement2, err := field25519.RandomElement(nil) - require.NoError(t, err) - randomElement3, err := field25519.RandomElement(new(buggedReader)) - require.Error(t, err) - - require.Equal(t, field25519, randomElement1.Field()) - require.Equal(t, field25519, randomElement2.Field()) - require.NotEqual(t, randomElement1.Value, randomElement2.Value) - require.Nil(t, randomElement3) -} - -func TestElementFromBytes(t *testing.T) { - element := field25519.ElementFromBytes(oneBelowModulus.Bytes()) - - require.Equal(t, field25519, element.Field()) - require.Equal(t, oneBelowModulus, element.Value) -} - -func TestReducedElementFromBytes(t *testing.T) { - element := field25519.ReducedElementFromBytes(oneBelowModulus.Bytes()) - - require.Equal(t, field25519, element.Field()) - require.Equal(t, oneBelowModulus, element.Value) - - element = field25519.ReducedElementFromBytes(oneAboveModulus.Bytes()) - - require.Equal(t, field25519, element.Field()) - require.Equal(t, one, element.Value) -} - -func TestAddElement(t *testing.T) { - element1 := field25519.NewElement(one) - element2 := field25519.NewElement(big.NewInt(2)) - element3 := field25519.NewElement(oneBelowModulus) - element4 := &Element{field25519, modulus} - - require.Equal(t, element2, element1.Add(element1)) - require.Equal(t, big.NewInt(3), element1.Add(element2).Value) - require.Equal(t, big.NewInt(3), element2.Add(element1).Value) - require.Equal(t, one, element1.Add(element4).Value) - require.Equal(t, one, element3.Add(element2).Value) - assertElementZero(t, element1.Add(element3)) - assertUnequalFieldsPanic(t, element1.Add) -} - -func TestSubElement(t *testing.T) { - element1 := field25519.NewElement(one) - element2 := field25519.NewElement(big.NewInt(2)) - element3 := field25519.NewElement(oneBelowModulus) - element4 := &Element{field25519, modulus} - - assertElementZero(t, element1.Sub(element1)) - require.Equal(t, element3, element1.Sub(element2)) - require.Equal(t, element1, element2.Sub(element1)) - require.Equal(t, element1, element1.Sub(element4)) - require.Equal(t, element3, element4.Sub(element1)) - require.Equal(t, element1, element4.Sub(element3)) - require.Equal(t, element3, element3.Sub(element4)) - assertUnequalFieldsPanic(t, element1.Sub) -} - -func TestMulElement(t *testing.T) { - element1 := field25519.NewElement(one) - element2 := field25519.NewElement(big.NewInt(2)) - element3 := field25519.NewElement(oneBelowModulus) - element4 := field25519.NewElement(zero()) - expectedProduct, ok := new(big.Int).SetString( - "1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3eb", - 16, - ) - require.True(t, ok) - - assertElementZero(t, element1.Mul(element4)) - assertElementZero(t, element4.Mul(element1)) - require.Equal(t, element3, element1.Mul(element3)) - require.Equal(t, element3, element3.Mul(element1)) - require.Equal(t, expectedProduct, element3.Mul(element2).Value) - require.Equal(t, expectedProduct, element2.Mul(element3).Value) - assertUnequalFieldsPanic(t, element1.Mul) -} - -func TestDivElement(t *testing.T) { - element1 := field25519.NewElement(one) - element2 := field25519.NewElement(big.NewInt(2)) - element3 := field25519.NewElement(oneBelowModulus) - element4 := field25519.NewElement(zero()) - expectedQuotient1, ok := new(big.Int).SetString( - "80000000000000000000000000000000a6f7cef517bce6b2c09318d2e7ae9f6", - 16, - ) - require.True(t, ok) - expectedQuotient2, ok := new(big.Int).SetString( - "1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3eb", - 16, - ) - require.True(t, ok) - - assertElementZero(t, element4.Div(element3)) - require.Equal(t, element3, element3.Div(element1)) - require.Equal(t, expectedQuotient1, element3.Div(element2).Value) - require.Equal(t, expectedQuotient2, element2.Div(element3).Value) - require.Panics(t, func() { element3.Div(element4) }) - assertUnequalFieldsPanic(t, element1.Div) -} - -func TestIsEqualElement(t *testing.T) { - element1 := field25519.NewElement(oneBelowModulus) - element2 := field25519.NewElement(big.NewInt(23)) - element3 := field25519.NewElement(oneBelowModulus) - altField := NewField(big.NewInt(23)) - altElement1 := altField.NewElement(one) - - require.False(t, element1.IsEqual(element2)) - require.True(t, element1.IsEqual(element3)) - require.True(t, element1.IsEqual(element1)) - require.False(t, element1.IsEqual(altElement1)) -} - -func TestBigIntElement(t *testing.T) { - element := field25519.NewElement(oneBelowModulus) - - require.Equal(t, oneBelowModulus, element.BigInt()) -} - -func TestBytesElement(t *testing.T) { - element := field25519.NewElement(oneBelowModulus) - - require.Equal( - t, - []byte{ - 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0xde, 0xf9, 0xde, 0xa2, - 0xf7, 0x9c, 0xd6, 0x58, 0x12, 0x63, 0x1a, 0x5c, 0xf5, - 0xd3, 0xec, - }, - element.Bytes(), - ) -} - -func TestCloneElement(t *testing.T) { - element := field25519.NewElement(oneBelowModulus) - clone := element.Clone() - - require.Equal(t, clone, element) - - clone.Value.Add(one, one) - - require.NotEqual(t, clone, element) -} - -// Tests un/marshaling Element -func TestElementMarshalJsonRoundTrip(t *testing.T) { - reallyBigInt1, ok := new( - big.Int, - ).SetString("12365234878725472538962348629568356835892346729834725643857832", 10) - require.True(t, ok) - - reallyBigInt2, ok := new( - big.Int, - ).SetString("123652348787DEF9DEA2F79CD65812631A5CF5D3ED46729834725643857832", 16) - require.True(t, ok) - - ins := []*Element{ - newElement(field25519, big.NewInt(300)), - newElement(field25519, big.NewInt(300000)), - newElement(field25519, big.NewInt(12812798)), - newElement(field25519, big.NewInt(17)), - newElement(field25519, big.NewInt(5066680)), - newElement(field25519, big.NewInt(3005)), - newElement(field25519, big.NewInt(317)), - newElement(field25519, big.NewInt(323)), - newElement(field25519, reallyBigInt1), - newElement(field25519, reallyBigInt2), - newElement(field25519, oneBelowModulus), - } - - // Run all the tests! - for _, in := range ins { - bytes, err := json.Marshal(in) - require.NoError(t, err) - require.NotNil(t, bytes) - - // Unmarshal and test - out := &Element{} - err = json.Unmarshal(bytes, &out) - require.NoError(t, err) - require.NotNil(t, out) - require.NotNil(t, out.Modulus) - require.NotNil(t, out.Value) - - require.Equal(t, in.Modulus.Bytes(), out.Modulus.Bytes()) - require.Equal(t, in.Value.Bytes(), out.Value.Bytes()) - } -} diff --git a/crypto/core/curves/k256_bench_test.go b/crypto/core/curves/k256_bench_test.go deleted file mode 100644 index ed8a9dcb8..000000000 --- a/crypto/core/curves/k256_bench_test.go +++ /dev/null @@ -1,446 +0,0 @@ -package curves - -import ( - crand "crypto/rand" - "crypto/sha256" - "io" - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - - mod "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/internal" -) - -func BenchmarkK256(b *testing.B) { - // 1000 points - b.Run("1000 point add - btcec", func(b *testing.B) { - b.StopTimer() - points := make([]*BenchPoint, 1000) - for i := range points { - points[i] = points[i].Random(crand.Reader).(*BenchPoint) - } - acc := new(BenchPoint).Identity() - b.StartTimer() - for _, pt := range points { - acc = acc.Add(pt) - } - }) - b.Run("1000 point add - ct k256", func(b *testing.B) { - b.StopTimer() - curve := K256() - points := make([]*PointK256, 1000) - for i := range points { - points[i] = curve.NewIdentityPoint().Random(crand.Reader).(*PointK256) - } - acc := curve.NewIdentityPoint() - b.StartTimer() - for _, pt := range points { - acc = acc.Add(pt) - } - }) - b.Run("1000 point double - btcec", func(b *testing.B) { - b.StopTimer() - acc := new(BenchPoint).Generator() - b.StartTimer() - for i := 0; i < 1000; i++ { - acc = acc.Double() - } - }) - b.Run("1000 point double - ct k256", func(b *testing.B) { - b.StopTimer() - acc := new(PointK256).Generator() - b.StartTimer() - for i := 0; i < 1000; i++ { - acc = acc.Double() - } - }) - b.Run("1000 point multiply - btcec", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalar, 1000) - for i := range scalars { - s := new(BenchScalar).Random(crand.Reader) - scalars[i] = s.(*BenchScalar) - } - acc := new(BenchPoint).Generator().Mul(new(BenchScalar).New(2)) - b.StartTimer() - for _, sc := range scalars { - acc = acc.Mul(sc) - } - }) - b.Run("1000 point multiply - ct k256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarK256, 1000) - for i := range scalars { - s := new(ScalarK256).Random(crand.Reader) - scalars[i] = s.(*ScalarK256) - } - acc := new(PointK256).Generator() - b.StartTimer() - for _, sc := range scalars { - acc = acc.Mul(sc) - } - }) - b.Run("1000 scalar invert - btcec", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalar, 1000) - for i := range scalars { - s := new(BenchScalar).Random(crand.Reader) - scalars[i] = s.(*BenchScalar) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Invert() - } - }) - b.Run("1000 scalar invert - ct k256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarK256, 1000) - for i := range scalars { - s := new(ScalarK256).Random(crand.Reader) - scalars[i] = s.(*ScalarK256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Invert() - } - }) - b.Run("1000 scalar sqrt - btcec", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalar, 1000) - for i := range scalars { - s := new(BenchScalar).Random(crand.Reader) - scalars[i] = s.(*BenchScalar) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Sqrt() - } - }) - b.Run("1000 scalar sqrt - ct k256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarK256, 1000) - for i := range scalars { - s := new(ScalarK256).Random(crand.Reader) - scalars[i] = s.(*ScalarK256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Sqrt() - } - }) -} - -type BenchScalar struct { - value *big.Int -} - -func (s *BenchScalar) Random(reader io.Reader) Scalar { - var v [32]byte - _, _ = reader.Read(v[:]) - value := new(big.Int).SetBytes(v[:]) - return &BenchScalar{ - value: value.Mod(value, btcec.S256().N), - } -} - -func (s *BenchScalar) Hash(bytes []byte) Scalar { - h := sha256.Sum256(bytes) - value := new(big.Int).SetBytes(h[:]) - return &BenchScalar{ - value: value.Mod(value, btcec.S256().N), - } -} - -func (s *BenchScalar) Zero() Scalar { - return &BenchScalar{ - value: big.NewInt(0), - } -} - -func (s *BenchScalar) One() Scalar { - return &BenchScalar{ - value: big.NewInt(1), - } -} - -func (s *BenchScalar) IsZero() bool { - return s.value.Cmp(big.NewInt(0)) == 0 -} - -func (s *BenchScalar) IsOne() bool { - return s.value.Cmp(big.NewInt(1)) == 0 -} - -func (s *BenchScalar) IsOdd() bool { - return s.value.Bit(0) == 1 -} - -func (s *BenchScalar) IsEven() bool { - return s.value.Bit(0) == 0 -} - -func (s *BenchScalar) New(value int) Scalar { - v := big.NewInt(int64(value)) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Cmp(rhs Scalar) int { - r := rhs.(*BenchScalar) - return s.value.Cmp(r.value) -} - -func (s *BenchScalar) Square() Scalar { - v := new(big.Int).Mul(s.value, s.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Double() Scalar { - v := new(big.Int).Add(s.value, s.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Invert() (Scalar, error) { - return &BenchScalar{ - value: new(big.Int).ModInverse(s.value, btcec.S256().N), - }, nil -} - -func (s *BenchScalar) Sqrt() (Scalar, error) { - return &BenchScalar{ - value: new(big.Int).ModSqrt(s.value, btcec.S256().N), - }, nil -} - -func (s *BenchScalar) Cube() Scalar { - v := new(big.Int).Mul(s.value, s.value) - v.Mul(v, s.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Add(rhs Scalar) Scalar { - r := rhs.(*BenchScalar) - v := new(big.Int).Add(s.value, r.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Sub(rhs Scalar) Scalar { - r := rhs.(*BenchScalar) - v := new(big.Int).Sub(s.value, r.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Mul(rhs Scalar) Scalar { - r := rhs.(*BenchScalar) - v := new(big.Int).Mul(s.value, r.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) MulAdd(y, z Scalar) Scalar { - yy := y.(*BenchScalar) - zz := z.(*BenchScalar) - v := new(big.Int).Mul(s.value, yy.value) - v.Add(v, zz.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Div(rhs Scalar) Scalar { - r := rhs.(*BenchScalar) - v := new(big.Int).ModInverse(r.value, btcec.S256().N) - v.Mul(v, s.value) - return &BenchScalar{ - value: v.Mod(v, btcec.S256().N), - } -} - -func (s *BenchScalar) Neg() Scalar { - v, _ := mod.Neg(s.value, btcec.S256().N) - return &BenchScalar{ - value: v, - } -} - -func (s *BenchScalar) SetBigInt(v *big.Int) (Scalar, error) { - return &BenchScalar{ - value: new(big.Int).Set(v), - }, nil -} - -func (s *BenchScalar) BigInt() *big.Int { - return new(big.Int).Set(s.value) -} - -func (s *BenchScalar) Point() Point { - return (&BenchPoint{}).Identity() -} - -func (s *BenchScalar) Bytes() []byte { - return internal.ReverseScalarBytes(s.value.Bytes()) -} - -func (s *BenchScalar) SetBytes(bytes []byte) (Scalar, error) { - value := new(big.Int).SetBytes(internal.ReverseScalarBytes(bytes)) - value.Mod(value, btcec.S256().N) - return &BenchScalar{ - value, - }, nil -} - -func (s *BenchScalar) SetBytesWide(bytes []byte) (Scalar, error) { - value := new(big.Int).SetBytes(internal.ReverseScalarBytes(bytes)) - value.Mod(value, btcec.S256().N) - return &BenchScalar{ - value, - }, nil -} - -func (s *BenchScalar) Clone() Scalar { - return &BenchScalar{ - value: new(big.Int).Set(s.value), - } -} - -type BenchPoint struct { - x, y *big.Int -} - -func (p *BenchPoint) Random(reader io.Reader) Point { - var k [32]byte - curve := btcec.S256() - _, _ = reader.Read(k[:]) - x, y := curve.ScalarBaseMult(k[:]) - for !curve.IsOnCurve(x, y) { - _, _ = reader.Read(k[:]) - x, y = curve.ScalarBaseMult(k[:]) - } - return &BenchPoint{x, y} -} - -func (p *BenchPoint) Hash(bytes []byte) Point { - return nil -} - -func (p *BenchPoint) Identity() Point { - return &BenchPoint{x: big.NewInt(0), y: big.NewInt(0)} -} - -func (p *BenchPoint) Generator() Point { - return &BenchPoint{ - x: new(big.Int).Set(btcec.S256().Gx), - y: new(big.Int).Set(btcec.S256().Gy), - } -} - -func (p *BenchPoint) IsIdentity() bool { - return false -} - -func (p *BenchPoint) IsNegative() bool { - return false -} - -func (p *BenchPoint) IsOnCurve() bool { - return btcec.S256().IsOnCurve(p.x, p.y) -} - -func (p *BenchPoint) Double() Point { - x, y := btcec.S256().Double(p.x, p.y) - return &BenchPoint{ - x, y, - } -} - -func (p *BenchPoint) Scalar() Scalar { - return &BenchScalar{value: big.NewInt(0)} -} - -func (p *BenchPoint) Neg() Point { - y, _ := mod.Neg(p.y, btcec.S256().P) - return &BenchPoint{ - x: new(big.Int).Set(p.x), y: y, - } -} - -func (p *BenchPoint) Add(rhs Point) Point { - r := rhs.(*BenchPoint) - x, y := btcec.S256().Add(p.x, p.y, r.x, r.y) - return &BenchPoint{ - x, y, - } -} - -func (p *BenchPoint) Sub(rhs Point) Point { - t := rhs.Neg().(*BenchPoint) - return t.Add(p) -} - -func (p *BenchPoint) Mul(rhs Scalar) Point { - k := rhs.Bytes() - x, y := btcec.S256().ScalarMult(p.x, p.y, k) - return &BenchPoint{ - x, y, - } -} - -func (p *BenchPoint) Equal(rhs Point) bool { - r := rhs.(*BenchPoint) - return p.x.Cmp(r.x) == 0 && p.y.Cmp(r.y) == 0 -} - -func (p *BenchPoint) Set(x, y *big.Int) (Point, error) { - return &BenchPoint{ - x, y, - }, nil -} - -func (p *BenchPoint) ToAffineCompressed() []byte { - return nil -} - -func (p *BenchPoint) ToAffineUncompressed() []byte { - return nil -} - -func (p *BenchPoint) FromAffineCompressed(bytes []byte) (Point, error) { - return nil, nil -} - -func (p *BenchPoint) FromAffineUncompressed(bytes []byte) (Point, error) { - return nil, nil -} - -func (p *BenchPoint) CurveName() string { - return btcec.S256().Name -} - -func (p *BenchPoint) SumOfProducts(points []Point, scalars []Scalar) Point { - biScalars := make([]*big.Int, len(scalars)) - for i := 0; i < len(scalars); i++ { - biScalars[i] = scalars[i].BigInt() - } - return sumOfProductsPippenger(points, biScalars) -} - -//func rhsK256(x *big.Int) *big.Int { -// // y^2 = x^3 + B -// x3, _ := mod.Exp(x, big.NewInt(3), btcec.S256().P) -// x3.Add(x3, btcec.S256().B) -// return x3.ModSqrt(x3, btcec.S256().P) -//} diff --git a/crypto/core/curves/k256_curve.go b/crypto/core/curves/k256_curve.go deleted file mode 100644 index 54af5df77..000000000 --- a/crypto/core/curves/k256_curve.go +++ /dev/null @@ -1,672 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - "fmt" - "io" - "math/big" - "sync" - - "github.com/btcsuite/btcd/btcec/v2" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - secp256k1 "github.com/sonr-io/sonr/crypto/core/curves/native/k256" - "github.com/sonr-io/sonr/crypto/core/curves/native/k256/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/k256/fq" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - oldK256Initonce sync.Once - oldK256 Koblitz256 -) - -type Koblitz256 struct { - *elliptic.CurveParams -} - -func oldK256InitAll() { - curve := btcec.S256() - oldK256.CurveParams = new(elliptic.CurveParams) - oldK256.P = curve.P - oldK256.N = curve.N - oldK256.Gx = curve.Gx - oldK256.Gy = curve.Gy - oldK256.B = curve.B - oldK256.BitSize = curve.BitSize - oldK256.Name = K256Name -} - -func K256Curve() *Koblitz256 { - oldK256Initonce.Do(oldK256InitAll) - return &oldK256 -} - -func (curve *Koblitz256) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *Koblitz256) IsOnCurve(x, y *big.Int) bool { - _, err := secp256k1.K256PointNew().SetBigInt(x, y) - return err == nil -} - -func (curve *Koblitz256) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - p1, err := secp256k1.K256PointNew().SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - p2, err := secp256k1.K256PointNew().SetBigInt(x2, y2) - if err != nil { - return nil, nil - } - return p1.Add(p1, p2).BigInt() -} - -func (curve *Koblitz256) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p1, err := secp256k1.K256PointNew().SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - return p1.Double(p1).BigInt() -} - -func (curve *Koblitz256) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p1, err := secp256k1.K256PointNew().SetBigInt(Bx, By) - if err != nil { - return nil, nil - } - var bytes [32]byte - copy(bytes[:], internal.ReverseScalarBytes(k)) - s, err := fq.K256FqNew().SetBytes(&bytes) - if err != nil { - return nil, nil - } - return p1.Mul(p1, s).BigInt() -} - -func (curve *Koblitz256) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - var bytes [32]byte - copy(bytes[:], internal.ReverseScalarBytes(k)) - s, err := fq.K256FqNew().SetBytes(&bytes) - if err != nil { - return nil, nil - } - p1 := secp256k1.K256PointNew().Generator() - return p1.Mul(p1, s).BigInt() -} - -type ScalarK256 struct { - value *native.Field -} - -type PointK256 struct { - value *native.EllipticPoint -} - -func (s *ScalarK256) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarK256) Hash(bytes []byte) Scalar { - dst := []byte("secp256k1_XMD:SHA-256_SSWU_RO_") - xmd := native.ExpandMsgXmd(native.EllipticPointHasherSha256(), bytes, dst, 48) - var t [64]byte - copy(t[:48], internal.ReverseScalarBytes(xmd)) - - return &ScalarK256{ - value: fq.K256FqNew().SetBytesWide(&t), - } -} - -func (s *ScalarK256) Zero() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().SetZero(), - } -} - -func (s *ScalarK256) One() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().SetOne(), - } -} - -func (s *ScalarK256) IsZero() bool { - return s.value.IsZero() == 1 -} - -func (s *ScalarK256) IsOne() bool { - return s.value.IsOne() == 1 -} - -func (s *ScalarK256) IsOdd() bool { - return s.value.Bytes()[0]&1 == 1 -} - -func (s *ScalarK256) IsEven() bool { - return s.value.Bytes()[0]&1 == 0 -} - -func (s *ScalarK256) New(value int) Scalar { - t := fq.K256FqNew() - v := big.NewInt(int64(value)) - if value < 0 { - v.Mod(v, t.Params.BiModulus) - } - return &ScalarK256{ - value: t.SetBigInt(v), - } -} - -func (s *ScalarK256) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarK256) - if ok { - return s.value.Cmp(r.value) - } else { - return -2 - } -} - -func (s *ScalarK256) Square() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().Square(s.value), - } -} - -func (s *ScalarK256) Double() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().Double(s.value), - } -} - -func (s *ScalarK256) Invert() (Scalar, error) { - value, wasInverted := fq.K256FqNew().Invert(s.value) - if !wasInverted { - return nil, fmt.Errorf("inverse doesn't exist") - } - return &ScalarK256{ - value, - }, nil -} - -func (s *ScalarK256) Sqrt() (Scalar, error) { - value, wasSquare := fq.K256FqNew().Sqrt(s.value) - if !wasSquare { - return nil, fmt.Errorf("not a square") - } - return &ScalarK256{ - value, - }, nil -} - -func (s *ScalarK256) Cube() Scalar { - value := fq.K256FqNew().Mul(s.value, s.value) - value.Mul(value, s.value) - return &ScalarK256{ - value, - } -} - -func (s *ScalarK256) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarK256) - if ok { - return &ScalarK256{ - value: fq.K256FqNew().Add(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarK256) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarK256) - if ok { - return &ScalarK256{ - value: fq.K256FqNew().Sub(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarK256) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarK256) - if ok { - return &ScalarK256{ - value: fq.K256FqNew().Mul(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarK256) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarK256) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarK256) - if ok { - v, wasInverted := fq.K256FqNew().Invert(r.value) - if !wasInverted { - return nil - } - v.Mul(v, s.value) - return &ScalarK256{value: v} - } else { - return nil - } -} - -func (s *ScalarK256) Neg() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().Neg(s.value), - } -} - -func (s *ScalarK256) SetBigInt(v *big.Int) (Scalar, error) { - if v == nil { - return nil, fmt.Errorf("'v' cannot be nil") - } - value := fq.K256FqNew().SetBigInt(v) - return &ScalarK256{ - value, - }, nil -} - -func (s *ScalarK256) BigInt() *big.Int { - return s.value.BigInt() -} - -func (s *ScalarK256) Bytes() []byte { - t := s.value.Bytes() - return internal.ReverseScalarBytes(t[:]) -} - -func (s *ScalarK256) SetBytes(bytes []byte) (Scalar, error) { - if len(bytes) != 32 { - return nil, fmt.Errorf("invalid length") - } - var seq [32]byte - copy(seq[:], internal.ReverseScalarBytes(bytes)) - value, err := fq.K256FqNew().SetBytes(&seq) - if err != nil { - return nil, err - } - return &ScalarK256{ - value, - }, nil -} - -func (s *ScalarK256) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) != 64 { - return nil, fmt.Errorf("invalid length") - } - var seq [64]byte - copy(seq[:], bytes) - return &ScalarK256{ - value: fq.K256FqNew().SetBytesWide(&seq), - }, nil -} - -func (s *ScalarK256) Point() Point { - return new(PointK256).Identity() -} - -func (s *ScalarK256) Clone() Scalar { - return &ScalarK256{ - value: fq.K256FqNew().Set(s.value), - } -} - -func (s *ScalarK256) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarK256) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarK256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarK256) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarK256) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarK256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarK256) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarK256) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarK256) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (p *PointK256) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointK256) Hash(bytes []byte) Point { - value, err := secp256k1.K256PointNew().Hash(bytes, native.EllipticPointHasherSha256()) - // Note: Interface constraint prevents returning error directly - // Returning nil on error for now, caller should check for nil - if err != nil { - // Log error for debugging if logger is available - return nil - } - - return &PointK256{value} -} - -func (p *PointK256) Identity() Point { - return &PointK256{ - value: secp256k1.K256PointNew().Identity(), - } -} - -func (p *PointK256) Generator() Point { - return &PointK256{ - value: secp256k1.K256PointNew().Generator(), - } -} - -func (p *PointK256) IsIdentity() bool { - return p.value.IsIdentity() -} - -func (p *PointK256) IsNegative() bool { - return p.value.GetY().Value[0]&1 == 1 -} - -func (p *PointK256) IsOnCurve() bool { - return p.value.IsOnCurve() -} - -func (p *PointK256) Double() Point { - value := secp256k1.K256PointNew().Double(p.value) - return &PointK256{value} -} - -func (p *PointK256) Scalar() Scalar { - return new(ScalarK256).Zero() -} - -func (p *PointK256) Neg() Point { - value := secp256k1.K256PointNew().Neg(p.value) - return &PointK256{value} -} - -func (p *PointK256) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointK256) - if ok { - value := secp256k1.K256PointNew().Add(p.value, r.value) - return &PointK256{value} - } else { - return nil - } -} - -func (p *PointK256) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointK256) - if ok { - value := secp256k1.K256PointNew().Sub(p.value, r.value) - return &PointK256{value} - } else { - return nil - } -} - -func (p *PointK256) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarK256) - if ok { - value := secp256k1.K256PointNew().Mul(p.value, r.value) - return &PointK256{value} - } else { - return nil - } -} - -func (p *PointK256) Equal(rhs Point) bool { - r, ok := rhs.(*PointK256) - if ok { - return p.value.Equal(r.value) == 1 - } else { - return false - } -} - -func (p *PointK256) Set(x, y *big.Int) (Point, error) { - value, err := secp256k1.K256PointNew().SetBigInt(x, y) - if err != nil { - return nil, err - } - return &PointK256{value}, nil -} - -func (p *PointK256) ToAffineCompressed() []byte { - var x [33]byte - x[0] = byte(2) - - t := secp256k1.K256PointNew().ToAffine(p.value) - - x[0] |= t.Y.Bytes()[0] & 1 - - xBytes := t.X.Bytes() - copy(x[1:], internal.ReverseScalarBytes(xBytes[:])) - return x[:] -} - -func (p *PointK256) ToAffineUncompressed() []byte { - var out [65]byte - out[0] = byte(4) - t := secp256k1.K256PointNew().ToAffine(p.value) - arr := t.X.Bytes() - copy(out[1:33], internal.ReverseScalarBytes(arr[:])) - arr = t.Y.Bytes() - copy(out[33:], internal.ReverseScalarBytes(arr[:])) - return out[:] -} - -func (p *PointK256) FromAffineCompressed(bytes []byte) (Point, error) { - var raw [native.FieldBytes]byte - if len(bytes) != 33 { - return nil, fmt.Errorf("invalid byte sequence") - } - sign := int(bytes[0]) - if sign != 2 && sign != 3 { - return nil, fmt.Errorf("invalid sign byte") - } - sign &= 0x1 - - copy(raw[:], internal.ReverseScalarBytes(bytes[1:])) - x, err := fp.K256FpNew().SetBytes(&raw) - if err != nil { - return nil, err - } - - value := secp256k1.K256PointNew().Identity() - rhs := fp.K256FpNew() - p.value.Arithmetic.RhsEq(rhs, x) - // test that rhs is quadratic residue - // if not, then this Point is at infinity - y, wasQr := fp.K256FpNew().Sqrt(rhs) - if wasQr { - // fix the sign - sigY := int(y.Bytes()[0] & 1) - if sigY != sign { - y.Neg(y) - } - value.X = x - value.Y = y - value.Z.SetOne() - } - return &PointK256{value}, nil -} - -func (p *PointK256) FromAffineUncompressed(bytes []byte) (Point, error) { - var arr [native.FieldBytes]byte - if len(bytes) != 65 { - return nil, fmt.Errorf("invalid byte sequence") - } - if bytes[0] != 4 { - return nil, fmt.Errorf("invalid sign byte") - } - - copy(arr[:], internal.ReverseScalarBytes(bytes[1:33])) - x, err := fp.K256FpNew().SetBytes(&arr) - if err != nil { - return nil, err - } - copy(arr[:], internal.ReverseScalarBytes(bytes[33:])) - y, err := fp.K256FpNew().SetBytes(&arr) - if err != nil { - return nil, err - } - value := secp256k1.K256PointNew() - value.X = x - value.Y = y - value.Z.SetOne() - return &PointK256{value}, nil -} - -func (p *PointK256) CurveName() string { - return p.value.Params.Name -} - -func (p *PointK256) SumOfProducts(points []Point, scalars []Scalar) Point { - nPoints := make([]*native.EllipticPoint, len(points)) - nScalars := make([]*native.Field, len(scalars)) - for i, pt := range points { - ptv, ok := pt.(*PointK256) - if !ok { - return nil - } - nPoints[i] = ptv.value - } - for i, sc := range scalars { - s, ok := sc.(*ScalarK256) - if !ok { - return nil - } - nScalars[i] = s.value - } - value := secp256k1.K256PointNew() - _, err := value.SumOfProducts(nPoints, nScalars) - if err != nil { - return nil - } - return &PointK256{value} -} - -func (p *PointK256) X() *native.Field { - return p.value.GetX() -} - -func (p *PointK256) Y() *native.Field { - return p.value.GetY() -} - -func (p *PointK256) Params() *elliptic.CurveParams { - return K256Curve().Params() -} - -func (p *PointK256) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointK256) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointK256) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointK256) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointK256) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointK256) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointK256) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointK256) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointK256) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} diff --git a/crypto/core/curves/k256_curve_test.go b/crypto/core/curves/k256_curve_test.go deleted file mode 100755 index dc4c1b7eb..000000000 --- a/crypto/core/curves/k256_curve_test.go +++ /dev/null @@ -1,620 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - crand "crypto/rand" - "math/big" - "sync" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" -) - -type mockReader struct { - index int - seed []byte -} - -var ( - mockRngInitonce sync.Once - mockRng mockReader -) - -func newMockReader() { - mockRng.index = 0 - mockRng.seed = make([]byte, 32) - for i := range mockRng.seed { - mockRng.seed[i] = 1 - } -} - -func testRng() *mockReader { - mockRngInitonce.Do(newMockReader) - return &mockRng -} - -func (m *mockReader) Read(p []byte) (n int, err error) { - limit := len(m.seed) - for i := range p { - p[i] = m.seed[m.index] - m.index += 1 - m.index %= limit - } - n = len(p) - err = nil - return n, err -} - -func TestScalarK256Random(t *testing.T) { - curve := K256() - sc := curve.Scalar.Random(testRng()) - s, ok := sc.(*ScalarK256) - require.True(t, ok) - expected, _ := new( - big.Int, - ).SetString("2f71aaec5e14d747c72e46cdcaffffe6f542f38b3f0925469ceb24ac1c65885d", 16) - require.Equal(t, s.value.BigInt(), expected) - // Try 10 random values - for i := 0; i < 10; i++ { - sc := curve.Scalar.Random(crand.Reader) - _, ok := sc.(*ScalarK256) - require.True(t, ok) - require.True(t, !sc.IsZero()) - } -} - -func TestScalarK256Hash(t *testing.T) { - var b [32]byte - k256 := K256() - sc := k256.Scalar.Hash(b[:]) - s, ok := sc.(*ScalarK256) - require.True(t, ok) - expected, _ := new( - big.Int, - ).SetString("e5cb3500b809a8202de0834a805068bc21bde09bd6367815e7523a37adf8f52e", 16) - require.Equal(t, s.value.BigInt(), expected) -} - -func TestScalarK256Zero(t *testing.T) { - k256 := K256() - sc := k256.Scalar.Zero() - require.True(t, sc.IsZero()) - require.True(t, sc.IsEven()) -} - -func TestScalarK256One(t *testing.T) { - k256 := K256() - sc := k256.Scalar.One() - require.True(t, sc.IsOne()) - require.True(t, sc.IsOdd()) -} - -func TestScalarK256New(t *testing.T) { - k256 := K256() - three := k256.Scalar.New(3) - require.True(t, three.IsOdd()) - four := k256.Scalar.New(4) - require.True(t, four.IsEven()) - neg1 := k256.Scalar.New(-1) - require.True(t, neg1.IsEven()) - neg2 := k256.Scalar.New(-2) - require.True(t, neg2.IsOdd()) -} - -func TestScalarK256Square(t *testing.T) { - k256 := K256() - three := k256.Scalar.New(3) - nine := k256.Scalar.New(9) - require.Equal(t, three.Square().Cmp(nine), 0) -} - -func TestScalarK256Cube(t *testing.T) { - k256 := K256() - three := k256.Scalar.New(3) - twentySeven := k256.Scalar.New(27) - require.Equal(t, three.Cube().Cmp(twentySeven), 0) -} - -func TestScalarK256Double(t *testing.T) { - k256 := K256() - three := k256.Scalar.New(3) - six := k256.Scalar.New(6) - require.Equal(t, three.Double().Cmp(six), 0) -} - -func TestScalarK256Neg(t *testing.T) { - k256 := K256() - one := k256.Scalar.One() - neg1 := k256.Scalar.New(-1) - require.Equal(t, one.Neg().Cmp(neg1), 0) - lotsOfThrees := k256.Scalar.New(333333) - expected := k256.Scalar.New(-333333) - require.Equal(t, lotsOfThrees.Neg().Cmp(expected), 0) -} - -func TestScalarK256Invert(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - actual, _ := nine.Invert() - sa, _ := actual.(*ScalarK256) - bn, _ := new( - big.Int, - ).SetString("8e38e38e38e38e38e38e38e38e38e38d842841d57dd303af6a9150f8e5737996", 16) - expected, err := k256.Scalar.SetBigInt(bn) - require.NoError(t, err) - require.Equal(t, sa.Cmp(expected), 0) -} - -func TestScalarK256Sqrt(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - actual, err := nine.Sqrt() - sa, _ := actual.(*ScalarK256) - expected := k256.Scalar.New(3) - require.NoError(t, err) - require.Equal(t, sa.Cmp(expected), 0) -} - -func TestScalarK256Add(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - six := k256.Scalar.New(6) - fifteen := nine.Add(six) - require.NotNil(t, fifteen) - expected := k256.Scalar.New(15) - require.Equal(t, expected.Cmp(fifteen), 0) - n := new(big.Int).Set(btcec.S256().N) - n.Sub(n, big.NewInt(3)) - - upper, err := k256.Scalar.SetBigInt(n) - require.NoError(t, err) - actual := upper.Add(nine) - require.NotNil(t, actual) - require.Equal(t, actual.Cmp(six), 0) -} - -func TestScalarK256Sub(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - six := k256.Scalar.New(6) - n := new(big.Int).Set(btcec.S256().N) - n.Sub(n, big.NewInt(3)) - - expected, err := k256.Scalar.SetBigInt(n) - require.NoError(t, err) - actual := six.Sub(nine) - require.Equal(t, expected.Cmp(actual), 0) - - actual = nine.Sub(six) - require.Equal(t, actual.Cmp(k256.Scalar.New(3)), 0) -} - -func TestScalarK256Mul(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - six := k256.Scalar.New(6) - actual := nine.Mul(six) - require.Equal(t, actual.Cmp(k256.Scalar.New(54)), 0) - n := new(big.Int).Set(btcec.S256().N) - n.Sub(n, big.NewInt(1)) - upper, err := k256.Scalar.SetBigInt(n) - require.NoError(t, err) - require.Equal(t, upper.Mul(upper).Cmp(k256.Scalar.New(1)), 0) -} - -func TestScalarK256Div(t *testing.T) { - k256 := K256() - nine := k256.Scalar.New(9) - actual := nine.Div(nine) - require.Equal(t, actual.Cmp(k256.Scalar.New(1)), 0) - require.Equal(t, k256.Scalar.New(54).Div(nine).Cmp(k256.Scalar.New(6)), 0) -} - -func TestScalarK256Serialize(t *testing.T) { - k256 := K256() - sc := k256.Scalar.New(255) - sequence := sc.Bytes() - require.Equal(t, len(sequence), 32) - require.Equal( - t, - sequence, - []byte{ - 0x00, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0xff, - }, - ) - ret, err := k256.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - - // Try 10 random values - for i := 0; i < 10; i++ { - sc = k256.Scalar.Random(crand.Reader) - sequence = sc.Bytes() - require.Equal(t, len(sequence), 32) - ret, err = k256.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - } -} - -func TestScalarK256Nil(t *testing.T) { - k256 := K256() - one := k256.Scalar.New(1) - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, one.Div(nil)) - require.Nil(t, k256.Scalar.Random(nil)) - require.Equal(t, one.Cmp(nil), -2) - _, err := k256.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointK256Random(t *testing.T) { - curve := K256() - sc := curve.Point.Random(testRng()) - s, ok := sc.(*PointK256) - require.True(t, ok) - expectedX, _ := new( - big.Int, - ).SetString("c6e18a1d7cf834462675b31581639a18e14fd0f73f8dfd5fe2993f88f6fbe008", 16) - expectedY, _ := new( - big.Int, - ).SetString("b65fab3243c5d07cef005d7fb335ebe8019efd954e95e68c86ef9b3bd7bccd36", 16) - require.Equal(t, s.X().BigInt(), expectedX) - require.Equal(t, s.Y().BigInt(), expectedY) - // Try 10 random values - for i := 0; i < 10; i++ { - sc := curve.Point.Random(crand.Reader) - _, ok := sc.(*PointK256) - require.True(t, ok) - require.True(t, !sc.IsIdentity()) - } -} - -func TestPointK256Hash(t *testing.T) { - var b [32]byte - curve := K256() - sc := curve.Point.Hash(b[:]) - s, ok := sc.(*PointK256) - require.True(t, ok) - expectedX, _ := new( - big.Int, - ).SetString("95d0ad42f68ddb5a808469dd75fa866890dcc7d039844e0e2d58a6d25bd9a66b", 16) - expectedY, _ := new( - big.Int, - ).SetString("f37c564d05168dab4413caacdb8e3426143fc5fb24a470ccd8a51856c11d163c", 16) - require.Equal(t, s.X().BigInt(), expectedX) - require.Equal(t, s.Y().BigInt(), expectedY) -} - -func TestPointK256Identity(t *testing.T) { - k256 := K256() - sc := k256.Point.Identity() - require.True(t, sc.IsIdentity()) - require.Equal( - t, - sc.ToAffineCompressed(), - []byte{ - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - }, - ) -} - -func TestPointK256Generator(t *testing.T) { - curve := K256() - sc := curve.Point.Generator() - s, ok := sc.(*PointK256) - require.True(t, ok) - require.Equal(t, s.X().BigInt().Cmp(btcec.S256().Gx), 0) - require.Equal(t, s.Y().BigInt().Cmp(btcec.S256().Gy), 0) -} - -func TestPointK256Set(t *testing.T) { - k256 := K256() - iden, err := k256.Point.Set(big.NewInt(0), big.NewInt(0)) - require.NoError(t, err) - require.True(t, iden.IsIdentity()) - _, err = k256.Point.Set(btcec.S256().Gx, btcec.S256().Gy) - require.NoError(t, err) -} - -func TestPointK256Double(t *testing.T) { - curve := K256() - g := curve.Point.Generator() - g2 := g.Double() - require.True(t, g2.Equal(g.Mul(curve.Scalar.New(2)))) - i := curve.Point.Identity() - require.True(t, i.Double().Equal(i)) - gg := curve.Point.Generator().Add(curve.Point.Generator()) - require.True(t, g2.Equal(gg)) -} - -func TestPointK256Neg(t *testing.T) { - k256 := K256() - g := k256.Point.Generator().Neg() - require.True(t, g.Neg().Equal(k256.Point.Generator())) - require.True(t, k256.Point.Identity().Neg().Equal(k256.Point.Identity())) -} - -func TestPointK256Add(t *testing.T) { - curve := K256() - pt := curve.Point.Generator().(*PointK256) - pt1 := pt.Add(pt).(*PointK256) - pt2 := pt.Double().(*PointK256) - pt3 := pt.Mul(curve.Scalar.New(2)).(*PointK256) - - require.True(t, pt1.Equal(pt2)) - require.True(t, pt1.Equal(pt3)) - require.True(t, pt.Add(pt).Equal(pt.Double())) - require.True(t, pt.Mul(curve.Scalar.New(3)).Equal(pt.Add(pt).Add(pt))) -} - -func TestPointK256Sub(t *testing.T) { - curve := K256() - g := curve.Point.Generator() - pt := curve.Point.Generator().Mul(curve.Scalar.New(4)) - - require.True(t, pt.Sub(g).Sub(g).Sub(g).Equal(g)) - require.True(t, pt.Sub(g).Sub(g).Sub(g).Sub(g).IsIdentity()) -} - -func TestPointK256Mul(t *testing.T) { - curve := K256() - g := curve.Point.Generator() - pt := curve.Point.Generator().Mul(curve.Scalar.New(4)) - require.True(t, g.Double().Double().Equal(pt)) -} - -func TestPointK256Serialize(t *testing.T) { - curve := K256() - ss := curve.Scalar.Random(testRng()) - - g := curve.Point.Generator() - ppt := g.Mul(ss).(*PointK256) - - require.Equal( - t, - ppt.ToAffineCompressed(), - []byte{ - 0x2, - 0x1b, - 0xa7, - 0x7e, - 0x98, - 0xd6, - 0xd8, - 0x49, - 0x45, - 0xa4, - 0x75, - 0xd8, - 0x6, - 0xc0, - 0x94, - 0x5b, - 0x8c, - 0xf0, - 0x5b, - 0x8a, - 0xb2, - 0x76, - 0xbb, - 0x9f, - 0x6e, - 0x52, - 0x9a, - 0x11, - 0x9c, - 0x79, - 0xdd, - 0xf6, - 0x5a, - }, - ) - require.Equal( - t, - ppt.ToAffineUncompressed(), - []byte{ - 0x4, - 0x1b, - 0xa7, - 0x7e, - 0x98, - 0xd6, - 0xd8, - 0x49, - 0x45, - 0xa4, - 0x75, - 0xd8, - 0x6, - 0xc0, - 0x94, - 0x5b, - 0x8c, - 0xf0, - 0x5b, - 0x8a, - 0xb2, - 0x76, - 0xbb, - 0x9f, - 0x6e, - 0x52, - 0x9a, - 0x11, - 0x9c, - 0x79, - 0xdd, - 0xf6, - 0x5a, - 0xb2, - 0x96, - 0x7c, - 0x59, - 0x4, - 0xeb, - 0x9a, - 0xaa, - 0xa9, - 0x1d, - 0x4d, - 0xd0, - 0x2d, - 0xc6, - 0x37, - 0xee, - 0x4a, - 0x95, - 0x51, - 0x60, - 0xab, - 0xab, - 0xf7, - 0xdb, - 0x30, - 0x7d, - 0x7d, - 0x0, - 0x68, - 0x6c, - 0xcf, - 0xf6, - }, - ) - retP, err := ppt.FromAffineCompressed(ppt.ToAffineCompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - retP, err = ppt.FromAffineUncompressed(ppt.ToAffineUncompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - - // smoke test - for i := 0; i < 25; i++ { - s := curve.Scalar.Random(crand.Reader) - pt := g.Mul(s) - cmprs := pt.ToAffineCompressed() - require.Equal(t, len(cmprs), 33) - retC, err := pt.FromAffineCompressed(cmprs) - require.NoError(t, err) - require.True(t, pt.Equal(retC)) - - un := pt.ToAffineUncompressed() - require.Equal(t, len(un), 65) - retU, err := pt.FromAffineUncompressed(un) - require.NoError(t, err) - require.True(t, pt.Equal(retU)) - } -} - -func TestPointK256Nil(t *testing.T) { - k256 := K256() - one := k256.Point.Generator() - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, k256.Scalar.Random(nil)) - require.False(t, one.Equal(nil)) - _, err := k256.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointK256SumOfProducts(t *testing.T) { - lhs := new(PointK256).Generator().Mul(new(ScalarK256).New(50)) - points := make([]Point, 5) - for i := range points { - points[i] = new(PointK256).Generator() - } - scalars := []Scalar{ - new(ScalarK256).New(8), - new(ScalarK256).New(9), - new(ScalarK256).New(10), - new(ScalarK256).New(11), - new(ScalarK256).New(12), - } - rhs := lhs.SumOfProducts(points, scalars) - require.NotNil(t, rhs) - require.True(t, lhs.Equal(rhs)) - - for j := 0; j < 25; j++ { - lhs = lhs.Identity() - for i := range points { - points[i] = new(PointK256).Random(crand.Reader) - scalars[i] = new(ScalarK256).Random(crand.Reader) - lhs = lhs.Add(points[i].Mul(scalars[i])) - } - rhs = lhs.SumOfProducts(points, scalars) - require.NotNil(t, rhs) - require.True(t, lhs.Equal(rhs)) - } -} diff --git a/crypto/core/curves/native/bls12381/bls12381.go b/crypto/core/curves/native/bls12381/bls12381.go deleted file mode 100644 index 4bd748951..000000000 --- a/crypto/core/curves/native/bls12381/bls12381.go +++ /dev/null @@ -1,81 +0,0 @@ -package bls12381 - -import ( - "math/bits" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -var fqModulusBytes = [native.FieldBytes]byte{ - 0x01, - 0x00, - 0x00, - 0x00, - 0xff, - 0xff, - 0xff, - 0xff, - 0xfe, - 0x5b, - 0xfe, - 0xff, - 0x02, - 0xa4, - 0xbd, - 0x53, - 0x05, - 0xd8, - 0xa1, - 0x09, - 0x08, - 0xd8, - 0x39, - 0x33, - 0x48, - 0x7d, - 0x9d, - 0x29, - 0x53, - 0xa7, - 0xed, - 0x73, -} - -const ( - // The BLS parameter x for BLS12-381 is -0xd201000000010000 - paramX = uint64(0xd201000000010000) - Limbs = 6 - FieldBytes = 48 - WideFieldBytes = 96 - DoubleWideFieldBytes = 192 -) - -// mac Multiply and Accumulate - compute a + (b * c) + d, return the result and new carry -func mac(a, b, c, d uint64) (uint64, uint64) { - hi, lo := bits.Mul64(b, c) - carry2, carry := bits.Add64(a, d, 0) - hi, _ = bits.Add64(hi, 0, carry) - lo, carry = bits.Add64(lo, carry2, 0) - hi, _ = bits.Add64(hi, 0, carry) - - return lo, hi -} - -// adc Add w/Carry -func adc(x, y, carry uint64) (uint64, uint64) { - sum := x + y + carry - // The sum will overflow if both top bits are set (x & y) or if one of them - // is (x | y), and a carry from the lower place happened. If such a carry - // happens, the top bit will be 1 + 0 + 1 = 0 (&^ sum). - carryOut := ((x & y) | ((x | y) &^ sum)) >> 63 - carryOut |= ((x & carry) | ((x | carry) &^ sum)) >> 63 - carryOut |= ((y & carry) | ((y | carry) &^ sum)) >> 63 - return sum, carryOut -} - -// sbb Subtract with borrow -func sbb(x, y, borrow uint64) (uint64, uint64) { - diff := x - (y + borrow) - borrowOut := ((^x & y) | (^(x ^ y) & diff)) >> 63 - return diff, borrowOut -} diff --git a/crypto/core/curves/native/bls12381/fp.go b/crypto/core/curves/native/bls12381/fp.go deleted file mode 100644 index a19f28e83..000000000 --- a/crypto/core/curves/native/bls12381/fp.go +++ /dev/null @@ -1,697 +0,0 @@ -package bls12381 - -import ( - "encoding/binary" - "fmt" - "io" - "math/big" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -// fp field element mod p -type fp [Limbs]uint64 - -var ( - modulus = fp{ - 0xb9feffffffffaaab, - 0x1eabfffeb153ffff, - 0x6730d2a0f6b0f624, - 0x64774b84f38512bf, - 0x4b1ba7b6434bacd7, - 0x1a0111ea397fe69a, - } - halfModulus = fp{ - 0xdcff_7fff_ffff_d556, - 0x0f55_ffff_58a9_ffff, - 0xb398_6950_7b58_7b12, - 0xb23b_a5c2_79c2_895f, - 0x258d_d3db_21a5_d66b, - 0x0d00_88f5_1cbf_f34d, - } - // 2^256 mod p - r = fp{ - 0x760900000002fffd, - 0xebf4000bc40c0002, - 0x5f48985753c758ba, - 0x77ce585370525745, - 0x5c071a97a256ec6d, - 0x15f65ec3fa80e493, - } - // 2^512 mod p - r2 = fp{ - 0xf4df1f341c341746, - 0x0a76e6a609d104f1, - 0x8de5476c4c95b6d5, - 0x67eb88a9939d83c0, - 0x9a793e85b519952d, - 0x11988fe592cae3aa, - } - // 2^768 mod p - r3 = fp{ - 0xed48ac6bd94ca1e0, - 0x315f831e03a7adf8, - 0x9a53352a615e29dd, - 0x34c04e5e921e1761, - 0x2512d43565724728, - 0x0aa6346091755d4d, - } - biModulus = new(big.Int).SetBytes([]byte{ - 0x1a, 0x01, 0x11, 0xea, 0x39, 0x7f, 0xe6, 0x9a, 0x4b, 0x1b, 0xa7, 0xb6, 0x43, 0x4b, 0xac, 0xd7, 0x64, 0x77, 0x4b, 0x84, 0xf3, 0x85, 0x12, 0xbf, 0x67, 0x30, 0xd2, 0xa0, 0xf6, 0xb0, 0xf6, 0x24, 0x1e, 0xab, 0xff, 0xfe, 0xb1, 0x53, 0xff, 0xff, 0xb9, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xab, - }, - ) -) - -// inv = -(p^{-1} mod 2^64) mod 2^64 -const ( - inv = 0x89f3_fffc_fffc_fffd - hashBytes = 64 -) - -// IsZero returns 1 if fp == 0, 0 otherwise -func (f *fp) IsZero() int { - t := f[0] - t |= f[1] - t |= f[2] - t |= f[3] - t |= f[4] - t |= f[5] - return int(((int64(t) | int64(-t)) >> 63) + 1) -} - -// IsNonZero returns 1 if fp != 0, 0 otherwise -func (f *fp) IsNonZero() int { - t := f[0] - t |= f[1] - t |= f[2] - t |= f[3] - t |= f[4] - t |= f[5] - return int(-((int64(t) | int64(-t)) >> 63)) -} - -// IsOne returns 1 if fp == 1, 0 otherwise -func (f *fp) IsOne() int { - return f.Equal(&r) -} - -// Cmp returns -1 if f < rhs -// 0 if f == rhs -// 1 if f > rhs -func (f *fp) Cmp(rhs *fp) int { - gt := uint64(0) - lt := uint64(0) - for i := 5; i >= 0; i-- { - // convert to two 64-bit numbers where - // the leading bits are zeros and hold no meaning - // so rhs - f actually means gt - // and f - rhs actually means lt. - rhsH := rhs[i] >> 32 - rhsL := rhs[i] & 0xffffffff - lhsH := f[i] >> 32 - lhsL := f[i] & 0xffffffff - - // Check the leading bit - // if negative then f > rhs - // if positive then f < rhs - gt |= (rhsH - lhsH) >> 32 & 1 &^ lt - lt |= (lhsH - rhsH) >> 32 & 1 &^ gt - gt |= (rhsL - lhsL) >> 32 & 1 &^ lt - lt |= (lhsL - rhsL) >> 32 & 1 &^ gt - } - // Make the result -1 for <, 0 for =, 1 for > - return int(gt) - int(lt) -} - -// Equal returns 1 if fp == rhs, 0 otherwise -func (f *fp) Equal(rhs *fp) int { - t := f[0] ^ rhs[0] - t |= f[1] ^ rhs[1] - t |= f[2] ^ rhs[2] - t |= f[3] ^ rhs[3] - t |= f[4] ^ rhs[4] - t |= f[5] ^ rhs[5] - return int(((int64(t) | int64(-t)) >> 63) + 1) -} - -// LexicographicallyLargest returns 1 if -// this element is strictly lexicographically larger than its negation -// 0 otherwise -func (f *fp) LexicographicallyLargest() int { - var ff fp - ff.fromMontgomery(f) - - _, borrow := sbb(ff[0], halfModulus[0], 0) - _, borrow = sbb(ff[1], halfModulus[1], borrow) - _, borrow = sbb(ff[2], halfModulus[2], borrow) - _, borrow = sbb(ff[3], halfModulus[3], borrow) - _, borrow = sbb(ff[4], halfModulus[4], borrow) - _, borrow = sbb(ff[5], halfModulus[5], borrow) - - return (int(borrow) - 1) & 1 -} - -// Sgn0 returns the lowest bit value -func (f *fp) Sgn0() int { - t := new(fp).fromMontgomery(f) - return int(t[0] & 1) -} - -// SetOne fp = r -func (f *fp) SetOne() *fp { - f[0] = r[0] - f[1] = r[1] - f[2] = r[2] - f[3] = r[3] - f[4] = r[4] - f[5] = r[5] - return f -} - -// SetZero fp = 0 -func (f *fp) SetZero() *fp { - f[0] = 0 - f[1] = 0 - f[2] = 0 - f[3] = 0 - f[4] = 0 - f[5] = 0 - return f -} - -// SetUint64 fp = rhs -func (f *fp) SetUint64(rhs uint64) *fp { - f[0] = rhs - f[1] = 0 - f[2] = 0 - f[3] = 0 - f[4] = 0 - f[5] = 0 - return f.toMontgomery(f) -} - -// Random generates a random field element -func (f *fp) Random(reader io.Reader) (*fp, error) { - var t [WideFieldBytes]byte - n, err := reader.Read(t[:]) - if err != nil { - return nil, err - } - if n != WideFieldBytes { - return nil, fmt.Errorf("can only read %d when %d are needed", n, WideFieldBytes) - } - return f.Hash(t[:]), nil -} - -// Hash converts the byte sequence into a field element -func (f *fp) Hash(input []byte) *fp { - dst := []byte("BLS12381_XMD:SHA-256_SSWU_RO_") - xmd := native.ExpandMsgXmd(native.EllipticPointHasherSha256(), input, dst, hashBytes) - var t [WideFieldBytes]byte - copy(t[:hashBytes], internal.ReverseScalarBytes(xmd)) - return f.SetBytesWide(&t) -} - -// toMontgomery converts this field to montgomery form -func (f *fp) toMontgomery(a *fp) *fp { - // arg.R^0 * R^2 / R = arg.R - return f.Mul(a, &r2) -} - -// fromMontgomery converts this field from montgomery form -func (f *fp) fromMontgomery(a *fp) *fp { - // Mul by 1 is division by 2^256 mod q - // out.Mul(arg, &[native.FieldLimbs]uint64{1, 0, 0, 0}) - return f.montReduce(&[Limbs * 2]uint64{a[0], a[1], a[2], a[3], a[4], a[5], 0, 0, 0, 0, 0, 0}) -} - -// Neg performs modular negation -func (f *fp) Neg(a *fp) *fp { - // Subtract `arg` from `modulus`. Ignore final borrow - // since it can't underflow. - var t [Limbs]uint64 - var borrow uint64 - t[0], borrow = sbb(modulus[0], a[0], 0) - t[1], borrow = sbb(modulus[1], a[1], borrow) - t[2], borrow = sbb(modulus[2], a[2], borrow) - t[3], borrow = sbb(modulus[3], a[3], borrow) - t[4], borrow = sbb(modulus[4], a[4], borrow) - t[5], _ = sbb(modulus[5], a[5], borrow) - - // t could be `modulus` if `arg`=0. Set mask=0 if self=0 - // and 0xff..ff if `arg`!=0 - mask := a[0] | a[1] | a[2] | a[3] | a[4] | a[5] - mask = -((mask | -mask) >> 63) - f[0] = t[0] & mask - f[1] = t[1] & mask - f[2] = t[2] & mask - f[3] = t[3] & mask - f[4] = t[4] & mask - f[5] = t[5] & mask - return f -} - -// Square performs modular square -func (f *fp) Square(a *fp) *fp { - var r [2 * Limbs]uint64 - var carry uint64 - - r[1], carry = mac(0, a[0], a[1], 0) - r[2], carry = mac(0, a[0], a[2], carry) - r[3], carry = mac(0, a[0], a[3], carry) - r[4], carry = mac(0, a[0], a[4], carry) - r[5], r[6] = mac(0, a[0], a[5], carry) - - r[3], carry = mac(r[3], a[1], a[2], 0) - r[4], carry = mac(r[4], a[1], a[3], carry) - r[5], carry = mac(r[5], a[1], a[4], carry) - r[6], r[7] = mac(r[6], a[1], a[5], carry) - - r[5], carry = mac(r[5], a[2], a[3], 0) - r[6], carry = mac(r[6], a[2], a[4], carry) - r[7], r[8] = mac(r[7], a[2], a[5], carry) - - r[7], carry = mac(r[7], a[3], a[4], 0) - r[8], r[9] = mac(r[8], a[3], a[5], carry) - - r[9], r[10] = mac(r[9], a[4], a[5], 0) - - r[11] = r[10] >> 63 - r[10] = (r[10] << 1) | r[9]>>63 - r[9] = (r[9] << 1) | r[8]>>63 - r[8] = (r[8] << 1) | r[7]>>63 - r[7] = (r[7] << 1) | r[6]>>63 - r[6] = (r[6] << 1) | r[5]>>63 - r[5] = (r[5] << 1) | r[4]>>63 - r[4] = (r[4] << 1) | r[3]>>63 - r[3] = (r[3] << 1) | r[2]>>63 - r[2] = (r[2] << 1) | r[1]>>63 - r[1] = r[1] << 1 - - r[0], carry = mac(0, a[0], a[0], 0) - r[1], carry = adc(0, r[1], carry) - r[2], carry = mac(r[2], a[1], a[1], carry) - r[3], carry = adc(0, r[3], carry) - r[4], carry = mac(r[4], a[2], a[2], carry) - r[5], carry = adc(0, r[5], carry) - r[6], carry = mac(r[6], a[3], a[3], carry) - r[7], carry = adc(0, r[7], carry) - r[8], carry = mac(r[8], a[4], a[4], carry) - r[9], carry = adc(0, r[9], carry) - r[10], carry = mac(r[10], a[5], a[5], carry) - r[11], _ = adc(0, r[11], carry) - - return f.montReduce(&r) -} - -// Double this element -func (f *fp) Double(a *fp) *fp { - return f.Add(a, a) -} - -// Mul performs modular multiplication -func (f *fp) Mul(arg1, arg2 *fp) *fp { - // Schoolbook multiplication - var r [2 * Limbs]uint64 - var carry uint64 - - r[0], carry = mac(0, arg1[0], arg2[0], 0) - r[1], carry = mac(0, arg1[0], arg2[1], carry) - r[2], carry = mac(0, arg1[0], arg2[2], carry) - r[3], carry = mac(0, arg1[0], arg2[3], carry) - r[4], carry = mac(0, arg1[0], arg2[4], carry) - r[5], r[6] = mac(0, arg1[0], arg2[5], carry) - - r[1], carry = mac(r[1], arg1[1], arg2[0], 0) - r[2], carry = mac(r[2], arg1[1], arg2[1], carry) - r[3], carry = mac(r[3], arg1[1], arg2[2], carry) - r[4], carry = mac(r[4], arg1[1], arg2[3], carry) - r[5], carry = mac(r[5], arg1[1], arg2[4], carry) - r[6], r[7] = mac(r[6], arg1[1], arg2[5], carry) - - r[2], carry = mac(r[2], arg1[2], arg2[0], 0) - r[3], carry = mac(r[3], arg1[2], arg2[1], carry) - r[4], carry = mac(r[4], arg1[2], arg2[2], carry) - r[5], carry = mac(r[5], arg1[2], arg2[3], carry) - r[6], carry = mac(r[6], arg1[2], arg2[4], carry) - r[7], r[8] = mac(r[7], arg1[2], arg2[5], carry) - - r[3], carry = mac(r[3], arg1[3], arg2[0], 0) - r[4], carry = mac(r[4], arg1[3], arg2[1], carry) - r[5], carry = mac(r[5], arg1[3], arg2[2], carry) - r[6], carry = mac(r[6], arg1[3], arg2[3], carry) - r[7], carry = mac(r[7], arg1[3], arg2[4], carry) - r[8], r[9] = mac(r[8], arg1[3], arg2[5], carry) - - r[4], carry = mac(r[4], arg1[4], arg2[0], 0) - r[5], carry = mac(r[5], arg1[4], arg2[1], carry) - r[6], carry = mac(r[6], arg1[4], arg2[2], carry) - r[7], carry = mac(r[7], arg1[4], arg2[3], carry) - r[8], carry = mac(r[8], arg1[4], arg2[4], carry) - r[9], r[10] = mac(r[9], arg1[4], arg2[5], carry) - - r[5], carry = mac(r[5], arg1[5], arg2[0], 0) - r[6], carry = mac(r[6], arg1[5], arg2[1], carry) - r[7], carry = mac(r[7], arg1[5], arg2[2], carry) - r[8], carry = mac(r[8], arg1[5], arg2[3], carry) - r[9], carry = mac(r[9], arg1[5], arg2[4], carry) - r[10], r[11] = mac(r[10], arg1[5], arg2[5], carry) - - return f.montReduce(&r) -} - -// MulBy3b returns arg * 12 or 3 * b -func (f *fp) MulBy3b(arg *fp) *fp { - var a, t fp - a.Double(arg) // 2 - t.Double(&a) // 4 - a.Double(&t) // 8 - a.Add(&a, &t) // 12 - return f.Set(&a) -} - -// Add performs modular addition -func (f *fp) Add(arg1, arg2 *fp) *fp { - var t fp - var carry uint64 - - t[0], carry = adc(arg1[0], arg2[0], 0) - t[1], carry = adc(arg1[1], arg2[1], carry) - t[2], carry = adc(arg1[2], arg2[2], carry) - t[3], carry = adc(arg1[3], arg2[3], carry) - t[4], carry = adc(arg1[4], arg2[4], carry) - t[5], _ = adc(arg1[5], arg2[5], carry) - - // Subtract the modulus to ensure the value - // is smaller. - return f.Sub(&t, &modulus) -} - -// Sub performs modular subtraction -func (f *fp) Sub(arg1, arg2 *fp) *fp { - d0, borrow := sbb(arg1[0], arg2[0], 0) - d1, borrow := sbb(arg1[1], arg2[1], borrow) - d2, borrow := sbb(arg1[2], arg2[2], borrow) - d3, borrow := sbb(arg1[3], arg2[3], borrow) - d4, borrow := sbb(arg1[4], arg2[4], borrow) - d5, borrow := sbb(arg1[5], arg2[5], borrow) - - // If underflow occurred on the final limb, borrow 0xff...ff, otherwise - // borrow = 0x00...00. Conditionally mask to add the modulus - borrow = -borrow - d0, carry := adc(d0, modulus[0]&borrow, 0) - d1, carry = adc(d1, modulus[1]&borrow, carry) - d2, carry = adc(d2, modulus[2]&borrow, carry) - d3, carry = adc(d3, modulus[3]&borrow, carry) - d4, carry = adc(d4, modulus[4]&borrow, carry) - d5, _ = adc(d5, modulus[5]&borrow, carry) - - f[0] = d0 - f[1] = d1 - f[2] = d2 - f[3] = d3 - f[4] = d4 - f[5] = d5 - return f -} - -// Sqrt performs modular square root -func (f *fp) Sqrt(a *fp) (*fp, int) { - // Shank's method, as p = 3 (mod 4). This means - // exponentiate by (p+1)/4. This only works for elements - // that are actually quadratic residue, - // so check the result at the end. - var c, z fp - z.pow(a, &fp{ - 0xee7fbfffffffeaab, - 0x07aaffffac54ffff, - 0xd9cc34a83dac3d89, - 0xd91dd2e13ce144af, - 0x92c6e9ed90d2eb35, - 0x0680447a8e5ff9a6, - }) - - c.Square(&z) - wasSquare := c.Equal(a) - f.CMove(f, &z, wasSquare) - return f, wasSquare -} - -// Invert performs modular inverse -func (f *fp) Invert(a *fp) (*fp, int) { - // Exponentiate by p - 2 - t := &fp{} - t.pow(a, &fp{ - 0xb9feffffffffaaa9, - 0x1eabfffeb153ffff, - 0x6730d2a0f6b0f624, - 0x64774b84f38512bf, - 0x4b1ba7b6434bacd7, - 0x1a0111ea397fe69a, - }) - wasInverted := a.IsNonZero() - f.CMove(a, t, wasInverted) - return f, wasInverted -} - -// SetBytes converts a little endian byte array into a field element -// return 0 if the bytes are not in the field, 1 if they are -func (f *fp) SetBytes(arg *[FieldBytes]byte) (*fp, int) { - var borrow uint64 - t := &fp{} - - t[0] = binary.LittleEndian.Uint64(arg[:8]) - t[1] = binary.LittleEndian.Uint64(arg[8:16]) - t[2] = binary.LittleEndian.Uint64(arg[16:24]) - t[3] = binary.LittleEndian.Uint64(arg[24:32]) - t[4] = binary.LittleEndian.Uint64(arg[32:40]) - t[5] = binary.LittleEndian.Uint64(arg[40:]) - - // Try to subtract the modulus - _, borrow = sbb(t[0], modulus[0], 0) - _, borrow = sbb(t[1], modulus[1], borrow) - _, borrow = sbb(t[2], modulus[2], borrow) - _, borrow = sbb(t[3], modulus[3], borrow) - _, borrow = sbb(t[4], modulus[4], borrow) - _, borrow = sbb(t[5], modulus[5], borrow) - - // If the element is smaller than modulus then the - // subtraction will underflow, producing a borrow value - // of 1. Otherwise, it'll be zero. - mask := int(borrow) - return f.CMove(f, t.toMontgomery(t), mask), mask -} - -// SetBytesWide takes 96 bytes as input and treats them as a 512-bit number. -// Attributed to https://github.com/zcash/pasta_curves/blob/main/src/fields/Fp.rs#L255 -// We reduce an arbitrary 768-bit number by decomposing it into two 384-bit digits -// with the higher bits multiplied by 2^384. Thus, we perform two reductions -// -// 1. the lower bits are multiplied by r^2, as normal -// 2. the upper bits are multiplied by r^2 * 2^384 = r^3 -// -// and computing their sum in the field. It remains to see that arbitrary 384-bit -// numbers can be placed into Montgomery form safely using the reduction. The -// reduction works so long as the product is less than r=2^384 multiplied by -// the modulus. This holds because for any `c` smaller than the modulus, we have -// that (2^384 - 1)*c is an acceptable product for the reduction. Therefore, the -// reduction always works so long as `c` is in the field; in this case it is either the -// constant `r2` or `r3`. -func (f *fp) SetBytesWide(a *[WideFieldBytes]byte) *fp { - d0 := &fp{ - binary.LittleEndian.Uint64(a[:8]), - binary.LittleEndian.Uint64(a[8:16]), - binary.LittleEndian.Uint64(a[16:24]), - binary.LittleEndian.Uint64(a[24:32]), - binary.LittleEndian.Uint64(a[32:40]), - binary.LittleEndian.Uint64(a[40:48]), - } - d1 := &fp{ - binary.LittleEndian.Uint64(a[48:56]), - binary.LittleEndian.Uint64(a[56:64]), - binary.LittleEndian.Uint64(a[64:72]), - binary.LittleEndian.Uint64(a[72:80]), - binary.LittleEndian.Uint64(a[80:88]), - binary.LittleEndian.Uint64(a[88:96]), - } - // d0*r2 + d1*r3 - d0.Mul(d0, &r2) - d1.Mul(d1, &r3) - return f.Add(d0, d1) -} - -// SetBigInt initializes an element from big.Int -// The value is reduced by the modulus -func (f *fp) SetBigInt(bi *big.Int) *fp { - var buffer [FieldBytes]byte - t := new(big.Int).Set(bi) - t.Mod(t, biModulus) - t.FillBytes(buffer[:]) - copy(buffer[:], internal.ReverseScalarBytes(buffer[:])) - _, _ = f.SetBytes(&buffer) - return f -} - -// Set copies a into fp -func (f *fp) Set(a *fp) *fp { - f[0] = a[0] - f[1] = a[1] - f[2] = a[2] - f[3] = a[3] - f[4] = a[4] - f[5] = a[5] - return f -} - -// SetLimbs converts an array into a field element -// by converting to montgomery form -func (f *fp) SetLimbs(a *[Limbs]uint64) *fp { - return f.toMontgomery((*fp)(a)) -} - -// SetRaw converts a raw array into a field element -// Assumes input is already in montgomery form -func (f *fp) SetRaw(a *[Limbs]uint64) *fp { - f[0] = a[0] - f[1] = a[1] - f[2] = a[2] - f[3] = a[3] - f[4] = a[4] - f[5] = a[5] - return f -} - -// Bytes converts a field element to a little endian byte array -func (f *fp) Bytes() [FieldBytes]byte { - var out [FieldBytes]byte - t := new(fp).fromMontgomery(f) - binary.LittleEndian.PutUint64(out[:8], t[0]) - binary.LittleEndian.PutUint64(out[8:16], t[1]) - binary.LittleEndian.PutUint64(out[16:24], t[2]) - binary.LittleEndian.PutUint64(out[24:32], t[3]) - binary.LittleEndian.PutUint64(out[32:40], t[4]) - binary.LittleEndian.PutUint64(out[40:], t[5]) - return out -} - -// BigInt converts this element into the big.Int struct -func (f *fp) BigInt() *big.Int { - buffer := f.Bytes() - return new(big.Int).SetBytes(internal.ReverseScalarBytes(buffer[:])) -} - -// Raw converts this element into the a [FieldLimbs]uint64 -func (f *fp) Raw() [Limbs]uint64 { - t := new(fp).fromMontgomery(f) - return *t -} - -// CMove performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f *fp) CMove(arg1, arg2 *fp, choice int) *fp { - mask := uint64(-choice) - f[0] = arg1[0] ^ ((arg1[0] ^ arg2[0]) & mask) - f[1] = arg1[1] ^ ((arg1[1] ^ arg2[1]) & mask) - f[2] = arg1[2] ^ ((arg1[2] ^ arg2[2]) & mask) - f[3] = arg1[3] ^ ((arg1[3] ^ arg2[3]) & mask) - f[4] = arg1[4] ^ ((arg1[4] ^ arg2[4]) & mask) - f[5] = arg1[5] ^ ((arg1[5] ^ arg2[5]) & mask) - return f -} - -// CNeg conditionally negates a if choice == 1 -func (f *fp) CNeg(a *fp, choice int) *fp { - var t fp - t.Neg(a) - return f.CMove(f, &t, choice) -} - -// Exp raises base^exp. -func (f *fp) Exp(base, exp *fp) *fp { - e := (&fp{}).fromMontgomery(exp) - return f.pow(base, e) -} - -func (f *fp) pow(base, e *fp) *fp { - var tmp, res fp - res.SetOne() - - for i := len(e) - 1; i >= 0; i-- { - for j := 63; j >= 0; j-- { - res.Square(&res) - tmp.Mul(&res, base) - res.CMove(&res, &tmp, int(e[i]>>j)&1) - } - } - f[0] = res[0] - f[1] = res[1] - f[2] = res[2] - f[3] = res[3] - f[4] = res[4] - f[5] = res[5] - return f -} - -// montReduce performs the montgomery reduction -func (f *fp) montReduce(r *[2 * Limbs]uint64) *fp { - // Taken from Algorithm 14.32 in Handbook of Applied Cryptography - var r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, carry, k uint64 - var rr fp - - k = r[0] * inv - _, carry = mac(r[0], k, modulus[0], 0) - r1, carry = mac(r[1], k, modulus[1], carry) - r2, carry = mac(r[2], k, modulus[2], carry) - r3, carry = mac(r[3], k, modulus[3], carry) - r4, carry = mac(r[4], k, modulus[4], carry) - r5, carry = mac(r[5], k, modulus[5], carry) - r6, r7 = adc(r[6], 0, carry) - - k = r1 * inv - _, carry = mac(r1, k, modulus[0], 0) - r2, carry = mac(r2, k, modulus[1], carry) - r3, carry = mac(r3, k, modulus[2], carry) - r4, carry = mac(r4, k, modulus[3], carry) - r5, carry = mac(r5, k, modulus[4], carry) - r6, carry = mac(r6, k, modulus[5], carry) - r7, r8 = adc(r7, r[7], carry) - - k = r2 * inv - _, carry = mac(r2, k, modulus[0], 0) - r3, carry = mac(r3, k, modulus[1], carry) - r4, carry = mac(r4, k, modulus[2], carry) - r5, carry = mac(r5, k, modulus[3], carry) - r6, carry = mac(r6, k, modulus[4], carry) - r7, carry = mac(r7, k, modulus[5], carry) - r8, r9 = adc(r8, r[8], carry) - - k = r3 * inv - _, carry = mac(r3, k, modulus[0], 0) - r4, carry = mac(r4, k, modulus[1], carry) - r5, carry = mac(r5, k, modulus[2], carry) - r6, carry = mac(r6, k, modulus[3], carry) - r7, carry = mac(r7, k, modulus[4], carry) - r8, carry = mac(r8, k, modulus[5], carry) - r9, r10 = adc(r9, r[9], carry) - - k = r4 * inv - _, carry = mac(r4, k, modulus[0], 0) - r5, carry = mac(r5, k, modulus[1], carry) - r6, carry = mac(r6, k, modulus[2], carry) - r7, carry = mac(r7, k, modulus[3], carry) - r8, carry = mac(r8, k, modulus[4], carry) - r9, carry = mac(r9, k, modulus[5], carry) - r10, r11 = adc(r10, r[10], carry) - - k = r5 * inv - _, carry = mac(r5, k, modulus[0], 0) - rr[0], carry = mac(r6, k, modulus[1], carry) - rr[1], carry = mac(r7, k, modulus[2], carry) - rr[2], carry = mac(r8, k, modulus[3], carry) - rr[3], carry = mac(r9, k, modulus[4], carry) - rr[4], carry = mac(r10, k, modulus[5], carry) - rr[5], _ = adc(r11, r[11], carry) - - return f.Sub(&rr, &modulus) -} diff --git a/crypto/core/curves/native/bls12381/fp12.go b/crypto/core/curves/native/bls12381/fp12.go deleted file mode 100755 index 847930f2f..000000000 --- a/crypto/core/curves/native/bls12381/fp12.go +++ /dev/null @@ -1,231 +0,0 @@ -package bls12381 - -import "io" - -// fp12 represents an element a + b w of fp^12 = fp^6 / w^2 - v. -type fp12 struct { - A, B fp6 -} - -// SetFp creates an element from a lower field -func (f *fp12) SetFp(a *fp) *fp12 { - f.A.SetFp(a) - f.B.SetZero() - return f -} - -// SetFp2 creates an element from a lower field -func (f *fp12) SetFp2(a *fp2) *fp12 { - f.A.SetFp2(a) - f.B.SetZero() - return f -} - -// SetFp6 creates an element from a lower field -func (f *fp12) SetFp6(a *fp6) *fp12 { - f.A.Set(a) - f.B.SetZero() - return f -} - -// Set copies the value `a` -func (f *fp12) Set(a *fp12) *fp12 { - f.A.Set(&a.A) - f.B.Set(&a.B) - return f -} - -// SetZero fp6 to zero -func (f *fp12) SetZero() *fp12 { - f.A.SetZero() - f.B.SetZero() - return f -} - -// SetOne fp6 to multiplicative identity element -func (f *fp12) SetOne() *fp12 { - f.A.SetOne() - f.B.SetZero() - return f -} - -// Random generates a random field element -func (f *fp12) Random(reader io.Reader) (*fp12, error) { - a, err := new(fp6).Random(reader) - if err != nil { - return nil, err - } - b, err := new(fp6).Random(reader) - if err != nil { - return nil, err - } - f.A.Set(a) - f.B.Set(b) - return f, nil -} - -// Square computes arg^2 -func (f *fp12) Square(arg *fp12) *fp12 { - var ab, apb, aTick, bTick, t fp6 - - ab.Mul(&arg.A, &arg.B) - apb.Add(&arg.A, &arg.B) - - aTick.MulByNonResidue(&arg.B) - aTick.Add(&aTick, &arg.A) - aTick.Mul(&aTick, &apb) - aTick.Sub(&aTick, &ab) - t.MulByNonResidue(&ab) - aTick.Sub(&aTick, &t) - - bTick.Double(&ab) - - f.A.Set(&aTick) - f.B.Set(&bTick) - return f -} - -// Invert computes this element's field inversion -func (f *fp12) Invert(arg *fp12) (*fp12, int) { - var a, b, t fp6 - a.Square(&arg.A) - b.Square(&arg.B) - b.MulByNonResidue(&b) - a.Sub(&a, &b) - _, wasInverted := t.Invert(&a) - - a.Mul(&arg.A, &t) - t.Neg(&t) - b.Mul(&arg.B, &t) - f.A.CMove(&f.A, &a, wasInverted) - f.B.CMove(&f.B, &b, wasInverted) - return f, wasInverted -} - -// Add computes arg1+arg2 -func (f *fp12) Add(arg1, arg2 *fp12) *fp12 { - f.A.Add(&arg1.A, &arg2.A) - f.B.Add(&arg1.B, &arg2.B) - return f -} - -// Sub computes arg1-arg2 -func (f *fp12) Sub(arg1, arg2 *fp12) *fp12 { - f.A.Sub(&arg1.A, &arg2.A) - f.B.Sub(&arg1.B, &arg2.B) - return f -} - -// Mul computes arg1*arg2 -func (f *fp12) Mul(arg1, arg2 *fp12) *fp12 { - var aa, bb, a2b2, a, b fp6 - - aa.Mul(&arg1.A, &arg2.A) - bb.Mul(&arg1.B, &arg2.B) - a2b2.Add(&arg2.A, &arg2.B) - b.Add(&arg1.A, &arg1.B) - b.Mul(&b, &a2b2) - b.Sub(&b, &aa) - b.Sub(&b, &bb) - a.MulByNonResidue(&bb) - a.Add(&a, &aa) - - f.A.Set(&a) - f.B.Set(&b) - return f -} - -// Neg computes the field negation -func (f *fp12) Neg(arg *fp12) *fp12 { - f.A.Neg(&arg.A) - f.B.Neg(&arg.B) - return f -} - -// MulByABD computes arg * a * b * c -func (f *fp12) MulByABD(arg *fp12, a, b, d *fp2) *fp12 { - var aa, bb, aTick, bTick fp6 - var bd fp2 - - aa.MulByAB(&arg.A, a, b) - bb.MulByB(&arg.B, d) - bd.Add(b, d) - - bTick.Add(&arg.A, &arg.B) - bTick.MulByAB(&bTick, a, &bd) - bTick.Sub(&bTick, &aa) - bTick.Sub(&bTick, &bb) - - aTick.MulByNonResidue(&bb) - aTick.Add(&aTick, &aa) - - f.A.Set(&aTick) - f.B.Set(&bTick) - - return f -} - -// Conjugate computes the field conjugation -func (f *fp12) Conjugate(arg *fp12) *fp12 { - f.A.Set(&arg.A) - f.B.Neg(&arg.B) - return f -} - -// FrobeniusMap raises this element to p. -func (f *fp12) FrobeniusMap(arg *fp12) *fp12 { - var a, b, up1epm1div6 fp6 - - // (u + 1)^((p - 1) / 6) - up1epm1div6.A = fp2{ - A: fp{ - 0x07089552b319d465, - 0xc6695f92b50a8313, - 0x97e83cccd117228f, - 0xa35baecab2dc29ee, - 0x1ce393ea5daace4d, - 0x08f2220fb0fb66eb, - }, - B: fp{ - 0xb2f66aad4ce5d646, - 0x5842a06bfc497cec, - 0xcf4895d42599d394, - 0xc11b9cba40a8e8d0, - 0x2e3813cbe5a0de89, - 0x110eefda88847faf, - }, - } - - a.FrobeniusMap(&arg.A) - b.FrobeniusMap(&arg.B) - - // b' = b' * (u + 1)^((p - 1) / 6) - b.Mul(&b, &up1epm1div6) - - f.A.Set(&a) - f.B.Set(&b) - return f -} - -// Equal returns 1 if fp12 == rhs, 0 otherwise -func (f *fp12) Equal(rhs *fp12) int { - return f.A.Equal(&rhs.A) & f.B.Equal(&rhs.B) -} - -// IsZero returns 1 if fp6 == 0, 0 otherwise -func (f *fp12) IsZero() int { - return f.A.IsZero() & f.B.IsZero() -} - -// IsOne returns 1 if fp12 == 1, 0 otherwise -func (f *fp12) IsOne() int { - return f.A.IsOne() & f.B.IsZero() -} - -// CMove performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f *fp12) CMove(arg1, arg2 *fp12, choice int) *fp12 { - f.A.CMove(&arg1.A, &arg2.A, choice) - f.B.CMove(&arg1.B, &arg2.B, choice) - return f -} diff --git a/crypto/core/curves/native/bls12381/fp12_test.go b/crypto/core/curves/native/bls12381/fp12_test.go deleted file mode 100755 index c0ee091a3..000000000 --- a/crypto/core/curves/native/bls12381/fp12_test.go +++ /dev/null @@ -1,417 +0,0 @@ -package bls12381 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFp12Arithmetic(t *testing.T) { - var aa, bb, cc, d, e, f fp12 - a := fp12{ - A: fp6{ - A: fp2{ - A: fp{ - 0x47f9cb98b1b82d58, - 0x5fe911eba3aa1d9d, - 0x96bf1b5f4dd81db3, - 0x8100d27cc9259f5b, - 0xafa20b9674640eab, - 0x09bbcea7d8d9497d, - }, - B: fp{ - 0x0303cb98b1662daa, - 0xd93110aa0a621d5a, - 0xbfa9820c5be4a468, - 0x0ba3643ecb05a348, - 0xdc3534bb1f1c25a6, - 0x06c305bb19c0e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9cb98b162d858, - 0x0be9109cf7aa1d57, - 0xc791bc55fece41d2, - 0xf84c57704e385ec2, - 0xcb49c1d9c010e60f, - 0x0acdb8e158bfe3c8, - }, - B: fp{ - 0x8aefcb98b15f8306, - 0x3ea1108fe4f21d54, - 0xcf79f69fa1b7df3b, - 0xe4f54aa1d16b1a3c, - 0xba5e4ef86105a679, - 0x0ed86c0797bee5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5cb98b15c2db4, - 0x71591082d23a1d51, - 0xd76230e944a17ca4, - 0xd19e3dd3549dd5b6, - 0xa972dc1701fa66e3, - 0x12e31f2dd6bde7d6, - }, - B: fp{ - 0xad2acb98b1732d9d, - 0x2cfd10dd06961d64, - 0x07396b86c6ef24e8, - 0xbd76e2fdb1bfc820, - 0x6afea7f6de94d0d5, - 0x10994b0c5744c040, - }, - }, - }, - B: fp6{ - A: fp2{ - A: fp{ - 0x47f9cb98b1b82d58, - 0x5fe911eba3aa1d9d, - 0x96bf1b5f4dd81db3, - 0x8100d27cc9259f5b, - 0xafa20b9674640eab, - 0x09bbcea7d8d9497d, - }, - B: fp{ - 0x0303cb98b1662daa, - 0xd93110aa0a621d5a, - 0xbfa9820c5be4a468, - 0x0ba3643ecb05a348, - 0xdc3534bb1f1c25a6, - 0x06c305bb19c0e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9cb98b162d858, - 0x0be9109cf7aa1d57, - 0xc791bc55fece41d2, - 0xf84c57704e385ec2, - 0xcb49c1d9c010e60f, - 0x0acdb8e158bfe3c8, - }, - B: fp{ - 0x8aefcb98b15f8306, - 0x3ea1108fe4f21d54, - 0xcf79f69fa1b7df3b, - 0xe4f54aa1d16b1a3c, - 0xba5e4ef86105a679, - 0x0ed86c0797bee5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5cb98b15c2db4, - 0x71591082d23a1d51, - 0xd76230e944a17ca4, - 0xd19e3dd3549dd5b6, - 0xa972dc1701fa66e3, - 0x12e31f2dd6bde7d6, - }, - B: fp{ - 0xad2acb98b1732d9d, - 0x2cfd10dd06961d64, - 0x07396b86c6ef24e8, - 0xbd76e2fdb1bfc820, - 0x6afea7f6de94d0d5, - 0x10994b0c5744c040, - }, - }, - }, - } - - b := fp12{ - A: fp6{ - A: fp2{ - A: fp{ - 0x47f9_cb98_b1b8_2d58, - 0x5fe9_11eb_a3aa_1d9d, - 0x96bf_1b5f_4dd8_1db3, - 0x8100_d272_c925_9f5b, - 0xafa2_0b96_7464_0eab, - 0x09bb_cea7_d8d9_497d, - }, - B: fp{ - 0x0303_cb98_b166_2daa, - 0xd931_10aa_0a62_1d5a, - 0xbfa9_820c_5be4_a468, - 0x0ba3_643e_cb05_a348, - 0xdc35_34bb_1f1c_25a6, - 0x06c3_05bb_19c0_e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9_cb98_b162_d858, - 0x0be9_109c_f7aa_1d57, - 0xc791_bc55_fece_41d2, - 0xf84c_5770_4e38_5ec2, - 0xcb49_c1d9_c010_e60f, - 0x0acd_b8e1_58bf_e348, - }, - B: fp{ - 0x8aef_cb98_b15f_8306, - 0x3ea1_108f_e4f2_1d54, - 0xcf79_f69f_a1b7_df3b, - 0xe4f5_4aa1_d16b_1a3c, - 0xba5e_4ef8_6105_a679, - 0x0ed8_6c07_97be_e5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5_cb98_b15c_2db4, - 0x7159_1082_d23a_1d51, - 0xd762_30e9_44a1_7ca4, - 0xd19e_3dd3_549d_d5b6, - 0xa972_dc17_01fa_66e3, - 0x12e3_1f2d_d6bd_e7d6, - }, - B: fp{ - 0xad2a_cb98_b173_2d9d, - 0x2cfd_10dd_0696_1d64, - 0x0739_6b86_c6ef_24e8, - 0xbd76_e2fd_b1bf_c820, - 0x6afe_a7f6_de94_d0d5, - 0x1099_4b0c_5744_c040, - }, - }, - }, - B: fp6{ - A: fp2{ - A: fp{ - 0x47f9_cb98_b1b8_2d58, - 0x5fe9_11eb_a3aa_1d9d, - 0x96bf_1b5f_4dd2_1db3, - 0x8100_d27c_c925_9f5b, - 0xafa2_0b96_7464_0eab, - 0x09bb_cea7_d8d9_497d, - }, - B: fp{ - 0x0303_cb98_b166_2daa, - 0xd931_10aa_0a62_1d5a, - 0xbfa9_820c_5be4_a468, - 0x0ba3_643e_cb05_a348, - 0xdc35_34bb_1f1c_25a6, - 0x06c3_05bb_19c0_e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9_cb98_b162_d858, - 0x0be9_109c_f7aa_1d57, - 0xc791_bc55_fece_41d2, - 0xf84c_5770_4e38_5ec2, - 0xcb49_c1d9_c010_e60f, - 0x0acd_b8e1_58bf_e3c8, - }, - B: fp{ - 0x8aef_cb98_b15f_8306, - 0x3ea1_108f_e4f2_1d54, - 0xcf79_f69f_a117_df3b, - 0xe4f5_4aa1_d16b_1a3c, - 0xba5e_4ef8_6105_a679, - 0x0ed8_6c07_97be_e5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5_cb98_b15c_2db4, - 0x7159_1082_d23a_1d51, - 0xd762_30e9_44a1_7ca4, - 0xd19e_3dd3_549d_d5b6, - 0xa972_dc17_01fa_66e3, - 0x12e3_1f2d_d6bd_e7d6, - }, - B: fp{ - 0xad2a_cb98_b173_2d9d, - 0x2cfd_10dd_0696_1d64, - 0x0739_6b86_c6ef_24e8, - 0xbd76_e2fd_b1bf_c820, - 0x6afe_a7f6_de94_d0d5, - 0x1099_4b0c_5744_c040, - }, - }, - }, - } - - c := fp12{ - A: fp6{ - A: fp2{ - A: fp{ - 0x47f9_cb98_71b8_2d58, - 0x5fe9_11eb_a3aa_1d9d, - 0x96bf_1b5f_4dd8_1db3, - 0x8100_d27c_c925_9f5b, - 0xafa2_0b96_7464_0eab, - 0x09bb_cea7_d8d9_497d, - }, - B: fp{ - 0x0303_cb98_b166_2daa, - 0xd931_10aa_0a62_1d5a, - 0xbfa9_820c_5be4_a468, - 0x0ba3_643e_cb05_a348, - 0xdc35_34bb_1f1c_25a6, - 0x06c3_05bb_19c0_e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9_cb98_b162_d858, - 0x0be9_109c_f7aa_1d57, - 0x7791_bc55_fece_41d2, - 0xf84c_5770_4e38_5ec2, - 0xcb49_c1d9_c010_e60f, - 0x0acd_b8e1_58bf_e3c8, - }, - B: fp{ - 0x8aef_cb98_b15f_8306, - 0x3ea1_108f_e4f2_1d54, - 0xcf79_f69f_a1b7_df3b, - 0xe4f5_4aa1_d16b_133c, - 0xba5e_4ef8_6105_a679, - 0x0ed8_6c07_97be_e5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5_cb98_b15c_2db4, - 0x7159_1082_d23a_1d51, - 0xd762_40e9_44a1_7ca4, - 0xd19e_3dd3_549d_d5b6, - 0xa972_dc17_01fa_66e3, - 0x12e3_1f2d_d6bd_e7d6, - }, - B: fp{ - 0xad2a_cb98_b173_2d9d, - 0x2cfd_10dd_0696_1d64, - 0x0739_6b86_c6ef_24e8, - 0xbd76_e2fd_b1bf_c820, - 0x6afe_a7f6_de94_d0d5, - 0x1099_4b0c_1744_c040, - }, - }, - }, - B: fp6{ - A: fp2{ - A: fp{ - 0x47f9_cb98_b1b8_2d58, - 0x5fe9_11eb_a3aa_1d9d, - 0x96bf_1b5f_4dd8_1db3, - 0x8100_d27c_c925_9f5b, - 0xafa2_0b96_7464_0eab, - 0x09bb_cea7_d8d9_497d, - }, - B: fp{ - 0x0303_cb98_b166_2daa, - 0xd931_10aa_0a62_1d5a, - 0xbfa9_820c_5be4_a468, - 0x0ba3_643e_cb05_a348, - 0xdc35_34bb_1f1c_25a6, - 0x06c3_05bb_19c0_e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9_cb98_b162_d858, - 0x0be9_109c_f7aa_1d57, - 0xc791_bc55_fece_41d2, - 0xf84c_5770_4e38_5ec2, - 0xcb49_c1d3_c010_e60f, - 0x0acd_b8e1_58bf_e3c8, - }, - B: fp{ - 0x8aef_cb98_b15f_8306, - 0x3ea1_108f_e4f2_1d54, - 0xcf79_f69f_a1b7_df3b, - 0xe4f5_4aa1_d16b_1a3c, - 0xba5e_4ef8_6105_a679, - 0x0ed8_6c07_97be_e5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5_cb98_b15c_2db4, - 0x7159_1082_d23a_1d51, - 0xd762_30e9_44a1_7ca4, - 0xd19e_3dd3_549d_d5b6, - 0xa972_dc17_01fa_66e3, - 0x12e3_1f2d_d6bd_e7d6, - }, - B: fp{ - 0xad2a_cb98_b173_2d9d, - 0x2cfd_10dd_0696_1d64, - 0x0739_6b86_c6ef_24e8, - 0xbd76_e2fd_b1bf_c820, - 0x6afe_a7f6_de94_d0d5, - 0x1099_4b0c_5744_1040, - }, - }, - }, - } - - aa.Square(&a) - aa.Invert(&aa) - aa.Square(&aa) - aa.Add(&aa, &c) - - bb.Square(&b) - bb.Invert(&bb) - bb.Square(&bb) - bb.Add(&bb, &aa) - - cc.Square(&c) - cc.Invert(&cc) - cc.Square(&cc) - cc.Add(&cc, &bb) - - d.Square(&aa) - e.Mul(&aa, &aa) - require.Equal(t, 1, e.Equal(&d)) - - d.Square(&bb) - e.Mul(&bb, &bb) - require.Equal(t, 1, e.Equal(&d)) - - d.Square(&cc) - e.Mul(&cc, &cc) - require.Equal(t, 1, e.Equal(&d)) - - d.Square(&cc) - e.Add(&aa, &bb) - d.Mul(&d, &e) - - e.Mul(&cc, &cc) - e.Mul(&e, &aa) - f.Mul(&cc, &cc) - f.Mul(&f, &bb) - e.Add(&e, &f) - - require.Equal(t, 1, e.Equal(&d)) - - d.Invert(&aa) - e.Invert(&bb) - f.Mul(&aa, &bb) - f.Invert(&f) - require.Equal(t, 1, f.Equal(e.Mul(&e, &d))) - - require.Equal(t, 1, d.Mul(&d, &aa).IsOne()) - - require.Equal(t, 0, aa.Equal(d.FrobeniusMap(&aa))) - d.FrobeniusMap(&aa). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d). - FrobeniusMap(&d) - require.Equal(t, 1, aa.Equal(&d)) -} diff --git a/crypto/core/curves/native/bls12381/fp2.go b/crypto/core/curves/native/bls12381/fp2.go deleted file mode 100755 index 85cdd10b8..000000000 --- a/crypto/core/curves/native/bls12381/fp2.go +++ /dev/null @@ -1,344 +0,0 @@ -package bls12381 - -import ( - "io" -) - -// fp2 is a point in p^2 -type fp2 struct { - A, B fp -} - -// Set copies a into fp2 -func (f *fp2) Set(a *fp2) *fp2 { - f.A.Set(&a.A) - f.B.Set(&a.B) - return f -} - -// SetZero fp2 = 0 -func (f *fp2) SetZero() *fp2 { - f.A.SetZero() - f.B.SetZero() - return f -} - -// SetOne fp2 to the multiplicative identity element -func (f *fp2) SetOne() *fp2 { - f.A.SetOne() - f.B.SetZero() - return f -} - -// SetFp creates an element from a lower field -func (f *fp2) SetFp(a *fp) *fp2 { - f.A.Set(a) - f.B.SetZero() - return f -} - -// Random generates a random field element -func (f *fp2) Random(reader io.Reader) (*fp2, error) { - a, err := new(fp).Random(reader) - if err != nil { - return nil, err - } - b, err := new(fp).Random(reader) - if err != nil { - return nil, err - } - f.A = *a - f.B = *b - return f, nil -} - -// IsZero returns 1 if fp2 == 0, 0 otherwise -func (f *fp2) IsZero() int { - return f.A.IsZero() & f.B.IsZero() -} - -// IsOne returns 1 if fp2 == 1, 0 otherwise -func (f *fp2) IsOne() int { - return f.A.IsOne() & f.B.IsZero() -} - -// Equal returns 1 if f == rhs, 0 otherwise -func (f *fp2) Equal(rhs *fp2) int { - return f.A.Equal(&rhs.A) & f.B.Equal(&rhs.B) -} - -// LexicographicallyLargest returns 1 if -// this element is strictly lexicographically larger than its negation -// 0 otherwise -func (f *fp2) LexicographicallyLargest() int { - // If this element's B coefficient is lexicographically largest - // then it is lexicographically largest. Otherwise, in the event - // the B coefficient is zero and the A coefficient is - // lexicographically largest, then this element is lexicographically - // largest. - - return f.B.LexicographicallyLargest() | - f.B.IsZero()&f.A.LexicographicallyLargest() -} - -// Sgn0 returns the lowest bit value -func (f *fp2) Sgn0() int { - // if A = 0 return B.Sgn0 else A.Sgn0 - a := f.A.IsZero() - t := f.B.Sgn0() & a - a = -a + 1 - t |= f.A.Sgn0() & a - return t -} - -// FrobeniusMap raises this element to p. -func (f *fp2) FrobeniusMap(a *fp2) *fp2 { - // This is always just a conjugation. If you're curious why, here's - // an article about it: https://alicebob.cryptoland.net/the-frobenius-endomorphism-with-finite-fields/ - return f.Conjugate(a) -} - -// Conjugate computes the conjugation of this element -func (f *fp2) Conjugate(a *fp2) *fp2 { - f.A.Set(&a.A) - f.B.Neg(&a.B) - return f -} - -// MulByNonResidue computes the following: -// multiply a + bu by u + 1, getting -// au + a + bu^2 + bu -// and because u^2 = -1, we get -// (a - b) + (a + b)u -func (f *fp2) MulByNonResidue(a *fp2) *fp2 { - var aa, bb fp - aa.Sub(&a.A, &a.B) - bb.Add(&a.A, &a.B) - f.A.Set(&aa) - f.B.Set(&bb) - return f -} - -// Square computes the square of this element -func (f *fp2) Square(arg *fp2) *fp2 { - var a, b, c fp - - // Complex squaring: - // - // v0 = a * b - // a' = (a + b) * (a + \beta*b) - v0 - \beta * v0 - // b' = 2 * v0 - // - // In BLS12-381's F_{p^2}, our \beta is -1, so we - // can modify this formula: - // - // a' = (a + b) * (a - b) - // b' = 2 * a * b - a.Add(&arg.A, &arg.B) - b.Sub(&arg.A, &arg.B) - c.Add(&arg.A, &arg.A) - - f.A.Mul(&a, &b) - f.B.Mul(&c, &arg.B) - return f -} - -// Add performs field addition -func (f *fp2) Add(arg1, arg2 *fp2) *fp2 { - f.A.Add(&arg1.A, &arg2.A) - f.B.Add(&arg1.B, &arg2.B) - return f -} - -// Double doubles specified element -func (f *fp2) Double(a *fp2) *fp2 { - f.A.Double(&a.A) - f.B.Double(&a.B) - return f -} - -// Sub performs field subtraction -func (f *fp2) Sub(arg1, arg2 *fp2) *fp2 { - f.A.Sub(&arg1.A, &arg2.A) - f.B.Sub(&arg1.B, &arg2.B) - return f -} - -// Mul computes Karatsuba multiplication -func (f *fp2) Mul(arg1, arg2 *fp2) *fp2 { - var v0, v1, t, a, b fp - - // Karatsuba multiplication: - // - // v0 = a0 * b0 - // v1 = a1 * b1 - // c0 = v0 + \beta * v1 - // c1 = (a0 + a1) * (b0 + b1) - v0 - v1 - // - // In BLS12-381's F_{p^2}, our \beta is -1, so we - // can modify this formula. (Also, since we always - // subtract v1, we can compute v1 = -a1 * b1.) - // - // v0 = a0 * a1 - // v1 = (-b0) * b1 - // a' = v0 + v1 - // b' = (a0 + b0) * (a1 + b1) - v0 + v1 - v0.Mul(&arg1.A, &arg2.A) - v1.Mul(new(fp).Neg(&arg1.B), &arg2.B) - - a.Add(&v0, &v1) - b.Add(&arg1.A, &arg1.B) - t.Add(&arg2.A, &arg2.B) - b.Mul(&b, &t) - b.Sub(&b, &v0) - b.Add(&b, &v1) - f.A.Set(&a) - f.B.Set(&b) - return f -} - -func (f *fp2) Mul0(arg1 *fp2, arg2 *fp) *fp2 { - f.A.Mul(&arg1.A, arg2) - f.B.Mul(&arg1.B, arg2) - return f -} - -// MulBy3b returns arg * 12 or 3 * b -func (f *fp2) MulBy3b(arg *fp2) *fp2 { - return f.Mul(arg, &curveG23B) -} - -// Neg performs field negation -func (f *fp2) Neg(a *fp2) *fp2 { - f.A.Neg(&a.A) - f.B.Neg(&a.B) - return f -} - -// Sqrt performs field square root -func (f *fp2) Sqrt(a *fp2) (*fp2, int) { - // Algorithm 9, https://eprint.iacr.org/2012/685.pdf - // with constant time modifications. - var a1, alpha, x0, t, res, res2 fp2 - e1 := a.IsZero() - // a1 = self^((p - 3) / 4) - a1.pow(a, &[Limbs]uint64{ - 0xee7fbfffffffeaaa, - 0x07aaffffac54ffff, - 0xd9cc34a83dac3d89, - 0xd91dd2e13ce144af, - 0x92c6e9ed90d2eb35, - 0x0680447a8e5ff9a6, - }) - - // alpha = a1^2 * a = a^((p - 3) / 2 + 1) = a^((p - 1) / 2) - alpha.Square(&a1) - alpha.Mul(&alpha, a) - - // x0 = self^((p + 1) / 4) - x0.Mul(&a1, a) - - // In the event that alpha = -1, the element is order p - 1. So - // we're just trying to get the square of an element of the subfield - // fp. This is given by x0 * u, since u = sqrt(-1). Since the element - // x0 = a + bu has b = 0, the solution is therefore au. - res2.A.Neg(&x0.B) - res2.B.Set(&x0.A) - // alpha == -1 - e2 := alpha.Equal(&fp2{ - A: fp{ - 0x43f5fffffffcaaae, - 0x32b7fff2ed47fffd, - 0x07e83a49a2e99d69, - 0xeca8f3318332bb7a, - 0xef148d1ea0f4c069, - 0x040ab3263eff0206, - }, - B: fp{}, - }) - - // Otherwise, the correct solution is (1 + alpha)^((p - 1) // 2) * x0 - t.SetOne() - t.Add(&t, &alpha) - t.pow(&t, &[Limbs]uint64{ - 0xdcff7fffffffd555, - 0x0f55ffff58a9ffff, - 0xb39869507b587b12, - 0xb23ba5c279c2895f, - 0x258dd3db21a5d66b, - 0x0d0088f51cbff34d, - }) - t.Mul(&t, &x0) - // if a = 0, then its zero - res.CMove(&res2, &res, e1) - // if alpha = -1, its not (1 + alpha)^((p - 1) // 2) * x0 - // but au - res.CMove(&t, &res, e2) - - // is the result^2 = a - t.Square(&res) - e3 := t.Equal(a) - f.CMove(f, &res, e3) - return f, e3 -} - -// Invert computes the multiplicative inverse of this field -// element, returning the original value of fp2 -// in the case that this element is zero. -func (f *fp2) Invert(arg *fp2) (*fp2, int) { - // We wish to find the multiplicative inverse of a nonzero - // element a + bu in fp2. We leverage an identity - // - // (a + bu)(a - bu) = a^2 + b^2 - // - // which holds because u^2 = -1. This can be rewritten as - // - // (a + bu)(a - bu)/(a^2 + b^2) = 1 - // - // because a^2 + b^2 = 0 has no nonzero solutions for (a, b). - // This gives that (a - bu)/(a^2 + b^2) is the inverse - // of (a + bu). Importantly, this can be computing using - // only a single inversion in fp. - var a, b, t fp - a.Square(&arg.A) - b.Square(&arg.B) - a.Add(&a, &b) - _, wasInverted := t.Invert(&a) - // a * t - a.Mul(&arg.A, &t) - // b * -t - b.Neg(&t) - b.Mul(&b, &arg.B) - f.A.CMove(&f.A, &a, wasInverted) - f.B.CMove(&f.B, &b, wasInverted) - return f, wasInverted -} - -// CMove performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f *fp2) CMove(arg1, arg2 *fp2, choice int) *fp2 { - f.A.CMove(&arg1.A, &arg2.A, choice) - f.B.CMove(&arg1.B, &arg2.B, choice) - return f -} - -// CNeg conditionally negates a if choice == 1 -func (f *fp2) CNeg(a *fp2, choice int) *fp2 { - var t fp2 - t.Neg(a) - return f.CMove(f, &t, choice) -} - -func (f *fp2) pow(base *fp2, exp *[Limbs]uint64) *fp2 { - res := (&fp2{}).SetOne() - tmp := (&fp2{}).SetZero() - - for i := len(exp) - 1; i >= 0; i-- { - for j := 63; j >= 0; j-- { - res.Square(res) - tmp.Mul(res, base) - res.CMove(res, tmp, int(exp[i]>>j)&1) - } - } - return f.Set(res) -} diff --git a/crypto/core/curves/native/bls12381/fp2_test.go b/crypto/core/curves/native/bls12381/fp2_test.go deleted file mode 100755 index c10aceedf..000000000 --- a/crypto/core/curves/native/bls12381/fp2_test.go +++ /dev/null @@ -1,424 +0,0 @@ -package bls12381 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFp2Square(t *testing.T) { - a := fp2{ - A: fp{ - 0xc9a2183163ee70d4, - 0xbc3770a7196b5c91, - 0xa247f8c1304c5f44, - 0xb01fc2a3726c80b5, - 0xe1d293e5bbd919c9, - 0x04b78e80020ef2ca, - }, - B: fp{ - 0x952ea4460462618f, - 0x238d5eddf025c62f, - 0xf6c94b012ea92e72, - 0x03ce24eac1c93808, - 0x055950f945da483c, - 0x010a768d0df4eabc, - }, - } - b := fp2{ - A: fp{ - 0xa1e09175a4d2c1fe, - 0x8b33acfc204eff12, - 0xe24415a11b456e42, - 0x61d996b1b6ee1936, - 0x1164dbe8667c853c, - 0x0788557acc7d9c79, - }, - B: fp{ - 0xda6a87cc6f48fa36, - 0x0fc7b488277c1903, - 0x9445ac4adc448187, - 0x02616d5bc9099209, - 0xdbed46772db58d48, - 0x11b94d5076c7b7b1, - }, - } - - require.Equal(t, &b, a.Square(&a)) -} - -func TestFp2Mul(t *testing.T) { - a := fp2{ - A: fp{ - 0xc9a2183163ee70d4, - 0xbc3770a7196b5c91, - 0xa247f8c1304c5f44, - 0xb01fc2a3726c80b5, - 0xe1d293e5bbd919c9, - 0x04b78e80020ef2ca, - }, - B: fp{ - 0x952ea4460462618f, - 0x238d5eddf025c62f, - 0xf6c94b012ea92e72, - 0x03ce24eac1c93808, - 0x055950f945da483c, - 0x010a768d0df4eabc, - }, - } - b := fp2{ - A: fp{ - 0xa1e09175a4d2c1fe, - 0x8b33acfc204eff12, - 0xe24415a11b456e42, - 0x61d996b1b6ee1936, - 0x1164dbe8667c853c, - 0x0788557acc7d9c79, - }, - B: fp{ - 0xda6a87cc6f48fa36, - 0x0fc7b488277c1903, - 0x9445ac4adc448187, - 0x02616d5bc9099209, - 0xdbed46772db58d48, - 0x11b94d5076c7b7b1, - }, - } - c := fp2{ - A: fp{ - 0xf597483e27b4e0f7, - 0x610fbadf811dae5f, - 0x8432af917714327a, - 0x6a9a9603cf88f09e, - 0xf05a7bf8bad0eb01, - 0x09549131c003ffae, - }, - B: fp{ - 0x963b02d0f93d37cd, - 0xc95ce1cdb30a73d4, - 0x308725fa3126f9b8, - 0x56da3c167fab0d50, - 0x6b5086b5f4b6d6af, - 0x09c39f062f18e9f2, - }, - } - - require.Equal(t, 1, c.Equal(new(fp2).Mul(&a, &b))) -} - -func TestFp2Add(t *testing.T) { - a := fp2{ - A: fp{ - 0xc9a2183163ee70d4, - 0xbc3770a7196b5c91, - 0xa247f8c1304c5f44, - 0xb01fc2a3726c80b5, - 0xe1d293e5bbd919c9, - 0x04b78e80020ef2ca, - }, - B: fp{ - 0x952ea4460462618f, - 0x238d5eddf025c62f, - 0xf6c94b012ea92e72, - 0x03ce24eac1c93808, - 0x055950f945da483c, - 0x010a768d0df4eabc, - }, - } - b := fp2{ - A: fp{ - 0xa1e09175a4d2c1fe, - 0x8b33acfc204eff12, - 0xe24415a11b456e42, - 0x61d996b1b6ee1936, - 0x1164dbe8667c853c, - 0x0788557acc7d9c79, - }, - B: fp{ - 0xda6a87cc6f48fa36, - 0x0fc7b488277c1903, - 0x9445ac4adc448187, - 0x02616d5bc9099209, - 0xdbed46772db58d48, - 0x11b94d5076c7b7b1, - }, - } - c := fp2{ - A: fp{ - 0x6b82a9a708c132d2, - 0x476b1da339ba5ba4, - 0x848c0e624b91cd87, - 0x11f95955295a99ec, - 0xf3376fce22559f06, - 0x0c3fe3face8c8f43, - }, - B: fp{ - 0x6f992c1273ab5bc5, - 0x3355136617a1df33, - 0x8b0ef74c0aedaff9, - 0x062f92468ad2ca12, - 0xe1469770738fd584, - 0x12c3c3dd84bca26d, - }, - } - - require.Equal(t, 1, c.Equal(new(fp2).Add(&a, &b))) -} - -func TestFp2Sub(t *testing.T) { - a := fp2{ - A: fp{ - 0xc9a2183163ee70d4, - 0xbc3770a7196b5c91, - 0xa247f8c1304c5f44, - 0xb01fc2a3726c80b5, - 0xe1d293e5bbd919c9, - 0x04b78e80020ef2ca, - }, - B: fp{ - 0x952ea4460462618f, - 0x238d5eddf025c62f, - 0xf6c94b012ea92e72, - 0x03ce24eac1c93808, - 0x055950f945da483c, - 0x010a768d0df4eabc, - }, - } - b := fp2{ - A: fp{ - 0xa1e09175a4d2c1fe, - 0x8b33acfc204eff12, - 0xe24415a11b456e42, - 0x61d996b1b6ee1936, - 0x1164dbe8667c853c, - 0x0788557acc7d9c79, - }, - B: fp{ - 0xda6a87cc6f48fa36, - 0x0fc7b488277c1903, - 0x9445ac4adc448187, - 0x02616d5bc9099209, - 0xdbed46772db58d48, - 0x11b94d5076c7b7b1, - }, - } - c := fp2{ - A: fp{ - 0xe1c086bbbf1b5981, - 0x4fafc3a9aa705d7e, - 0x2734b5c10bb7e726, - 0xb2bd7776af037a3e, - 0x1b895fb398a84164, - 0x17304aef6f113cec, - }, - B: fp{ - 0x74c31c7995191204, - 0x3271aa5479fdad2b, - 0xc9b471574915a30f, - 0x65e40313ec44b8be, - 0x7487b2385b7067cb, - 0x09523b26d0ad19a4, - }, - } - - require.Equal(t, 1, c.Equal(new(fp2).Sub(&a, &b))) -} - -func TestFp2Neg(t *testing.T) { - a := fp2{ - A: fp{ - 0xc9a2183163ee70d4, - 0xbc3770a7196b5c91, - 0xa247f8c1304c5f44, - 0xb01fc2a3726c80b5, - 0xe1d293e5bbd919c9, - 0x04b78e80020ef2ca, - }, - B: fp{ - 0x952ea4460462618f, - 0x238d5eddf025c62f, - 0xf6c94b012ea92e72, - 0x03ce24eac1c93808, - 0x055950f945da483c, - 0x010a768d0df4eabc, - }, - } - b := fp2{ - A: fp{ - 0xf05ce7ce9c1139d7, - 0x62748f5797e8a36d, - 0xc4e8d9dfc66496df, - 0xb45788e181189209, - 0x694913d08772930d, - 0x1549836a3770f3cf, - }, - B: fp{ - 0x24d05bb9fb9d491c, - 0xfb1ea120c12e39d0, - 0x7067879fc807c7b1, - 0x60a9269a31bbdab6, - 0x45c256bcfd71649b, - 0x18f69b5d2b8afbde, - }, - } - - require.Equal(t, 1, b.Equal(new(fp2).Neg(&a))) -} - -func TestFp2Sqrt(t *testing.T) { - a := fp2{ - A: fp{ - 0x2beed14627d7f9e9, - 0xb6614e06660e5dce, - 0x06c4cc7c2f91d42c, - 0x996d78474b7a63cc, - 0xebaebc4c820d574e, - 0x18865e12d93fd845, - }, - B: fp{ - 0x7d828664baf4f566, - 0xd17e663996ec7339, - 0x679ead55cb4078d0, - 0xfe3b2260e001ec28, - 0x305993d043d91b68, - 0x0626f03c0489b72d, - }, - } - - asq, wasSquare := (&fp2{}).Sqrt(&a) - require.Equal(t, 1, wasSquare) - require.Equal(t, 1, a.Equal(asq.Square(asq))) - - b := fp2{ - A: fp{ - 0x6631000000105545, - 0x211400400eec000d, - 0x3fa7af30c820e316, - 0xc52a8b8d6387695d, - 0x9fb4e61d1e83eac5, - 0x005cb922afe84dc7, - }, - B: fp{}, - } - bsq, wasSquare := (&fp2{}).Sqrt(&b) - require.Equal(t, 1, wasSquare) - require.Equal(t, 1, b.Equal(bsq.Square(bsq))) - - c := fp2{ - A: fp{ - 0x44f600000051ffae, - 0x86b8014199480043, - 0xd7159952f1f3794a, - 0x755d6e3dfe1ffc12, - 0xd36cd6db5547e905, - 0x02f8c8ecbf1867bb, - }, - B: fp{}, - } - csq, wasSquare := (&fp2{}).Sqrt(&c) - require.Equal(t, 1, wasSquare) - require.Equal(t, 1, c.Equal(csq.Square(csq))) - - d := fp2{ - A: fp{ - 0xc5fa1bc8fd00d7f6, - 0x3830ca454606003b, - 0x2b287f1104b102da, - 0xa7fb30f28230f23e, - 0x339cdb9ee953dbf0, - 0x0d78ec51d989fc57, - }, - B: fp{ - 0x27ec4898cf87f613, - 0x9de1394e1abb05a5, - 0x0947f85dc170fc14, - 0x586fbc696b6114b7, - 0x2b3475a4077d7169, - 0x13e1c895cc4b6c22, - }, - } - _, wasSquare = (&fp2{}).Sqrt(&d) - require.Equal(t, 0, wasSquare) - - _, wasSquare = (&fp2{}).Sqrt(&fp2{}) - require.Equal(t, 1, wasSquare) -} - -func TestFp2Invert(t *testing.T) { - a := fp2{ - A: fp{ - 0x1128ecad67549455, - 0x9e7a1cff3a4ea1a8, - 0xeb208d51e08bcf27, - 0xe98ad40811f5fc2b, - 0x736c3a59232d511d, - 0x10acd42d29cfcbb6, - }, - B: fp{ - 0xd328e37cc2f58d41, - 0x948df0858a605869, - 0x6032f9d56f93a573, - 0x2be483ef3fffdc87, - 0x30ef61f88f483c2a, - 0x1333f55a35725be0, - }, - } - - b := fp2{ - A: fp{ - 0x0581a1333d4f48a6, - 0x58242f6ef0748500, - 0x0292c955349e6da5, - 0xba37721ddd95fcd0, - 0x70d167903aa5dfc5, - 0x11895e118b58a9d5, - }, - B: fp{ - 0x0eda09d2d7a85d17, - 0x8808e137a7d1a2cf, - 0x43ae2625c1ff21db, - 0xf85ac9fdf7a74c64, - 0x8fccdda5b8da9738, - 0x08e84f0cb32cd17d, - }, - } - - ainv, wasInverted := (&fp2{}).Invert(&a) - require.Equal(t, 1, wasInverted) - require.Equal(t, 1, b.Equal(ainv)) - - _, wasInverted = (&fp2{}).Invert(&fp2{}) - require.Equal(t, 0, wasInverted) -} - -func TestFp2LexicographicallyLargest(t *testing.T) { - require.Equal(t, 0, new(fp2).SetZero().LexicographicallyLargest()) - require.Equal(t, 0, new(fp2).SetOne().LexicographicallyLargest()) - - a := fp2{ - A: fp{ - 0x1128_ecad_6754_9455, - 0x9e7a_1cff_3a4e_a1a8, - 0xeb20_8d51_e08b_cf27, - 0xe98a_d408_11f5_fc2b, - 0x736c_3a59_232d_511d, - 0x10ac_d42d_29cf_cbb6, - }, - B: fp{ - 0xd328_e37c_c2f5_8d41, - 0x948d_f085_8a60_5869, - 0x6032_f9d5_6f93_a573, - 0x2be4_83ef_3fff_dc87, - 0x30ef_61f8_8f48_3c2a, - 0x1333_f55a_3572_5be0, - }, - } - - require.Equal(t, 1, a.LexicographicallyLargest()) - aNeg := new(fp2).Neg(&a) - require.Equal(t, 0, aNeg.LexicographicallyLargest()) - a.B.SetZero() - require.Equal(t, 0, a.LexicographicallyLargest()) - aNeg.B.SetZero() - require.Equal(t, 1, aNeg.LexicographicallyLargest()) -} diff --git a/crypto/core/curves/native/bls12381/fp6.go b/crypto/core/curves/native/bls12381/fp6.go deleted file mode 100755 index 0863fd152..000000000 --- a/crypto/core/curves/native/bls12381/fp6.go +++ /dev/null @@ -1,340 +0,0 @@ -package bls12381 - -import "io" - -// fp6 represents an element -// a + b v + c v^2 of fp^6 = fp^2 / v^3 - u - 1. -type fp6 struct { - A, B, C fp2 -} - -// Set fp6 = a -func (f *fp6) Set(a *fp6) *fp6 { - f.A.Set(&a.A) - f.B.Set(&a.B) - f.C.Set(&a.C) - return f -} - -// SetFp creates an element from a lower field -func (f *fp6) SetFp(a *fp) *fp6 { - f.A.SetFp(a) - f.B.SetZero() - f.C.SetZero() - return f -} - -// SetFp2 creates an element from a lower field -func (f *fp6) SetFp2(a *fp2) *fp6 { - f.A.Set(a) - f.B.SetZero() - f.C.SetZero() - return f -} - -// SetZero fp6 to zero -func (f *fp6) SetZero() *fp6 { - f.A.SetZero() - f.B.SetZero() - f.C.SetZero() - return f -} - -// SetOne fp6 to multiplicative identity element -func (f *fp6) SetOne() *fp6 { - f.A.SetOne() - f.B.SetZero() - f.C.SetZero() - return f -} - -// Random generates a random field element -func (f *fp6) Random(reader io.Reader) (*fp6, error) { - a, err := new(fp2).Random(reader) - if err != nil { - return nil, err - } - b, err := new(fp2).Random(reader) - if err != nil { - return nil, err - } - c, err := new(fp2).Random(reader) - if err != nil { - return nil, err - } - f.A.Set(a) - f.B.Set(b) - f.C.Set(c) - return f, nil -} - -// Add computes arg1+arg2 -func (f *fp6) Add(arg1, arg2 *fp6) *fp6 { - f.A.Add(&arg1.A, &arg2.A) - f.B.Add(&arg1.B, &arg2.B) - f.C.Add(&arg1.C, &arg2.C) - return f -} - -// Double computes arg1+arg1 -func (f *fp6) Double(arg *fp6) *fp6 { - return f.Add(arg, arg) -} - -// Sub computes arg1-arg2 -func (f *fp6) Sub(arg1, arg2 *fp6) *fp6 { - f.A.Sub(&arg1.A, &arg2.A) - f.B.Sub(&arg1.B, &arg2.B) - f.C.Sub(&arg1.C, &arg2.C) - return f -} - -// Mul computes arg1*arg2 -func (f *fp6) Mul(arg1, arg2 *fp6) *fp6 { - var aa, bb, cc, s, t1, t2, t3 fp2 - - aa.Mul(&arg1.A, &arg2.A) - bb.Mul(&arg1.B, &arg2.B) - cc.Mul(&arg1.C, &arg2.C) - - t1.Add(&arg2.B, &arg2.C) - s.Add(&arg1.B, &arg1.C) - t1.Mul(&t1, &s) - t1.Sub(&t1, &bb) - t1.Sub(&t1, &cc) - t1.MulByNonResidue(&t1) - t1.Add(&t1, &aa) - - t3.Add(&arg2.A, &arg2.C) - s.Add(&arg1.A, &arg1.C) - t3.Mul(&t3, &s) - t3.Sub(&t3, &aa) - t3.Add(&t3, &bb) - t3.Sub(&t3, &cc) - - t2.Add(&arg2.A, &arg2.B) - s.Add(&arg1.A, &arg1.B) - t2.Mul(&t2, &s) - t2.Sub(&t2, &aa) - t2.Sub(&t2, &bb) - cc.MulByNonResidue(&cc) - t2.Add(&t2, &cc) - - f.A.Set(&t1) - f.B.Set(&t2) - f.C.Set(&t3) - return f -} - -// MulByB scales this field by a scalar in the B coefficient -func (f *fp6) MulByB(arg *fp6, b *fp2) *fp6 { - var bB, t1, t2 fp2 - bB.Mul(&arg.B, b) - // (b + c) * arg2 - bB - t1.Add(&arg.B, &arg.C) - t1.Mul(&t1, b) - t1.Sub(&t1, &bB) - t1.MulByNonResidue(&t1) - - t2.Add(&arg.A, &arg.B) - t2.Mul(&t2, b) - t2.Sub(&t2, &bB) - - f.A.Set(&t1) - f.B.Set(&t2) - f.C.Set(&bB) - return f -} - -// MulByAB scales this field by scalars in the A and B coefficients -func (f *fp6) MulByAB(arg *fp6, a, b *fp2) *fp6 { - var aA, bB, t1, t2, t3 fp2 - - aA.Mul(&arg.A, a) - bB.Mul(&arg.B, b) - - t1.Add(&arg.B, &arg.C) - t1.Mul(&t1, b) - t1.Sub(&t1, &bB) - t1.MulByNonResidue(&t1) - t1.Add(&t1, &aA) - - t2.Add(a, b) - t3.Add(&arg.A, &arg.B) - t2.Mul(&t2, &t3) - t2.Sub(&t2, &aA) - t2.Sub(&t2, &bB) - - t3.Add(&arg.A, &arg.C) - t3.Mul(&t3, a) - t3.Sub(&t3, &aA) - t3.Add(&t3, &bB) - - f.A.Set(&t1) - f.B.Set(&t2) - f.C.Set(&t3) - - return f -} - -// MulByNonResidue multiplies by quadratic nonresidue v. -func (f *fp6) MulByNonResidue(arg *fp6) *fp6 { - // Given a + bv + cv^2, this produces - // av + bv^2 + cv^3 - // but because v^3 = u + 1, we have - // c(u + 1) + av + bv^2 - var a, b, c fp2 - a.MulByNonResidue(&arg.C) - b.Set(&arg.A) - c.Set(&arg.B) - f.A.Set(&a) - f.B.Set(&b) - f.C.Set(&c) - return f -} - -// FrobeniusMap raises this element to p. -func (f *fp6) FrobeniusMap(arg *fp6) *fp6 { - var a, b, c fp2 - pm1Div3 := fp2{ - A: fp{}, - B: fp{ - 0xcd03c9e48671f071, - 0x5dab22461fcda5d2, - 0x587042afd3851b95, - 0x8eb60ebe01bacb9e, - 0x03f97d6e83d050d2, - 0x18f0206554638741, - }, - } - p2m2Div3 := fp2{ - A: fp{ - 0x890dc9e4867545c3, - 0x2af322533285a5d5, - 0x50880866309b7e2c, - 0xa20d1b8c7e881024, - 0x14e4f04fe2db9068, - 0x14e56d3f1564853a, - }, - B: fp{}, - } - a.FrobeniusMap(&arg.A) - b.FrobeniusMap(&arg.B) - c.FrobeniusMap(&arg.C) - - // b = b * (u + 1)^((p - 1) / 3) - b.Mul(&b, &pm1Div3) - - // c = c * (u + 1)^((2p - 2) / 3) - c.Mul(&c, &p2m2Div3) - - f.A.Set(&a) - f.B.Set(&b) - f.C.Set(&c) - return f -} - -// Square computes fp6^2 -func (f *fp6) Square(arg *fp6) *fp6 { - var s0, s1, s2, s3, s4, ab, bc fp2 - - s0.Square(&arg.A) - ab.Mul(&arg.A, &arg.B) - s1.Double(&ab) - s2.Sub(&arg.A, &arg.B) - s2.Add(&s2, &arg.C) - s2.Square(&s2) - bc.Mul(&arg.B, &arg.C) - s3.Double(&bc) - s4.Square(&arg.C) - - f.A.MulByNonResidue(&s3) - f.A.Add(&f.A, &s0) - - f.B.MulByNonResidue(&s4) - f.B.Add(&f.B, &s1) - - // s1 + s2 + s3 - s0 - s4 - f.C.Add(&s1, &s2) - f.C.Add(&f.C, &s3) - f.C.Sub(&f.C, &s0) - f.C.Sub(&f.C, &s4) - - return f -} - -// Invert computes this element's field inversion -func (f *fp6) Invert(arg *fp6) (*fp6, int) { - var a, b, c, s, t fp2 - - // a' = a^2 - (b * c).mul_by_nonresidue() - a.Mul(&arg.B, &arg.C) - a.MulByNonResidue(&a) - t.Square(&arg.A) - a.Sub(&t, &a) - - // b' = (c^2).mul_by_nonresidue() - (a * b) - b.Square(&arg.C) - b.MulByNonResidue(&b) - t.Mul(&arg.A, &arg.B) - b.Sub(&b, &t) - - // c' = b^2 - (a * c) - c.Square(&arg.B) - t.Mul(&arg.A, &arg.C) - c.Sub(&c, &t) - - // t = ((b * c') + (c * b')).mul_by_nonresidue() + (a * a') - s.Mul(&arg.B, &c) - t.Mul(&arg.C, &b) - s.Add(&s, &t) - s.MulByNonResidue(&s) - - t.Mul(&arg.A, &a) - s.Add(&s, &t) - - _, wasInverted := t.Invert(&s) - - // newA = a' * t^-1 - s.Mul(&a, &t) - f.A.CMove(&f.A, &s, wasInverted) - // newB = b' * t^-1 - s.Mul(&b, &t) - f.B.CMove(&f.B, &s, wasInverted) - // newC = c' * t^-1 - s.Mul(&c, &t) - f.C.CMove(&f.C, &s, wasInverted) - return f, wasInverted -} - -// Neg computes the field negation -func (f *fp6) Neg(arg *fp6) *fp6 { - f.A.Neg(&arg.A) - f.B.Neg(&arg.B) - f.C.Neg(&arg.C) - return f -} - -// IsZero returns 1 if fp6 == 0, 0 otherwise -func (f *fp6) IsZero() int { - return f.A.IsZero() & f.B.IsZero() & f.C.IsZero() -} - -// IsOne returns 1 if fp6 == 1, 0 otherwise -func (f *fp6) IsOne() int { - return f.A.IsOne() & f.B.IsZero() & f.B.IsZero() -} - -// Equal returns 1 if fp6 == rhs, 0 otherwise -func (f *fp6) Equal(rhs *fp6) int { - return f.A.Equal(&rhs.A) & f.B.Equal(&rhs.B) & f.C.Equal(&rhs.C) -} - -// CMove performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f *fp6) CMove(arg1, arg2 *fp6, choice int) *fp6 { - f.A.CMove(&arg1.A, &arg2.A, choice) - f.B.CMove(&arg1.B, &arg2.B, choice) - f.C.CMove(&arg1.C, &arg2.C, choice) - return f -} diff --git a/crypto/core/curves/native/bls12381/fp6_test.go b/crypto/core/curves/native/bls12381/fp6_test.go deleted file mode 100755 index 82319d37d..000000000 --- a/crypto/core/curves/native/bls12381/fp6_test.go +++ /dev/null @@ -1,217 +0,0 @@ -package bls12381 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFp6Arithmetic(t *testing.T) { - a := fp6{ - A: fp2{ - A: fp{ - 0x47f9cb98b1b82d58, - 0x5fe911eba3aa1d9d, - 0x96bf1b5f4dd81db3, - 0x8100d27cc9259f5b, - 0xafa20b9674640eab, - 0x09bbcea7d8d9497d, - }, - B: fp{ - 0x0303cb98b1662daa, - 0xd93110aa0a621d5a, - 0xbfa9820c5be4a468, - 0x0ba3643ecb05a348, - 0xdc3534bb1f1c25a6, - 0x06c305bb19c0e1c1, - }, - }, - B: fp2{ - A: fp{ - 0x46f9cb98b162d858, - 0x0be9109cf7aa1d57, - 0xc791bc55fece41d2, - 0xf84c57704e385ec2, - 0xcb49c1d9c010e60f, - 0x0acdb8e158bfe3c8, - }, - B: fp{ - 0x8aefcb98b15f8306, - 0x3ea1108fe4f21d54, - 0xcf79f69fa1b7df3b, - 0xe4f54aa1d16b1a3c, - 0xba5e4ef86105a679, - 0x0ed86c0797bee5cf, - }, - }, - C: fp2{ - A: fp{ - 0xcee5cb98b15c2db4, - 0x71591082d23a1d51, - 0xd76230e944a17ca4, - 0xd19e3dd3549dd5b6, - 0xa972dc1701fa66e3, - 0x12e31f2dd6bde7d6, - }, - B: fp{ - 0xad2acb98b1732d9d, - 0x2cfd10dd06961d64, - 0x07396b86c6ef24e8, - 0xbd76e2fdb1bfc820, - 0x6afea7f6de94d0d5, - 0x10994b0c5744c040, - }, - }, - } - b := fp6{ - A: fp2{ - A: fp{ - 0xf120cb98b16fd84b, - 0x5fb510cff3de1d61, - 0x0f21a5d069d8c251, - 0xaa1fd62f34f2839a, - 0x5a1335157f89913f, - 0x14a3fe329643c247, - }, - B: fp{ - 0x3516cb98b16c82f9, - 0x926d10c2e1261d5f, - 0x1709e01a0cc25fba, - 0x96c8c960b8253f14, - 0x4927c234207e51a9, - 0x18aeb158d542c44e, - }, - }, - B: fp2{ - A: fp{ - 0xbf0dcb98b16982fc, - 0xa67910b71d1a1d5c, - 0xb7c147c2b8fb06ff, - 0x1efa710d47d2e7ce, - 0xed20a79c7e27653c, - 0x02b85294dac1dfba, - }, - B: fp{ - 0x9d52cb98b18082e5, - 0x621d111151761d6f, - 0xe79882603b48af43, - 0x0ad31637a4f4da37, - 0xaeac737c5ac1cf2e, - 0x006e7e735b48b824, - }, - }, - C: fp2{ - A: fp{ - 0xe148cb98b17d2d93, - 0x94d511043ebe1d6c, - 0xef80bca9de324cac, - 0xf77c0969282795b1, - 0x9dc1009afbb68f97, - 0x047931999a47ba2b, - }, - B: fp{ - 0x253ecb98b179d841, - 0xc78d10f72c061d6a, - 0xf768f6f3811bea15, - 0xe424fc9aab5a512b, - 0x8cd58db99cab5001, - 0x0883e4bfd946bc32, - }, - }, - } - c := fp6{ - A: fp2{ - A: fp{ - 0x6934cb98b17682ef, - 0xfa4510ea194e1d67, - 0xff51313d2405877e, - 0xd0cdefcc2e8d0ca5, - 0x7bea1ad83da0106b, - 0x0c8e97e61845be39, - }, - B: fp{ - 0x4779cb98b18d82d8, - 0xb5e911444daa1d7a, - 0x2f286bdaa6532fc2, - 0xbca694f68baeff0f, - 0x3d75e6b81a3a7a5d, - 0x0a44c3c498cc96a3, - }, - }, - B: fp2{ - A: fp{ - 0x8b6fcb98b18a2d86, - 0xe8a111373af21d77, - 0x3710a624493ccd2b, - 0xa94f88280ee1ba89, - 0x2c8a73d6bb2f3ac7, - 0x0e4f76ead7cb98aa, - }, - B: fp{ - 0xcf65cb98b186d834, - 0x1b59112a283a1d74, - 0x3ef8e06dec266a95, - 0x95f87b5992147603, - 0x1b9f00f55c23fb31, - 0x125a2a1116ca9ab1, - }, - }, - C: fp2{ - A: fp{ - 0x135bcb98b18382e2, - 0x4e11111d15821d72, - 0x46e11ab78f1007fe, - 0x82a16e8b1547317d, - 0x0ab38e13fd18bb9b, - 0x1664dd3755c99cb8, - }, - B: fp{ - 0xce65cb98b1318334, - 0xc7590fdb7c3a1d2e, - 0x6fcb81649d1c8eb3, - 0x0d44004d1727356a, - 0x3746b738a7d0d296, - 0x136c144a96b134fc, - }, - }, - } - - d := new(fp6).Square(&a) - e := new(fp6).Mul(&a, &a) - require.Equal(t, 1, e.Equal(d)) - - d.Square(&b) - e.Mul(&b, &b) - require.Equal(t, 1, e.Equal(d)) - - d.Square(&c) - e.Mul(&c, &c) - require.Equal(t, 1, e.Equal(d)) - - // (a + b) * c^2 - d.Add(&a, &b) - d.Mul(d, new(fp6).Square(&c)) - - e.Mul(&c, &c) - e.Mul(e, &a) - tt := new(fp6).Mul(&c, &c) - tt.Mul(tt, &b) - e.Add(e, tt) - - require.Equal(t, 1, d.Equal(e)) - - _, wasInverted := d.Invert(&a) - require.Equal(t, 1, wasInverted) - _, wasInverted = e.Invert(&b) - require.Equal(t, 1, wasInverted) - - tt.Mul(&a, &b) - _, wasInverted = tt.Invert(tt) - require.Equal(t, 1, wasInverted) - d.Mul(d, e) - require.Equal(t, 1, tt.Equal(d)) - - _, _ = d.Invert(&a) - e.SetOne() - require.Equal(t, 1, e.Equal(d.Mul(d, &a))) -} diff --git a/crypto/core/curves/native/bls12381/fp_test.go b/crypto/core/curves/native/bls12381/fp_test.go deleted file mode 100644 index 225eaa615..000000000 --- a/crypto/core/curves/native/bls12381/fp_test.go +++ /dev/null @@ -1,346 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls12381 - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFpSetOne(t *testing.T) { - var fp fp - fp.SetOne() - require.NotNil(t, fp) - require.Equal(t, fp, r) -} - -func TestFpSetUint64(t *testing.T) { - var act fp - act.SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act[0], uint64(0xf6ea9fde37db5e8c)) -} - -func TestFpAdd(t *testing.T) { - var lhs, rhs, exp, res fp - lhs.SetOne() - rhs.SetOne() - exp.SetUint64(2) - res.Add(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(&exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - res.Add(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, exp, res) - } -} - -func TestFpSub(t *testing.T) { - var lhs, rhs, exp, res fp - lhs.SetOne() - rhs.SetOne() - exp.SetZero() - res.Sub(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(&exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - res.Sub(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, exp, res) - } -} - -func TestFpMul(t *testing.T) { - var lhs, rhs, exp, res fp - lhs.SetOne() - rhs.SetOne() - exp.SetOne() - res.Mul(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(&exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - res.Mul(&lhs, &rhs) - require.NotNil(t, res) - require.Equal(t, exp, res) - } -} - -func TestFpDouble(t *testing.T) { - var a, e, res fp - a.SetUint64(2) - e.SetUint64(4) - require.Equal(t, &e, res.Double(&a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a.SetUint64(uint64(tv)) - e.SetUint64(ttv) - require.Equal(t, &e, res.Double(&a)) - } -} - -func TestFpSquare(t *testing.T) { - var a, e, res fp - a.SetUint64(4) - e.SetUint64(16) - require.Equal(t, 1, e.Equal(res.Square(&a))) - - a.SetUint64(2854263694) - e.SetUint64(8146821234886525636) - require.Equal(t, 1, e.Equal(res.Square(&a))) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, 1, e.Equal(res.Square(&a)), "exp = %d, j = %d", exp, j) - } -} - -func TestFpNeg(t *testing.T) { - var g, a, e fp - g.SetLimbs(&[Limbs]uint64{7, 0, 0, 0, 0, 0}) - a.SetOne() - a.Neg(&a) - e.SetRaw( - &[Limbs]uint64{ - 0x43f5fffffffcaaae, - 0x32b7fff2ed47fffd, - 0x07e83a49a2e99d69, - 0xeca8f3318332bb7a, - 0xef148d1ea0f4c069, - 0x040ab3263eff0206, - }, - ) - require.Equal(t, 1, e.Equal(&a)) - a.Neg(&g) - e.SetRaw( - &[Limbs]uint64{ - 0x21baffffffe90017, - 0x445bffa5cba3ffed, - 0xd028c5627db257bc, - 0x14275ad5a2de0d96, - 0x3e7434202365960e, - 0x0249d4217f792796, - }, - ) - require.Equal(t, e, a) -} - -func TestFpExp(t *testing.T) { - var a, e, by fp - e.SetUint64(8) - a.SetUint64(2) - by.SetUint64(3) - require.Equal(t, &e, a.Exp(&a, &by)) -} - -func TestFpSqrt(t *testing.T) { - var t1, t2, t3 fp - t1.SetUint64(2) - t2.Neg(&t1) - t3.Square(&t1) - _, wasSquare := t3.Sqrt(&t3) - - require.Equal(t, 1, wasSquare) - require.Equal(t, 1, t1.Equal(&t3)|t2.Equal(&t3)) - t1.SetUint64(5) - _, wasSquare = t1.Sqrt(&t1) - require.Equal(t, 0, wasSquare) -} - -func TestFpInvert(t *testing.T) { - var two, twoInv, a, lhs, rhs, rhsInv fp - twoInv.SetRaw( - &[Limbs]uint64{ - 0x1804000000015554, - 0x855000053ab00001, - 0x633cb57c253c276f, - 0x6e22d1ec31ebb502, - 0xd3916126f2d14ca2, - 0x17fbb8571a006596, - }, - ) - two.SetUint64(2) - _, inverted := a.Invert(&two) - require.Equal(t, 1, inverted) - require.Equal(t, &a, &twoInv) - - lhs.SetUint64(9) - rhs.SetUint64(3) - _, inverted = rhsInv.Invert(&rhs) - require.Equal(t, 1, inverted) - require.Equal(t, &rhs, lhs.Mul(&lhs, &rhsInv)) - - rhs.SetZero() - _, inverted = lhs.Invert(&rhs) - require.Equal(t, 0, inverted) -} - -func TestFpCMove(t *testing.T) { - var t1, t2, tt fp - t1.SetUint64(5) - t2.SetUint64(10) - require.Equal(t, &t1, tt.CMove(&t1, &t2, 0)) - require.Equal(t, &t2, tt.CMove(&t1, &t2, 1)) -} - -func TestFpBytes(t *testing.T) { - var t1, t2 fp - t1.SetUint64(99) - seq := t1.Bytes() - _, suc := t2.SetBytes(&seq) - require.Equal(t, 1, suc) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, suc = t2.SetBytes(&seq) - require.Equal(t, 1, suc) - require.Equal(t, t1, t2) - } -} - -func TestFpBigInt(t *testing.T) { - var t1, t2, e fp - t1.SetBigInt(big.NewInt(9999)) - t2.SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e.SetRaw( - &[Limbs]uint64{ - 0x922af810e5e35f31, - 0x6bc75973ed382d59, - 0xd4716c9d4d491d42, - 0x69d98d1ebeeb3f6e, - 0x7e425d7b46d4a82b, - 0x12d04b0965870e92, - }, - ) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Neg(&e) - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFpSetBytesWideBigInt(t *testing.T) { - var a fp - var tv2 [96]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, biModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a.SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} - -func TestFpToMontgomery(t *testing.T) { - var v fp - v.SetUint64(2) - require.Equal( - t, - fp{ - 0x321300000006554f, - 0xb93c0018d6c40005, - 0x57605e0db0ddbb51, - 0x8b256521ed1f9bcb, - 0x6cf28d7901622c03, - 0x11ebab9dbb81e28c, - }, - v, - ) -} - -func TestFpFromMontgomery(t *testing.T) { - var v fp - e := fp{2, 0, 0, 0, 0, 0} - v.SetUint64(2) - v.fromMontgomery(&v) - require.Equal(t, e, v) -} - -func TestFpLexicographicallyLargest(t *testing.T) { - require.Equal(t, 0, new(fp).SetZero().LexicographicallyLargest()) - require.Equal(t, 0, new(fp).SetOne().LexicographicallyLargest()) - require.Equal(t, 0, (&fp{ - 0xa1fafffffffe5557, - 0x995bfff976a3fffe, - 0x03f41d24d174ceb4, - 0xf6547998c1995dbd, - 0x778a468f507a6034, - 0x020559931f7f8103, - }).LexicographicallyLargest()) - require.Equal(t, 1, (&fp{ - 0x1804000000015554, - 0x855000053ab00001, - 0x633cb57c253c276f, - 0x6e22d1ec31ebb502, - 0xd3916126f2d14ca2, - 0x17fbb8571a006596, - }).LexicographicallyLargest()) - require.Equal(t, 1, (&fp{ - 0x43f5fffffffcaaae, - 0x32b7fff2ed47fffd, - 0x07e83a49a2e99d69, - 0xeca8f3318332bb7a, - 0xef148d1ea0f4c069, - 0x040ab3263eff0206, - }).LexicographicallyLargest()) -} diff --git a/crypto/core/curves/native/bls12381/fq.go b/crypto/core/curves/native/bls12381/fq.go deleted file mode 100644 index 059e85daf..000000000 --- a/crypto/core/curves/native/bls12381/fq.go +++ /dev/null @@ -1,455 +0,0 @@ -package bls12381 - -import ( - "encoding/binary" - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -type Fq [native.FieldLimbs]uint64 - -var ( - bls12381FqInitonce sync.Once - bls12381FqParams native.FieldParams -) - -// 2^S * t = MODULUS - 1 with t odd -const fqS = 32 - -// qInv = -(q^{-1} mod 2^64) mod 2^64 -const qInv = 0xfffffffeffffffff - -// fqGenerator = 7 (multiplicative fqGenerator of r-1 order, that is also quadratic nonresidue) -var fqGenerator = [native.FieldLimbs]uint64{ - 0x0000000efffffff1, - 0x17e363d300189c0f, - 0xff9c57876f8457b0, - 0x351332208fc5a8c4, -} - -// fqModulus -var fqModulus = [native.FieldLimbs]uint64{ - 0xffffffff00000001, - 0x53bda402fffe5bfe, - 0x3339d80809a1d805, - 0x73eda753299d7d48, -} - -func Bls12381FqNew() *native.Field { - return &native.Field{ - Value: [native.FieldLimbs]uint64{}, - Params: getBls12381FqParams(), - Arithmetic: bls12381FqArithmetic{}, - } -} - -func bls12381FqParamsInit() { - bls12381FqParams = native.FieldParams{ - R: [native.FieldLimbs]uint64{ - 0x00000001fffffffe, - 0x5884b7fa00034802, - 0x998c4fefecbc4ff5, - 0x1824b159acc5056f, - }, - R2: [native.FieldLimbs]uint64{ - 0xc999e990f3f29c6d, - 0x2b6cedcb87925c23, - 0x05d314967254398f, - 0x0748d9d99f59ff11, - }, - R3: [native.FieldLimbs]uint64{ - 0xc62c1807439b73af, - 0x1b3e0d188cf06990, - 0x73d13c71c7b5f418, - 0x6e2a5bb9c8db33e9, - }, - Modulus: [native.FieldLimbs]uint64{ - 0xffffffff00000001, - 0x53bda402fffe5bfe, - 0x3339d80809a1d805, - 0x73eda753299d7d48, - }, - BiModulus: new(big.Int).SetBytes([]byte{ - 0x73, 0xed, 0xa7, 0x53, 0x29, 0x9d, 0x7d, 0x48, 0x33, 0x39, 0xd8, 0x08, 0x09, 0xa1, 0xd8, 0x05, 0x53, 0xbd, 0xa4, 0x02, 0xff, 0xfe, 0x5b, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, - }), - } -} - -func getBls12381FqParams() *native.FieldParams { - bls12381FqInitonce.Do(bls12381FqParamsInit) - return &bls12381FqParams -} - -// bls12381FqArithmetic is a struct with all the methods needed for working -// in mod q -type bls12381FqArithmetic struct{} - -// ToMontgomery converts this field to montgomery form -func (f bls12381FqArithmetic) ToMontgomery(out, arg *[native.FieldLimbs]uint64) { - // arg.R^0 * R^2 / R = arg.R - f.Mul(out, arg, &getBls12381FqParams().R2) -} - -// FromMontgomery converts this field from montgomery form -func (f bls12381FqArithmetic) FromMontgomery(out, arg *[native.FieldLimbs]uint64) { - // Mul by 1 is division by 2^256 mod q - // f.Mul(out, arg, &[native.FieldLimbs]uint64{1, 0, 0, 0}) - f.montReduce(out, &[native.FieldLimbs * 2]uint64{arg[0], arg[1], arg[2], arg[3], 0, 0, 0, 0}) -} - -// Neg performs modular negation -func (f bls12381FqArithmetic) Neg(out, arg *[native.FieldLimbs]uint64) { - // Subtract `arg` from `fqModulus`. Ignore final borrow - // since it can't underflow. - var t [native.FieldLimbs]uint64 - var borrow uint64 - t[0], borrow = sbb(fqModulus[0], arg[0], 0) - t[1], borrow = sbb(fqModulus[1], arg[1], borrow) - t[2], borrow = sbb(fqModulus[2], arg[2], borrow) - t[3], _ = sbb(fqModulus[3], arg[3], borrow) - - // t could be `fqModulus` if `arg`=0. Set mask=0 if self=0 - // and 0xff..ff if `arg`!=0 - mask := t[0] | t[1] | t[2] | t[3] - mask = -((mask | -mask) >> 63) - out[0] = t[0] & mask - out[1] = t[1] & mask - out[2] = t[2] & mask - out[3] = t[3] & mask -} - -// Square performs modular square -func (f bls12381FqArithmetic) Square(out, arg *[native.FieldLimbs]uint64) { - var r [2 * native.FieldLimbs]uint64 - var carry uint64 - - r[1], carry = mac(0, arg[0], arg[1], 0) - r[2], carry = mac(0, arg[0], arg[2], carry) - r[3], r[4] = mac(0, arg[0], arg[3], carry) - - r[3], carry = mac(r[3], arg[1], arg[2], 0) - r[4], r[5] = mac(r[4], arg[1], arg[3], carry) - - r[5], r[6] = mac(r[5], arg[2], arg[3], 0) - - r[7] = r[6] >> 63 - r[6] = (r[6] << 1) | r[5]>>63 - r[5] = (r[5] << 1) | r[4]>>63 - r[4] = (r[4] << 1) | r[3]>>63 - r[3] = (r[3] << 1) | r[2]>>63 - r[2] = (r[2] << 1) | r[1]>>63 - r[1] = r[1] << 1 - - r[0], carry = mac(0, arg[0], arg[0], 0) - r[1], carry = adc(0, r[1], carry) - r[2], carry = mac(r[2], arg[1], arg[1], carry) - r[3], carry = adc(0, r[3], carry) - r[4], carry = mac(r[4], arg[2], arg[2], carry) - r[5], carry = adc(0, r[5], carry) - r[6], carry = mac(r[6], arg[3], arg[3], carry) - r[7], _ = adc(0, r[7], carry) - - f.montReduce(out, &r) -} - -// Mul performs modular multiplication -func (f bls12381FqArithmetic) Mul(out, arg1, arg2 *[native.FieldLimbs]uint64) { - // Schoolbook multiplication - var r [2 * native.FieldLimbs]uint64 - var carry uint64 - - r[0], carry = mac(0, arg1[0], arg2[0], 0) - r[1], carry = mac(0, arg1[0], arg2[1], carry) - r[2], carry = mac(0, arg1[0], arg2[2], carry) - r[3], r[4] = mac(0, arg1[0], arg2[3], carry) - - r[1], carry = mac(r[1], arg1[1], arg2[0], 0) - r[2], carry = mac(r[2], arg1[1], arg2[1], carry) - r[3], carry = mac(r[3], arg1[1], arg2[2], carry) - r[4], r[5] = mac(r[4], arg1[1], arg2[3], carry) - - r[2], carry = mac(r[2], arg1[2], arg2[0], 0) - r[3], carry = mac(r[3], arg1[2], arg2[1], carry) - r[4], carry = mac(r[4], arg1[2], arg2[2], carry) - r[5], r[6] = mac(r[5], arg1[2], arg2[3], carry) - - r[3], carry = mac(r[3], arg1[3], arg2[0], 0) - r[4], carry = mac(r[4], arg1[3], arg2[1], carry) - r[5], carry = mac(r[5], arg1[3], arg2[2], carry) - r[6], r[7] = mac(r[6], arg1[3], arg2[3], carry) - - f.montReduce(out, &r) -} - -// Add performs modular addition -func (f bls12381FqArithmetic) Add(out, arg1, arg2 *[native.FieldLimbs]uint64) { - var t [native.FieldLimbs]uint64 - var carry uint64 - - t[0], carry = adc(arg1[0], arg2[0], 0) - t[1], carry = adc(arg1[1], arg2[1], carry) - t[2], carry = adc(arg1[2], arg2[2], carry) - t[3], _ = adc(arg1[3], arg2[3], carry) - - // Subtract the fqModulus to ensure the value - // is smaller. - f.Sub(out, &t, &fqModulus) -} - -// Sub performs modular subtraction -func (f bls12381FqArithmetic) Sub(out, arg1, arg2 *[native.FieldLimbs]uint64) { - d0, borrow := sbb(arg1[0], arg2[0], 0) - d1, borrow := sbb(arg1[1], arg2[1], borrow) - d2, borrow := sbb(arg1[2], arg2[2], borrow) - d3, borrow := sbb(arg1[3], arg2[3], borrow) - - // If underflow occurred on the final limb, borrow 0xff...ff, otherwise - // borrow = 0x00...00. Conditionally mask to add the fqModulus - borrow = -borrow - d0, carry := adc(d0, fqModulus[0]&borrow, 0) - d1, carry = adc(d1, fqModulus[1]&borrow, carry) - d2, carry = adc(d2, fqModulus[2]&borrow, carry) - d3, _ = adc(d3, fqModulus[3]&borrow, carry) - - out[0] = d0 - out[1] = d1 - out[2] = d2 - out[3] = d3 -} - -// Sqrt performs modular square root -func (f bls12381FqArithmetic) Sqrt(wasSquare *int, out, arg *[native.FieldLimbs]uint64) { - // See sqrt_ts_ct at - // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.4 - // c1 := fqS - // c2 := (q - 1) / (2^c1) - c2 := [4]uint64{ - 0xfffe5bfeffffffff, - 0x09a1d80553bda402, - 0x299d7d483339d808, - 0x0000000073eda753, - } - // c3 := (c2 - 1) / 2 - c3 := [native.FieldLimbs]uint64{ - 0x7fff2dff7fffffff, - 0x04d0ec02a9ded201, - 0x94cebea4199cec04, - 0x0000000039f6d3a9, - } - // c4 := fqGenerator - var c5 [native.FieldLimbs]uint64 - native.Pow(&c5, &fqGenerator, &c2, getBls12381FqParams(), f) - // c5 := [native.FieldLimbs]uint64{0x1015708f7e368fe1, 0x31c6c5456ecc4511, 0x5281fe8998a19ea1, 0x0279089e10c63fe8} - var z, t, b, c, tv [native.FieldLimbs]uint64 - - native.Pow(&z, arg, &c3, getBls12381FqParams(), f) - f.Square(&t, &z) - f.Mul(&t, &t, arg) - f.Mul(&z, &z, arg) - - copy(b[:], t[:]) - copy(c[:], c5[:]) - - for i := fqS; i >= 2; i-- { - for j := 1; j <= i-2; j++ { - f.Square(&b, &b) - } - // if b == 1 flag = 0 else flag = 1 - flag := -(&native.Field{ - Value: b, - Params: getBls12381FqParams(), - Arithmetic: f, - }).IsOne() + 1 - f.Mul(&tv, &z, &c) - f.Selectznz(&z, &z, &tv, flag) - f.Square(&c, &c) - f.Mul(&tv, &t, &c) - f.Selectznz(&t, &t, &tv, flag) - copy(b[:], t[:]) - } - f.Square(&c, &z) - *wasSquare = (&native.Field{ - Value: c, - Params: getBls12381FqParams(), - Arithmetic: f, - }).Equal(&native.Field{ - Value: *arg, - Params: getBls12381FqParams(), - Arithmetic: f, - }) - f.Selectznz(out, out, &z, *wasSquare) -} - -// Invert performs modular inverse -func (f bls12381FqArithmetic) Invert(wasInverted *int, out, arg *[native.FieldLimbs]uint64) { - // Using an addition chain from - // https://github.com/kwantam/addchain - var t0, t1, t2, t3, t4, t5, t6, t7, t8 [native.FieldLimbs]uint64 - var t9, t11, t12, t13, t14, t15, t16, t17 [native.FieldLimbs]uint64 - - f.Square(&t0, arg) - f.Mul(&t1, &t0, arg) - f.Square(&t16, &t0) - f.Square(&t6, &t16) - f.Mul(&t5, &t6, &t0) - f.Mul(&t0, &t6, &t16) - f.Mul(&t12, &t5, &t16) - f.Square(&t2, &t6) - f.Mul(&t7, &t5, &t6) - f.Mul(&t15, &t0, &t5) - f.Square(&t17, &t12) - f.Mul(&t1, &t1, &t17) - f.Mul(&t3, &t7, &t2) - f.Mul(&t8, &t1, &t17) - f.Mul(&t4, &t8, &t2) - f.Mul(&t9, &t8, &t7) - f.Mul(&t7, &t4, &t5) - f.Mul(&t11, &t4, &t17) - f.Mul(&t5, &t9, &t17) - f.Mul(&t14, &t7, &t15) - f.Mul(&t13, &t11, &t12) - f.Mul(&t12, &t11, &t17) - f.Mul(&t15, &t15, &t12) - f.Mul(&t16, &t16, &t15) - f.Mul(&t3, &t3, &t16) - f.Mul(&t17, &t17, &t3) - f.Mul(&t0, &t0, &t17) - f.Mul(&t6, &t6, &t0) - f.Mul(&t2, &t2, &t6) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t17) - native.Pow2k(&t0, &t0, 9, f) - f.Mul(&t0, &t0, &t16) - native.Pow2k(&t0, &t0, 9, f) - f.Mul(&t0, &t0, &t15) - native.Pow2k(&t0, &t0, 9, f) - f.Mul(&t0, &t0, &t15) - native.Pow2k(&t0, &t0, 7, f) - f.Mul(&t0, &t0, &t14) - native.Pow2k(&t0, &t0, 7, f) - f.Mul(&t0, &t0, &t13) - native.Pow2k(&t0, &t0, 10, f) - f.Mul(&t0, &t0, &t12) - native.Pow2k(&t0, &t0, 9, f) - f.Mul(&t0, &t0, &t11) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t8) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, arg) - native.Pow2k(&t0, &t0, 14, f) - f.Mul(&t0, &t0, &t9) - native.Pow2k(&t0, &t0, 10, f) - f.Mul(&t0, &t0, &t8) - native.Pow2k(&t0, &t0, 15, f) - f.Mul(&t0, &t0, &t7) - native.Pow2k(&t0, &t0, 10, f) - f.Mul(&t0, &t0, &t6) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t5) - native.Pow2k(&t0, &t0, 16, f) - f.Mul(&t0, &t0, &t3) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 7, f) - f.Mul(&t0, &t0, &t4) - native.Pow2k(&t0, &t0, 9, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t3) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t3) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 8, f) - f.Mul(&t0, &t0, &t2) - native.Pow2k(&t0, &t0, 5, f) - f.Mul(&t0, &t0, &t1) - native.Pow2k(&t0, &t0, 5, f) - f.Mul(&t0, &t0, &t1) - - *wasInverted = (&native.Field{ - Value: *arg, - Params: getBls12381FqParams(), - Arithmetic: f, - }).IsNonZero() - f.Selectznz(out, out, &t0, *wasInverted) -} - -// FromBytes converts a little endian byte array into a field element -func (f bls12381FqArithmetic) FromBytes( - out *[native.FieldLimbs]uint64, - arg *[native.FieldBytes]byte, -) { - out[0] = binary.LittleEndian.Uint64(arg[:8]) - out[1] = binary.LittleEndian.Uint64(arg[8:16]) - out[2] = binary.LittleEndian.Uint64(arg[16:24]) - out[3] = binary.LittleEndian.Uint64(arg[24:]) -} - -// ToBytes converts a field element to a little endian byte array -func (f bls12381FqArithmetic) ToBytes( - out *[native.FieldBytes]byte, - arg *[native.FieldLimbs]uint64, -) { - binary.LittleEndian.PutUint64(out[:8], arg[0]) - binary.LittleEndian.PutUint64(out[8:16], arg[1]) - binary.LittleEndian.PutUint64(out[16:24], arg[2]) - binary.LittleEndian.PutUint64(out[24:], arg[3]) -} - -// Selectznz performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f bls12381FqArithmetic) Selectznz(out, arg1, arg2 *[native.FieldLimbs]uint64, choice int) { - b := uint64(-choice) - out[0] = arg1[0] ^ ((arg1[0] ^ arg2[0]) & b) - out[1] = arg1[1] ^ ((arg1[1] ^ arg2[1]) & b) - out[2] = arg1[2] ^ ((arg1[2] ^ arg2[2]) & b) - out[3] = arg1[3] ^ ((arg1[3] ^ arg2[3]) & b) -} - -func (f bls12381FqArithmetic) montReduce( - out *[native.FieldLimbs]uint64, - r *[2 * native.FieldLimbs]uint64, -) { - // Taken from Algorithm 14.32 in Handbook of Applied Cryptography - var r1, r2, r3, r4, r5, r6, carry, carry2, k uint64 - var rr [native.FieldLimbs]uint64 - - k = r[0] * qInv - _, carry = mac(r[0], k, fqModulus[0], 0) - r1, carry = mac(r[1], k, fqModulus[1], carry) - r2, carry = mac(r[2], k, fqModulus[2], carry) - r3, carry = mac(r[3], k, fqModulus[3], carry) - r4, carry2 = adc(r[4], 0, carry) - - k = r1 * qInv - _, carry = mac(r1, k, fqModulus[0], 0) - r2, carry = mac(r2, k, fqModulus[1], carry) - r3, carry = mac(r3, k, fqModulus[2], carry) - r4, carry = mac(r4, k, fqModulus[3], carry) - r5, carry2 = adc(r[5], carry2, carry) - - k = r2 * qInv - _, carry = mac(r2, k, fqModulus[0], 0) - r3, carry = mac(r3, k, fqModulus[1], carry) - r4, carry = mac(r4, k, fqModulus[2], carry) - r5, carry = mac(r5, k, fqModulus[3], carry) - r6, carry2 = adc(r[6], carry2, carry) - - k = r3 * qInv - _, carry = mac(r3, k, fqModulus[0], 0) - rr[0], carry = mac(r4, k, fqModulus[1], carry) - rr[1], carry = mac(r5, k, fqModulus[2], carry) - rr[2], carry = mac(r6, k, fqModulus[3], carry) - rr[3], _ = adc(r[7], carry2, carry) - - f.Sub(out, &rr, &fqModulus) -} diff --git a/crypto/core/curves/native/bls12381/fq_test.go b/crypto/core/curves/native/bls12381/fq_test.go deleted file mode 100644 index 431a2b625..000000000 --- a/crypto/core/curves/native/bls12381/fq_test.go +++ /dev/null @@ -1,353 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls12381 - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFqSetOne(t *testing.T) { - fq := Bls12381FqNew().SetOne() - require.NotNil(t, fq) - require.Equal(t, fq.Value, getBls12381FqParams().R) -} - -func TestFqSetUint64(t *testing.T) { - act := Bls12381FqNew().SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act.Value[0], uint64(0xbc98da2820121c89)) -} - -func TestFqAdd(t *testing.T) { - lhs := Bls12381FqNew().SetOne() - rhs := Bls12381FqNew().SetOne() - exp := Bls12381FqNew().SetUint64(2) - res := Bls12381FqNew().Add(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := Bls12381FqNew().Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqSub(t *testing.T) { - lhs := Bls12381FqNew().SetOne() - rhs := Bls12381FqNew().SetOne() - exp := Bls12381FqNew().SetZero() - res := Bls12381FqNew().Sub(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := Bls12381FqNew().Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqMul(t *testing.T) { - lhs := Bls12381FqNew().SetOne() - rhs := Bls12381FqNew().SetOne() - exp := Bls12381FqNew().SetOne() - res := Bls12381FqNew().Mul(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := Bls12381FqNew().Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqDouble(t *testing.T) { - a := Bls12381FqNew().SetUint64(2) - e := Bls12381FqNew().SetUint64(4) - require.Equal(t, e, Bls12381FqNew().Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = Bls12381FqNew().SetUint64(uint64(tv)) - e = Bls12381FqNew().SetUint64(ttv) - require.Equal(t, e, Bls12381FqNew().Double(a)) - } -} - -func TestFqSquare(t *testing.T) { - a := Bls12381FqNew().SetUint64(4) - e := Bls12381FqNew().SetUint64(16) - require.Equal(t, 1, e.Equal(a.Square(a))) - - a.SetUint64(2854263694) - e.SetUint64(8146821234886525636) - require.Equal(t, 1, e.Equal(a.Square(a))) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, 1, e.Equal(a.Square(a)), "exp = %d, j = %d", exp, j) - } -} - -func TestFqNeg(t *testing.T) { - g := Bls12381FqNew().SetRaw(&fqGenerator) - a := Bls12381FqNew().SetOne() - a.Neg(a) - e := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0xfffffffd00000003, 0xfb38ec08fffb13fc, 0x99ad88181ce5880f, 0x5bc8f5f97cd877d8}) - require.Equal(t, 1, e.Equal(a)) - a.Neg(g) - e = Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0xfffffff000000010, 0x3bda402fffe5bfef, 0x339d80809a1d8055, 0x3eda753299d7d483}) - require.Equal(t, e, a) -} - -func TestFqExp(t *testing.T) { - e := Bls12381FqNew().SetUint64(8) - a := Bls12381FqNew().SetUint64(2) - by := Bls12381FqNew().SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFqSqrt(t *testing.T) { - t1 := Bls12381FqNew().SetUint64(2) - t2 := Bls12381FqNew().Neg(t1) - t3 := Bls12381FqNew().Square(t1) - _, wasSquare := t3.Sqrt(t3) - - require.True(t, wasSquare) - require.Equal(t, 1, t1.Equal(t3)|t2.Equal(t3)) - t1.SetUint64(5) - _, wasSquare = Bls12381FqNew().Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFqInvert(t *testing.T) { - twoInv := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0xffffffff, 0xac425bfd0001a401, 0xccc627f7f65e27fa, 0xc1258acd66282b7}) - two := Bls12381FqNew().SetUint64(2) - a, inverted := Bls12381FqNew().Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnity := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0xb9b58d8c5f0e466a, 0x5b1b4c801819d7ec, 0x0af53ae352a31e64, 0x5bf3adda19e9b27b}) - rootOfUnityInv := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0x4256481adcf3219a, 0x45f37b7f96b6cad3, 0xf9c3f1d75f7a3b27, 0x2d2fc049658afd43}) - a, inverted = Bls12381FqNew().Invert(rootOfUnity) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := Bls12381FqNew().SetUint64(9) - rhs := Bls12381FqNew().SetUint64(3) - rhsInv, inverted := Bls12381FqNew().Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, Bls12381FqNew().Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = Bls12381FqNew().Invert(rhs) - require.False(t, inverted) -} - -func TestFqCMove(t *testing.T) { - t1 := Bls12381FqNew().SetUint64(5) - t2 := Bls12381FqNew().SetUint64(10) - require.Equal(t, t1, Bls12381FqNew().CMove(t1, t2, 0)) - require.Equal(t, t2, Bls12381FqNew().CMove(t1, t2, 1)) -} - -func TestFqBytes(t *testing.T) { - t1 := Bls12381FqNew().SetUint64(99) - seq := t1.Bytes() - t2, err := Bls12381FqNew().SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFqCmp(t *testing.T) { - tests := []struct { - a *native.Field - b *native.Field - e int - }{ - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{2731658267414164836, 14655288906067898431, 6537465423330262322, 8306191141697566219}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{6472764012681988529, 10848812988401906064, 2961825807536828898, 4282183981941645679}), - e: 1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{8023004109510539223, 4652004072850285717, 1877219145646046927, 383214385093921911}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{10099384440823804262, 16139476942229308465, 8636966320777393798, 5435928725024696785}), - e: -1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{3741840066202388211, 12165774400417314871, 16619312580230515379, 16195032234110087705}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{3905865991286066744, 543690822309071825, 17963103015950210055, 3745476720756119742}), - e: 1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{16660853697936147788, 7799793619412111108, 13515141085171033220, 2641079731236069032}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{17790588295388238399, 571847801379669440, 14537208974498222469, 12792570372087452754}), - e: -1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{3912839285384959186, 2701177075110484070, 6453856448115499033, 6475797457962597458}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{1282566391665688512, 13503640416992806563, 2962240104675990153, 3374904770947067689}), - e: 1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{5716631803409360103, 7859567470082614154, 12747956220853330146, 18434584096087315020}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{16317076441459028418, 12854146980376319601, 2258436689269031143, 9531877130792223752}), - e: 1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{17955191469941083403, 10350326247207200880, 17263512235150705075, 12700328451238078022}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{6767595547459644695, 7146403825494928147, 12269344038346710612, 9122477829383225603}), - e: 1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{17099388671847024438, 6426264987820696548, 10641143464957227405, 7709745403700754098}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{10799154372990268556, 17178492485719929374, 5705777922258988797, 8051037767683567782}), - e: -1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{4567139260680454325, 1629385880182139061, 16607020832317899145, 1261011562621553200}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{13487234491304534488, 17872642955936089265, 17651026784972590233, 9468934643333871559}), - e: -1, - }, - { - a: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{18071070103467571798, 11787850505799426140, 10631355976141928593, 4867785203635092610}), - b: Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{12596443599426461624, 10176122686151524591, 17075755296887483439, 6726169532695070719}), - e: -1, - }, - } - - for _, test := range tests { - require.Equal(t, test.e, test.a.Cmp(test.b)) - require.Equal(t, -test.e, test.b.Cmp(test.a)) - require.Equal(t, 0, test.a.Cmp(test.a)) - require.Equal(t, 0, test.b.Cmp(test.b)) - } -} - -func TestFqBigInt(t *testing.T) { - t1 := Bls12381FqNew().SetBigInt(big.NewInt(9999)) - t2 := Bls12381FqNew().SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0x673053fc60e06500, 0x86e6d480b4f76ada, 0x7fc68f9fefa23291, 0x3fb17f49bdda126d}) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Neg(e) - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFqSetBytesWide(t *testing.T) { - e := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{0xc759fba87ff8c5a6, 0x9ef5194839e7df44, 0x21375d22b678bf0e, 0x38b105387033fd57}) - - a := Bls12381FqNew().SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} - -func TestFqSetBytesWideBigInt(t *testing.T) { - params := getBls12381FqParams() - var tv2 [64]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, params.BiModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a := Bls12381FqNew().SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} - -func TestFqToMontgomery(t *testing.T) { - v := Bls12381FqNew().SetUint64(2) - require.Equal( - t, - [native.FieldLimbs]uint64{ - 0x3fffffffc, - 0xb1096ff400069004, - 0x33189fdfd9789fea, - 0x304962b3598a0adf, - }, - v.Value, - ) -} - -func TestFqFromMontgomery(t *testing.T) { - e := [native.FieldLimbs]uint64{2, 0, 0, 0} - a := [native.FieldLimbs]uint64{0, 0, 0, 0} - v := Bls12381FqNew().SetUint64(2) - v.Arithmetic.FromMontgomery(&a, &v.Value) - require.Equal(t, e, a) -} diff --git a/crypto/core/curves/native/bls12381/g1.go b/crypto/core/curves/native/bls12381/g1.go deleted file mode 100644 index ee3c09056..000000000 --- a/crypto/core/curves/native/bls12381/g1.go +++ /dev/null @@ -1,1123 +0,0 @@ -package bls12381 - -import ( - "fmt" - "io" - "math/big" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - g1x = fp{ - 0x5cb38790fd530c16, - 0x7817fc679976fff5, - 0x154f95c7143ba1c1, - 0xf0ae6acdf3d0e747, - 0xedce6ecc21dbf440, - 0x120177419e0bfb75, - } - g1y = fp{ - 0xbaac93d50ce72271, - 0x8c22631a7918fd8e, - 0xdd595f13570725ce, - 0x51ac582950405194, - 0x0e1c8c3fad0059c0, - 0x0bbc3efc5008a26a, - } - curveG1B = fp{ - 0xaa270000000cfff3, - 0x53cc0032fc34000a, - 0x478fe97a6b0a807f, - 0xb1d37ebee6ba24d7, - 0x8ec9733bbf78ab2f, - 0x09d645513d83de7e, - } - osswuMapA = fp{ - 0x2f65aa0e9af5aa51, - 0x86464c2d1e8416c3, - 0xb85ce591b7bd31e2, - 0x27e11c91b5f24e7c, - 0x28376eda6bfc1835, - 0x155455c3e5071d85, - } - osswuMapB = fp{ - 0xfb996971fe22a1e0, - 0x9aa93eb35b742d6f, - 0x8c476013de99c5c4, - 0x873e27c3a221e571, - 0xca72b5e45a52d888, - 0x06824061418a386b, - } - osswuMapC1 = fp{ - 0xee7fbfffffffeaaa, - 0x07aaffffac54ffff, - 0xd9cc34a83dac3d89, - 0xd91dd2e13ce144af, - 0x92c6e9ed90d2eb35, - 0x0680447a8e5ff9a6, - } - osswuMapC2 = fp{ - 0x43b571cad3215f1f, - 0xccb460ef1c702dc2, - 0x742d884f4f97100b, - 0xdb2c3e3238a3382b, - 0xe40f3fa13fce8f88, - 0x0073a2af9892a2ff, - } - oswwuMapZ = fp{ - 0x886c00000023ffdc, - 0x0f70008d3090001d, - 0x77672417ed5828c3, - 0x9dac23e943dc1740, - 0x50553f1b9c131521, - 0x078c712fbe0ab6e8, - } - oswwuMapXd1 = *((&fp{}).Mul(&oswwuMapZ, &osswuMapA)) - negOsswuMapA = *(&fp{}).Neg(&osswuMapA) - - g1IsoXNum = []fp{ - { - 0x4d18b6f3af00131c, - 0x19fa219793fee28c, - 0x3f2885f1467f19ae, - 0x23dcea34f2ffb304, - 0xd15b58d2ffc00054, - 0x0913be200a20bef4, - }, - { - 0x898985385cdbbd8b, - 0x3c79e43cc7d966aa, - 0x1597e193f4cd233a, - 0x8637ef1e4d6623ad, - 0x11b22deed20d827b, - 0x07097bc5998784ad, - }, - { - 0xa542583a480b664b, - 0xfc7169c026e568c6, - 0x5ba2ef314ed8b5a6, - 0x5b5491c05102f0e7, - 0xdf6e99707d2a0079, - 0x0784151ed7605524, - }, - { - 0x494e212870f72741, - 0xab9be52fbda43021, - 0x26f5577994e34c3d, - 0x049dfee82aefbd60, - 0x65dadd7828505289, - 0x0e93d431ea011aeb, - }, - { - 0x90ee774bd6a74d45, - 0x7ada1c8a41bfb185, - 0x0f1a8953b325f464, - 0x104c24211be4805c, - 0x169139d319ea7a8f, - 0x09f20ead8e532bf6, - }, - { - 0x6ddd93e2f43626b7, - 0xa5482c9aa1ccd7bd, - 0x143245631883f4bd, - 0x2e0a94ccf77ec0db, - 0xb0282d480e56489f, - 0x18f4bfcbb4368929, - }, - { - 0x23c5f0c953402dfd, - 0x7a43ff6958ce4fe9, - 0x2c390d3d2da5df63, - 0xd0df5c98e1f9d70f, - 0xffd89869a572b297, - 0x1277ffc72f25e8fe, - }, - { - 0x79f4f0490f06a8a6, - 0x85f894a88030fd81, - 0x12da3054b18b6410, - 0xe2a57f6505880d65, - 0xbba074f260e400f1, - 0x08b76279f621d028, - }, - { - 0xe67245ba78d5b00b, - 0x8456ba9a1f186475, - 0x7888bff6e6b33bb4, - 0xe21585b9a30f86cb, - 0x05a69cdcef55feee, - 0x09e699dd9adfa5ac, - }, - { - 0x0de5c357bff57107, - 0x0a0db4ae6b1a10b2, - 0xe256bb67b3b3cd8d, - 0x8ad456574e9db24f, - 0x0443915f50fd4179, - 0x098c4bf7de8b6375, - }, - { - 0xe6b0617e7dd929c7, - 0xfe6e37d442537375, - 0x1dafdeda137a489e, - 0xe4efd1ad3f767ceb, - 0x4a51d8667f0fe1cf, - 0x054fdf4bbf1d821c, - }, - { - 0x72db2a50658d767b, - 0x8abf91faa257b3d5, - 0xe969d6833764ab47, - 0x464170142a1009eb, - 0xb14f01aadb30be2f, - 0x18ae6a856f40715d, - }, - } - g1IsoXDen = []fp{ - { - 0xb962a077fdb0f945, - 0xa6a9740fefda13a0, - 0xc14d568c3ed6c544, - 0xb43fc37b908b133e, - 0x9c0b3ac929599016, - 0x0165aa6c93ad115f, - }, - { - 0x23279a3ba506c1d9, - 0x92cfca0a9465176a, - 0x3b294ab13755f0ff, - 0x116dda1c5070ae93, - 0xed4530924cec2045, - 0x083383d6ed81f1ce, - }, - { - 0x9885c2a6449fecfc, - 0x4a2b54ccd37733f0, - 0x17da9ffd8738c142, - 0xa0fba72732b3fafd, - 0xff364f36e54b6812, - 0x0f29c13c660523e2, - }, - { - 0xe349cc118278f041, - 0xd487228f2f3204fb, - 0xc9d325849ade5150, - 0x43a92bd69c15c2df, - 0x1c2c7844bc417be4, - 0x12025184f407440c, - }, - { - 0x587f65ae6acb057b, - 0x1444ef325140201f, - 0xfbf995e71270da49, - 0xccda066072436a42, - 0x7408904f0f186bb2, - 0x13b93c63edf6c015, - }, - { - 0xfb918622cd141920, - 0x4a4c64423ecaddb4, - 0x0beb232927f7fb26, - 0x30f94df6f83a3dc2, - 0xaeedd424d780f388, - 0x06cc402dd594bbeb, - }, - { - 0xd41f761151b23f8f, - 0x32a92465435719b3, - 0x64f436e888c62cb9, - 0xdf70a9a1f757c6e4, - 0x6933a38d5b594c81, - 0x0c6f7f7237b46606, - }, - { - 0x693c08747876c8f7, - 0x22c9850bf9cf80f0, - 0x8e9071dab950c124, - 0x89bc62d61c7baf23, - 0xbc6be2d8dad57c23, - 0x17916987aa14a122, - }, - { - 0x1be3ff439c1316fd, - 0x9965243a7571dfa7, - 0xc7f7f62962f5cd81, - 0x32c6aa9af394361c, - 0xbbc2ee18e1c227f4, - 0x0c102cbac531bb34, - }, - { - 0x997614c97bacbf07, - 0x61f86372b99192c0, - 0x5b8c95fc14353fc3, - 0xca2b066c2a87492f, - 0x16178f5bbf698711, - 0x12a6dcd7f0f4e0e8, - }, - { - 0x760900000002fffd, - 0xebf4000bc40c0002, - 0x5f48985753c758ba, - 0x77ce585370525745, - 0x5c071a97a256ec6d, - 0x15f65ec3fa80e493, - }, - } - g1IsoYNum = []fp{ - { - 0x2b567ff3e2837267, - 0x1d4d9e57b958a767, - 0xce028fea04bd7373, - 0xcc31a30a0b6cd3df, - 0x7d7b18a682692693, - 0x0d300744d42a0310, - }, - { - 0x99c2555fa542493f, - 0xfe7f53cc4874f878, - 0x5df0608b8f97608a, - 0x14e03832052b49c8, - 0x706326a6957dd5a4, - 0x0a8dadd9c2414555, - }, - { - 0x13d942922a5cf63a, - 0x357e33e36e261e7d, - 0xcf05a27c8456088d, - 0x0000bd1de7ba50f0, - 0x83d0c7532f8c1fde, - 0x13f70bf38bbf2905, - }, - { - 0x5c57fd95bfafbdbb, - 0x28a359a65e541707, - 0x3983ceb4f6360b6d, - 0xafe19ff6f97e6d53, - 0xb3468f4550192bf7, - 0x0bb6cde49d8ba257, - }, - { - 0x590b62c7ff8a513f, - 0x314b4ce372cacefd, - 0x6bef32ce94b8a800, - 0x6ddf84a095713d5f, - 0x64eace4cb0982191, - 0x0386213c651b888d, - }, - { - 0xa5310a31111bbcdd, - 0xa14ac0f5da148982, - 0xf9ad9cc95423d2e9, - 0xaa6ec095283ee4a7, - 0xcf5b1f022e1c9107, - 0x01fddf5aed881793, - }, - { - 0x65a572b0d7a7d950, - 0xe25c2d8183473a19, - 0xc2fcebe7cb877dbd, - 0x05b2d36c769a89b0, - 0xba12961be86e9efb, - 0x07eb1b29c1dfde1f, - }, - { - 0x93e09572f7c4cd24, - 0x364e929076795091, - 0x8569467e68af51b5, - 0xa47da89439f5340f, - 0xf4fa918082e44d64, - 0x0ad52ba3e6695a79, - }, - { - 0x911429844e0d5f54, - 0xd03f51a3516bb233, - 0x3d587e5640536e66, - 0xfa86d2a3a9a73482, - 0xa90ed5adf1ed5537, - 0x149c9c326a5e7393, - }, - { - 0x462bbeb03c12921a, - 0xdc9af5fa0a274a17, - 0x9a558ebde836ebed, - 0x649ef8f11a4fae46, - 0x8100e1652b3cdc62, - 0x1862bd62c291dacb, - }, - { - 0x05c9b8ca89f12c26, - 0x0194160fa9b9ac4f, - 0x6a643d5a6879fa2c, - 0x14665bdd8846e19d, - 0xbb1d0d53af3ff6bf, - 0x12c7e1c3b28962e5, - }, - { - 0xb55ebf900b8a3e17, - 0xfedc77ec1a9201c4, - 0x1f07db10ea1a4df4, - 0x0dfbd15dc41a594d, - 0x389547f2334a5391, - 0x02419f98165871a4, - }, - { - 0xb416af000745fc20, - 0x8e563e9d1ea6d0f5, - 0x7c763e17763a0652, - 0x01458ef0159ebbef, - 0x8346fe421f96bb13, - 0x0d2d7b829ce324d2, - }, - { - 0x93096bb538d64615, - 0x6f2a2619951d823a, - 0x8f66b3ea59514fa4, - 0xf563e63704f7092f, - 0x724b136c4cf2d9fa, - 0x046959cfcfd0bf49, - }, - { - 0xea748d4b6e405346, - 0x91e9079c2c02d58f, - 0x41064965946d9b59, - 0xa06731f1d2bbe1ee, - 0x07f897e267a33f1b, - 0x1017290919210e5f, - }, - { - 0x872aa6c17d985097, - 0xeecc53161264562a, - 0x07afe37afff55002, - 0x54759078e5be6838, - 0xc4b92d15db8acca8, - 0x106d87d1b51d13b9, - }, - } - g1IsoYDen = []fp{ - { - 0xeb6c359d47e52b1c, - 0x18ef5f8a10634d60, - 0xddfa71a0889d5b7e, - 0x723e71dcc5fc1323, - 0x52f45700b70d5c69, - 0x0a8b981ee47691f1, - }, - { - 0x616a3c4f5535b9fb, - 0x6f5f037395dbd911, - 0xf25f4cc5e35c65da, - 0x3e50dffea3c62658, - 0x6a33dca523560776, - 0x0fadeff77b6bfe3e, - }, - { - 0x2be9b66df470059c, - 0x24a2c159a3d36742, - 0x115dbe7ad10c2a37, - 0xb6634a652ee5884d, - 0x04fe8bb2b8d81af4, - 0x01c2a7a256fe9c41, - }, - { - 0xf27bf8ef3b75a386, - 0x898b367476c9073f, - 0x24482e6b8c2f4e5f, - 0xc8e0bbd6fe110806, - 0x59b0c17f7631448a, - 0x11037cd58b3dbfbd, - }, - { - 0x31c7912ea267eec6, - 0x1dbf6f1c5fcdb700, - 0xd30d4fe3ba86fdb1, - 0x3cae528fbee9a2a4, - 0xb1cce69b6aa9ad9a, - 0x044393bb632d94fb, - }, - { - 0xc66ef6efeeb5c7e8, - 0x9824c289dd72bb55, - 0x71b1a4d2f119981d, - 0x104fc1aafb0919cc, - 0x0e49df01d942a628, - 0x096c3a09773272d4, - }, - { - 0x9abc11eb5fadeff4, - 0x32dca50a885728f0, - 0xfb1fa3721569734c, - 0xc4b76271ea6506b3, - 0xd466a75599ce728e, - 0x0c81d4645f4cb6ed, - }, - { - 0x4199f10e5b8be45b, - 0xda64e495b1e87930, - 0xcb353efe9b33e4ff, - 0x9e9efb24aa6424c6, - 0xf08d33680a237465, - 0x0d3378023e4c7406, - }, - { - 0x7eb4ae92ec74d3a5, - 0xc341b4aa9fac3497, - 0x5be603899e907687, - 0x03bfd9cca75cbdeb, - 0x564c2935a96bfa93, - 0x0ef3c33371e2fdb5, - }, - { - 0x7ee91fd449f6ac2e, - 0xe5d5bd5cb9357a30, - 0x773a8ca5196b1380, - 0xd0fda172174ed023, - 0x6cb95e0fa776aead, - 0x0d22d5a40cec7cff, - }, - { - 0xf727e09285fd8519, - 0xdc9d55a83017897b, - 0x7549d8bd057894ae, - 0x178419613d90d8f8, - 0xfce95ebdeb5b490a, - 0x0467ffaef23fc49e, - }, - { - 0xc1769e6a7c385f1b, - 0x79bc930deac01c03, - 0x5461c75a23ede3b5, - 0x6e20829e5c230c45, - 0x828e0f1e772a53cd, - 0x116aefa749127bff, - }, - { - 0x101c10bf2744c10a, - 0xbbf18d053a6a3154, - 0xa0ecf39ef026f602, - 0xfc009d4996dc5153, - 0xb9000209d5bd08d3, - 0x189e5fe4470cd73c, - }, - { - 0x7ebd546ca1575ed2, - 0xe47d5a981d081b55, - 0x57b2b625b6d4ca21, - 0xb0a1ba04228520cc, - 0x98738983c2107ff3, - 0x13dddbc4799d81d6, - }, - { - 0x09319f2e39834935, - 0x039e952cbdb05c21, - 0x55ba77a9a2f76493, - 0xfd04e3dfc6086467, - 0xfb95832e7d78742e, - 0x0ef9c24eccaf5e0e, - }, - { - 0x760900000002fffd, - 0xebf4000bc40c0002, - 0x5f48985753c758ba, - 0x77ce585370525745, - 0x5c071a97a256ec6d, - 0x15f65ec3fa80e493, - }, - } -) - -// G1 is a point in g1 -type G1 struct { - x, y, z fp -} - -// Random creates a random point on the curve -// from the specified reader -func (g1 *G1) Random(reader io.Reader) (*G1, error) { - var seed [native.WideFieldBytes]byte - n, err := reader.Read(seed[:]) - if err != nil { - return nil, errors.Wrap(err, "random could not read from stream") - } - if n != native.WideFieldBytes { - return nil, fmt.Errorf("insufficient bytes read %d when %d are needed", n, WideFieldBytes) - } - dst := []byte("BLS12381G1_XMD:SHA-256_SSWU_RO_") - return g1.Hash(native.EllipticPointHasherSha256(), seed[:], dst), nil -} - -// Hash uses the hasher to map bytes to a valid point -func (g1 *G1) Hash(hash *native.EllipticPointHasher, msg, dst []byte) *G1 { - var u []byte - var u0, u1 fp - var r0, r1, q0, q1 G1 - - switch hash.Type() { - case native.XMD: - u = native.ExpandMsgXmd(hash, msg, dst, 128) - case native.XOF: - u = native.ExpandMsgXof(hash, msg, dst, 128) - } - - var buf [WideFieldBytes]byte - copy(buf[:64], internal.ReverseScalarBytes(u[:64])) - u0.SetBytesWide(&buf) - copy(buf[:64], internal.ReverseScalarBytes(u[64:])) - u1.SetBytesWide(&buf) - - r0.osswu3mod4(&u0) - r1.osswu3mod4(&u1) - q0.isogenyMap(&r0) - q1.isogenyMap(&r1) - g1.Add(&q0, &q1) - return g1.ClearCofactor(g1) -} - -// Identity returns the identity point -func (g1 *G1) Identity() *G1 { - g1.x.SetZero() - g1.y.SetOne() - g1.z.SetZero() - return g1 -} - -// Generator returns the base point -func (g1 *G1) Generator() *G1 { - g1.x.Set(&g1x) - g1.y.Set(&g1y) - g1.z.SetOne() - return g1 -} - -// IsIdentity returns true if this point is at infinity -func (g1 *G1) IsIdentity() int { - return g1.z.IsZero() -} - -// IsOnCurve determines if this point represents a valid curve point -func (g1 *G1) IsOnCurve() int { - // Y^2 Z = X^3 + b Z^3 - var lhs, rhs, t fp - lhs.Square(&g1.y) - lhs.Mul(&lhs, &g1.z) - - rhs.Square(&g1.x) - rhs.Mul(&rhs, &g1.x) - t.Square(&g1.z) - t.Mul(&t, &g1.z) - t.Mul(&t, &curveG1B) - rhs.Add(&rhs, &t) - - return lhs.Equal(&rhs) -} - -// InCorrectSubgroup returns 1 if the point is torsion free, 0 otherwise -func (g1 *G1) InCorrectSubgroup() int { - var t G1 - t.multiply(g1, &fqModulusBytes) - return t.IsIdentity() -} - -// Add adds this point to another point. -func (g1 *G1) Add(arg1, arg2 *G1) *G1 { - // Algorithm 7, https://eprint.iacr.org/2015/1060.pdf - var t0, t1, t2, t3, t4, x3, y3, z3 fp - - t0.Mul(&arg1.x, &arg2.x) - t1.Mul(&arg1.y, &arg2.y) - t2.Mul(&arg1.z, &arg2.z) - t3.Add(&arg1.x, &arg1.y) - t4.Add(&arg2.x, &arg2.y) - t3.Mul(&t3, &t4) - t4.Add(&t0, &t1) - t3.Sub(&t3, &t4) - t4.Add(&arg1.y, &arg1.z) - x3.Add(&arg2.y, &arg2.z) - t4.Mul(&t4, &x3) - x3.Add(&t1, &t2) - t4.Sub(&t4, &x3) - x3.Add(&arg1.x, &arg1.z) - y3.Add(&arg2.x, &arg2.z) - x3.Mul(&x3, &y3) - y3.Add(&t0, &t2) - y3.Sub(&x3, &y3) - x3.Double(&t0) - t0.Add(&t0, &x3) - t2.MulBy3b(&t2) - z3.Add(&t1, &t2) - t1.Sub(&t1, &t2) - y3.MulBy3b(&y3) - x3.Mul(&t4, &y3) - t2.Mul(&t3, &t1) - x3.Sub(&t2, &x3) - y3.Mul(&y3, &t0) - t1.Mul(&t1, &z3) - y3.Add(&t1, &y3) - t0.Mul(&t0, &t3) - z3.Mul(&z3, &t4) - z3.Add(&z3, &t0) - - g1.x.Set(&x3) - g1.y.Set(&y3) - g1.z.Set(&z3) - return g1 -} - -// Sub subtracts the two points -func (g1 *G1) Sub(arg1, arg2 *G1) *G1 { - var t G1 - t.Neg(arg2) - return g1.Add(arg1, &t) -} - -// Double this point -func (g1 *G1) Double(a *G1) *G1 { - // Algorithm 9, https://eprint.iacr.org/2015/1060.pdf - var t0, t1, t2, x3, y3, z3 fp - - t0.Square(&a.y) - z3.Double(&t0) - z3.Double(&z3) - z3.Double(&z3) - t1.Mul(&a.y, &a.z) - t2.Square(&a.z) - t2.MulBy3b(&t2) - x3.Mul(&t2, &z3) - y3.Add(&t0, &t2) - z3.Mul(&t1, &z3) - t1.Double(&t2) - t2.Add(&t2, &t1) - t0.Sub(&t0, &t2) - y3.Mul(&t0, &y3) - y3.Add(&y3, &x3) - t1.Mul(&a.x, &a.y) - x3.Mul(&t0, &t1) - x3.Double(&x3) - - e := a.IsIdentity() - g1.x.CMove(&x3, t0.SetZero(), e) - g1.z.CMove(&z3, &t0, e) - g1.y.CMove(&y3, t0.SetOne(), e) - return g1 -} - -// Mul multiplies this point by the input scalar -func (g1 *G1) Mul(a *G1, s *native.Field) *G1 { - bytes := s.Bytes() - return g1.multiply(a, &bytes) -} - -func (g1 *G1) multiply(a *G1, bytes *[native.FieldBytes]byte) *G1 { - var p G1 - precomputed := [16]*G1{} - precomputed[0] = new(G1).Identity() - precomputed[1] = new(G1).Set(a) - for i := 2; i < 16; i += 2 { - precomputed[i] = new(G1).Double(precomputed[i>>1]) - precomputed[i+1] = new(G1).Add(precomputed[i], a) - } - p.Identity() - for i := 0; i < 256; i += 4 { - // Brouwer / windowing method. window size of 4. - for j := 0; j < 4; j++ { - p.Double(&p) - } - window := bytes[32-1-i>>3] >> (4 - i&0x04) & 0x0F - p.Add(&p, precomputed[window]) - } - return g1.Set(&p) -} - -// MulByX multiplies by BLS X using double and add -func (g1 *G1) MulByX(a *G1) *G1 { - // Skip first bit since its always zero - var s, t, r G1 - r.Identity() - t.Set(a) - - for x := paramX >> 1; x != 0; x >>= 1 { - t.Double(&t) - s.Add(&r, &t) - r.CMove(&r, &s, int(x&1)) - } - // Since BLS_X is negative, flip the sign - return g1.Neg(&r) -} - -// ClearCofactor multiplies by (1 - z), where z is the parameter of BLS12-381, which -// [suffices to clear](https://ia.cr/2019/403) the cofactor and map -// elliptic curve points to elements of G1. -func (g1 *G1) ClearCofactor(a *G1) *G1 { - var t G1 - t.MulByX(a) - return g1.Sub(a, &t) -} - -// Neg negates this point -func (g1 *G1) Neg(a *G1) *G1 { - g1.Set(a) - g1.y.CNeg(&a.y, -(a.IsIdentity() - 1)) - return g1 -} - -// Set copies a into g1 -func (g1 *G1) Set(a *G1) *G1 { - g1.x.Set(&a.x) - g1.y.Set(&a.y) - g1.z.Set(&a.z) - return g1 -} - -// BigInt returns the x and y as big.Ints in affine -func (g1 *G1) BigInt() (x, y *big.Int) { - var t G1 - t.ToAffine(g1) - x = t.x.BigInt() - y = t.y.BigInt() - return x, y -} - -// SetBigInt creates a point from affine x, y -// and returns the point if it is on the curve -func (g1 *G1) SetBigInt(x, y *big.Int) (*G1, error) { - var xx, yy fp - var pp G1 - pp.x = *(xx.SetBigInt(x)) - pp.y = *(yy.SetBigInt(y)) - - if pp.x.IsZero()&pp.y.IsZero() == 1 { - pp.Identity() - return g1.Set(&pp), nil - } - - pp.z.SetOne() - - // If not the identity point and not on the curve then invalid - if (pp.IsOnCurve()&pp.InCorrectSubgroup())|(xx.IsZero()&yy.IsZero()) == 0 { - return nil, fmt.Errorf("invalid coordinates") - } - return g1.Set(&pp), nil -} - -// ToCompressed serializes this element into compressed form. -func (g1 *G1) ToCompressed() [FieldBytes]byte { - var out [FieldBytes]byte - var t G1 - t.ToAffine(g1) - xBytes := t.x.Bytes() - copy(out[:], internal.ReverseScalarBytes(xBytes[:])) - isInfinity := byte(g1.IsIdentity()) - // Compressed flag - out[0] |= 1 << 7 - // Is infinity - out[0] |= (1 << 6) & -isInfinity - // Sign of y only set if not infinity - out[0] |= (byte(t.y.LexicographicallyLargest()) << 5) & (isInfinity - 1) - return out -} - -// FromCompressed deserializes this element from compressed form. -func (g1 *G1) FromCompressed(input *[FieldBytes]byte) (*G1, error) { - var xFp, yFp fp - var x [FieldBytes]byte - var p G1 - compressedFlag := int((input[0] >> 7) & 1) - infinityFlag := int((input[0] >> 6) & 1) - sortFlag := int((input[0] >> 5) & 1) - - if compressedFlag != 1 { - return nil, errors.New("compressed flag must be set") - } - - if infinityFlag == 1 { - return g1.Identity(), nil - } - - copy(x[:], internal.ReverseScalarBytes(input[:])) - // Mask away the flag bits - x[FieldBytes-1] &= 0x1F - _, valid := xFp.SetBytes(&x) - - if valid != 1 { - return nil, errors.New("invalid bytes - not in field") - } - - yFp.Square(&xFp) - yFp.Mul(&yFp, &xFp) - yFp.Add(&yFp, &curveG1B) - - _, wasSquare := yFp.Sqrt(&yFp) - if wasSquare != 1 { - return nil, errors.New("point is not on the curve") - } - - yFp.CNeg(&yFp, yFp.LexicographicallyLargest()^sortFlag) - p.x.Set(&xFp) - p.y.Set(&yFp) - p.z.SetOne() - if p.InCorrectSubgroup() == 0 { - return nil, errors.New("point is not in correct subgroup") - } - return g1.Set(&p), nil -} - -// ToUncompressed serializes this element into uncompressed form. -func (g1 *G1) ToUncompressed() [WideFieldBytes]byte { - var out [WideFieldBytes]byte - var t G1 - t.ToAffine(g1) - xBytes := t.x.Bytes() - yBytes := t.y.Bytes() - copy(out[:FieldBytes], internal.ReverseScalarBytes(xBytes[:])) - copy(out[FieldBytes:], internal.ReverseScalarBytes(yBytes[:])) - isInfinity := byte(g1.IsIdentity()) - out[0] |= (1 << 6) & -isInfinity - return out -} - -// FromUncompressed deserializes this element from uncompressed form. -func (g1 *G1) FromUncompressed(input *[WideFieldBytes]byte) (*G1, error) { - var xFp, yFp fp - var t [FieldBytes]byte - var p G1 - infinityFlag := int((input[0] >> 6) & 1) - - if infinityFlag == 1 { - return g1.Identity(), nil - } - - copy(t[:], internal.ReverseScalarBytes(input[:FieldBytes])) - // Mask away top bits - t[FieldBytes-1] &= 0x1F - - _, valid := xFp.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - x not in field") - } - copy(t[:], internal.ReverseScalarBytes(input[FieldBytes:])) - _, valid = yFp.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - y not in field") - } - - p.x.Set(&xFp) - p.y.Set(&yFp) - p.z.SetOne() - - if p.IsOnCurve() == 0 { - return nil, errors.New("point is not on the curve") - } - if p.InCorrectSubgroup() == 0 { - return nil, errors.New("point is not in correct subgroup") - } - return g1.Set(&p), nil -} - -// ToAffine converts the point into affine coordinates -func (g1 *G1) ToAffine(a *G1) *G1 { - var wasInverted int - var zero, x, y, z fp - _, wasInverted = z.Invert(&a.z) - x.Mul(&a.x, &z) - y.Mul(&a.y, &z) - - g1.x.CMove(&zero, &x, wasInverted) - g1.y.CMove(&zero, &y, wasInverted) - g1.z.CMove(&zero, z.SetOne(), wasInverted) - return g1 -} - -// GetX returns the affine X coordinate -func (g1 *G1) GetX() *fp { - var t G1 - t.ToAffine(g1) - return &t.x -} - -// GetY returns the affine Y coordinate -func (g1 *G1) GetY() *fp { - var t G1 - t.ToAffine(g1) - return &t.y -} - -// Equal returns 1 if the two points are equal 0 otherwise. -func (g1 *G1) Equal(rhs *G1) int { - var x1, x2, y1, y2 fp - var e1, e2 int - - // This technique avoids inversions - x1.Mul(&g1.x, &rhs.z) - x2.Mul(&rhs.x, &g1.z) - - y1.Mul(&g1.y, &rhs.z) - y2.Mul(&rhs.y, &g1.z) - - e1 = g1.z.IsZero() - e2 = rhs.z.IsZero() - - // Both at infinity or coordinates are the same - return (e1 & e2) | (^e1 & ^e2)&x1.Equal(&x2)&y1.Equal(&y2) -} - -// CMove sets g1 = arg1 if choice == 0 and g1 = arg2 if choice == 1 -func (g1 *G1) CMove(arg1, arg2 *G1, choice int) *G1 { - g1.x.CMove(&arg1.x, &arg2.x, choice) - g1.y.CMove(&arg1.y, &arg2.y, choice) - g1.z.CMove(&arg1.z, &arg2.z, choice) - return g1 -} - -// SumOfProducts computes the multi-exponentiation for the specified -// points and scalars and stores the result in `g1`. -// Returns an error if the lengths of the arguments is not equal. -func (g1 *G1) SumOfProducts(points []*G1, scalars []*native.Field) (*G1, error) { - const Upper = 256 - const W = 4 - const Windows = Upper / W // careful--use ceiling division in case this doesn't divide evenly - var sum G1 - if len(points) != len(scalars) { - return nil, fmt.Errorf("length mismatch") - } - - bucketSize := 1 << W - windows := make([]G1, Windows) - bytes := make([][32]byte, len(scalars)) - buckets := make([]G1, bucketSize) - - for i := 0; i < len(windows); i++ { - windows[i].Identity() - } - - for i, scalar := range scalars { - bytes[i] = scalar.Bytes() - } - - for j := 0; j < len(windows); j++ { - for i := 0; i < bucketSize; i++ { - buckets[i].Identity() - } - - for i := 0; i < len(scalars); i++ { - // j*W to get the nibble - // >> 3 to convert to byte, / 8 - // (W * j & W) gets the nibble, mod W - // 1 << W - 1 to get the offset - index := bytes[i][j*W>>3] >> (W * j & W) & (1< 0; i-- { - sum.Add(&sum, &buckets[i]) - windows[j].Add(&windows[j], &sum) - } - } - - g1.Identity() - for i := len(windows) - 1; i >= 0; i-- { - for j := 0; j < W; j++ { - g1.Double(g1) - } - - g1.Add(g1, &windows[i]) - } - return g1, nil -} - -func (g1 *G1) osswu3mod4(u *fp) *G1 { - // Taken from section 8.8.1 in - // - var tv1, tv2, tv3, tv4, xd, x1n, x2n, gxd, gx1, y1, y2 fp - - // tv1 = u^2 - tv1.Square(u) - // tv3 = Z * tv1 - tv3.Mul(&oswwuMapZ, &tv1) - // tv2 = tv3^2 - tv2.Square(&tv3) - // xd = tv2 + tv3 - xd.Add(&tv2, &tv3) - // x1n = xd + 1 - x1n.Add(&xd, &r) - // x1n = x1n * B - x1n.Mul(&x1n, &osswuMapB) - // xd = -A * xd - xd.Mul(&negOsswuMapA, &xd) - // xd = CMOV(xd, Z * A, xd == 0) - xd.CMove(&xd, &oswwuMapXd1, xd.IsZero()) - // tv2 = xd^2 - tv2.Square(&xd) - - gxd.Mul(&tv2, &xd) - tv2.Mul(&tv2, &osswuMapA) - gx1.Square(&x1n) - gx1.Add(&gx1, &tv2) - gx1.Mul(&gx1, &x1n) - tv2.Mul(&osswuMapB, &gxd) - - gx1.Add(&gx1, &tv2) - tv4.Square(&gxd) - tv2.Mul(&gx1, &gxd) - tv4.Mul(&tv4, &tv2) - y1.pow(&tv4, &osswuMapC1) - y1.Mul(&y1, &tv2) - - x2n.Mul(&tv3, &x1n) - y2.Mul(&y1, &osswuMapC2) - y2.Mul(&y2, &tv1) - y2.Mul(&y2, u) - - tv2.Square(&y1) - tv2.Mul(&tv2, &gxd) - e2 := tv2.Equal(&gx1) - - x2n.CMove(&x2n, &x1n, e2) - y2.CMove(&y2, &y1, e2) - - e3 := u.Sgn0() ^ y2.Sgn0() - y2.CNeg(&y2, e3) - - g1.z.SetOne() - g1.y.Set(&y2) - _, _ = g1.x.Invert(&xd) - g1.x.Mul(&g1.x, &x2n) - return g1 -} - -func (g1 *G1) isogenyMap(a *G1) *G1 { - const Degree = 16 - var xs [Degree]fp - xs[0] = r - xs[1].Set(&a.x) - xs[2].Square(&a.x) - for i := 3; i < Degree; i++ { - xs[i].Mul(&xs[i-1], &a.x) - } - - xNum := computeKFp(xs[:], g1IsoXNum) - xDen := computeKFp(xs[:], g1IsoXDen) - yNum := computeKFp(xs[:], g1IsoYNum) - yDen := computeKFp(xs[:], g1IsoYDen) - - g1.x.Invert(&xDen) - g1.x.Mul(&g1.x, &xNum) - - g1.y.Invert(&yDen) - g1.y.Mul(&g1.y, &yNum) - g1.y.Mul(&g1.y, &a.y) - g1.z.SetOne() - return g1 -} - -func computeKFp(xxs []fp, k []fp) fp { - var xx, t fp - for i := range k { - xx.Add(&xx, t.Mul(&xxs[i], &k[i])) - } - return xx -} diff --git a/crypto/core/curves/native/bls12381/g1_test.go b/crypto/core/curves/native/bls12381/g1_test.go deleted file mode 100644 index 07079728d..000000000 --- a/crypto/core/curves/native/bls12381/g1_test.go +++ /dev/null @@ -1,431 +0,0 @@ -package bls12381 - -import ( - crand "crypto/rand" - "encoding/hex" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -func TestG1IsOnCurve(t *testing.T) { - require.Equal(t, 1, new(G1).Identity().IsOnCurve()) - require.Equal(t, 1, new(G1).Generator().IsOnCurve()) - - z := fp{ - 0xba7afa1f9a6fe250, - 0xfa0f5b595eafe731, - 0x3bdc477694c306e7, - 0x2149be4b3949fa24, - 0x64aa6e0649b2078c, - 0x12b108ac33643c3e, - } - - gen := new(G1).Generator() - test := G1{ - x: *(gen.x.Mul(&gen.x, &z)), - y: *(gen.y.Mul(&gen.y, &z)), - z: z, - } - require.Equal(t, 1, test.IsOnCurve()) - test.x = z - require.Equal(t, 0, test.IsOnCurve()) -} - -func TestG1Equality(t *testing.T) { - a := new(G1).Generator() - b := new(G1).Identity() - - require.Equal(t, 1, a.Equal(a)) - require.Equal(t, 1, b.Equal(b)) - require.Equal(t, 0, a.Equal(b)) - require.Equal(t, 0, b.Equal(a)) - - z := fp{ - 0xba7afa1f9a6fe250, - 0xfa0f5b595eafe731, - 0x3bdc477694c306e7, - 0x2149be4b3949fa24, - 0x64aa6e0649b2078c, - 0x12b108ac33643c3e, - } - - c := G1{} - c.x.Mul(&a.x, &z) - c.y.Mul(&a.y, &z) - c.z.Set(&z) - - require.Equal(t, 1, c.IsOnCurve()) - - require.Equal(t, 1, a.Equal(&c)) - require.Equal(t, 0, b.Equal(&c)) - - c.y.Neg(&c.y) - require.Equal(t, 1, c.IsOnCurve()) - - require.Equal(t, 0, a.Equal(&c)) - - c.y.Neg(&c.y) - c.x.Set(&z) - require.Equal(t, 0, c.IsOnCurve()) -} - -func TestG1Double(t *testing.T) { - t0 := new(G1).Identity() - t0.Double(t0) - require.Equal(t, 1, t0.IsIdentity()) - require.Equal(t, 1, t0.IsOnCurve()) - - t0.Double(t0.Generator()) - require.Equal(t, 0, t0.IsIdentity()) - require.Equal(t, 1, t0.IsOnCurve()) - e := G1{ - x: fp{ - 0x53e978ce58a9ba3c, - 0x3ea0583c4f3d65f9, - 0x4d20bb47f0012960, - 0xa54c664ae5b2b5d9, - 0x26b552a39d7eb21f, - 0x0008895d26e68785, - }, - y: fp{ - 0x70110b3298293940, - 0xda33c5393f1f6afc, - 0xb86edfd16a5aa785, - 0xaec6d1c9e7b1c895, - 0x25cfc2b522d11720, - 0x06361c83f8d09b15, - }, - z: r, - } - - require.Equal(t, 1, e.Equal(t0)) -} - -func TestG1Add(t *testing.T) { - g := new(G1).Generator() - a := new(G1).Identity() - b := new(G1).Identity() - c := new(G1).Add(a, b) - require.Equal(t, 1, c.IsIdentity()) - require.Equal(t, 1, c.IsOnCurve()) - - b.Generator() - z := fp{ - 0xba7afa1f9a6fe250, - 0xfa0f5b595eafe731, - 0x3bdc477694c306e7, - 0x2149be4b3949fa24, - 0x64aa6e0649b2078c, - 0x12b108ac33643c3e, - } - b.x.Mul(&b.x, &z) - b.y.Mul(&b.y, &z) - b.z.Set(&z) - c.Add(a, b) - require.Equal(t, 0, c.IsIdentity()) - require.Equal(t, 1, g.Equal(c)) - - a.Generator() - a.Double(a) - a.Double(a) - b.Generator() - b.Double(b) - c.Add(a, b) - d := new(G1).Generator() - for i := 0; i < 5; i++ { - d.Add(d, g) - } - require.Equal(t, 0, c.IsIdentity()) - require.Equal(t, 1, c.IsOnCurve()) - require.Equal(t, 0, d.IsIdentity()) - require.Equal(t, 1, d.IsOnCurve()) - require.Equal(t, 1, c.Equal(d)) - - beta := fp{ - 0xcd03c9e48671f071, - 0x5dab22461fcda5d2, - 0x587042afd3851b95, - 0x8eb60ebe01bacb9e, - 0x03f97d6e83d050d2, - 0x18f0206554638741, - } - beta.Square(&beta) - a.Generator() - a.Double(a) - a.Double(a) - b.x.Mul(&a.x, &beta) - b.y.Neg(&a.y) - b.z.Set(&a.z) - require.Equal(t, 1, a.IsOnCurve()) - require.Equal(t, 1, b.IsOnCurve()) - c.Add(a, b) - d.x.Set(&fp{ - 0x29e1e987ef68f2d0, - 0xc5f3ec531db03233, - 0xacd6c4b6ca19730f, - 0x18ad9e827bc2bab7, - 0x46e3b2c5785cc7a9, - 0x07e571d42d22ddd6, - }) - d.y.Set(&fp{ - 0x94d117a7e5a539e7, - 0x8e17ef673d4b5d22, - 0x9d746aaf508a33ea, - 0x8c6d883d2516c9a2, - 0x0bc3b8d5fb0447f7, - 0x07bfa4c7210f4f44, - }) - d.z.SetOne() - require.Equal(t, 1, c.Equal(d)) -} - -func TestG1Sub(t *testing.T) { - a := new(G1).Generator() - b := new(G1).Generator() - require.Equal(t, 1, a.Sub(a, b).IsIdentity()) - b.Double(b) - a.Generator() - require.Equal(t, 1, b.Sub(b, a).Equal(a)) -} - -func TestG1Mul(t *testing.T) { - g := new(G1).Generator() - a := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{ - 0x2b568297a56da71c, - 0xd8c39ecb0ef375d1, - 0x435c38da67bfbf96, - 0x8088a05026b659b2, - }) - b := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{ - 0x785fdd9b26ef8b85, - 0xc997f25837695c18, - 0x4c8dbc39e7b756c1, - 0x70d9b6cc6d87df20, - }) - c := Bls12381FqNew().Mul(a, b) - t1 := new(G1).Generator() - t1.Mul(t1, a) - t1.Mul(t1, b) - require.Equal(t, 1, t1.Equal(g.Mul(g, c))) -} - -func TestG1Neg(t *testing.T) { - a := new(G1).Generator() - b := new(G1).Neg(a) - require.Equal(t, 1, new(G1).Add(a, b).IsIdentity()) - require.Equal(t, 1, new(G1).Sub(a, b.Neg(b)).IsIdentity()) - a.Identity() - require.Equal(t, 1, a.Neg(a).IsIdentity()) -} - -func TestG1InCorrectSubgroup(t *testing.T) { - // ZCash test vector - a := G1{ - x: fp{ - 0x0abaf895b97e43c8, - 0xba4c6432eb9b61b0, - 0x12506f52adfe307f, - 0x75028c3439336b72, - 0x84744f05b8e9bd71, - 0x113d554fb09554f7, - }, - y: fp{ - 0x73e90e88f5cf01c0, - 0x37007b65dd3197e2, - 0x5cf9a1992f0d7c78, - 0x4f83c10b9eb3330d, - 0xf6a63f6f07f60961, - 0x0c53b5b97e634df3, - }, - z: *(new(fp).SetOne()), - } - require.Equal(t, 0, a.InCorrectSubgroup()) - - require.Equal(t, 1, new(G1).Identity().InCorrectSubgroup()) - require.Equal(t, 1, new(G1).Generator().InCorrectSubgroup()) -} - -func TestG1MulByX(t *testing.T) { - // multiplying by `x` a point in G1 is the same as multiplying by - // the equivalent scalar. - generator := new(G1).Generator() - x := Bls12381FqNew().SetUint64(paramX) - x.Neg(x) - lhs := new(G1).Mul(generator, x) - rhs := new(G1).MulByX(generator) - require.Equal(t, 1, lhs.Equal(rhs)) - - pt := new(G1).Generator() - s := Bls12381FqNew().SetUint64(42) - pt.Mul(pt, s) - lhs.Mul(pt, x) - rhs.MulByX(pt) - require.Equal(t, 1, lhs.Equal(rhs)) -} - -func TestG1ClearCofactor(t *testing.T) { - // the generator (and the identity) are always on the curve, - // even after clearing the cofactor - generator := new(G1).Generator() - generator.ClearCofactor(generator) - require.Equal(t, 1, generator.IsOnCurve()) - id := new(G1).Identity() - id.ClearCofactor(id) - require.Equal(t, 1, id.IsOnCurve()) - - z := fp{ - 0x3d2d1c670671394e, - 0x0ee3a800a2f7c1ca, - 0x270f4f21da2e5050, - 0xe02840a53f1be768, - 0x55debeb597512690, - 0x08bd25353dc8f791, - } - - point := G1{ - x: fp{ - 0x48af5ff540c817f0, - 0xd73893acaf379d5a, - 0xe6c43584e18e023c, - 0x1eda39c30f188b3e, - 0xf618c6d3ccc0f8d8, - 0x0073542cd671e16c, - }, - y: fp{ - 0x57bf8be79461d0ba, - 0xfc61459cee3547c3, - 0x0d23567df1ef147b, - 0x0ee187bcce1d9b64, - 0xb0c8cfbe9dc8fdc1, - 0x1328661767ef368b, - }, - z: *(&fp{}).Set(&z), - } - point.x.Mul(&point.x, &z) - point.z.Square(&z) - point.z.Mul(&point.z, &z) - - require.Equal(t, 1, point.IsOnCurve()) - require.Equal(t, 0, point.InCorrectSubgroup()) - clearedPoint := new(G1).ClearCofactor(&point) - require.Equal(t, 1, clearedPoint.IsOnCurve()) - require.Equal(t, 1, clearedPoint.InCorrectSubgroup()) - - // in BLS12-381 the cofactor in G1 can be - // cleared multiplying by (1-x) - hEff := Bls12381FqNew().SetOne() - hEff.Add(hEff, Bls12381FqNew().SetUint64(paramX)) - point.Mul(&point, hEff) - require.Equal(t, 1, clearedPoint.Equal(&point)) -} - -func TestG1Hash(t *testing.T) { - dst := []byte("QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_") - tests := []struct { - input, expected string - }{ - { - "", - "052926add2207b76ca4fa57a8734416c8dc95e24501772c814278700eed6d1e4e8cf62d9c09db0fac349612b759e79a108ba738453bfed09cb546dbb0783dbb3a5f1f566ed67bb6be0e8c67e2e81a4cc68ee29813bb7994998f3eae0c9c6a265", - }, - { - "abc", - "03567bc5ef9c690c2ab2ecdf6a96ef1c139cc0b2f284dca0a9a7943388a49a3aee664ba5379a7655d3c68900be2f69030b9c15f3fe6e5cf4211f346271d7b01c8f3b28be689c8429c85b67af215533311f0b8dfaaa154fa6b88176c229f2885d", - }, - { - "abcdef0123456789", - "11e0b079dea29a68f0383ee94fed1b940995272407e3bb916bbf268c263ddd57a6a27200a784cbc248e84f357ce82d9803a87ae2caf14e8ee52e51fa2ed8eefe80f02457004ba4d486d6aa1f517c0889501dc7413753f9599b099ebcbbd2d709", - }, - { - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - "15f68eaa693b95ccb85215dc65fa81038d69629f70aeee0d0f677cf22285e7bf58d7cb86eefe8f2e9bc3f8cb84fac4881807a1d50c29f430b8cafc4f8638dfeeadf51211e1602a5f184443076715f91bb90a48ba1e370edce6ae1062f5e6dd38", - }, - { - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "082aabae8b7dedb0e78aeb619ad3bfd9277a2f77ba7fad20ef6aabdc6c31d19ba5a6d12283553294c1825c4b3ca2dcfe05b84ae5a942248eea39e1d91030458c40153f3b654ab7872d779ad1e942856a20c438e8d99bc8abfbf74729ce1f7ac8", - }, - } - - pt := new(G1).Identity() - ept := new(G1).Identity() - var b [WideFieldBytes]byte - for _, tst := range tests { - i := []byte(tst.input) - e, _ := hex.DecodeString(tst.expected) - copy(b[:], e) - _, _ = ept.FromUncompressed(&b) - pt.Hash(native.EllipticPointHasherSha256(), i, dst) - require.Equal(t, 1, pt.Equal(ept)) - } -} - -func TestSerialization(t *testing.T) { - a := new( - G1, - ).Hash(native.EllipticPointHasherSha256(), []byte("a"), []byte("BLS12381G1_XMD:SHA-256_SSWU_RO_")) - b := new( - G1, - ).Hash(native.EllipticPointHasherSha256(), []byte("b"), []byte("BLS12381G1_XMD:SHA-256_SSWU_RO_")) - - aBytes := a.ToCompressed() - bBytes := b.ToCompressed() - - aa, err := new(G1).FromCompressed(&aBytes) - require.NoError(t, err) - require.Equal(t, 1, a.Equal(aa)) - - bb, err := new(G1).FromCompressed(&bBytes) - require.NoError(t, err) - require.Equal(t, 1, b.Equal(bb)) - - auBytes := a.ToUncompressed() - buBytes := b.ToUncompressed() - - _, err = aa.FromUncompressed(&auBytes) - require.NoError(t, err) - require.Equal(t, 1, a.Equal(aa)) - - _, err = bb.FromUncompressed(&buBytes) - require.NoError(t, err) - require.Equal(t, 1, b.Equal(bb)) - - bBytes = a.ToCompressed() - a.Neg(a) - aBytes = a.ToCompressed() - _, err = aa.FromCompressed(&aBytes) - require.NoError(t, err) - require.Equal(t, 1, a.Equal(aa)) - _, err = aa.FromCompressed(&bBytes) - require.NoError(t, err) - require.Equal(t, 0, a.Equal(aa)) - require.Equal(t, 1, aa.Equal(a.Neg(a))) -} - -func TestSumOfProducts(t *testing.T) { - var b [64]byte - h0, _ := new(G1).Random(crand.Reader) - _, _ = crand.Read(b[:]) - s := Bls12381FqNew().SetBytesWide(&b) - _, _ = crand.Read(b[:]) - sTilde := Bls12381FqNew().SetBytesWide(&b) - _, _ = crand.Read(b[:]) - c := Bls12381FqNew().SetBytesWide(&b) - - lhs := new(G1).Mul(h0, s) - rhs, _ := new(G1).SumOfProducts([]*G1{h0}, []*native.Field{s}) - require.Equal(t, 1, lhs.Equal(rhs)) - - u := new(G1).Mul(h0, s) - uTilde := new(G1).Mul(h0, sTilde) - sHat := Bls12381FqNew().Mul(c, s) - sHat.Sub(sTilde, sHat) - - rhs.Mul(u, c) - rhs.Add(rhs, new(G1).Mul(h0, sHat)) - require.Equal(t, 1, uTilde.Equal(rhs)) - _, _ = rhs.SumOfProducts([]*G1{u, h0}, []*native.Field{c, sHat}) - require.Equal(t, 1, uTilde.Equal(rhs)) -} diff --git a/crypto/core/curves/native/bls12381/g2.go b/crypto/core/curves/native/bls12381/g2.go deleted file mode 100644 index 3209f0513..000000000 --- a/crypto/core/curves/native/bls12381/g2.go +++ /dev/null @@ -1,1122 +0,0 @@ -package bls12381 - -import ( - "fmt" - "io" - "math/big" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - g2x = fp2{ - A: fp{ - 0xf5f2_8fa2_0294_0a10, - 0xb3f5_fb26_87b4_961a, - 0xa1a8_93b5_3e2a_e580, - 0x9894_999d_1a3c_aee9, - 0x6f67_b763_1863_366b, - 0x0581_9192_4350_bcd7, - }, - B: fp{ - 0xa5a9_c075_9e23_f606, - 0xaaa0_c59d_bccd_60c3, - 0x3bb1_7e18_e286_7806, - 0x1b1a_b6cc_8541_b367, - 0xc2b6_ed0e_f215_8547, - 0x1192_2a09_7360_edf3, - }, - } - g2y = fp2{ - A: fp{ - 0x4c73_0af8_6049_4c4a, - 0x597c_fa1f_5e36_9c5a, - 0xe7e6_856c_aa0a_635a, - 0xbbef_b5e9_6e0d_495f, - 0x07d3_a975_f0ef_25a2, - 0x0083_fd8e_7e80_dae5, - }, - B: fp{ - 0xadc0_fc92_df64_b05d, - 0x18aa_270a_2b14_61dc, - 0x86ad_ac6a_3be4_eba0, - 0x7949_5c4e_c93d_a33a, - 0xe717_5850_a43c_caed, - 0x0b2b_c2a1_63de_1bf2, - }, - } - curveG2B = fp2{ - A: fp{ - 0xaa27_0000_000c_fff3, - 0x53cc_0032_fc34_000a, - 0x478f_e97a_6b0a_807f, - 0xb1d3_7ebe_e6ba_24d7, - 0x8ec9_733b_bf78_ab2f, - 0x09d6_4551_3d83_de7e, - }, - B: fp{ - 0xaa27_0000_000c_fff3, - 0x53cc_0032_fc34_000a, - 0x478f_e97a_6b0a_807f, - 0xb1d3_7ebe_e6ba_24d7, - 0x8ec9_733b_bf78_ab2f, - 0x09d6_4551_3d83_de7e, - }, - } - curveG23B = fp2{ - A: fp{ - 0x447600000027552e, - 0xdcb8009a43480020, - 0x6f7ee9ce4a6e8b59, - 0xb10330b7c0a95bc6, - 0x6140b1fcfb1e54b7, - 0x0381be097f0bb4e1, - }, - B: fp{ - 0x447600000027552e, - 0xdcb8009a43480020, - 0x6f7ee9ce4a6e8b59, - 0xb10330b7c0a95bc6, - 0x6140b1fcfb1e54b7, - 0x0381be097f0bb4e1, - }, - } - sswuMapA = fp2{ - A: fp{}, - B: fp{ - 0xe53a000003135242, - 0x01080c0fdef80285, - 0xe7889edbe340f6bd, - 0x0b51375126310601, - 0x02d6985717c744ab, - 0x1220b4e979ea5467, - }, - } - sswuMapB = fp2{ - A: fp{ - 0x22ea00000cf89db2, - 0x6ec832df71380aa4, - 0x6e1b94403db5a66e, - 0x75bf3c53a79473ba, - 0x3dd3a569412c0a34, - 0x125cdb5e74dc4fd1, - }, - B: fp{ - 0x22ea00000cf89db2, - 0x6ec832df71380aa4, - 0x6e1b94403db5a66e, - 0x75bf3c53a79473ba, - 0x3dd3a569412c0a34, - 0x125cdb5e74dc4fd1, - }, - } - sswuMapZ = fp2{ - A: fp{ - 0x87ebfffffff9555c, - 0x656fffe5da8ffffa, - 0x0fd0749345d33ad2, - 0xd951e663066576f4, - 0xde291a3d41e980d3, - 0x0815664c7dfe040d, - }, - B: fp{ - 0x43f5fffffffcaaae, - 0x32b7fff2ed47fffd, - 0x07e83a49a2e99d69, - 0xeca8f3318332bb7a, - 0xef148d1ea0f4c069, - 0x040ab3263eff0206, - }, - } - sswuMapZInv = fp2{ - A: fp{ - 0xacd0000000011110, - 0x9dd9999dc88ccccd, - 0xb5ca2ac9b76352bf, - 0xf1b574bcf4bc90ce, - 0x42dab41f28a77081, - 0x132fc6ac14cd1e12, - }, - B: fp{ - 0xe396ffffffff2223, - 0x4fbf332fcd0d9998, - 0x0c4bbd3c1aff4cc4, - 0x6b9c91267926ca58, - 0x29ae4da6aef7f496, - 0x10692e942f195791, - }, - } - swwuMapMbDivA = fp2{ - A: fp{ - 0x903c555555474fb3, - 0x5f98cc95ce451105, - 0x9f8e582eefe0fade, - 0xc68946b6aebbd062, - 0x467a4ad10ee6de53, - 0x0e7146f483e23a05, - }, - B: fp{ - 0x29c2aaaaaab85af8, - 0xbf133368e30eeefa, - 0xc7a27a7206cffb45, - 0x9dee04ce44c9425c, - 0x04a15ce53464ce83, - 0x0b8fcaf5b59dac95, - }, - } - - g2IsoXNum = []fp2{ - { - A: fp{ - 0x47f671c71ce05e62, - 0x06dd57071206393e, - 0x7c80cd2af3fd71a2, - 0x048103ea9e6cd062, - 0xc54516acc8d037f6, - 0x13808f550920ea41, - }, - B: fp{ - 0x47f671c71ce05e62, - 0x06dd57071206393e, - 0x7c80cd2af3fd71a2, - 0x048103ea9e6cd062, - 0xc54516acc8d037f6, - 0x13808f550920ea41, - }, - }, - { - A: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - B: fp{ - 0x5fe55555554c71d0, - 0x873fffdd236aaaa3, - 0x6a6b4619b26ef918, - 0x21c2888408874945, - 0x2836cda7028cabc5, - 0x0ac73310a7fd5abd, - }, - }, - { - A: fp{ - 0x0a0c5555555971c3, - 0xdb0c00101f9eaaae, - 0xb1fb2f941d797997, - 0xd3960742ef416e1c, - 0xb70040e2c20556f4, - 0x149d7861e581393b, - }, - B: fp{ - 0xaff2aaaaaaa638e8, - 0x439fffee91b55551, - 0xb535a30cd9377c8c, - 0x90e144420443a4a2, - 0x941b66d3814655e2, - 0x0563998853fead5e, - }, - }, - { - A: fp{ - 0x40aac71c71c725ed, - 0x190955557a84e38e, - 0xd817050a8f41abc3, - 0xd86485d4c87f6fb1, - 0x696eb479f885d059, - 0x198e1a74328002d2, - }, - B: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - } - g2IsoXDen = []fp2{ - { - A: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - B: fp{ - 0x1f3affffff13ab97, - 0xf25bfc611da3ff3e, - 0xca3757cb3819b208, - 0x3e6427366f8cec18, - 0x03977bc86095b089, - 0x04f69db13f39a952, - }, - }, - { - A: fp{ - 0x447600000027552e, - 0xdcb8009a43480020, - 0x6f7ee9ce4a6e8b59, - 0xb10330b7c0a95bc6, - 0x6140b1fcfb1e54b7, - 0x0381be097f0bb4e1, - }, - B: fp{ - 0x7588ffffffd8557d, - 0x41f3ff646e0bffdf, - 0xf7b1e8d2ac426aca, - 0xb3741acd32dbb6f8, - 0xe9daf5b9482d581f, - 0x167f53e0ba7431b8, - }, - }, - { - A: fp{ - 0x760900000002fffd, - 0xebf4000bc40c0002, - 0x5f48985753c758ba, - 0x77ce585370525745, - 0x5c071a97a256ec6d, - 0x15f65ec3fa80e493, - }, - B: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - } - g2IsoYNum = []fp2{ - { - A: fp{ - 0x96d8f684bdfc77be, - 0xb530e4f43b66d0e2, - 0x184a88ff379652fd, - 0x57cb23ecfae804e1, - 0x0fd2e39eada3eba9, - 0x08c8055e31c5d5c3, - }, - B: fp{ - 0x96d8f684bdfc77be, - 0xb530e4f43b66d0e2, - 0x184a88ff379652fd, - 0x57cb23ecfae804e1, - 0x0fd2e39eada3eba9, - 0x08c8055e31c5d5c3, - }, - }, - { - A: fp{ - 0o00000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - B: fp{ - 0xbf0a71c71c91b406, - 0x4d6d55d28b7638fd, - 0x9d82f98e5f205aee, - 0xa27aa27b1d1a18d5, - 0x02c3b2b2d2938e86, - 0x0c7d13420b09807f, - }, - }, - { - A: fp{ - 0xd7f9555555531c74, - 0x21cffff748daaaa8, - 0x5a9ad1866c9bbe46, - 0x4870a2210221d251, - 0x4a0db369c0a32af1, - 0x02b1ccc429ff56af, - }, - B: fp{ - 0xe205aaaaaaac8e37, - 0xfcdc000768795556, - 0x0c96011a8a1537dd, - 0x1c06a963f163406e, - 0x010df44c82a881e6, - 0x174f45260f808feb, - }, - }, - { - A: fp{ - 0xa470bda12f67f35c, - 0xc0fe38e23327b425, - 0xc9d3d0f2c6f0678d, - 0x1c55c9935b5a982e, - 0x27f6c0e2f0746764, - 0x117c5e6e28aa9054, - }, - B: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - } - g2IsoYDen = []fp2{ - { - A: fp{ - 0x0162fffffa765adf, - 0x8f7bea480083fb75, - 0x561b3c2259e93611, - 0x11e19fc1a9c875d5, - 0xca713efc00367660, - 0x03c6a03d41da1151, - }, - B: fp{ - 0x0162fffffa765adf, - 0x8f7bea480083fb75, - 0x561b3c2259e93611, - 0x11e19fc1a9c875d5, - 0xca713efc00367660, - 0x03c6a03d41da1151, - }, - }, - { - A: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - B: fp{ - 0x5db0fffffd3b02c5, - 0xd713f52358ebfdba, - 0x5ea60761a84d161a, - 0xbb2c75a34ea6c44a, - 0x0ac6735921c1119b, - 0x0ee3d913bdacfbf6, - }, - }, - { - A: fp{ - 0x66b10000003affc5, - 0xcb1400e764ec0030, - 0xa73e5eb56fa5d106, - 0x8984c913a0fe09a9, - 0x11e10afb78ad7f13, - 0x05429d0e3e918f52, - }, - B: fp{ - 0x534dffffffc4aae6, - 0x5397ff174c67ffcf, - 0xbff273eb870b251d, - 0xdaf2827152870915, - 0x393a9cbaca9e2dc3, - 0x14be74dbfaee5748, - }, - }, - { - A: fp{ - 0x760900000002fffd, - 0xebf4000bc40c0002, - 0x5f48985753c758ba, - 0x77ce585370525745, - 0x5c071a97a256ec6d, - 0x15f65ec3fa80e493, - }, - B: fp{ - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - } - - // 1 / ((u+1) ^ ((q-1)/3)) - psiCoeffX = fp2{ - A: fp{}, - B: fp{ - 0x890dc9e4867545c3, - 0x2af322533285a5d5, - 0x50880866309b7e2c, - 0xa20d1b8c7e881024, - 0x14e4f04fe2db9068, - 0x14e56d3f1564853a, - }, - } - // 1 / ((u+1) ^ (p-1)/2) - psiCoeffY = fp2{ - A: fp{ - 0x3e2f585da55c9ad1, - 0x4294213d86c18183, - 0x382844c88b623732, - 0x92ad2afd19103e18, - 0x1d794e4fac7cf0b9, - 0x0bd592fc7d825ec8, - }, - B: fp{ - 0x7bcfa7a25aa30fda, - 0xdc17dec12a927e7c, - 0x2f088dd86b4ebef1, - 0xd1ca2087da74d4a7, - 0x2da2596696cebc1d, - 0x0e2b7eedbbfd87d2, - }, - } - - // 1 / 2 ^ ((q-1)/3) - psi2CoeffX = fp2{ - A: fp{ - 0xcd03c9e48671f071, - 0x5dab22461fcda5d2, - 0x587042afd3851b95, - 0x8eb60ebe01bacb9e, - 0x03f97d6e83d050d2, - 0x18f0206554638741, - }, - B: fp{}, - } -) - -// G2 is a point in g2 -type G2 struct { - x, y, z fp2 -} - -// Random creates a random point on the curve -// from the specified reader -func (g2 *G2) Random(reader io.Reader) (*G2, error) { - var seed [native.WideFieldBytes]byte - n, err := reader.Read(seed[:]) - if err != nil { - return nil, errors.Wrap(err, "random could not read from stream") - } - if n != native.WideFieldBytes { - return nil, fmt.Errorf("insufficient bytes read %d when %d are needed", n, WideFieldBytes) - } - dst := []byte("BLS12381G2_XMD:SHA-256_SSWU_RO_") - return g2.Hash(native.EllipticPointHasherSha256(), seed[:], dst), nil -} - -// Hash uses the hasher to map bytes to a valid point -func (g2 *G2) Hash(hash *native.EllipticPointHasher, msg, dst []byte) *G2 { - var u []byte - var u0, u1 fp2 - var r0, r1, q0, q1 G2 - - switch hash.Type() { - case native.XMD: - u = native.ExpandMsgXmd(hash, msg, dst, 256) - case native.XOF: - u = native.ExpandMsgXof(hash, msg, dst, 256) - } - - var buf [96]byte - copy(buf[:64], internal.ReverseScalarBytes(u[:64])) - u0.A.SetBytesWide(&buf) - copy(buf[:64], internal.ReverseScalarBytes(u[64:128])) - u0.B.SetBytesWide(&buf) - copy(buf[:64], internal.ReverseScalarBytes(u[128:192])) - u1.A.SetBytesWide(&buf) - copy(buf[:64], internal.ReverseScalarBytes(u[192:])) - u1.B.SetBytesWide(&buf) - - r0.sswu(&u0) - r1.sswu(&u1) - q0.isogenyMap(&r0) - q1.isogenyMap(&r1) - g2.Add(&q0, &q1) - return g2.ClearCofactor(g2) -} - -// Identity returns the identity point -func (g2 *G2) Identity() *G2 { - g2.x.SetZero() - g2.y.SetOne() - g2.z.SetZero() - return g2 -} - -// Generator returns the base point -func (g2 *G2) Generator() *G2 { - g2.x.Set(&g2x) - g2.y.Set(&g2y) - g2.z.SetOne() - return g2 -} - -// IsIdentity returns true if this point is at infinity -func (g2 *G2) IsIdentity() int { - return g2.z.IsZero() -} - -// IsOnCurve determines if this point represents a valid curve point -func (g2 *G2) IsOnCurve() int { - // Y^2 Z = X^3 + b Z^3 - var lhs, rhs, t fp2 - lhs.Square(&g2.y) - lhs.Mul(&lhs, &g2.z) - - rhs.Square(&g2.x) - rhs.Mul(&rhs, &g2.x) - t.Square(&g2.z) - t.Mul(&t, &g2.z) - t.Mul(&t, &curveG2B) - rhs.Add(&rhs, &t) - - return lhs.Equal(&rhs) -} - -// InCorrectSubgroup returns 1 if the point is torsion free, 0 otherwise -func (g2 *G2) InCorrectSubgroup() int { - var t G2 - t.multiply(g2, &fqModulusBytes) - return t.IsIdentity() -} - -// Add adds this point to another point. -func (g2 *G2) Add(arg1, arg2 *G2) *G2 { - // Algorithm 7, https://eprint.iacr.org/2015/1060.pdf - var t0, t1, t2, t3, t4, x3, y3, z3 fp2 - - t0.Mul(&arg1.x, &arg2.x) - t1.Mul(&arg1.y, &arg2.y) - t2.Mul(&arg1.z, &arg2.z) - t3.Add(&arg1.x, &arg1.y) - t4.Add(&arg2.x, &arg2.y) - t3.Mul(&t3, &t4) - t4.Add(&t0, &t1) - t3.Sub(&t3, &t4) - t4.Add(&arg1.y, &arg1.z) - x3.Add(&arg2.y, &arg2.z) - t4.Mul(&t4, &x3) - x3.Add(&t1, &t2) - t4.Sub(&t4, &x3) - x3.Add(&arg1.x, &arg1.z) - y3.Add(&arg2.x, &arg2.z) - x3.Mul(&x3, &y3) - y3.Add(&t0, &t2) - y3.Sub(&x3, &y3) - x3.Double(&t0) - t0.Add(&t0, &x3) - t2.MulBy3b(&t2) - z3.Add(&t1, &t2) - t1.Sub(&t1, &t2) - y3.MulBy3b(&y3) - x3.Mul(&t4, &y3) - t2.Mul(&t3, &t1) - x3.Sub(&t2, &x3) - y3.Mul(&y3, &t0) - t1.Mul(&t1, &z3) - y3.Add(&t1, &y3) - t0.Mul(&t0, &t3) - z3.Mul(&z3, &t4) - z3.Add(&z3, &t0) - - g2.x.Set(&x3) - g2.y.Set(&y3) - g2.z.Set(&z3) - return g2 -} - -// Sub subtracts the two points -func (g2 *G2) Sub(arg1, arg2 *G2) *G2 { - var t G2 - t.Neg(arg2) - return g2.Add(arg1, &t) -} - -// Double this point -func (g2 *G2) Double(a *G2) *G2 { - // Algorithm 9, https://eprint.iacr.org/2015/1060.pdf - var t0, t1, t2, x3, y3, z3 fp2 - - t0.Square(&a.y) - z3.Double(&t0) - z3.Double(&z3) - z3.Double(&z3) - t1.Mul(&a.y, &a.z) - t2.Square(&a.z) - t2.MulBy3b(&t2) - x3.Mul(&t2, &z3) - y3.Add(&t0, &t2) - z3.Mul(&t1, &z3) - t1.Double(&t2) - t2.Add(&t2, &t1) - t0.Sub(&t0, &t2) - y3.Mul(&t0, &y3) - y3.Add(&y3, &x3) - t1.Mul(&a.x, &a.y) - x3.Mul(&t0, &t1) - x3.Double(&x3) - - e := a.IsIdentity() - g2.x.CMove(&x3, t0.SetZero(), e) - g2.z.CMove(&z3, &t0, e) - g2.y.CMove(&y3, t0.SetOne(), e) - return g2 -} - -// Mul multiplies this point by the input scalar -func (g2 *G2) Mul(a *G2, s *native.Field) *G2 { - bytes := s.Bytes() - return g2.multiply(a, &bytes) -} - -func (g2 *G2) multiply(a *G2, bytes *[native.FieldBytes]byte) *G2 { - var p G2 - precomputed := [16]*G2{} - precomputed[0] = new(G2).Identity() - precomputed[1] = new(G2).Set(a) - for i := 2; i < 16; i += 2 { - precomputed[i] = new(G2).Double(precomputed[i>>1]) - precomputed[i+1] = new(G2).Add(precomputed[i], a) - } - p.Identity() - for i := 0; i < 256; i += 4 { - // Brouwer / windowing method. window size of 4. - for j := 0; j < 4; j++ { - p.Double(&p) - } - window := bytes[32-1-i>>3] >> (4 - i&0x04) & 0x0F - p.Add(&p, precomputed[window]) - } - return g2.Set(&p) -} - -// MulByX multiplies by BLS X using double and add -func (g2 *G2) MulByX(a *G2) *G2 { - // Skip first bit since its always zero - var s, t, r G2 - r.Identity() - t.Set(a) - - for x := paramX >> 1; x != 0; x >>= 1 { - t.Double(&t) - s.Add(&r, &t) - r.CMove(&r, &s, int(x&1)) - } - // Since BLS_X is negative, flip the sign - return g2.Neg(&r) -} - -// ClearCofactor using [Budroni-Pintore](https://ia.cr/2017/419). -// This is equivalent to multiplying by h_{eff} = 3(z^2 - 1) * h_2 -// where h_2 is the cofactor of G_2 and z is the parameter of BLS12-381. -func (g2 *G2) ClearCofactor(a *G2) *G2 { - var t1, t2, t3, pt G2 - - t1.MulByX(a) - t2.psi(a) - - pt.Double(a) - pt.psi2(&pt) - - t3.Add(&t1, &t2) - t3.MulByX(&t3) - - pt.Add(&pt, &t3) - pt.Sub(&pt, &t1) - pt.Sub(&pt, &t2) - pt.Sub(&pt, a) - return g2.Set(&pt) -} - -// Neg negates this point -func (g2 *G2) Neg(a *G2) *G2 { - g2.Set(a) - g2.y.CNeg(&a.y, -(a.IsIdentity() - 1)) - return g2 -} - -// Set copies a into g2 -func (g2 *G2) Set(a *G2) *G2 { - g2.x.Set(&a.x) - g2.y.Set(&a.y) - g2.z.Set(&a.z) - return g2 -} - -// BigInt returns the x and y as big.Ints in affine -func (g2 *G2) BigInt() (x, y *big.Int) { - var t G2 - out := t.ToUncompressed() - x = new(big.Int).SetBytes(out[:WideFieldBytes]) - y = new(big.Int).SetBytes(out[WideFieldBytes:]) - return x, y -} - -// SetBigInt creates a point from affine x, y -// and returns the point if it is on the curve -func (g2 *G2) SetBigInt(x, y *big.Int) (*G2, error) { - var tt [DoubleWideFieldBytes]byte - - if len(x.Bytes()) == 0 && len(y.Bytes()) == 0 { - return g2.Identity(), nil - } - x.FillBytes(tt[:WideFieldBytes]) - y.FillBytes(tt[WideFieldBytes:]) - - return g2.FromUncompressed(&tt) -} - -// ToCompressed serializes this element into compressed form. -func (g2 *G2) ToCompressed() [WideFieldBytes]byte { - var out [WideFieldBytes]byte - var t G2 - t.ToAffine(g2) - xABytes := t.x.A.Bytes() - xBBytes := t.x.B.Bytes() - copy(out[:FieldBytes], internal.ReverseScalarBytes(xBBytes[:])) - copy(out[FieldBytes:], internal.ReverseScalarBytes(xABytes[:])) - isInfinity := byte(g2.IsIdentity()) - // Compressed flag - out[0] |= 1 << 7 - // Is infinity - out[0] |= (1 << 6) & -isInfinity - // Sign of y only set if not infinity - out[0] |= (byte(t.y.LexicographicallyLargest()) << 5) & (isInfinity - 1) - return out -} - -// FromCompressed deserializes this element from compressed form. -func (g2 *G2) FromCompressed(input *[WideFieldBytes]byte) (*G2, error) { - var xFp, yFp fp2 - var xA, xB [FieldBytes]byte - var p G2 - compressedFlag := int((input[0] >> 7) & 1) - infinityFlag := int((input[0] >> 6) & 1) - sortFlag := int((input[0] >> 5) & 1) - - if compressedFlag != 1 { - return nil, errors.New("compressed flag must be set") - } - - if infinityFlag == 1 { - return g2.Identity(), nil - } - - copy(xB[:], internal.ReverseScalarBytes(input[:FieldBytes])) - copy(xA[:], internal.ReverseScalarBytes(input[FieldBytes:])) - // Mask away the flag bits - xB[FieldBytes-1] &= 0x1F - _, validA := xFp.A.SetBytes(&xA) - _, validB := xFp.B.SetBytes(&xB) - - if validA&validB != 1 { - return nil, errors.New("invalid bytes - not in field") - } - - // Recover a y-coordinate given x by y = sqrt(x^3 + 4) - yFp.Square(&xFp) - yFp.Mul(&yFp, &xFp) - yFp.Add(&yFp, &curveG2B) - - _, wasSquare := yFp.Sqrt(&yFp) - if wasSquare != 1 { - return nil, errors.New("point is not on the curve") - } - - yFp.CNeg(&yFp, yFp.LexicographicallyLargest()^sortFlag) - p.x.Set(&xFp) - p.y.Set(&yFp) - p.z.SetOne() - if p.InCorrectSubgroup() == 0 { - return nil, errors.New("point is not in correct subgroup") - } - return g2.Set(&p), nil -} - -// ToUncompressed serializes this element into uncompressed form. -func (g2 *G2) ToUncompressed() [DoubleWideFieldBytes]byte { - var out [DoubleWideFieldBytes]byte - var t G2 - t.ToAffine(g2) - bytes := t.x.B.Bytes() - copy(out[:FieldBytes], internal.ReverseScalarBytes(bytes[:])) - bytes = t.x.A.Bytes() - copy(out[FieldBytes:WideFieldBytes], internal.ReverseScalarBytes(bytes[:])) - bytes = t.y.B.Bytes() - copy(out[WideFieldBytes:WideFieldBytes+FieldBytes], internal.ReverseScalarBytes(bytes[:])) - bytes = t.y.A.Bytes() - copy(out[WideFieldBytes+FieldBytes:], internal.ReverseScalarBytes(bytes[:])) - isInfinity := byte(g2.IsIdentity()) - out[0] |= (1 << 6) & -isInfinity - return out -} - -// FromUncompressed deserializes this element from uncompressed form. -func (g2 *G2) FromUncompressed(input *[DoubleWideFieldBytes]byte) (*G2, error) { - var a, b fp - var t [FieldBytes]byte - var p G2 - infinityFlag := int((input[0] >> 6) & 1) - - if infinityFlag == 1 { - return g2.Identity(), nil - } - - copy(t[:], internal.ReverseScalarBytes(input[:FieldBytes])) - // Mask away top bits - t[FieldBytes-1] &= 0x1F - - _, valid := b.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - x.B not in field") - } - copy(t[:], internal.ReverseScalarBytes(input[FieldBytes:WideFieldBytes])) - _, valid = a.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - x.A not in field") - } - - p.x.B.Set(&b) - p.x.A.Set(&a) - - copy(t[:], internal.ReverseScalarBytes(input[WideFieldBytes:WideFieldBytes+FieldBytes])) - _, valid = b.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - y.B not in field") - } - copy(t[:], internal.ReverseScalarBytes(input[FieldBytes+WideFieldBytes:])) - _, valid = a.SetBytes(&t) - if valid == 0 { - return nil, errors.New("invalid bytes - y.A not in field") - } - - p.y.B.Set(&b) - p.y.A.Set(&a) - p.z.SetOne() - - if p.IsOnCurve() == 0 { - return nil, errors.New("point is not on the curve") - } - if p.InCorrectSubgroup() == 0 { - return nil, errors.New("point is not in correct subgroup") - } - return g2.Set(&p), nil -} - -// ToAffine converts the point into affine coordinates -func (g2 *G2) ToAffine(a *G2) *G2 { - var wasInverted int - var zero, x, y, z fp2 - _, wasInverted = z.Invert(&a.z) - x.Mul(&a.x, &z) - y.Mul(&a.y, &z) - - g2.x.CMove(&zero, &x, wasInverted) - g2.y.CMove(&zero, &y, wasInverted) - g2.z.CMove(&zero, z.SetOne(), wasInverted) - return g2 -} - -// GetX returns the affine X coordinate -func (g2 *G2) GetX() *fp2 { - var t G2 - t.ToAffine(g2) - return &t.x -} - -// GetY returns the affine Y coordinate -func (g2 *G2) GetY() *fp2 { - var t G2 - t.ToAffine(g2) - return &t.y -} - -// Equal returns 1 if the two points are equal 0 otherwise. -func (g2 *G2) Equal(rhs *G2) int { - var x1, x2, y1, y2 fp2 - var e1, e2 int - - // This technique avoids inversions - x1.Mul(&g2.x, &rhs.z) - x2.Mul(&rhs.x, &g2.z) - - y1.Mul(&g2.y, &rhs.z) - y2.Mul(&rhs.y, &g2.z) - - e1 = g2.z.IsZero() - e2 = rhs.z.IsZero() - - // Both at infinity or coordinates are the same - return (e1 & e2) | (^e1 & ^e2)&x1.Equal(&x2)&y1.Equal(&y2) -} - -// CMove sets g2 = arg1 if choice == 0 and g2 = arg2 if choice == 1 -func (g2 *G2) CMove(arg1, arg2 *G2, choice int) *G2 { - g2.x.CMove(&arg1.x, &arg2.x, choice) - g2.y.CMove(&arg1.y, &arg2.y, choice) - g2.z.CMove(&arg1.z, &arg2.z, choice) - return g2 -} - -// SumOfProducts computes the multi-exponentiation for the specified -// points and scalars and stores the result in `g2`. -// Returns an error if the lengths of the arguments is not equal. -func (g2 *G2) SumOfProducts(points []*G2, scalars []*native.Field) (*G2, error) { - const Upper = 256 - const W = 4 - const Windows = Upper / W // careful--use ceiling division in case this doesn't divide evenly - var sum G2 - if len(points) != len(scalars) { - return nil, fmt.Errorf("length mismatch") - } - - bucketSize := 1 << W - windows := make([]G2, Windows) - bytes := make([][32]byte, len(scalars)) - buckets := make([]G2, bucketSize) - for i := 0; i < len(windows); i++ { - windows[i].Identity() - } - - for i, scalar := range scalars { - bytes[i] = scalar.Bytes() - } - - for j := 0; j < len(windows); j++ { - for i := 0; i < bucketSize; i++ { - buckets[i].Identity() - } - - for i := 0; i < len(scalars); i++ { - // j*W to get the nibble - // >> 3 to convert to byte, / 8 - // (W * j & W) gets the nibble, mod W - // 1 << W - 1 to get the offset - index := bytes[i][j*W>>3] >> (W * j & W) & (1< 0; i-- { - sum.Add(&sum, &buckets[i]) - windows[j].Add(&windows[j], &sum) - } - } - - g2.Identity() - for i := len(windows) - 1; i >= 0; i-- { - for j := 0; j < W; j++ { - g2.Double(g2) - } - - g2.Add(g2, &windows[i]) - } - return g2, nil -} - -func (g2 *G2) psi(a *G2) *G2 { - g2.x.FrobeniusMap(&a.x) - g2.y.FrobeniusMap(&a.y) - // z = frobenius(z) - g2.z.FrobeniusMap(&a.z) - - // x = frobenius(x)/((u+1)^((p-1)/3)) - g2.x.Mul(&g2.x, &psiCoeffX) - // y = frobenius(y)/(u+1)^((p-1)/2) - g2.y.Mul(&g2.y, &psiCoeffY) - - return g2 -} - -func (g2 *G2) psi2(a *G2) *G2 { - // x = frobenius^2(x)/2^((p-1)/3); note that q^2 is the order of the field. - g2.x.Mul(&a.x, &psi2CoeffX) - // y = -frobenius^2(y); note that q^2 is the order of the field. - g2.y.Neg(&a.y) - g2.z.Set(&a.z) - return g2 -} - -func (g2 *G2) sswu(u *fp2) *G2 { - /// simplified swu map for q = 9 mod 16 where AB == 0 - // - var tv1, tv2, x1, x2, gx1, gx2, x, y, y2, t fp2 - - tv1.Square(u) - tv1.Mul(&tv1, &sswuMapZ) - - tv2.Square(&tv1) - - x1.Add(&tv1, &tv2) - x1.Invert(&x1) - x1.Add(&x1, (&fp2{}).SetOne()) - x1.CMove(&x1, &sswuMapZInv, x1.IsZero()) - x1.Mul(&x1, &swwuMapMbDivA) - - gx1.Square(&x1) - gx1.Add(&gx1, &sswuMapA) - gx1.Mul(&gx1, &x1) - gx1.Add(&gx1, &sswuMapB) - - x2.Mul(&tv1, &x1) - - tv2.Mul(&tv2, &tv1) - - gx2.Mul(&gx1, &tv2) - - _, e2 := t.Sqrt(&gx1) - - x.CMove(&x2, &x1, e2) - y2.CMove(&gx2, &gx1, e2) - - y.Sqrt(&y2) - - y.CNeg(&y, u.Sgn0()^y.Sgn0()) - g2.x.Set(&x) - g2.y.Set(&y) - g2.z.SetOne() - return g2 -} - -func (g2 *G2) isogenyMap(a *G2) *G2 { - const Degree = 4 - var xs [Degree]fp2 - xs[0].SetOne() - xs[1].Set(&a.x) - xs[2].Square(&a.x) - for i := 3; i < Degree; i++ { - xs[i].Mul(&xs[i-1], &a.x) - } - - xNum := computeKFp2(xs[:], g2IsoXNum) - xDen := computeKFp2(xs[:], g2IsoXDen) - yNum := computeKFp2(xs[:], g2IsoYNum) - yDen := computeKFp2(xs[:], g2IsoYDen) - - g2.x.Invert(&xDen) - g2.x.Mul(&g2.x, &xNum) - - g2.y.Invert(&yDen) - g2.y.Mul(&g2.y, &yNum) - g2.y.Mul(&g2.y, &a.y) - g2.z.SetOne() - return g2 -} - -func computeKFp2(xxs []fp2, k []fp2) fp2 { - var xx, t fp2 - for i := range k { - xx.Add(&xx, t.Mul(&xxs[i], &k[i])) - } - return xx -} diff --git a/crypto/core/curves/native/bls12381/g2_test.go b/crypto/core/curves/native/bls12381/g2_test.go deleted file mode 100644 index 67c7332c1..000000000 --- a/crypto/core/curves/native/bls12381/g2_test.go +++ /dev/null @@ -1,569 +0,0 @@ -package bls12381 - -import ( - crand "crypto/rand" - "encoding/hex" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -func TestG2IsOnCurve(t *testing.T) { - require.Equal(t, 1, new(G2).Identity().IsOnCurve()) - require.Equal(t, 1, new(G2).Generator().IsOnCurve()) - - z := fp2{ - A: fp{ - 0xba7a_fa1f_9a6f_e250, - 0xfa0f_5b59_5eaf_e731, - 0x3bdc_4776_94c3_06e7, - 0x2149_be4b_3949_fa24, - 0x64aa_6e06_49b2_078c, - 0x12b1_08ac_3364_3c3e, - }, - B: fp{ - 0x1253_25df_3d35_b5a8, - 0xdc46_9ef5_555d_7fe3, - 0x02d7_16d2_4431_06a9, - 0x05a1_db59_a6ff_37d0, - 0x7cf7_784e_5300_bb8f, - 0x16a8_8922_c7a5_e844, - }, - } - - test := new(G2).Generator() - test.x.Mul(&test.x, &z) - test.y.Mul(&test.y, &z) - test.z.Set(&z) - - require.Equal(t, 1, test.IsOnCurve()) - - test.x.Set(&z) - require.Equal(t, 0, test.IsOnCurve()) -} - -func TestG2Equal(t *testing.T) { - a := new(G2).Generator() - b := new(G2).Identity() - - require.Equal(t, 1, a.Equal(a)) - require.Equal(t, 0, a.Equal(b)) - require.Equal(t, 1, b.Equal(b)) -} - -func TestG2ToAffine(t *testing.T) { - a := new(G2).Generator() - - z := fp2{ - A: fp{ - 0xba7afa1f9a6fe250, - 0xfa0f5b595eafe731, - 0x3bdc477694c306e7, - 0x2149be4b3949fa24, - 0x64aa6e0649b2078c, - 0x12b108ac33643c3e, - }, - B: fp{ - 0x125325df3d35b5a8, - 0xdc469ef5555d7fe3, - 0x02d716d2443106a9, - 0x05a1db59a6ff37d0, - 0x7cf7784e5300bb8f, - 0x16a88922c7a5e844, - }, - } - - a.x.Mul(&a.x, &z) - a.y.Mul(&a.y, &z) - a.z.Set(&z) - - require.Equal(t, 1, a.ToAffine(a).Equal(new(G2).Generator())) -} - -func TestG2Double(t *testing.T) { - a := new(G2).Identity() - require.Equal(t, 1, a.Double(a).IsIdentity()) - - a.Generator() - a.Double(a) - e := G2{ - x: fp2{ - A: fp{ - 0xe9d9e2da9620f98b, - 0x54f1199346b97f36, - 0x3db3b820376bed27, - 0xcfdb31c9b0b64f4c, - 0x41d7c12786354493, - 0x05710794c255c064, - }, - B: fp{ - 0xd6c1d3ca6ea0d06e, - 0xda0cbd905595489f, - 0x4f5352d43479221d, - 0x8ade5d736f8c97e0, - 0x48cc8433925ef70e, - 0x08d7ea71ea91ef81, - }, - }, - y: fp2{ - A: fp{ - 0x15ba26eb4b0d186f, - 0x0d086d64b7e9e01e, - 0xc8b848dd652f4c78, - 0xeecf46a6123bae4f, - 0x255e8dd8b6dc812a, - 0x164142af21dcf93f, - }, - B: fp{ - 0xf9b4a1a895984db4, - 0xd417b114cccff748, - 0x6856301fc89f086e, - 0x41c777878931e3da, - 0x3556b155066a2105, - 0x00acf7d325cb89cf, - }, - }, - z: *((&fp2{}).SetOne()), - } - require.Equal(t, 1, e.Equal(a)) -} - -func TestG2Add(t *testing.T) { - a := new(G2).Identity() - b := new(G2).Identity() - c := new(G2).Add(a, b) - require.Equal(t, 1, c.IsIdentity()) - b.Generator() - c.Add(a, b) - require.Equal(t, 1, c.Equal(b)) - - a.Generator() - a.Double(a) - a.Double(a) - b.Double(b) - c.Add(a, b) - - d := new(G2).Generator() - e := new(G2).Generator() - for i := 0; i < 5; i++ { - e.Add(e, d) - } - require.Equal(t, 1, e.Equal(c)) - - // Degenerate case - beta := fp2{ - A: fp{ - 0xcd03c9e48671f071, - 0x5dab22461fcda5d2, - 0x587042afd3851b95, - 0x8eb60ebe01bacb9e, - 0x03f97d6e83d050d2, - 0x18f0206554638741, - }, - B: fp{}, - } - beta.Square(&beta) - b.x.Mul(&a.x, &beta) - b.y.Neg(&a.y) - b.z.Set(&a.z) - require.Equal(t, 1, b.IsOnCurve()) - - c.Add(a, b) - - e.x.Set(&fp2{ - A: fp{ - 0x705abc799ca773d3, - 0xfe132292c1d4bf08, - 0xf37ece3e07b2b466, - 0x887e1c43f447e301, - 0x1e0970d033bc77e8, - 0x1985c81e20a693f2, - }, - B: fp{ - 0x1d79b25db36ab924, - 0x23948e4d529639d3, - 0x471ba7fb0d006297, - 0x2c36d4b4465dc4c0, - 0x82bbc3cfec67f538, - 0x051d2728b67bf952, - }, - }) - e.y.Set(&fp2{ - A: fp{ - 0x41b1bbf6576c0abf, - 0xb6cc93713f7a0f9a, - 0x6b65b43e48f3f01f, - 0xfb7a4cfcaf81be4f, - 0x3e32dadc6ec22cb6, - 0x0bb0fc49d79807e3, - }, - B: fp{ - 0x7d1397788f5f2ddf, - 0xab2907144ff0d8e8, - 0x5b7573e0cdb91f92, - 0x4cb8932dd31daf28, - 0x62bbfac6db052a54, - 0x11f95c16d14c3bbe, - }, - }) - e.z.SetOne() - require.Equal(t, 1, e.Equal(c)) -} - -func TestG2Neg(t *testing.T) { - a := new(G2).Generator() - b := new(G2).Neg(a) - require.Equal(t, 1, new(G2).Add(a, b).IsIdentity()) - require.Equal(t, 1, new(G2).Sub(a, b.Neg(b)).IsIdentity()) - a.Identity() - require.Equal(t, 1, a.Neg(a).IsIdentity()) -} - -func TestG2Mul(t *testing.T) { - g := new(G2).Generator() - a := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{ - 0x2b56_8297_a56d_a71c, - 0xd8c3_9ecb_0ef3_75d1, - 0x435c_38da_67bf_bf96, - 0x8088_a050_26b6_59b2, - }) - b := Bls12381FqNew().SetRaw(&[native.FieldLimbs]uint64{ - 0x785f_dd9b_26ef_8b85, - 0xc997_f258_3769_5c18, - 0x4c8d_bc39_e7b7_56c1, - 0x70d9_b6cc_6d87_df20, - }) - c := Bls12381FqNew().Mul(a, b) - - t1 := new(G2).Generator() - t1.Mul(t1, a) - t1.Mul(t1, b) - require.Equal(t, 1, t1.Equal(g.Mul(g, c))) -} - -func TestG2InCorrectSubgroup(t *testing.T) { - a := G2{ - x: fp2{ - A: fp{ - 0x89f550c813db6431, - 0xa50be8c456cd8a1a, - 0xa45b374114cae851, - 0xbb6190f5bf7fff63, - 0x970ca02c3ba80bc7, - 0x02b85d24e840fbac, - }, - B: fp{ - 0x6888bc53d70716dc, - 0x3dea6b4117682d70, - 0xd8f5f930500ca354, - 0x6b5ecb6556f5c155, - 0xc96bef0434778ab0, - 0x05081505515006ad, - }, - }, - y: fp2{ - A: fp{ - 0x3cf1ea0d434b0f40, - 0x1a0dc610e603e333, - 0x7f89956160c72fa0, - 0x25ee03decf6431c5, - 0xeee8e206ec0fe137, - 0x097592b226dfef28, - }, - B: fp{ - 0x71e8bb5f29247367, - 0xa5fe049e211831ce, - 0x0ce6b354502a3896, - 0x93b012000997314e, - 0x6759f3b6aa5b42ac, - 0x156944c4dfe92bbb, - }, - }, - z: *(&fp2{}).SetOne(), - } - require.Equal(t, 0, a.InCorrectSubgroup()) - - require.Equal(t, 1, new(G2).Identity().InCorrectSubgroup()) - require.Equal(t, 1, new(G2).Generator().InCorrectSubgroup()) -} - -func TestG2MulByX(t *testing.T) { - // multiplying by `x` a point in G2 is the same as multiplying by - // the equivalent scalar. - x := Bls12381FqNew().SetUint64(paramX) - x.Neg(x) - t1 := new(G2).Generator() - t1.MulByX(t1) - t2 := new(G2).Generator() - t2.Mul(t2, x) - require.Equal(t, 1, t1.Equal(t2)) - - point := new(G2).Generator() - a := Bls12381FqNew().SetUint64(42) - point.Mul(point, a) - - t1.MulByX(point) - t2.Mul(point, x) - require.Equal(t, 1, t1.Equal(t2)) -} - -func TestG2Psi(t *testing.T) { - generator := new(G2).Generator() - - z := fp2{ - A: fp{ - 0x0ef2ddffab187c0a, - 0x2424522b7d5ecbfc, - 0xc6f341a3398054f4, - 0x5523ddf409502df0, - 0xd55c0b5a88e0dd97, - 0x066428d704923e52, - }, - B: fp{ - 0x538bbe0c95b4878d, - 0xad04a50379522881, - 0x6d5c05bf5c12fb64, - 0x4ce4a069a2d34787, - 0x59ea6c8d0dffaeaf, - 0x0d42a083a75bd6f3, - }, - } - - // `point` is a random point in the curve - point := G2{ - x: fp2{ - A: fp{ - 0xee4c8cb7c047eaf2, - 0x44ca22eee036b604, - 0x33b3affb2aefe101, - 0x15d3e45bbafaeb02, - 0x7bfc2154cd7419a4, - 0x0a2d0c2b756e5edc, - }, - B: fp{ - 0xfc224361029a8777, - 0x4cbf2baab8740924, - 0xc5008c6ec6592c89, - 0xecc2c57b472a9c2d, - 0x8613eafd9d81ffb1, - 0x10fe54daa2d3d495, - }, - }, - y: fp2{ - A: fp{ - 0x7de7edc43953b75c, - 0x58be1d2de35e87dc, - 0x5731d30b0e337b40, - 0xbe93b60cfeaae4c9, - 0x8b22c203764bedca, - 0x01616c8d1033b771, - }, - B: fp{ - 0xea126fe476b5733b, - 0x85cee68b5dae1652, - 0x98247779f7272b04, - 0xa649c8b468c6e808, - 0xb5b9a62dff0c4e45, - 0x1555b67fc7bbe73d, - }, - }, - z: *(&fp2{}).Set(&z), - } - point.x.Mul(&point.x, &z) - point.z.Square(&point.z) - point.z.Mul(&point.z, &z) - require.Equal(t, 1, point.IsOnCurve()) - - // psi2(P) = psi(psi(P)) - tv1 := new(G2).psi2(generator) - tv2 := new(G2).psi(generator) - tv2.psi(tv2) - require.Equal(t, 1, tv1.Equal(tv2)) - - tv1.psi2(&point) - tv2.psi(&point) - tv2.psi(tv2) - require.Equal(t, 1, tv1.Equal(tv2)) - - // psi(P) is a morphism - tv1.Double(generator) - tv1.psi(tv1) - tv2.psi(generator) - tv2.Double(tv2) - require.Equal(t, 1, tv1.Equal(tv2)) - - tv1.psi(&point) - tv2.psi(generator) - tv1.Add(tv1, tv2) - - tv2.Set(&point) - tv3 := new(G2).Generator() - tv2.Add(tv2, tv3) - tv2.psi(tv2) - require.Equal(t, 1, tv1.Equal(tv2)) -} - -func TestG2ClearCofactor(t *testing.T) { - z := fp2{ - A: fp{ - 0x0ef2ddffab187c0a, - 0x2424522b7d5ecbfc, - 0xc6f341a3398054f4, - 0x5523ddf409502df0, - 0xd55c0b5a88e0dd97, - 0x066428d704923e52, - }, - B: fp{ - 0x538bbe0c95b4878d, - 0xad04a50379522881, - 0x6d5c05bf5c12fb64, - 0x4ce4a069a2d34787, - 0x59ea6c8d0dffaeaf, - 0x0d42a083a75bd6f3, - }, - } - - // `point` is a random point in the curve - point := G2{ - x: fp2{ - A: fp{ - 0xee4c8cb7c047eaf2, - 0x44ca22eee036b604, - 0x33b3affb2aefe101, - 0x15d3e45bbafaeb02, - 0x7bfc2154cd7419a4, - 0x0a2d0c2b756e5edc, - }, - B: fp{ - 0xfc224361029a8777, - 0x4cbf2baab8740924, - 0xc5008c6ec6592c89, - 0xecc2c57b472a9c2d, - 0x8613eafd9d81ffb1, - 0x10fe54daa2d3d495, - }, - }, - y: fp2{ - A: fp{ - 0x7de7edc43953b75c, - 0x58be1d2de35e87dc, - 0x5731d30b0e337b40, - 0xbe93b60cfeaae4c9, - 0x8b22c203764bedca, - 0x01616c8d1033b771, - }, - B: fp{ - 0xea126fe476b5733b, - 0x85cee68b5dae1652, - 0x98247779f7272b04, - 0xa649c8b468c6e808, - 0xb5b9a62dff0c4e45, - 0x1555b67fc7bbe73d, - }, - }, - z: fp2{}, - } - point.x.Mul(&point.x, &z) - point.z.Square(&z) - point.z.Mul(&point.z, &z) - - require.Equal(t, 1, point.IsOnCurve()) - require.Equal(t, 0, point.InCorrectSubgroup()) - - clearedPoint := new(G2).ClearCofactor(&point) - - require.Equal(t, 1, clearedPoint.IsOnCurve()) - require.Equal(t, 1, clearedPoint.InCorrectSubgroup()) - - // the generator (and the identity) are always on the curve, - // even after clearing the cofactor - generator := new(G2).Generator() - generator.ClearCofactor(generator) - require.Equal(t, 1, generator.InCorrectSubgroup()) - id := new(G2).Identity() - id.ClearCofactor(id) - require.Equal(t, 1, id.InCorrectSubgroup()) - - // test the effect on q-torsion points multiplying by h_eff modulo q - // h_eff % q = 0x2b116900400069009a40200040001ffff - hEffModq := [native.FieldBytes]byte{ - 0xff, 0xff, 0x01, 0x00, 0x04, 0x00, 0x02, 0xa4, 0x09, 0x90, 0x06, 0x00, 0x04, 0x90, 0x16, - 0xb1, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, - } - generator.Generator() - generator.multiply(generator, &hEffModq) - point.Generator().ClearCofactor(&point) - require.Equal(t, 1, point.Equal(generator)) - point.ClearCofactor(clearedPoint) - require.Equal(t, 1, point.Equal(clearedPoint.multiply(clearedPoint, &hEffModq))) -} - -func TestG2Hash(t *testing.T) { - dst := []byte("QUUX-V01-CS02-with-BLS12381G2_XMD:SHA-256_SSWU_RO_") - - tests := []struct { - input, expected string - }{ - { - "", - "05cb8437535e20ecffaef7752baddf98034139c38452458baeefab379ba13dff5bf5dd71b72418717047f5b0f37da03d0141ebfbdca40eb85b87142e130ab689c673cf60f1a3e98d69335266f30d9b8d4ac44c1038e9dcdd5393faf5c41fb78a12424ac32561493f3fe3c260708a12b7c620e7be00099a974e259ddc7d1f6395c3c811cdd19f1e8dbf3e9ecfdcbab8d60503921d7f6a12805e72940b963c0cf3471c7b2a524950ca195d11062ee75ec076daf2d4bc358c4b190c0c98064fdd92", - }, - { - "abc", - "139cddbccdc5e91b9623efd38c49f81a6f83f175e80b06fc374de9eb4b41dfe4ca3a230ed250fbe3a2acf73a41177fd802c2d18e033b960562aae3cab37a27ce00d80ccd5ba4b7fe0e7a210245129dbec7780ccc7954725f4168aff2787776e600aa65dae3c8d732d10ecd2c50f8a1baf3001578f71c694e03866e9f3d49ac1e1ce70dd94a733534f106d4cec0eddd161787327b68159716a37440985269cf584bcb1e621d3a7202be6ea05c4cfe244aeb197642555a0645fb87bf7466b2ba48", - }, - { - "abcdef0123456789", - "190d119345b94fbd15497bcba94ecf7db2cbfd1e1fe7da034d26cbba169fb3968288b3fafb265f9ebd380512a71c3f2c121982811d2491fde9ba7ed31ef9ca474f0e1501297f68c298e9f4c0028add35aea8bb83d53c08cfc007c1e005723cd00bb5e7572275c567462d91807de765611490205a941a5a6af3b1691bfe596c31225d3aabdf15faff860cb4ef17c7c3be05571a0f8d3c08d094576981f4a3b8eda0a8e771fcdcc8ecceaf1356a6acf17574518acb506e435b639353c2e14827c8", - }, - { - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - "0934aba516a52d8ae479939a91998299c76d39cc0c035cd18813bec433f587e2d7a4fef038260eef0cef4d02aae3eb9119a84dd7248a1066f737cc34502ee5555bd3c19f2ecdb3c7d9e24dc65d4e25e50d83f0f77105e955d78f4762d33c17da09bcccfa036b4847c9950780733633f13619994394c23ff0b32fa6b795844f4a0673e20282d07bc69641cee04f5e566214f81cd421617428bc3b9fe25afbb751d934a00493524bc4e065635b0555084dd54679df1536101b2c979c0152d09192", - }, - { - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "11fca2ff525572795a801eed17eb12785887c7b63fb77a42be46ce4a34131d71f7a73e95fee3f812aea3de78b4d0156901a6ba2f9a11fa5598b2d8ace0fbe0a0eacb65deceb476fbbcb64fd24557c2f4b18ecfc5663e54ae16a84f5ab7f6253403a47f8e6d1763ba0cad63d6114c0accbef65707825a511b251a660a9b3994249ae4e63fac38b23da0c398689ee2ab520b6798718c8aed24bc19cb27f866f1c9effcdbf92397ad6448b5c9db90d2b9da6cbabf48adc1adf59a1a28344e79d57e", - }, - } - - pt := new(G2).Identity() - ept := new(G2).Identity() - var b [DoubleWideFieldBytes]byte - for _, tst := range tests { - i := []byte(tst.input) - e, _ := hex.DecodeString(tst.expected) - copy(b[:], e) - _, _ = ept.FromUncompressed(&b) - pt.Hash(native.EllipticPointHasherSha256(), i, dst) - require.Equal(t, 1, pt.Equal(ept)) - } -} - -func TestG2SumOfProducts(t *testing.T) { - var b [64]byte - h0, _ := new(G2).Random(crand.Reader) - _, _ = crand.Read(b[:]) - s := Bls12381FqNew().SetBytesWide(&b) - _, _ = crand.Read(b[:]) - sTilde := Bls12381FqNew().SetBytesWide(&b) - _, _ = crand.Read(b[:]) - c := Bls12381FqNew().SetBytesWide(&b) - - lhs := new(G2).Mul(h0, s) - rhs, _ := new(G2).SumOfProducts([]*G2{h0}, []*native.Field{s}) - require.Equal(t, 1, lhs.Equal(rhs)) - - u := new(G2).Mul(h0, s) - uTilde := new(G2).Mul(h0, sTilde) - sHat := Bls12381FqNew().Mul(c, s) - sHat.Sub(sTilde, sHat) - - rhs.Mul(u, c) - rhs.Add(rhs, new(G2).Mul(h0, sHat)) - require.Equal(t, 1, uTilde.Equal(rhs)) - _, _ = rhs.SumOfProducts([]*G2{u, h0}, []*native.Field{c, sHat}) - require.Equal(t, 1, uTilde.Equal(rhs)) -} diff --git a/crypto/core/curves/native/bls12381/gt.go b/crypto/core/curves/native/bls12381/gt.go deleted file mode 100644 index 16ecc5dc2..000000000 --- a/crypto/core/curves/native/bls12381/gt.go +++ /dev/null @@ -1,434 +0,0 @@ -package bls12381 - -import ( - "io" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -// GtFieldBytes is the number of bytes needed to represent this field -const GtFieldBytes = 576 - -// Gt is the target group -type Gt fp12 - -// Random generates a random field element -func (gt *Gt) Random(reader io.Reader) (*Gt, error) { - _, err := (*fp12)(gt).Random(reader) - return gt, err -} - -// FinalExponentiation performs a "final exponentiation" routine to convert the result -// of a Miller loop into an element of `Gt` with help of efficient squaring -// operation in the so-called `cyclotomic subgroup` of `Fq6` so that -// it can be compared with other elements of `Gt`. -func (gt *Gt) FinalExponentiation(a *Gt) *Gt { - var t0, t1, t2, t3, t4, t5, t6, t fp12 - t0.FrobeniusMap((*fp12)(a)) - t0.FrobeniusMap(&t0) - t0.FrobeniusMap(&t0) - t0.FrobeniusMap(&t0) - t0.FrobeniusMap(&t0) - t0.FrobeniusMap(&t0) - - // Shouldn't happen since we enforce `a` to be non-zero but just in case - _, wasInverted := t1.Invert((*fp12)(a)) - t2.Mul(&t0, &t1) - t1.Set(&t2) - t2.FrobeniusMap(&t2) - t2.FrobeniusMap(&t2) - t2.Mul(&t2, &t1) - t1.cyclotomicSquare(&t2) - t1.Conjugate(&t1) - - t3.cyclotomicExp(&t2) - t4.cyclotomicSquare(&t3) - t5.Mul(&t1, &t3) - t1.cyclotomicExp(&t5) - t0.cyclotomicExp(&t1) - t6.cyclotomicExp(&t0) - t6.Mul(&t6, &t4) - t4.cyclotomicExp(&t6) - t5.Conjugate(&t5) - t4.Mul(&t4, &t5) - t4.Mul(&t4, &t2) - t5.Conjugate(&t2) - t1.Mul(&t1, &t2) - t1.FrobeniusMap(&t1) - t1.FrobeniusMap(&t1) - t1.FrobeniusMap(&t1) - t6.Mul(&t6, &t5) - t6.FrobeniusMap(&t6) - t3.Mul(&t3, &t0) - t3.FrobeniusMap(&t3) - t3.FrobeniusMap(&t3) - t3.Mul(&t3, &t1) - t3.Mul(&t3, &t6) - t.Mul(&t3, &t4) - (*fp12)(gt).CMove((*fp12)(gt), &t, wasInverted) - return gt -} - -// IsZero returns 1 if gt == 0, 0 otherwise -func (gt *Gt) IsZero() int { - return (*fp12)(gt).IsZero() -} - -// IsOne returns 1 if gt == 1, 0 otherwise -func (gt *Gt) IsOne() int { - return (*fp12)(gt).IsOne() -} - -// SetOne gt = one -func (gt *Gt) SetOne() *Gt { - (*fp12)(gt).SetOne() - return gt -} - -// Set copies a into gt -func (gt *Gt) Set(a *Gt) *Gt { - gt.A.Set(&a.A) - gt.B.Set(&a.B) - return gt -} - -// Bytes returns the Gt field byte representation -func (gt *Gt) Bytes() [GtFieldBytes]byte { - var out [GtFieldBytes]byte - t := gt.A.A.A.Bytes() - copy(out[:FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.A.A.B.Bytes() - copy(out[FieldBytes:2*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.A.B.A.Bytes() - copy(out[2*FieldBytes:3*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.A.B.B.Bytes() - copy(out[3*FieldBytes:4*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.A.C.A.Bytes() - copy(out[4*FieldBytes:5*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.A.C.B.Bytes() - copy(out[5*FieldBytes:6*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.A.A.Bytes() - copy(out[6*FieldBytes:7*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.A.B.Bytes() - copy(out[7*FieldBytes:8*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.B.A.Bytes() - copy(out[8*FieldBytes:9*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.B.B.Bytes() - copy(out[9*FieldBytes:10*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.C.A.Bytes() - copy(out[10*FieldBytes:11*FieldBytes], internal.ReverseScalarBytes(t[:])) - t = gt.B.C.B.Bytes() - copy(out[11*FieldBytes:12*FieldBytes], internal.ReverseScalarBytes(t[:])) - - return out -} - -// SetBytes attempts to convert a big-endian byte representation of -// a scalar into a `Gt`, failing if the input is not canonical. -func (gt *Gt) SetBytes(input *[GtFieldBytes]byte) (*Gt, int) { - var t [FieldBytes]byte - var valid [12]int - copy(t[:], internal.ReverseScalarBytes(input[:FieldBytes])) - _, valid[0] = gt.A.A.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[FieldBytes:2*FieldBytes])) - _, valid[1] = gt.A.A.B.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[2*FieldBytes:3*FieldBytes])) - _, valid[2] = gt.A.B.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[3*FieldBytes:4*FieldBytes])) - _, valid[3] = gt.A.B.B.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[4*FieldBytes:5*FieldBytes])) - _, valid[4] = gt.A.C.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[5*FieldBytes:6*FieldBytes])) - _, valid[5] = gt.A.C.B.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[6*FieldBytes:7*FieldBytes])) - _, valid[6] = gt.B.A.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[7*FieldBytes:8*FieldBytes])) - _, valid[7] = gt.B.A.B.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[8*FieldBytes:9*FieldBytes])) - _, valid[8] = gt.B.B.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[9*FieldBytes:10*FieldBytes])) - _, valid[9] = gt.B.B.B.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[10*FieldBytes:11*FieldBytes])) - _, valid[10] = gt.B.C.A.SetBytes(&t) - copy(t[:], internal.ReverseScalarBytes(input[11*FieldBytes:12*FieldBytes])) - _, valid[11] = gt.B.C.B.SetBytes(&t) - - return gt, valid[0] & valid[1] & - valid[2] & valid[3] & - valid[4] & valid[5] & - valid[6] & valid[7] & - valid[8] & valid[9] & - valid[10] & valid[11] -} - -// Equal returns 1 if gt == rhs, 0 otherwise -func (gt *Gt) Equal(rhs *Gt) int { - return (*fp12)(gt).Equal((*fp12)(rhs)) -} - -// Generator returns the base point -func (gt *Gt) Generator() *Gt { - // pairing(&G1::generator(), &G2::generator()) - gt.Set((*Gt)(&fp12{ - A: fp6{ - A: fp2{ - A: fp{ - 0x1972e433a01f85c5, - 0x97d32b76fd772538, - 0xc8ce546fc96bcdf9, - 0xcef63e7366d40614, - 0xa611342781843780, - 0x13f3448a3fc6d825, - }, - B: fp{ - 0xd26331b02e9d6995, - 0x9d68a482f7797e7d, - 0x9c9b29248d39ea92, - 0xf4801ca2e13107aa, - 0xa16c0732bdbcb066, - 0x083ca4afba360478, - }, - }, - B: fp2{ - A: fp{ - 0x59e261db0916b641, - 0x2716b6f4b23e960d, - 0xc8e55b10a0bd9c45, - 0x0bdb0bd99c4deda8, - 0x8cf89ebf57fdaac5, - 0x12d6b7929e777a5e, - }, - B: fp{ - 0x5fc85188b0e15f35, - 0x34a06e3a8f096365, - 0xdb3126a6e02ad62c, - 0xfc6f5aa97d9a990b, - 0xa12f55f5eb89c210, - 0x1723703a926f8889, - }, - }, - C: fp2{ - A: fp{ - 0x93588f2971828778, - 0x43f65b8611ab7585, - 0x3183aaf5ec279fdf, - 0xfa73d7e18ac99df6, - 0x64e176a6a64c99b0, - 0x179fa78c58388f1f, - }, - B: fp{ - 0x672a0a11ca2aef12, - 0x0d11b9b52aa3f16b, - 0xa44412d0699d056e, - 0xc01d0177221a5ba5, - 0x66e0cede6c735529, - 0x05f5a71e9fddc339, - }, - }, - }, - B: fp6{ - A: fp2{ - A: fp{ - 0xd30a88a1b062c679, - 0x5ac56a5d35fc8304, - 0xd0c834a6a81f290d, - 0xcd5430c2da3707c7, - 0xf0c27ff780500af0, - 0x09245da6e2d72eae, - }, - B: fp{ - 0x9f2e0676791b5156, - 0xe2d1c8234918fe13, - 0x4c9e459f3c561bf4, - 0xa3e85e53b9d3e3c1, - 0x820a121e21a70020, - 0x15af618341c59acc, - }, - }, - B: fp2{ - A: fp{ - 0x7c95658c24993ab1, - 0x73eb38721ca886b9, - 0x5256d749477434bc, - 0x8ba41902ea504a8b, - 0x04a3d3f80c86ce6d, - 0x18a64a87fb686eaa, - }, - B: fp{ - 0xbb83e71bb920cf26, - 0x2a5277ac92a73945, - 0xfc0ee59f94f046a0, - 0x7158cdf3786058f7, - 0x7cc1061b82f945f6, - 0x03f847aa9fdbe567, - }, - }, - C: fp2{ - A: fp{ - 0x8078dba56134e657, - 0x1cd7ec9a43998a6e, - 0xb1aa599a1a993766, - 0xc9a0f62f0842ee44, - 0x8e159be3b605dffa, - 0x0c86ba0d4af13fc2, - }, - B: fp{ - 0xe80ff2a06a52ffb1, - 0x7694ca48721a906c, - 0x7583183e03b08514, - 0xf567afdd40cee4e2, - 0x9a6d96d2e526a5fc, - 0x197e9f49861f2242, - }, - }, - }, - })) - return gt -} - -// Add adds this value to another value. -func (gt *Gt) Add(arg1, arg2 *Gt) *Gt { - (*fp12)(gt).Mul((*fp12)(arg1), (*fp12)(arg2)) - return gt -} - -// Double this value -func (gt *Gt) Double(a *Gt) *Gt { - (*fp12)(gt).Square((*fp12)(a)) - return gt -} - -// Sub subtracts the two values -func (gt *Gt) Sub(arg1, arg2 *Gt) *Gt { - var t fp12 - t.Conjugate((*fp12)(arg2)) - (*fp12)(gt).Mul((*fp12)(arg1), &t) - return gt -} - -// Neg negates this value -func (gt *Gt) Neg(a *Gt) *Gt { - (*fp12)(gt).Conjugate((*fp12)(a)) - return gt -} - -// Mul multiplies this value by the input scalar -func (gt *Gt) Mul(a *Gt, s *native.Field) *Gt { - var f, p fp12 - f.Set((*fp12)(a)) - bytes := s.Bytes() - - precomputed := [16]fp12{} - precomputed[1].Set(&f) - for i := 2; i < 16; i += 2 { - precomputed[i].Square(&precomputed[i>>1]) - precomputed[i+1].Mul(&precomputed[i], &f) - } - for i := 0; i < 256; i += 4 { - // Brouwer / windowing method. window size of 4. - for j := 0; j < 4; j++ { - p.Square(&p) - } - window := bytes[32-1-i>>3] >> (4 - i&0x04) & 0x0F - p.Mul(&p, &precomputed[window]) - } - (*fp12)(gt).Set(&p) - return gt -} - -// Square this value -func (gt *Gt) Square(a *Gt) *Gt { - (*fp12)(gt).cyclotomicSquare((*fp12)(a)) - return gt -} - -// Invert this value -func (gt *Gt) Invert(a *Gt) (*Gt, int) { - _, wasInverted := (*fp12)(gt).Invert((*fp12)(a)) - return gt, wasInverted -} - -func fp4Square(a, b, arg1, arg2 *fp2) { - var t0, t1, t2 fp2 - - t0.Square(arg1) - t1.Square(arg2) - t2.MulByNonResidue(&t1) - a.Add(&t2, &t0) - t2.Add(arg1, arg2) - t2.Square(&t2) - t2.Sub(&t2, &t0) - b.Sub(&t2, &t1) -} - -func (f *fp12) cyclotomicSquare(a *fp12) *fp12 { - // Adaptation of Algorithm 5.5.4, Guide to Pairing-Based Cryptography - // Faster Squaring in the Cyclotomic Subgroup of Sixth Degree Extensions - // https://eprint.iacr.org/2009/565.pdf - var z0, z1, z2, z3, z4, z5, t0, t1, t2, t3 fp2 - z0.Set(&a.A.A) - z4.Set(&a.A.B) - z3.Set(&a.A.C) - z2.Set(&a.B.A) - z1.Set(&a.B.B) - z5.Set(&a.B.C) - - fp4Square(&t0, &t1, &z0, &z1) - z0.Sub(&t0, &z0) - z0.Double(&z0) - z0.Add(&z0, &t0) - - z1.Add(&t1, &z1) - z1.Double(&z1) - z1.Add(&z1, &t1) - - fp4Square(&t0, &t1, &z2, &z3) - fp4Square(&t2, &t3, &z4, &z5) - - z4.Sub(&t0, &z4) - z4.Double(&z4) - z4.Add(&z4, &t0) - - z5.Add(&z5, &t1) - z5.Double(&z5) - z5.Add(&z5, &t1) - - t0.MulByNonResidue(&t3) - z2.Add(&z2, &t0) - z2.Double(&z2) - z2.Add(&z2, &t0) - - z3.Sub(&t2, &z3) - z3.Double(&z3) - z3.Add(&z3, &t2) - - f.A.A.Set(&z0) - f.A.B.Set(&z4) - f.A.C.Set(&z3) - - f.B.A.Set(&z2) - f.B.B.Set(&z1) - f.B.C.Set(&z5) - return f -} - -func (f *fp12) cyclotomicExp(a *fp12) *fp12 { - var t fp12 - t.SetOne() - foundOne := 0 - - for i := 63; i >= 0; i-- { - b := int((paramX >> i) & 1) - if foundOne == 1 { - t.cyclotomicSquare(&t) - } else { - foundOne = b - } - if b == 1 { - t.Mul(&t, a) - } - } - f.Conjugate(&t) - return f -} diff --git a/crypto/core/curves/native/bls12381/pairings.go b/crypto/core/curves/native/bls12381/pairings.go deleted file mode 100755 index c01ef092a..000000000 --- a/crypto/core/curves/native/bls12381/pairings.go +++ /dev/null @@ -1,254 +0,0 @@ -package bls12381 - -const coefficientsG2 = 68 - -type Engine struct { - pairs []pair -} - -type pair struct { - g1 G1 - g2 G2 -} - -type g2Prepared struct { - identity int - coefficients []coefficients -} - -type coefficients struct { - a, b, c fp2 -} - -func (c *coefficients) CMove(arg1, arg2 *coefficients, choice int) *coefficients { - c.a.CMove(&arg1.a, &arg2.a, choice) - c.b.CMove(&arg1.b, &arg2.b, choice) - c.c.CMove(&arg1.c, &arg2.c, choice) - return c -} - -// AddPair adds a pair of points to be paired -func (e *Engine) AddPair(g1 *G1, g2 *G2) *Engine { - var p pair - p.g1.ToAffine(g1) - p.g2.ToAffine(g2) - if p.g1.IsIdentity()|p.g2.IsIdentity() == 0 { - e.pairs = append(e.pairs, p) - } - return e -} - -// AddPairInvG1 adds a pair of points to be paired. G1 point is negated -func (e *Engine) AddPairInvG1(g1 *G1, g2 *G2) *Engine { - var p G1 - p.Neg(g1) - return e.AddPair(&p, g2) -} - -// AddPairInvG2 adds a pair of points to be paired. G2 point is negated -func (e *Engine) AddPairInvG2(g1 *G1, g2 *G2) *Engine { - var p G2 - p.Neg(g2) - return e.AddPair(g1, &p) -} - -func (e *Engine) Reset() *Engine { - e.pairs = []pair{} - return e -} - -func (e *Engine) Check() bool { - return e.pairing().IsOne() == 1 -} - -func (e *Engine) Result() *Gt { - return e.pairing() -} - -func (e *Engine) pairing() *Gt { - f := new(Gt).SetOne() - if len(e.pairs) == 0 { - return f - } - coeffs := e.computeCoeffs() - e.millerLoop((*fp12)(f), coeffs) - return f.FinalExponentiation(f) -} - -func (e *Engine) millerLoop(f *fp12, coeffs []g2Prepared) { - newF := new(fp12).SetZero() - found := 0 - cIdx := 0 - for i := 63; i >= 0; i-- { - x := int(((paramX >> 1) >> i) & 1) - if found == 0 { - found |= x - continue - } - - // doubling - for j, terms := range coeffs { - identity := e.pairs[j].g1.IsIdentity() | terms.identity - newF.Set(f) - ell(newF, terms.coefficients[cIdx], &e.pairs[j].g1) - f.CMove(newF, f, identity) - } - cIdx++ - - if x == 1 { - // adding - for j, terms := range coeffs { - identity := e.pairs[j].g1.IsIdentity() | terms.identity - newF.Set(f) - ell(newF, terms.coefficients[cIdx], &e.pairs[j].g1) - f.CMove(newF, f, identity) - } - cIdx++ - } - f.Square(f) - } - for j, terms := range coeffs { - identity := e.pairs[j].g1.IsIdentity() | terms.identity - newF.Set(f) - ell(newF, terms.coefficients[cIdx], &e.pairs[j].g1) - f.CMove(newF, f, identity) - } - f.Conjugate(f) -} - -func (e *Engine) computeCoeffs() []g2Prepared { - coeffs := make([]g2Prepared, len(e.pairs)) - for i, p := range e.pairs { - identity := p.g2.IsIdentity() - q := new(G2).Generator() - q.CMove(&p.g2, q, identity) - c := new(G2).Set(q) - cfs := make([]coefficients, coefficientsG2) - found := 0 - k := 0 - - for j := 63; j >= 0; j-- { - x := int(((paramX >> 1) >> j) & 1) - if found == 0 { - found |= x - continue - } - cfs[k] = doublingStep(c) - k++ - - if x == 1 { - cfs[k] = additionStep(c, q) - k++ - } - } - cfs[k] = doublingStep(c) - coeffs[i] = g2Prepared{ - coefficients: cfs, identity: identity, - } - } - return coeffs -} - -func ell(f *fp12, coeffs coefficients, p *G1) { - var x, y fp2 - x.A.Mul(&coeffs.a.A, &p.y) - x.B.Mul(&coeffs.a.B, &p.y) - y.A.Mul(&coeffs.b.A, &p.x) - y.B.Mul(&coeffs.b.B, &p.x) - f.MulByABD(f, &coeffs.c, &y, &x) -} - -func doublingStep(p *G2) coefficients { - // Adaptation of Algorithm 26, https://eprint.iacr.org/2010/354.pdf - var t0, t1, t2, t3, t4, t5, t6, zsqr fp2 - t0.Square(&p.x) - t1.Square(&p.y) - t2.Square(&t1) - t3.Add(&t1, &p.x) - t3.Square(&t3) - t3.Sub(&t3, &t0) - t3.Sub(&t3, &t2) - t3.Double(&t3) - t4.Double(&t0) - t4.Add(&t4, &t0) - t6.Add(&p.x, &t4) - t5.Square(&t4) - zsqr.Square(&p.z) - p.x.Sub(&t5, &t3) - p.x.Sub(&p.x, &t3) - p.z.Add(&p.z, &p.y) - p.z.Square(&p.z) - p.z.Sub(&p.z, &t1) - p.z.Sub(&p.z, &zsqr) - p.y.Sub(&t3, &p.x) - p.y.Mul(&p.y, &t4) - t2.Double(&t2) - t2.Double(&t2) - t2.Double(&t2) - p.y.Sub(&p.y, &t2) - t3.Mul(&t4, &zsqr) - t3.Double(&t3) - t3.Neg(&t3) - t6.Square(&t6) - t6.Sub(&t6, &t0) - t6.Sub(&t6, &t5) - t1.Double(&t1) - t1.Double(&t1) - t6.Sub(&t6, &t1) - t0.Mul(&p.z, &zsqr) - t0.Double(&t0) - - return coefficients{ - a: t0, b: t3, c: t6, - } -} - -func additionStep(r, q *G2) coefficients { - // Adaptation of Algorithm 27, https://eprint.iacr.org/2010/354.pdf - var zsqr, ysqr fp2 - var t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10 fp2 - zsqr.Square(&r.z) - ysqr.Square(&q.y) - t0.Mul(&zsqr, &q.x) - t1.Add(&q.y, &r.z) - t1.Square(&t1) - t1.Sub(&t1, &ysqr) - t1.Sub(&t1, &zsqr) - t1.Mul(&t1, &zsqr) - t2.Sub(&t0, &r.x) - t3.Square(&t2) - t4.Double(&t3) - t4.Double(&t4) - t5.Mul(&t4, &t2) - t6.Sub(&t1, &r.y) - t6.Sub(&t6, &r.y) - t9.Mul(&t6, &q.x) - t7.Mul(&t4, &r.x) - r.x.Square(&t6) - r.x.Sub(&r.x, &t5) - r.x.Sub(&r.x, &t7) - r.x.Sub(&r.x, &t7) - r.z.Add(&r.z, &t2) - r.z.Square(&r.z) - r.z.Sub(&r.z, &zsqr) - r.z.Sub(&r.z, &t3) - t10.Add(&q.y, &r.z) - t8.Sub(&t7, &r.x) - t8.Mul(&t8, &t6) - t0.Mul(&r.y, &t5) - t0.Double(&t0) - r.y.Sub(&t8, &t0) - t10.Square(&t10) - t10.Sub(&t10, &ysqr) - zsqr.Square(&r.z) - t10.Sub(&t10, &zsqr) - t9.Double(&t9) - t9.Sub(&t9, &t10) - t10.Double(&r.z) - t6.Neg(&t6) - t1.Double(&t6) - - return coefficients{ - a: t10, b: t1, c: t9, - } -} diff --git a/crypto/core/curves/native/bls12381/pairings_test.go b/crypto/core/curves/native/bls12381/pairings_test.go deleted file mode 100644 index 07e80289c..000000000 --- a/crypto/core/curves/native/bls12381/pairings_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package bls12381 - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -func TestSinglePairing(t *testing.T) { - g := new(G1).Generator() - h := new(G2).Generator() - - e := new(Engine) - e.AddPair(g, h) - p := e.Result() - p.Neg(p) - - e.Reset() - e.AddPairInvG2(g, h) - q := e.Result() - e.Reset() - e.AddPairInvG1(g, h) - r := e.Result() - - require.Equal(t, 1, p.Equal(q)) - require.Equal(t, 1, q.Equal(r)) -} - -func TestMultiPairing(t *testing.T) { - const Tests = 10 - e1 := new(Engine) - e2 := new(Engine) - - g1s := make([]*G1, Tests) - g2s := make([]*G2, Tests) - sc := make([]*native.Field, Tests) - res := make([]*Gt, Tests) - expected := new(Gt).SetOne() - - for i := 0; i < Tests; i++ { - var bytes [64]byte - g1s[i] = new(G1).Generator() - g2s[i] = new(G2).Generator() - sc[i] = Bls12381FqNew() - _, _ = crand.Read(bytes[:]) - sc[i].SetBytesWide(&bytes) - if i&1 == 0 { - g1s[i].Mul(g1s[i], sc[i]) - } else { - g2s[i].Mul(g2s[i], sc[i]) - } - e1.AddPair(g1s[i], g2s[i]) - e2.AddPair(g1s[i], g2s[i]) - res[i] = e1.Result() - e1.Reset() - expected.Add(expected, res[i]) - } - - actual := e2.Result() - require.Equal(t, 1, expected.Equal(actual)) -} diff --git a/crypto/core/curves/native/field.go b/crypto/core/curves/native/field.go deleted file mode 100644 index 4a2f29f5a..000000000 --- a/crypto/core/curves/native/field.go +++ /dev/null @@ -1,388 +0,0 @@ -package native - -import ( - "encoding/binary" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/internal" -) - -// FieldLimbs is the number of limbs needed to represent this field -const FieldLimbs = 4 - -// FieldBytes is the number of bytes needed to represent this field -const FieldBytes = 32 - -// WideFieldBytes is the number of bytes needed for safe conversion -// to this field to avoid bias when reduced -const WideFieldBytes = 64 - -// Field represents a field element -type Field struct { - // Value is the field elements value - Value [FieldLimbs]uint64 - // Params are the field parameters - Params *FieldParams - // Arithmetic are the field methods - Arithmetic FieldArithmetic -} - -// FieldParams are the field parameters -type FieldParams struct { - // R is 2^256 mod Modulus - R [FieldLimbs]uint64 - // R2 is 2^512 mod Modulus - R2 [FieldLimbs]uint64 - // R3 is 2^768 mod Modulus - R3 [FieldLimbs]uint64 - // Modulus of the field - Modulus [FieldLimbs]uint64 - // Modulus as big.Int - BiModulus *big.Int -} - -// FieldArithmetic are the methods that can be done on a field -type FieldArithmetic interface { - // ToMontgomery converts this field to montgomery form - ToMontgomery(out, arg *[FieldLimbs]uint64) - // FromMontgomery converts this field from montgomery form - FromMontgomery(out, arg *[FieldLimbs]uint64) - // Neg performs modular negation - Neg(out, arg *[FieldLimbs]uint64) - // Square performs modular square - Square(out, arg *[FieldLimbs]uint64) - // Mul performs modular multiplication - Mul(out, arg1, arg2 *[FieldLimbs]uint64) - // Add performs modular addition - Add(out, arg1, arg2 *[FieldLimbs]uint64) - // Sub performs modular subtraction - Sub(out, arg1, arg2 *[FieldLimbs]uint64) - // Sqrt performs modular square root - Sqrt(wasSquare *int, out, arg *[FieldLimbs]uint64) - // Invert performs modular inverse - Invert(wasInverted *int, out, arg *[FieldLimbs]uint64) - // FromBytes converts a little endian byte array into a field element - FromBytes(out *[FieldLimbs]uint64, arg *[FieldBytes]byte) - // ToBytes converts a field element to a little endian byte array - ToBytes(out *[FieldBytes]byte, arg *[FieldLimbs]uint64) - // Selectznz performs conditional select. - // selects arg1 if choice == 0 and arg2 if choice == 1 - Selectznz(out, arg1, arg2 *[FieldLimbs]uint64, choice int) -} - -// Cmp returns -1 if f < rhs -// 0 if f == rhs -// 1 if f > rhs -func (f *Field) Cmp(rhs *Field) int { - return cmpHelper(&f.Value, &rhs.Value) -} - -// cmpHelper returns -1 if lhs < rhs -// -1 if lhs == rhs -// 1 if lhs > rhs -// Public only for convenience for some internal implementations -func cmpHelper(lhs, rhs *[FieldLimbs]uint64) int { - gt := uint64(0) - lt := uint64(0) - for i := 3; i >= 0; i-- { - // convert to two 64-bit numbers where - // the leading bits are zeros and hold no meaning - // so rhs - fp actually means gt - // and fp - rhs actually means lt. - rhsH := rhs[i] >> 32 - rhsL := rhs[i] & 0xffffffff - lhsH := lhs[i] >> 32 - lhsL := lhs[i] & 0xffffffff - - // Check the leading bit - // if negative then fp > rhs - // if positive then fp < rhs - gt |= (rhsH - lhsH) >> 32 & 1 &^ lt - lt |= (lhsH - rhsH) >> 32 & 1 &^ gt - gt |= (rhsL - lhsL) >> 32 & 1 &^ lt - lt |= (lhsL - rhsL) >> 32 & 1 &^ gt - } - // Make the result -1 for <, 0 for =, 1 for > - return int(gt) - int(lt) -} - -// Equal returns 1 if f == rhs, 0 otherwise -func (f *Field) Equal(rhs *Field) int { - return equalHelper(&f.Value, &rhs.Value) -} - -func equalHelper(lhs, rhs *[FieldLimbs]uint64) int { - t := lhs[0] ^ rhs[0] - t |= lhs[1] ^ rhs[1] - t |= lhs[2] ^ rhs[2] - t |= lhs[3] ^ rhs[3] - return int(((int64(t) | int64(-t)) >> 63) + 1) -} - -// IsZero returns 1 if f == 0, 0 otherwise -func (f *Field) IsZero() int { - t := f.Value[0] - t |= f.Value[1] - t |= f.Value[2] - t |= f.Value[3] - return int(((int64(t) | int64(-t)) >> 63) + 1) -} - -// IsNonZero returns 1 if f != 0, 0 otherwise -func (f *Field) IsNonZero() int { - t := f.Value[0] - t |= f.Value[1] - t |= f.Value[2] - t |= f.Value[3] - return int(-((int64(t) | int64(-t)) >> 63)) -} - -// IsOne returns 1 if f == 1, 0 otherwise -func (f *Field) IsOne() int { - return equalHelper(&f.Value, &f.Params.R) -} - -// Set f = rhs -func (f *Field) Set(rhs *Field) *Field { - f.Value[0] = rhs.Value[0] - f.Value[1] = rhs.Value[1] - f.Value[2] = rhs.Value[2] - f.Value[3] = rhs.Value[3] - f.Params = rhs.Params - f.Arithmetic = rhs.Arithmetic - return f -} - -// SetUint64 f = rhs -func (f *Field) SetUint64(rhs uint64) *Field { - t := &[FieldLimbs]uint64{rhs, 0, 0, 0} - f.Arithmetic.ToMontgomery(&f.Value, t) - return f -} - -// SetOne f = r -func (f *Field) SetOne() *Field { - f.Value[0] = f.Params.R[0] - f.Value[1] = f.Params.R[1] - f.Value[2] = f.Params.R[2] - f.Value[3] = f.Params.R[3] - return f -} - -// SetZero f = 0 -func (f *Field) SetZero() *Field { - f.Value[0] = 0 - f.Value[1] = 0 - f.Value[2] = 0 - f.Value[3] = 0 - return f -} - -// SetBytesWide takes 64 bytes as input and treats them as a 512-bit number. -// Attributed to https://github.com/zcash/pasta_curves/blob/main/src/fields/Fp.rs#L255 -// We reduce an arbitrary 512-bit number by decomposing it into two 256-bit digits -// with the higher bits multiplied by 2^256. Thus, we perform two reductions -// -// 1. the lower bits are multiplied by r^2, as normal -// 2. the upper bits are multiplied by r^2 * 2^256 = r^3 -// -// and computing their sum in the field. It remains to see that arbitrary 256-bit -// numbers can be placed into Montgomery form safely using the reduction. The -// reduction works so long as the product is less than r=2^256 multiplied by -// the modulus. This holds because for any `c` smaller than the modulus, we have -// that (2^256 - 1)*c is an acceptable product for the reduction. Therefore, the -// reduction always works so long as `c` is in the field; in this case it is either the -// constant `r2` or `r3`. -func (f *Field) SetBytesWide(input *[WideFieldBytes]byte) *Field { - d0 := [FieldLimbs]uint64{ - binary.LittleEndian.Uint64(input[:8]), - binary.LittleEndian.Uint64(input[8:16]), - binary.LittleEndian.Uint64(input[16:24]), - binary.LittleEndian.Uint64(input[24:32]), - } - d1 := [FieldLimbs]uint64{ - binary.LittleEndian.Uint64(input[32:40]), - binary.LittleEndian.Uint64(input[40:48]), - binary.LittleEndian.Uint64(input[48:56]), - binary.LittleEndian.Uint64(input[56:64]), - } - // f.Arithmetic.ToMontgomery(&d0, &d0) - // f.Arithmetic.Mul(&d1, &d1, &f.Params.R2) - // f.Arithmetic.Add(&f.Value, &d0, &d0) - // Convert to Montgomery form - tv1 := &[FieldLimbs]uint64{} - tv2 := &[FieldLimbs]uint64{} - // d0*r2 + d1*r3 - f.Arithmetic.Mul(tv1, &d0, &f.Params.R2) - f.Arithmetic.Mul(tv2, &d1, &f.Params.R3) - f.Arithmetic.Add(&f.Value, tv1, tv2) - return f -} - -// SetBytes attempts to convert a little endian byte representation -// of a scalar into a `Fp`, failing if input is not canonical -func (f *Field) SetBytes(input *[FieldBytes]byte) (*Field, error) { - d0 := [FieldLimbs]uint64{0, 0, 0, 0} - f.Arithmetic.FromBytes(&d0, input) - - if cmpHelper(&d0, &f.Params.Modulus) != -1 { - return nil, fmt.Errorf("invalid byte sequence") - } - return f.SetLimbs(&d0), nil -} - -// SetBigInt initializes an element from big.Int -// The value is reduced by the modulus -func (f *Field) SetBigInt(bi *big.Int) *Field { - var buffer [FieldBytes]byte - t := new(big.Int).Set(bi) - t.Mod(t, f.Params.BiModulus) - t.FillBytes(buffer[:]) - copy(buffer[:], internal.ReverseScalarBytes(buffer[:])) - _, _ = f.SetBytes(&buffer) - return f -} - -// SetRaw converts a raw array into a field element -// Assumes input is already in montgomery form -func (f *Field) SetRaw(input *[FieldLimbs]uint64) *Field { - f.Value[0] = input[0] - f.Value[1] = input[1] - f.Value[2] = input[2] - f.Value[3] = input[3] - return f -} - -// SetLimbs converts an array into a field element -// by converting to montgomery form -func (f *Field) SetLimbs(input *[FieldLimbs]uint64) *Field { - f.Arithmetic.ToMontgomery(&f.Value, input) - return f -} - -// Bytes converts this element into a byte representation -// in little endian byte order -func (f *Field) Bytes() [FieldBytes]byte { - var output [FieldBytes]byte - tv := &[FieldLimbs]uint64{} - f.Arithmetic.FromMontgomery(tv, &f.Value) - f.Arithmetic.ToBytes(&output, tv) - return output -} - -// BigInt converts this element into the big.Int struct -func (f *Field) BigInt() *big.Int { - buffer := f.Bytes() - return new(big.Int).SetBytes(internal.ReverseScalarBytes(buffer[:])) -} - -// Raw converts this element into the a [FieldLimbs]uint64 -func (f *Field) Raw() [FieldLimbs]uint64 { - res := &[FieldLimbs]uint64{} - f.Arithmetic.FromMontgomery(res, &f.Value) - return *res -} - -// Double this element -func (f *Field) Double(a *Field) *Field { - f.Arithmetic.Add(&f.Value, &a.Value, &a.Value) - return f -} - -// Square this element -func (f *Field) Square(a *Field) *Field { - f.Arithmetic.Square(&f.Value, &a.Value) - return f -} - -// Sqrt this element, if it exists. If true, then value -// is a square root. If false, value is a QNR -func (f *Field) Sqrt(a *Field) (*Field, bool) { - wasSquare := 0 - f.Arithmetic.Sqrt(&wasSquare, &f.Value, &a.Value) - return f, wasSquare == 1 -} - -// Invert this element i.e. compute the multiplicative inverse -// return false, zero if this element is zero. -func (f *Field) Invert(a *Field) (*Field, bool) { - wasInverted := 0 - f.Arithmetic.Invert(&wasInverted, &f.Value, &a.Value) - return f, wasInverted == 1 -} - -// Mul returns the result from multiplying this element by rhs -func (f *Field) Mul(lhs, rhs *Field) *Field { - f.Arithmetic.Mul(&f.Value, &lhs.Value, &rhs.Value) - return f -} - -// Sub returns the result from subtracting rhs from this element -func (f *Field) Sub(lhs, rhs *Field) *Field { - f.Arithmetic.Sub(&f.Value, &lhs.Value, &rhs.Value) - return f -} - -// Add returns the result from adding rhs to this element -func (f *Field) Add(lhs, rhs *Field) *Field { - f.Arithmetic.Add(&f.Value, &lhs.Value, &rhs.Value) - return f -} - -// Neg returns negation of this element -func (f *Field) Neg(input *Field) *Field { - f.Arithmetic.Neg(&f.Value, &input.Value) - return f -} - -// Exp raises base^exp -func (f *Field) Exp(base, exp *Field) *Field { - e := [FieldLimbs]uint64{} - f.Arithmetic.FromMontgomery(&e, &exp.Value) - Pow(&f.Value, &base.Value, &e, f.Params, f.Arithmetic) - return f -} - -// CMove sets f = lhs if choice == 0 and f = rhs if choice == 1 -func (f *Field) CMove(lhs, rhs *Field, choice int) *Field { - f.Arithmetic.Selectznz(&f.Value, &lhs.Value, &rhs.Value, choice) - return f -} - -// Pow raises base^exp. The result is written to out. -// Public only for convenience for some internal implementations -func Pow(out, base, exp *[FieldLimbs]uint64, params *FieldParams, arithmetic FieldArithmetic) { - res := [FieldLimbs]uint64{params.R[0], params.R[1], params.R[2], params.R[3]} - tmp := [FieldLimbs]uint64{} - - for i := len(exp) - 1; i >= 0; i-- { - for j := 63; j >= 0; j-- { - arithmetic.Square(&res, &res) - arithmetic.Mul(&tmp, &res, base) - arithmetic.Selectznz(&res, &res, &tmp, int(exp[i]>>j)&1) - } - } - out[0] = res[0] - out[1] = res[1] - out[2] = res[2] - out[3] = res[3] -} - -// Pow2k raises arg to the power `2^k`. This result is written to out. -// Public only for convenience for some internal implementations -func Pow2k(out, arg *[FieldLimbs]uint64, k int, arithmetic FieldArithmetic) { - var t [FieldLimbs]uint64 - t[0] = arg[0] - t[1] = arg[1] - t[2] = arg[2] - t[3] = arg[3] - for i := 0; i < k; i++ { - arithmetic.Square(&t, &t) - } - - out[0] = t[0] - out[1] = t[1] - out[2] = t[2] - out[3] = t[3] -} diff --git a/crypto/core/curves/native/hash2field.go b/crypto/core/curves/native/hash2field.go deleted file mode 100755 index 1d000253d..000000000 --- a/crypto/core/curves/native/hash2field.go +++ /dev/null @@ -1,107 +0,0 @@ -package native - -import ( - "hash" - - "golang.org/x/crypto/sha3" -) - -// OversizeDstSalt is the salt used to hash a dst over MaxDstLen -var OversizeDstSalt = []byte("H2C-OVERSIZE-DST-") - -// MaxDstLen the max size for dst in hash to curve -const MaxDstLen = 255 - -func getDomainXmd(h hash.Hash, domain []byte) []byte { - var out []byte - if len(domain) > MaxDstLen { - h.Reset() - _, _ = h.Write(OversizeDstSalt) - _, _ = h.Write(domain) - out = h.Sum(nil) - } else { - out = domain - } - return out -} - -func getDomainXof(h sha3.ShakeHash, domain []byte) []byte { - var out []byte - if len(domain) > MaxDstLen { - h.Reset() - _, _ = h.Write(OversizeDstSalt) - _, _ = h.Write(domain) - var tv [64]byte - _, _ = h.Read(tv[:]) - out = tv[:] - } else { - out = domain - } - return out -} - -// ExpandMsgXmd expands the msg with the domain to output a byte array -// with outLen in size using a fixed size hash. -// See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-13#section-5.4.1 -func ExpandMsgXmd(h *EllipticPointHasher, msg, domain []byte, outLen int) []byte { - domain = getDomainXmd(h.xmd, domain) - domainLen := byte(len(domain)) - h.xmd.Reset() - // DST_prime = DST || I2OSP(len(DST), 1) - // b_0 = H(Z_pad || msg || l_i_b_str || I2OSP(0, 1) || DST_prime) - _, _ = h.xmd.Write(make([]byte, h.xmd.BlockSize())) - _, _ = h.xmd.Write(msg) - _, _ = h.xmd.Write([]byte{uint8(outLen >> 8), uint8(outLen)}) - _, _ = h.xmd.Write([]byte{0}) - _, _ = h.xmd.Write(domain) - _, _ = h.xmd.Write([]byte{domainLen}) - b0 := h.xmd.Sum(nil) - - // b_1 = H(b_0 || I2OSP(1, 1) || DST_prime) - h.xmd.Reset() - _, _ = h.xmd.Write(b0) - _, _ = h.xmd.Write([]byte{1}) - _, _ = h.xmd.Write(domain) - _, _ = h.xmd.Write([]byte{domainLen}) - b1 := h.xmd.Sum(nil) - - // b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime) - ell := (outLen + h.xmd.Size() - 1) / h.xmd.Size() - bi := b1 - out := make([]byte, outLen) - for i := 1; i < ell; i++ { - h.xmd.Reset() - // b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime) - tmp := make([]byte, h.xmd.Size()) - for j := 0; j < h.xmd.Size(); j++ { - tmp[j] = b0[j] ^ bi[j] - } - _, _ = h.xmd.Write(tmp) - _, _ = h.xmd.Write([]byte{1 + uint8(i)}) - _, _ = h.xmd.Write(domain) - _, _ = h.xmd.Write([]byte{domainLen}) - - // b_1 || ... || b_(ell - 1) - copy(out[(i-1)*h.xmd.Size():i*h.xmd.Size()], bi[:]) - bi = h.xmd.Sum(nil) - } - // b_ell - copy(out[(ell-1)*h.xmd.Size():], bi[:]) - return out[:outLen] -} - -// ExpandMsgXof expands the msg with the domain to output a byte array -// with outLen in size using a xof hash -// See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-13#section-5.4.2 -func ExpandMsgXof(h *EllipticPointHasher, msg, domain []byte, outLen int) []byte { - domain = getDomainXof(h.xof, domain) - domainLen := byte(len(domain)) - h.xof.Reset() - _, _ = h.xof.Write(msg) - _, _ = h.xof.Write([]byte{uint8(outLen >> 8), uint8(outLen)}) - _, _ = h.xof.Write(domain) - _, _ = h.xof.Write([]byte{domainLen}) - out := make([]byte, outLen) - _, _ = h.xof.Read(out) - return out -} diff --git a/crypto/core/curves/native/isogeny.go b/crypto/core/curves/native/isogeny.go deleted file mode 100755 index a29be01a6..000000000 --- a/crypto/core/curves/native/isogeny.go +++ /dev/null @@ -1,62 +0,0 @@ -package native - -// IsogenyParams are the parameters needed to map from an isogeny to the main curve -type IsogenyParams struct { - XNum [][FieldLimbs]uint64 - XDen [][FieldLimbs]uint64 - YNum [][FieldLimbs]uint64 - YDen [][FieldLimbs]uint64 -} - -// Map from the isogeny curve to the main curve using the parameters -func (p *IsogenyParams) Map(xIn, yIn *Field) (x, y *Field) { - var xNum, xDen, yNum, yDen, tv [FieldLimbs]uint64 - var wasInverted int - - xnumL := len(p.XNum) - xdenL := len(p.XDen) - ynumL := len(p.YNum) - ydenL := len(p.YDen) - - degree := 0 - for _, i := range []int{xnumL, xdenL, ynumL, ydenL} { - if degree < i { - degree = i - } - } - - xs := make([][FieldLimbs]uint64, degree) - xs[0] = xIn.Params.R // x[0] = x^0 - xs[1] = xIn.Value // x[1] = x^1 - xIn.Arithmetic.Square(&xs[2], &xIn.Value) // x[2] = x^2 - for i := 3; i < degree; i++ { - // x[i] = x^i - xIn.Arithmetic.Mul(&xs[i], &xs[i-1], &xIn.Value) - } - - computeIsoK(&xNum, &xs, &p.XNum, xIn.Arithmetic) - computeIsoK(&xDen, &xs, &p.XDen, xIn.Arithmetic) - computeIsoK(&yNum, &xs, &p.YNum, xIn.Arithmetic) - computeIsoK(&yDen, &xs, &p.YDen, xIn.Arithmetic) - - xIn.Arithmetic.Invert(&wasInverted, &xDen, &xDen) - x = new(Field).Set(xIn) - xIn.Arithmetic.Mul(&tv, &xNum, &xDen) - xIn.Arithmetic.Selectznz(&x.Value, &x.Value, &tv, wasInverted) - - yIn.Arithmetic.Invert(&wasInverted, &yDen, &yDen) - y = new(Field).Set(yIn) - yIn.Arithmetic.Mul(&tv, &yNum, &yDen) - yIn.Arithmetic.Selectznz(&y.Value, &y.Value, &tv, wasInverted) - yIn.Arithmetic.Mul(&y.Value, &y.Value, &yIn.Value) - return x, y -} - -func computeIsoK(out *[FieldLimbs]uint64, xxs, k *[][FieldLimbs]uint64, f FieldArithmetic) { - var tv [FieldLimbs]uint64 - - for i := range *k { - f.Mul(&tv, &(*xxs)[i], &(*k)[i]) - f.Add(out, out, &tv) - } -} diff --git a/crypto/core/curves/native/k256/fp/fp.go b/crypto/core/curves/native/k256/fp/fp.go deleted file mode 100644 index 42b0cb885..000000000 --- a/crypto/core/curves/native/k256/fp/fp.go +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -var ( - k256FpInitonce sync.Once - k256FpParams native.FieldParams -) - -func K256FpNew() *native.Field { - return &native.Field{ - Value: [native.FieldLimbs]uint64{}, - Params: getK256FpParams(), - Arithmetic: k256FpArithmetic{}, - } -} - -func k256FpParamsInit() { - k256FpParams = native.FieldParams{ - R: [native.FieldLimbs]uint64{ - 0x00000001000003d1, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - R2: [native.FieldLimbs]uint64{ - 0x000007a2000e90a1, - 0x0000000000000001, - 0x0000000000000000, - 0x0000000000000000, - }, - R3: [native.FieldLimbs]uint64{ - 0x002bb1e33795f671, - 0x0000000100000b73, - 0x0000000000000000, - 0x0000000000000000, - }, - Modulus: [native.FieldLimbs]uint64{ - 0xfffffffefffffc2f, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0xffffffffffffffff, - }, - BiModulus: new(big.Int).SetBytes([]byte{ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2f, - }), - } -} - -func getK256FpParams() *native.FieldParams { - k256FpInitonce.Do(k256FpParamsInit) - return &k256FpParams -} - -// k256FpArithmetic is a struct with all the methods needed for working -// in mod p -type k256FpArithmetic struct{} - -// ToMontgomery converts this field to montgomery form -func (f k256FpArithmetic) ToMontgomery(out, arg *[native.FieldLimbs]uint64) { - ToMontgomery((*MontgomeryDomainFieldElement)(out), (*NonMontgomeryDomainFieldElement)(arg)) -} - -// FromMontgomery converts this field from montgomery form -func (f k256FpArithmetic) FromMontgomery(out, arg *[native.FieldLimbs]uint64) { - FromMontgomery((*NonMontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Neg performs modular negation -func (f k256FpArithmetic) Neg(out, arg *[native.FieldLimbs]uint64) { - Opp((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Square performs modular square -func (f k256FpArithmetic) Square(out, arg *[native.FieldLimbs]uint64) { - Square((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Mul performs modular multiplication -func (f k256FpArithmetic) Mul(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Mul( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Add performs modular addition -func (f k256FpArithmetic) Add(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Add( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sub performs modular subtraction -func (f k256FpArithmetic) Sub(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Sub( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sqrt performs modular square root -func (f k256FpArithmetic) Sqrt(wasSquare *int, out, arg *[native.FieldLimbs]uint64) { - // p is congruent to 3 mod 4 we can compute - // sqrt using elem^(p+1)/4 mod p - // 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff0c - var s, t [native.FieldLimbs]uint64 - params := getK256FpParams() - native.Pow(&s, arg, &[native.FieldLimbs]uint64{ - 0xffffffffbfffff0c, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0x3fffffffffffffff, - }, params, f) - f.Square(&t, &s) - tv1 := &native.Field{Value: t, Params: params, Arithmetic: f} - tv2 := &native.Field{Value: *arg, Params: params, Arithmetic: f} - *wasSquare = tv1.Equal(tv2) - f.Selectznz(out, out, &s, *wasSquare) -} - -// Invert performs modular inverse -func (f k256FpArithmetic) Invert(wasInverted *int, out, arg *[native.FieldLimbs]uint64) { - // The binary representation of (p - 2) has 5 groups of 1s, with lengths in - // { 1, 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each group: - // [1], [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] - var s, x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223 [native.FieldLimbs]uint64 - - native.Pow2k(&x2, arg, 1, f) - f.Mul(&x2, &x2, arg) - - native.Pow2k(&x3, &x2, 1, f) - f.Mul(&x3, &x3, arg) - - native.Pow2k(&x6, &x3, 3, f) - f.Mul(&x6, &x6, &x3) - - native.Pow2k(&x9, &x6, 3, f) - f.Mul(&x9, &x9, &x3) - - native.Pow2k(&x11, &x9, 2, f) - f.Mul(&x11, &x11, &x2) - - native.Pow2k(&x22, &x11, 11, f) - f.Mul(&x22, &x22, &x11) - - native.Pow2k(&x44, &x22, 22, f) - f.Mul(&x44, &x44, &x22) - - native.Pow2k(&x88, &x44, 44, f) - f.Mul(&x88, &x88, &x44) - - native.Pow2k(&x176, &x88, 88, f) - f.Mul(&x176, &x176, &x88) - - native.Pow2k(&x220, &x176, 44, f) - f.Mul(&x220, &x220, &x44) - - native.Pow2k(&x223, &x220, 3, f) - f.Mul(&x223, &x223, &x3) - - // Use sliding window over the group - native.Pow2k(&s, &x223, 23, f) - f.Mul(&s, &s, &x22) - native.Pow2k(&s, &s, 5, f) - f.Mul(&s, &s, arg) - native.Pow2k(&s, &s, 3, f) - f.Mul(&s, &s, &x2) - native.Pow2k(&s, &s, 2, f) - f.Mul(&s, &s, arg) - - tv := &native.Field{Value: *arg, Params: getK256FpParams(), Arithmetic: f} - - *wasInverted = tv.IsNonZero() - f.Selectznz(out, out, &s, *wasInverted) -} - -// FromBytes converts a little endian byte array into a field element -func (f k256FpArithmetic) FromBytes(out *[native.FieldLimbs]uint64, arg *[native.FieldBytes]byte) { - FromBytes(out, arg) -} - -// ToBytes converts a field element to a little endian byte array -func (f k256FpArithmetic) ToBytes(out *[native.FieldBytes]byte, arg *[native.FieldLimbs]uint64) { - ToBytes(out, arg) -} - -// Selectznz performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f k256FpArithmetic) Selectznz(out, arg1, arg2 *[native.FieldLimbs]uint64, choice int) { - Selectznz(out, uint1(choice), arg1, arg2) -} diff --git a/crypto/core/curves/native/k256/fp/fp_test.go b/crypto/core/curves/native/k256/fp/fp_test.go deleted file mode 100644 index 6e01fa064..000000000 --- a/crypto/core/curves/native/k256/fp/fp_test.go +++ /dev/null @@ -1,330 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFpSetOne(t *testing.T) { - fp := K256FpNew().SetOne() - require.NotNil(t, fp) - require.Equal(t, fp.Value, getK256FpParams().R) -} - -func TestFpSetUint64(t *testing.T) { - act := K256FpNew().SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act.Value[0], uint64(0x1000000000000000)) -} - -func TestFpAdd(t *testing.T) { - lhs := K256FpNew().SetOne() - rhs := K256FpNew().SetOne() - exp := K256FpNew().SetUint64(2) - res := K256FpNew().Add(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, res.Equal(exp), 1) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := K256FpNew().Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpSub(t *testing.T) { - lhs := K256FpNew().SetOne() - rhs := K256FpNew().SetOne() - exp := K256FpNew().SetZero() - res := K256FpNew().Sub(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := K256FpNew().Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpMul(t *testing.T) { - lhs := K256FpNew().SetOne() - rhs := K256FpNew().SetOne() - exp := K256FpNew().SetOne() - res := K256FpNew().Mul(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := K256FpNew().Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpDouble(t *testing.T) { - a := K256FpNew().SetUint64(2) - e := K256FpNew().SetUint64(4) - require.Equal(t, e, K256FpNew().Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = K256FpNew().SetUint64(uint64(tv)) - e = K256FpNew().SetUint64(ttv) - require.Equal(t, e, K256FpNew().Double(a)) - } -} - -func TestFpSquare(t *testing.T) { - a := K256FpNew().SetUint64(4) - e := K256FpNew().SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFpNeg(t *testing.T) { - a := K256FpNew().SetOne() - a.Neg(a) - e := K256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xfffffffdfffff85e, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}) - require.Equal(t, e, a) -} - -func TestFpExp(t *testing.T) { - e := K256FpNew().SetUint64(8) - a := K256FpNew().SetUint64(2) - by := K256FpNew().SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFpSqrt(t *testing.T) { - t1 := K256FpNew().SetUint64(2) - t2 := K256FpNew().Neg(t1) - t3 := K256FpNew().Square(t1) - _, wasSquare := t3.Sqrt(t3) - require.True(t, wasSquare) - require.Equal(t, 1, t1.Equal(t3)|t2.Equal(t3)) - t1.SetUint64(5) - _, wasSquare = K256FpNew().Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFpInvert(t *testing.T) { - twoInv := K256FpNew().SetLimbs(&[native.FieldLimbs]uint64{ - 0xffffffff7ffffe18, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0x7fffffffffffffff, - }) - two := K256FpNew().SetUint64(2) - a, inverted := K256FpNew().Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - seven := K256FpNew().SetUint64(7) - sevenInv := K256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xdb6db6dab6db6afd, 0x6db6db6db6db6db6, 0xb6db6db6db6db6db, 0xdb6db6db6db6db6d}) - a, inverted = K256FpNew().Invert(seven) - require.True(t, inverted) - require.Equal(t, a, sevenInv) - - lhs := K256FpNew().SetUint64(9) - rhs := K256FpNew().SetUint64(3) - rhsInv, inverted := K256FpNew().Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, K256FpNew().Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = K256FpNew().Invert(rhs) - require.False(t, inverted) -} - -func TestFpCMove(t *testing.T) { - t1 := K256FpNew().SetUint64(5) - t2 := K256FpNew().SetUint64(10) - require.Equal(t, t1, K256FpNew().CMove(t1, t2, 0)) - require.Equal(t, t2, K256FpNew().CMove(t1, t2, 1)) -} - -func TestFpBytes(t *testing.T) { - t1 := K256FpNew().SetUint64(99) - seq := t1.Bytes() - t2, err := K256FpNew().SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFpCmp(t *testing.T) { - tests := []struct { - a *native.Field - b *native.Field - e int - }{ - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{2731658267414164836, 14655288906067898431, 6537465423330262322, 8306191141697566219}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{6472764012681988529, 10848812988401906064, 2961825807536828898, 4282183981941645679}), - e: 1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{8023004109510539223, 4652004072850285717, 1877219145646046927, 383214385093921911}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{10099384440823804262, 16139476942229308465, 8636966320777393798, 5435928725024696785}), - e: -1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{3741840066202388211, 12165774400417314871, 16619312580230515379, 16195032234110087705}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{3905865991286066744, 543690822309071825, 17963103015950210055, 3745476720756119742}), - e: 1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{16660853697936147788, 7799793619412111108, 13515141085171033220, 2641079731236069032}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{17790588295388238399, 571847801379669440, 14537208974498222469, 12792570372087452754}), - e: -1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{3912839285384959186, 2701177075110484070, 6453856448115499033, 6475797457962597458}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{1282566391665688512, 13503640416992806563, 2962240104675990153, 3374904770947067689}), - e: 1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{5716631803409360103, 7859567470082614154, 12747956220853330146, 18434584096087315020}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{16317076441459028418, 12854146980376319601, 2258436689269031143, 9531877130792223752}), - e: 1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{17955191469941083403, 10350326247207200880, 17263512235150705075, 12700328451238078022}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{6767595547459644695, 7146403825494928147, 12269344038346710612, 9122477829383225603}), - e: 1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{17099388671847024438, 6426264987820696548, 10641143464957227405, 7709745403700754098}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{10799154372990268556, 17178492485719929374, 5705777922258988797, 8051037767683567782}), - e: -1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{4567139260680454325, 1629385880182139061, 16607020832317899145, 1261011562621553200}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{13487234491304534488, 17872642955936089265, 17651026784972590233, 9468934643333871559}), - e: -1, - }, - { - a: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{18071070103467571798, 11787850505799426140, 10631355976141928593, 4867785203635092610}), - b: K256FpNew().SetRaw(&[native.FieldLimbs]uint64{12596443599426461624, 10176122686151524591, 17075755296887483439, 6726169532695070719}), - e: -1, - }, - } - - for _, test := range tests { - require.Equal(t, test.e, test.a.Cmp(test.b)) - require.Equal(t, -test.e, test.b.Cmp(test.a)) - require.Equal(t, 0, test.a.Cmp(test.a)) - require.Equal(t, 0, test.b.Cmp(test.b)) - } -} - -func TestFpBigInt(t *testing.T) { - t1 := K256FpNew().SetBigInt(big.NewInt(9999)) - t2 := K256FpNew().SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := K256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xc6c6c6c63939371d, 0xc6c6c6c6c6c6c6c6, 0x8d8d8dd28485081d, 0x8484848484848484}) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Value[0] = 0x39393938c6c6c512 - e.Value[1] = 0x3939393939393939 - e.Value[2] = 0x7272722d7b7af7e2 - e.Value[3] = 0x7b7b7b7b7b7b7b7b - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFpSetBytesWide(t *testing.T) { - e := K256FpNew().SetRaw(&[native.FieldLimbs]uint64{0x6aa784623e2d641e, 0x7c40617d755bae27, 0x206b7be66ed7b71b, 0x6d1e4fc581e19dc2}) - - a := K256FpNew().SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} - -func TestFpSetBytesWideBigInt(t *testing.T) { - params := getK256FpParams() - var tv2 [64]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, params.BiModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a := K256FpNew().SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} diff --git a/crypto/core/curves/native/k256/fp/secp256k1_fp.go b/crypto/core/curves/native/k256/fp/secp256k1_fp.go deleted file mode 100755 index bbf70c03d..000000000 --- a/crypto/core/curves/native/k256/fp/secp256k1_fp.go +++ /dev/null @@ -1,1942 +0,0 @@ -// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Go --no-wide-int --relax-primitive-carry-to-bitwidth 32,64 --cmovznz-by-mul --internal-static --package-case flatcase --public-function-case UpperCamelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case camelCase --no-prefix-fiat --doc-newline-in-typedef-bounds --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --doc-text-before-function-name ” --doc-text-before-type-name ” --package-name secp256k1 ” 64 '2^256 - 2^32 - 977' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp -// -// curve description (via package name): secp256k1 -// -// machine_wordsize = 64 (from "64") -// -// requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp -// -// m = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f (from "2^256 - 2^32 - 977") -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 -package fp - -import "math/bits" - -type ( - uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -) - -// MontgomeryDomainFieldElement is a field element in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type MontgomeryDomainFieldElement [4]uint64 - -// NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type NonMontgomeryDomainFieldElement [4]uint64 - -// cmovznzU64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func cmovznzU64(out1 *uint64, arg1 uint1, arg2 uint64, arg3 uint64) { - x1 := (uint64(arg1) * 0xffffffffffffffff) - x2 := ((x1 & arg3) | ((^x1) & arg2)) - *out1 = x2 -} - -// Mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Mul( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0xd838091dd2253531) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffffffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xffffffffffffffff) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xfffffffefffffc2f) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg2[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg2[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg2[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0xd838091dd2253531) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffffffffffff) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xffffffffffffffff) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xffffffffffffffff) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xfffffffefffffc2f) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg2[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg2[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg2[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg2[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0xd838091dd2253531) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffffffffffff) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xffffffffffffffff) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xffffffffffffffff) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xfffffffefffffc2f) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg2[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg2[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg2[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg2[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0xd838091dd2253531) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffffffffffff) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xffffffffffffffff) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xffffffffffffffff) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xfffffffefffffc2f) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xfffffffefffffc2f, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xffffffffffffffff, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xffffffffffffffff, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffffffffffff, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func Square(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0xd838091dd2253531) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffffffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xffffffffffffffff) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xfffffffefffffc2f) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg1[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg1[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg1[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg1[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0xd838091dd2253531) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffffffffffff) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xffffffffffffffff) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xffffffffffffffff) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xfffffffefffffc2f) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg1[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg1[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg1[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg1[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0xd838091dd2253531) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffffffffffff) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xffffffffffffffff) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xffffffffffffffff) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xfffffffefffffc2f) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg1[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg1[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg1[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg1[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0xd838091dd2253531) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffffffffffff) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xffffffffffffffff) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xffffffffffffffff) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xfffffffefffffc2f) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xfffffffefffffc2f, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xffffffffffffffff, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xffffffffffffffff, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffffffffffff, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Add( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - var x10 uint64 - x9, x10 = bits.Sub64(x1, 0xfffffffefffffc2f, uint64(0x0)) - var x11 uint64 - var x12 uint64 - x11, x12 = bits.Sub64(x3, 0xffffffffffffffff, uint64(uint1(x10))) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Sub64(x5, 0xffffffffffffffff, uint64(uint1(x12))) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Sub64(x7, 0xffffffffffffffff, uint64(uint1(x14))) - var x18 uint64 - _, x18 = bits.Sub64(uint64(uint1(x8)), uint64(0x0), uint64(uint1(x16))) - var x19 uint64 - cmovznzU64(&x19, uint1(x18), x9, x1) - var x20 uint64 - cmovznzU64(&x20, uint1(x18), x11, x3) - var x21 uint64 - cmovznzU64(&x21, uint1(x18), x13, x5) - var x22 uint64 - cmovznzU64(&x22, uint1(x18), x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// Sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Sub( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xfffffffefffffc2f), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, x9, uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, x9, uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, x9, uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// Opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func Opp(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xfffffffefffffc2f), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, x9, uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, x9, uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, x9, uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// FromMontgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func FromMontgomery(out1 *NonMontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0xd838091dd2253531) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0xffffffffffffffff) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0xffffffffffffffff) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x11, x10 = bits.Mul64(x2, 0xfffffffefffffc2f) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x11, x8, uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x9, x6, uint64(uint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(x7, x4, uint64(uint1(x15))) - var x19 uint64 - _, x19 = bits.Add64(x1, x10, uint64(0x0)) - var x20 uint64 - var x21 uint64 - x20, x21 = bits.Add64(uint64(0x0), x12, uint64(uint1(x19))) - var x22 uint64 - var x23 uint64 - x22, x23 = bits.Add64(uint64(0x0), x14, uint64(uint1(x21))) - var x24 uint64 - var x25 uint64 - x24, x25 = bits.Add64(uint64(0x0), x16, uint64(uint1(x23))) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(uint64(0x0), (uint64(uint1(x17)) + x5), uint64(uint1(x25))) - var x28 uint64 - var x29 uint64 - x28, x29 = bits.Add64(x20, arg1[1], uint64(0x0)) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x22, uint64(0x0), uint64(uint1(x29))) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x24, uint64(0x0), uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x26, uint64(0x0), uint64(uint1(x33))) - var x36 uint64 - _, x36 = bits.Mul64(x28, 0xd838091dd2253531) - var x38 uint64 - var x39 uint64 - x39, x38 = bits.Mul64(x36, 0xffffffffffffffff) - var x40 uint64 - var x41 uint64 - x41, x40 = bits.Mul64(x36, 0xffffffffffffffff) - var x42 uint64 - var x43 uint64 - x43, x42 = bits.Mul64(x36, 0xffffffffffffffff) - var x44 uint64 - var x45 uint64 - x45, x44 = bits.Mul64(x36, 0xfffffffefffffc2f) - var x46 uint64 - var x47 uint64 - x46, x47 = bits.Add64(x45, x42, uint64(0x0)) - var x48 uint64 - var x49 uint64 - x48, x49 = bits.Add64(x43, x40, uint64(uint1(x47))) - var x50 uint64 - var x51 uint64 - x50, x51 = bits.Add64(x41, x38, uint64(uint1(x49))) - var x53 uint64 - _, x53 = bits.Add64(x28, x44, uint64(0x0)) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x30, x46, uint64(uint1(x53))) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x32, x48, uint64(uint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x34, x50, uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64( - (uint64(uint1(x35)) + uint64(uint1(x27))), - (uint64(uint1(x51)) + x39), - uint64(uint1(x59)), - ) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x54, arg1[2], uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x56, uint64(0x0), uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x58, uint64(0x0), uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x60, uint64(0x0), uint64(uint1(x67))) - var x70 uint64 - _, x70 = bits.Mul64(x62, 0xd838091dd2253531) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x70, 0xffffffffffffffff) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x70, 0xffffffffffffffff) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x70, 0xffffffffffffffff) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x70, 0xfffffffefffffc2f) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x79, x76, uint64(0x0)) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x77, x74, uint64(uint1(x81))) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x75, x72, uint64(uint1(x83))) - var x87 uint64 - _, x87 = bits.Add64(x62, x78, uint64(0x0)) - var x88 uint64 - var x89 uint64 - x88, x89 = bits.Add64(x64, x80, uint64(uint1(x87))) - var x90 uint64 - var x91 uint64 - x90, x91 = bits.Add64(x66, x82, uint64(uint1(x89))) - var x92 uint64 - var x93 uint64 - x92, x93 = bits.Add64(x68, x84, uint64(uint1(x91))) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64( - (uint64(uint1(x69)) + uint64(uint1(x61))), - (uint64(uint1(x85)) + x73), - uint64(uint1(x93)), - ) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x88, arg1[3], uint64(0x0)) - var x98 uint64 - var x99 uint64 - x98, x99 = bits.Add64(x90, uint64(0x0), uint64(uint1(x97))) - var x100 uint64 - var x101 uint64 - x100, x101 = bits.Add64(x92, uint64(0x0), uint64(uint1(x99))) - var x102 uint64 - var x103 uint64 - x102, x103 = bits.Add64(x94, uint64(0x0), uint64(uint1(x101))) - var x104 uint64 - _, x104 = bits.Mul64(x96, 0xd838091dd2253531) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x104, 0xffffffffffffffff) - var x108 uint64 - var x109 uint64 - x109, x108 = bits.Mul64(x104, 0xffffffffffffffff) - var x110 uint64 - var x111 uint64 - x111, x110 = bits.Mul64(x104, 0xffffffffffffffff) - var x112 uint64 - var x113 uint64 - x113, x112 = bits.Mul64(x104, 0xfffffffefffffc2f) - var x114 uint64 - var x115 uint64 - x114, x115 = bits.Add64(x113, x110, uint64(0x0)) - var x116 uint64 - var x117 uint64 - x116, x117 = bits.Add64(x111, x108, uint64(uint1(x115))) - var x118 uint64 - var x119 uint64 - x118, x119 = bits.Add64(x109, x106, uint64(uint1(x117))) - var x121 uint64 - _, x121 = bits.Add64(x96, x112, uint64(0x0)) - var x122 uint64 - var x123 uint64 - x122, x123 = bits.Add64(x98, x114, uint64(uint1(x121))) - var x124 uint64 - var x125 uint64 - x124, x125 = bits.Add64(x100, x116, uint64(uint1(x123))) - var x126 uint64 - var x127 uint64 - x126, x127 = bits.Add64(x102, x118, uint64(uint1(x125))) - var x128 uint64 - var x129 uint64 - x128, x129 = bits.Add64( - (uint64(uint1(x103)) + uint64(uint1(x95))), - (uint64(uint1(x119)) + x107), - uint64(uint1(x127)), - ) - var x130 uint64 - var x131 uint64 - x130, x131 = bits.Sub64(x122, 0xfffffffefffffc2f, uint64(0x0)) - var x132 uint64 - var x133 uint64 - x132, x133 = bits.Sub64(x124, 0xffffffffffffffff, uint64(uint1(x131))) - var x134 uint64 - var x135 uint64 - x134, x135 = bits.Sub64(x126, 0xffffffffffffffff, uint64(uint1(x133))) - var x136 uint64 - var x137 uint64 - x136, x137 = bits.Sub64(x128, 0xffffffffffffffff, uint64(uint1(x135))) - var x139 uint64 - _, x139 = bits.Sub64(uint64(uint1(x129)), uint64(0x0), uint64(uint1(x137))) - var x140 uint64 - cmovznzU64(&x140, uint1(x139), x130, x122) - var x141 uint64 - cmovznzU64(&x141, uint1(x139), x132, x124) - var x142 uint64 - cmovznzU64(&x142, uint1(x139), x134, x126) - var x143 uint64 - cmovznzU64(&x143, uint1(x139), x136, x128) - out1[0] = x140 - out1[1] = x141 - out1[2] = x142 - out1[3] = x143 -} - -// ToMontgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func ToMontgomery(out1 *MontgomeryDomainFieldElement, arg1 *NonMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x7a2000e90a1) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(x6, x4, uint64(0x0)) - var x9 uint64 - _, x9 = bits.Mul64(x5, 0xd838091dd2253531) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x9, 0xffffffffffffffff) - var x13 uint64 - var x14 uint64 - x14, x13 = bits.Mul64(x9, 0xffffffffffffffff) - var x15 uint64 - var x16 uint64 - x16, x15 = bits.Mul64(x9, 0xffffffffffffffff) - var x17 uint64 - var x18 uint64 - x18, x17 = bits.Mul64(x9, 0xfffffffefffffc2f) - var x19 uint64 - var x20 uint64 - x19, x20 = bits.Add64(x18, x15, uint64(0x0)) - var x21 uint64 - var x22 uint64 - x21, x22 = bits.Add64(x16, x13, uint64(uint1(x20))) - var x23 uint64 - var x24 uint64 - x23, x24 = bits.Add64(x14, x11, uint64(uint1(x22))) - var x26 uint64 - _, x26 = bits.Add64(x5, x17, uint64(0x0)) - var x27 uint64 - var x28 uint64 - x27, x28 = bits.Add64(x7, x19, uint64(uint1(x26))) - var x29 uint64 - var x30 uint64 - x29, x30 = bits.Add64(uint64(uint1(x8)), x21, uint64(uint1(x28))) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(uint64(0x0), x23, uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(uint64(0x0), (uint64(uint1(x24)) + x12), uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x36, x35 = bits.Mul64(x1, 0x7a2000e90a1) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x36, x1, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x27, x35, uint64(0x0)) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x29, x37, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x31, uint64(uint1(x38)), uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x33, uint64(0x0), uint64(uint1(x44))) - var x47 uint64 - _, x47 = bits.Mul64(x39, 0xd838091dd2253531) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x47, 0xffffffffffffffff) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x47, 0xffffffffffffffff) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x47, 0xffffffffffffffff) - var x55 uint64 - var x56 uint64 - x56, x55 = bits.Mul64(x47, 0xfffffffefffffc2f) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x56, x53, uint64(0x0)) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x54, x51, uint64(uint1(x58))) - var x61 uint64 - var x62 uint64 - x61, x62 = bits.Add64(x52, x49, uint64(uint1(x60))) - var x64 uint64 - _, x64 = bits.Add64(x39, x55, uint64(0x0)) - var x65 uint64 - var x66 uint64 - x65, x66 = bits.Add64(x41, x57, uint64(uint1(x64))) - var x67 uint64 - var x68 uint64 - x67, x68 = bits.Add64(x43, x59, uint64(uint1(x66))) - var x69 uint64 - var x70 uint64 - x69, x70 = bits.Add64(x45, x61, uint64(uint1(x68))) - var x71 uint64 - var x72 uint64 - x71, x72 = bits.Add64( - (uint64(uint1(x46)) + uint64(uint1(x34))), - (uint64(uint1(x62)) + x50), - uint64(uint1(x70)), - ) - var x73 uint64 - var x74 uint64 - x74, x73 = bits.Mul64(x2, 0x7a2000e90a1) - var x75 uint64 - var x76 uint64 - x75, x76 = bits.Add64(x74, x2, uint64(0x0)) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Add64(x65, x73, uint64(0x0)) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x67, x75, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x69, uint64(uint1(x76)), uint64(uint1(x80))) - var x83 uint64 - var x84 uint64 - x83, x84 = bits.Add64(x71, uint64(0x0), uint64(uint1(x82))) - var x85 uint64 - _, x85 = bits.Mul64(x77, 0xd838091dd2253531) - var x87 uint64 - var x88 uint64 - x88, x87 = bits.Mul64(x85, 0xffffffffffffffff) - var x89 uint64 - var x90 uint64 - x90, x89 = bits.Mul64(x85, 0xffffffffffffffff) - var x91 uint64 - var x92 uint64 - x92, x91 = bits.Mul64(x85, 0xffffffffffffffff) - var x93 uint64 - var x94 uint64 - x94, x93 = bits.Mul64(x85, 0xfffffffefffffc2f) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x94, x91, uint64(0x0)) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x92, x89, uint64(uint1(x96))) - var x99 uint64 - var x100 uint64 - x99, x100 = bits.Add64(x90, x87, uint64(uint1(x98))) - var x102 uint64 - _, x102 = bits.Add64(x77, x93, uint64(0x0)) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x79, x95, uint64(uint1(x102))) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x81, x97, uint64(uint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x83, x99, uint64(uint1(x106))) - var x109 uint64 - var x110 uint64 - x109, x110 = bits.Add64( - (uint64(uint1(x84)) + uint64(uint1(x72))), - (uint64(uint1(x100)) + x88), - uint64(uint1(x108)), - ) - var x111 uint64 - var x112 uint64 - x112, x111 = bits.Mul64(x3, 0x7a2000e90a1) - var x113 uint64 - var x114 uint64 - x113, x114 = bits.Add64(x112, x3, uint64(0x0)) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x103, x111, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x105, x113, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x107, uint64(uint1(x114)), uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x109, uint64(0x0), uint64(uint1(x120))) - var x123 uint64 - _, x123 = bits.Mul64(x115, 0xd838091dd2253531) - var x125 uint64 - var x126 uint64 - x126, x125 = bits.Mul64(x123, 0xffffffffffffffff) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x123, 0xffffffffffffffff) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x123, 0xffffffffffffffff) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x123, 0xfffffffefffffc2f) - var x133 uint64 - var x134 uint64 - x133, x134 = bits.Add64(x132, x129, uint64(0x0)) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x130, x127, uint64(uint1(x134))) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x128, x125, uint64(uint1(x136))) - var x140 uint64 - _, x140 = bits.Add64(x115, x131, uint64(0x0)) - var x141 uint64 - var x142 uint64 - x141, x142 = bits.Add64(x117, x133, uint64(uint1(x140))) - var x143 uint64 - var x144 uint64 - x143, x144 = bits.Add64(x119, x135, uint64(uint1(x142))) - var x145 uint64 - var x146 uint64 - x145, x146 = bits.Add64(x121, x137, uint64(uint1(x144))) - var x147 uint64 - var x148 uint64 - x147, x148 = bits.Add64( - (uint64(uint1(x122)) + uint64(uint1(x110))), - (uint64(uint1(x138)) + x126), - uint64(uint1(x146)), - ) - var x149 uint64 - var x150 uint64 - x149, x150 = bits.Sub64(x141, 0xfffffffefffffc2f, uint64(0x0)) - var x151 uint64 - var x152 uint64 - x151, x152 = bits.Sub64(x143, 0xffffffffffffffff, uint64(uint1(x150))) - var x153 uint64 - var x154 uint64 - x153, x154 = bits.Sub64(x145, 0xffffffffffffffff, uint64(uint1(x152))) - var x155 uint64 - var x156 uint64 - x155, x156 = bits.Sub64(x147, 0xffffffffffffffff, uint64(uint1(x154))) - var x158 uint64 - _, x158 = bits.Sub64(uint64(uint1(x148)), uint64(0x0), uint64(uint1(x156))) - var x159 uint64 - cmovznzU64(&x159, uint1(x158), x149, x141) - var x160 uint64 - cmovznzU64(&x160, uint1(x158), x151, x143) - var x161 uint64 - cmovznzU64(&x161, uint1(x158), x153, x145) - var x162 uint64 - cmovznzU64(&x162, uint1(x158), x155, x147) - out1[0] = x159 - out1[1] = x160 - out1[2] = x161 - out1[3] = x162 -} - -// Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func Nonzero(out1 *uint64, arg1 *[4]uint64) { - x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) - *out1 = x1 -} - -// Selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Selectznz(out1 *[4]uint64, arg1 uint1, arg2 *[4]uint64, arg3 *[4]uint64) { - var x1 uint64 - cmovznzU64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - cmovznzU64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - cmovznzU64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - cmovznzU64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -func ToBytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func FromBytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} - -// SetOne returns the field element one in the Montgomery domain. -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = 1 mod m -// 0 ≤ eval out1 < m -func SetOne(out1 *MontgomeryDomainFieldElement) { - out1[0] = 0x1000003d1 - out1[1] = uint64(0x0) - out1[2] = uint64(0x0) - out1[3] = uint64(0x0) -} - -// Msat returns the saturated representation of the prime modulus. -// -// Postconditions: -// -// twos_complement_eval out1 = m -// 0 ≤ eval out1 < m -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Msat(out1 *[5]uint64) { - out1[0] = 0xfffffffefffffc2f - out1[1] = 0xffffffffffffffff - out1[2] = 0xffffffffffffffff - out1[3] = 0xffffffffffffffff - out1[4] = uint64(0x0) -} - -// Divstep computes a divstep. -// -// Preconditions: -// -// 0 ≤ eval arg4 < m -// 0 ≤ eval arg5 < m -// -// Postconditions: -// -// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) -// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) -// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) -// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) -// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) -// 0 ≤ eval out5 < m -// 0 ≤ eval out5 < m -// 0 ≤ eval out2 < m -// 0 ≤ eval out3 < m -// -// Input Bounds: -// -// arg1: [0x0 ~> 0xffffffffffffffff] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Divstep( - out1 *uint64, - out2 *[5]uint64, - out3 *[5]uint64, - out4 *[4]uint64, - out5 *[4]uint64, - arg1 uint64, - arg2 *[5]uint64, - arg3 *[5]uint64, - arg4 *[4]uint64, - arg5 *[4]uint64, -) { - var x1 uint64 - x1, _ = bits.Add64((^arg1), uint64(0x1), uint64(0x0)) - x3 := (uint1((x1 >> 63)) & (uint1(arg3[0]) & 0x1)) - var x4 uint64 - x4, _ = bits.Add64((^arg1), uint64(0x1), uint64(0x0)) - var x6 uint64 - cmovznzU64(&x6, x3, arg1, x4) - var x7 uint64 - cmovznzU64(&x7, x3, arg2[0], arg3[0]) - var x8 uint64 - cmovznzU64(&x8, x3, arg2[1], arg3[1]) - var x9 uint64 - cmovznzU64(&x9, x3, arg2[2], arg3[2]) - var x10 uint64 - cmovznzU64(&x10, x3, arg2[3], arg3[3]) - var x11 uint64 - cmovznzU64(&x11, x3, arg2[4], arg3[4]) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(uint64(0x1), (^arg2[0]), uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(uint64(0x0), (^arg2[1]), uint64(uint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(uint64(0x0), (^arg2[2]), uint64(uint1(x15))) - var x18 uint64 - var x19 uint64 - x18, x19 = bits.Add64(uint64(0x0), (^arg2[3]), uint64(uint1(x17))) - var x20 uint64 - x20, _ = bits.Add64(uint64(0x0), (^arg2[4]), uint64(uint1(x19))) - var x22 uint64 - cmovznzU64(&x22, x3, arg3[0], x12) - var x23 uint64 - cmovznzU64(&x23, x3, arg3[1], x14) - var x24 uint64 - cmovznzU64(&x24, x3, arg3[2], x16) - var x25 uint64 - cmovznzU64(&x25, x3, arg3[3], x18) - var x26 uint64 - cmovznzU64(&x26, x3, arg3[4], x20) - var x27 uint64 - cmovznzU64(&x27, x3, arg4[0], arg5[0]) - var x28 uint64 - cmovznzU64(&x28, x3, arg4[1], arg5[1]) - var x29 uint64 - cmovznzU64(&x29, x3, arg4[2], arg5[2]) - var x30 uint64 - cmovznzU64(&x30, x3, arg4[3], arg5[3]) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x27, x27, uint64(0x0)) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x28, x28, uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x29, x29, uint64(uint1(x34))) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x30, x30, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Sub64(x31, 0xfffffffefffffc2f, uint64(0x0)) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Sub64(x33, 0xffffffffffffffff, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Sub64(x35, 0xffffffffffffffff, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Sub64(x37, 0xffffffffffffffff, uint64(uint1(x44))) - var x48 uint64 - _, x48 = bits.Sub64(uint64(uint1(x38)), uint64(0x0), uint64(uint1(x46))) - x49 := arg4[3] - x50 := arg4[2] - x51 := arg4[1] - x52 := arg4[0] - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Sub64(uint64(0x0), x52, uint64(0x0)) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Sub64(uint64(0x0), x51, uint64(uint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Sub64(uint64(0x0), x50, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Sub64(uint64(0x0), x49, uint64(uint1(x58))) - var x61 uint64 - cmovznzU64(&x61, uint1(x60), uint64(0x0), 0xffffffffffffffff) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x53, (x61 & 0xfffffffefffffc2f), uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x55, x61, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x57, x61, uint64(uint1(x65))) - var x68 uint64 - x68, _ = bits.Add64(x59, x61, uint64(uint1(x67))) - var x70 uint64 - cmovznzU64(&x70, x3, arg5[0], x62) - var x71 uint64 - cmovznzU64(&x71, x3, arg5[1], x64) - var x72 uint64 - cmovznzU64(&x72, x3, arg5[2], x66) - var x73 uint64 - cmovznzU64(&x73, x3, arg5[3], x68) - x74 := (uint1(x22) & 0x1) - var x75 uint64 - cmovznzU64(&x75, x74, uint64(0x0), x7) - var x76 uint64 - cmovznzU64(&x76, x74, uint64(0x0), x8) - var x77 uint64 - cmovznzU64(&x77, x74, uint64(0x0), x9) - var x78 uint64 - cmovznzU64(&x78, x74, uint64(0x0), x10) - var x79 uint64 - cmovznzU64(&x79, x74, uint64(0x0), x11) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x22, x75, uint64(0x0)) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x23, x76, uint64(uint1(x81))) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x24, x77, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x25, x78, uint64(uint1(x85))) - var x88 uint64 - x88, _ = bits.Add64(x26, x79, uint64(uint1(x87))) - var x90 uint64 - cmovznzU64(&x90, x74, uint64(0x0), x27) - var x91 uint64 - cmovznzU64(&x91, x74, uint64(0x0), x28) - var x92 uint64 - cmovznzU64(&x92, x74, uint64(0x0), x29) - var x93 uint64 - cmovznzU64(&x93, x74, uint64(0x0), x30) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64(x70, x90, uint64(0x0)) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x71, x91, uint64(uint1(x95))) - var x98 uint64 - var x99 uint64 - x98, x99 = bits.Add64(x72, x92, uint64(uint1(x97))) - var x100 uint64 - var x101 uint64 - x100, x101 = bits.Add64(x73, x93, uint64(uint1(x99))) - var x102 uint64 - var x103 uint64 - x102, x103 = bits.Sub64(x94, 0xfffffffefffffc2f, uint64(0x0)) - var x104 uint64 - var x105 uint64 - x104, x105 = bits.Sub64(x96, 0xffffffffffffffff, uint64(uint1(x103))) - var x106 uint64 - var x107 uint64 - x106, x107 = bits.Sub64(x98, 0xffffffffffffffff, uint64(uint1(x105))) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Sub64(x100, 0xffffffffffffffff, uint64(uint1(x107))) - var x111 uint64 - _, x111 = bits.Sub64(uint64(uint1(x101)), uint64(0x0), uint64(uint1(x109))) - var x112 uint64 - x112, _ = bits.Add64(x6, uint64(0x1), uint64(0x0)) - x114 := ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)) - x115 := ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)) - x116 := ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)) - x117 := ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)) - x118 := ((x88 & 0x8000000000000000) | (x88 >> 1)) - var x119 uint64 - cmovznzU64(&x119, uint1(x48), x39, x31) - var x120 uint64 - cmovznzU64(&x120, uint1(x48), x41, x33) - var x121 uint64 - cmovznzU64(&x121, uint1(x48), x43, x35) - var x122 uint64 - cmovznzU64(&x122, uint1(x48), x45, x37) - var x123 uint64 - cmovznzU64(&x123, uint1(x111), x102, x94) - var x124 uint64 - cmovznzU64(&x124, uint1(x111), x104, x96) - var x125 uint64 - cmovznzU64(&x125, uint1(x111), x106, x98) - var x126 uint64 - cmovznzU64(&x126, uint1(x111), x108, x100) - *out1 = x112 - out2[0] = x7 - out2[1] = x8 - out2[2] = x9 - out2[3] = x10 - out2[4] = x11 - out3[0] = x114 - out3[1] = x115 - out3[2] = x116 - out3[3] = x117 - out3[4] = x118 - out4[0] = x119 - out4[1] = x120 - out4[2] = x121 - out4[3] = x122 - out5[0] = x123 - out5[1] = x124 - out5[2] = x125 - out5[3] = x126 -} - -// DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). -// -// Postconditions: -// -// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) -// 0 ≤ eval out1 < m -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func DivstepPrecomp(out1 *[4]uint64) { - out1[0] = 0xf201a41831525e0a - out1[1] = 0x9953f9ddcd648d85 - out1[2] = 0xe86029463db210a9 - out1[3] = 0x24fb8a3104b03709 -} diff --git a/crypto/core/curves/native/k256/fq/fq.go b/crypto/core/curves/native/k256/fq/fq.go deleted file mode 100644 index 6cc63c091..000000000 --- a/crypto/core/curves/native/k256/fq/fq.go +++ /dev/null @@ -1,493 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -var ( - k256FqInitonce sync.Once - k256FqParams native.FieldParams -) - -func K256FqNew() *native.Field { - return &native.Field{ - Value: [native.FieldLimbs]uint64{}, - Params: getK256FqParams(), - Arithmetic: k256FqArithmetic{}, - } -} - -func k256FqParamsInit() { - k256FqParams = native.FieldParams{ - R: [native.FieldLimbs]uint64{ - 0x402da1732fc9bebf, - 0x4551231950b75fc4, - 0x0000000000000001, - 0x0000000000000000, - }, - R2: [native.FieldLimbs]uint64{ - 0x896cf21467d7d140, - 0x741496c20e7cf878, - 0xe697f5e45bcd07c6, - 0x9d671cd581c69bc5, - }, - R3: [native.FieldLimbs]uint64{ - 0x7bc0cfe0e9ff41ed, - 0x0017648444d4322c, - 0xb1b31347f1d0b2da, - 0x555d800c18ef116d, - }, - Modulus: [native.FieldLimbs]uint64{ - 0xbfd25e8cd0364141, - 0xbaaedce6af48a03b, - 0xfffffffffffffffe, - 0xffffffffffffffff, - }, - BiModulus: new(big.Int).SetBytes([]byte{ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, - }, - ), - } -} - -func getK256FqParams() *native.FieldParams { - k256FqInitonce.Do(k256FqParamsInit) - return &k256FqParams -} - -// k256FqArithmetic is a struct with all the methods needed for working -// in mod q -type k256FqArithmetic struct{} - -// ToMontgomery converts this field to montgomery form -func (f k256FqArithmetic) ToMontgomery(out, arg *[native.FieldLimbs]uint64) { - ToMontgomery((*MontgomeryDomainFieldElement)(out), (*NonMontgomeryDomainFieldElement)(arg)) -} - -// FromMontgomery converts this field from montgomery form -func (f k256FqArithmetic) FromMontgomery(out, arg *[native.FieldLimbs]uint64) { - FromMontgomery((*NonMontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Neg performs modular negation -func (f k256FqArithmetic) Neg(out, arg *[native.FieldLimbs]uint64) { - Opp((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Square performs modular square -func (f k256FqArithmetic) Square(out, arg *[native.FieldLimbs]uint64) { - Square((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Mul performs modular multiplication -func (f k256FqArithmetic) Mul(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Mul( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Add performs modular addition -func (f k256FqArithmetic) Add(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Add( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sub performs modular subtraction -func (f k256FqArithmetic) Sub(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Sub( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sqrt performs modular square root -func (f k256FqArithmetic) Sqrt(wasSquare *int, out, arg *[native.FieldLimbs]uint64) { - // See sqrt_ts_ct at - // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.4 - // c1 := 6 - // c2 := (q - 1) / (2^c1) - // c2 := [4]uint64{ - // 0xeeff497a3340d905, - // 0xfaeabb739abd2280, - // 0xffffffffffffffff, - // 0x03ffffffffffffff, - //} - // c3 := (c2 - 1) / 2 - c3 := [native.FieldLimbs]uint64{ - 0x777fa4bd19a06c82, - 0xfd755db9cd5e9140, - 0xffffffffffffffff, - 0x01ffffffffffffff, - } - // c4 := generator - // c5 := new(Fq).pow(generator, c2) - c5 := [native.FieldLimbs]uint64{ - 0x944cf2a220910e04, - 0x815c829c780589f4, - 0x55980b07bc222113, - 0xc702b0d248825b36, - } - var z, t, b, c, tv [native.FieldLimbs]uint64 - - native.Pow(&z, arg, &c3, getK256FqParams(), f) - Square((*MontgomeryDomainFieldElement)(&t), (*MontgomeryDomainFieldElement)(&z)) - Mul( - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(arg), - ) - Mul( - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(arg), - ) - - copy(b[:], t[:]) - copy(c[:], c5[:]) - - for i := s; i >= 2; i-- { - for j := 1; j <= i-2; j++ { - Square((*MontgomeryDomainFieldElement)(&b), (*MontgomeryDomainFieldElement)(&b)) - } - // if b == 1 flag = 0 else flag = 1 - flag := -(&native.Field{ - Value: b, - Params: getK256FqParams(), - Arithmetic: f, - }).IsOne() + 1 - Mul( - (*MontgomeryDomainFieldElement)(&tv), - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(&c), - ) - Selectznz(&z, uint1(flag), &z, &tv) - Square((*MontgomeryDomainFieldElement)(&c), (*MontgomeryDomainFieldElement)(&c)) - Mul( - (*MontgomeryDomainFieldElement)(&tv), - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(&c), - ) - Selectznz(&t, uint1(flag), &t, &tv) - copy(b[:], t[:]) - } - Square((*MontgomeryDomainFieldElement)(&c), (*MontgomeryDomainFieldElement)(&z)) - *wasSquare = (&native.Field{ - Value: c, - Params: getK256FqParams(), - Arithmetic: f, - }).Equal(&native.Field{ - Value: *arg, - Params: getK256FqParams(), - Arithmetic: f, - }) - Selectznz(out, uint1(*wasSquare), out, &z) -} - -// Invert performs modular inverse -func (f k256FqArithmetic) Invert(wasInverted *int, out, arg *[native.FieldLimbs]uint64) { - // Using an addition chain from - // https://briansmith.org/ecc-inversion-addition-chains-01#secp256k1_scalar_inversion - var x1, x10, x11, x101, x111, x1001, x1011, x1101 [native.FieldLimbs]uint64 - var x6, x8, x14, x28, x56, tmp [native.FieldLimbs]uint64 - - copy(x1[:], arg[:]) - native.Pow2k(&x10, arg, 1, f) - Mul( - (*MontgomeryDomainFieldElement)(&x11), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x1), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x101), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x11), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x111), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x101), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x1001), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x111), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x1011), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x1001), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x1101), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x1011), - ) - - native.Pow2k(&x6, &x1101, 2, f) - Mul( - (*MontgomeryDomainFieldElement)(&x6), - (*MontgomeryDomainFieldElement)(&x6), - (*MontgomeryDomainFieldElement)(&x1011), - ) - - native.Pow2k(&x8, &x6, 2, f) - Mul( - (*MontgomeryDomainFieldElement)(&x8), - (*MontgomeryDomainFieldElement)(&x8), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&x14, &x8, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&x14), - (*MontgomeryDomainFieldElement)(&x14), - (*MontgomeryDomainFieldElement)(&x6), - ) - - native.Pow2k(&x28, &x14, 14, f) - Mul( - (*MontgomeryDomainFieldElement)(&x28), - (*MontgomeryDomainFieldElement)(&x28), - (*MontgomeryDomainFieldElement)(&x14), - ) - - native.Pow2k(&x56, &x28, 28, f) - Mul( - (*MontgomeryDomainFieldElement)(&x56), - (*MontgomeryDomainFieldElement)(&x56), - (*MontgomeryDomainFieldElement)(&x28), - ) - - native.Pow2k(&tmp, &x56, 56, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x56), - ) - - native.Pow2k(&tmp, &tmp, 14, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x14), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1011), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1011), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1101), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1001), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 10, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 9, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x8), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1001), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1011), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1101), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1101), - ) - - native.Pow2k(&tmp, &tmp, 10, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1101), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1001), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1), - ) - - native.Pow2k(&tmp, &tmp, 8, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x6), - ) - - *wasInverted = (&native.Field{ - Value: *arg, - Params: getK256FqParams(), - Arithmetic: f, - }).IsNonZero() - Selectznz(out, uint1(*wasInverted), out, &tmp) -} - -// FromBytes converts a little endian byte array into a field element -func (f k256FqArithmetic) FromBytes(out *[native.FieldLimbs]uint64, arg *[native.FieldBytes]byte) { - FromBytes(out, arg) -} - -// ToBytes converts a field element to a little endian byte array -func (f k256FqArithmetic) ToBytes(out *[native.FieldBytes]byte, arg *[native.FieldLimbs]uint64) { - ToBytes(out, arg) -} - -// Selectznz performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f k256FqArithmetic) Selectznz(out, arg1, arg2 *[native.FieldLimbs]uint64, choice int) { - Selectznz(out, uint1(choice), arg1, arg2) -} - -// generator = 7 mod q is a generator of the `q - 1` order multiplicative -// subgroup, or in other words a primitive element of the field. -// generator^t where t * 2^s + 1 = q -var generator = &[native.FieldLimbs]uint64{ - 0xc13f6a264e843739, - 0xe537f5b135039e5d, - 0x0000000000000008, - 0x0000000000000000, -} - -// s satisfies the equation 2^s * t = q - 1 with t odd. -var s = 6 diff --git a/crypto/core/curves/native/k256/fq/fq_test.go b/crypto/core/curves/native/k256/fq/fq_test.go deleted file mode 100644 index 9ff8fae27..000000000 --- a/crypto/core/curves/native/k256/fq/fq_test.go +++ /dev/null @@ -1,330 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFqSetOne(t *testing.T) { - fq := K256FqNew().SetOne() - require.NotNil(t, fq) - require.Equal(t, fq.Value, getK256FqParams().R) -} - -func TestFqSetUint64(t *testing.T) { - act := K256FqNew().SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act.Value[0], uint64(0xF000000000000000)) -} - -func TestFqAdd(t *testing.T) { - lhs := K256FqNew().SetOne() - rhs := K256FqNew().SetOne() - exp := K256FqNew().SetUint64(2) - res := K256FqNew().Add(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := K256FqNew().Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqSub(t *testing.T) { - lhs := K256FqNew().SetOne() - rhs := K256FqNew().SetOne() - exp := K256FqNew().SetZero() - res := K256FqNew().Sub(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := K256FqNew().Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqMul(t *testing.T) { - lhs := K256FqNew().SetOne() - rhs := K256FqNew().SetOne() - exp := K256FqNew().SetOne() - res := K256FqNew().Mul(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := K256FqNew().Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqDouble(t *testing.T) { - a := K256FqNew().SetUint64(2) - e := K256FqNew().SetUint64(4) - require.Equal(t, e, K256FqNew().Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = K256FqNew().SetUint64(uint64(tv)) - e = K256FqNew().SetUint64(ttv) - require.Equal(t, e, K256FqNew().Double(a)) - } -} - -func TestFqSquare(t *testing.T) { - a := K256FqNew().SetUint64(4) - e := K256FqNew().SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFqNeg(t *testing.T) { - g := K256FqNew().SetRaw(generator) - a := K256FqNew().SetOne() - a.Neg(a) - e := K256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x7fa4bd19a06c8282, 0x755db9cd5e914077, 0xfffffffffffffffd, 0xffffffffffffffff}) - require.Equal(t, e, a) - a.Neg(g) - e = K256FqNew().SetRaw(&[native.FieldLimbs]uint64{0xfe92f46681b20a08, 0xd576e7357a4501dd, 0xfffffffffffffff5, 0xffffffffffffffff}) - require.Equal(t, e, a) -} - -func TestFqExp(t *testing.T) { - e := K256FqNew().SetUint64(8) - a := K256FqNew().SetUint64(2) - by := K256FqNew().SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFqSqrt(t *testing.T) { - t1 := K256FqNew().SetUint64(2) - t2 := K256FqNew().Neg(t1) - t3 := K256FqNew().Square(t1) - _, wasSquare := t3.Sqrt(t3) - - require.True(t, wasSquare) - require.Equal(t, 1, t1.Equal(t3)|t2.Equal(t3)) - t1.SetUint64(5) - _, wasSquare = K256FqNew().Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFqInvert(t *testing.T) { - twoInv := K256FqNew().SetLimbs(&[native.FieldLimbs]uint64{0xdfe92f46681b20a1, 0x5d576e7357a4501d, 0xffffffffffffffff, 0x7fffffffffffffff}) - two := K256FqNew().SetUint64(2) - a, inverted := K256FqNew().Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnity := K256FqNew().SetLimbs(&[native.FieldLimbs]uint64{0x8619a9e760c01d0c, 0xa883c4fba37998df, 0x45607580b6eabd98, 0xf252b002544b2f99}) - rootOfUnityInv := K256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x7d99f8e21447e314, 0x5b60c477e7728d4c, 0xd78befc191f58654, 0x6897e5ff7824360f}) - a, inverted = K256FqNew().Invert(rootOfUnity) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := K256FqNew().SetUint64(9) - rhs := K256FqNew().SetUint64(3) - rhsInv, inverted := K256FqNew().Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, K256FqNew().Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = K256FqNew().Invert(rhs) - require.False(t, inverted) -} - -func TestFqCMove(t *testing.T) { - t1 := K256FqNew().SetUint64(5) - t2 := K256FqNew().SetUint64(10) - require.Equal(t, t1, K256FqNew().CMove(t1, t2, 0)) - require.Equal(t, t2, K256FqNew().CMove(t1, t2, 1)) -} - -func TestFqBytes(t *testing.T) { - t1 := K256FqNew().SetUint64(99) - seq := t1.Bytes() - t2, err := K256FqNew().SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFqCmp(t *testing.T) { - tests := []struct { - a *native.Field - b *native.Field - e int - }{ - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{2731658267414164836, 14655288906067898431, 6537465423330262322, 8306191141697566219}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{6472764012681988529, 10848812988401906064, 2961825807536828898, 4282183981941645679}), - e: 1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{8023004109510539223, 4652004072850285717, 1877219145646046927, 383214385093921911}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{10099384440823804262, 16139476942229308465, 8636966320777393798, 5435928725024696785}), - e: -1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{3741840066202388211, 12165774400417314871, 16619312580230515379, 16195032234110087705}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{3905865991286066744, 543690822309071825, 17963103015950210055, 3745476720756119742}), - e: 1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{16660853697936147788, 7799793619412111108, 13515141085171033220, 2641079731236069032}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{17790588295388238399, 571847801379669440, 14537208974498222469, 12792570372087452754}), - e: -1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{3912839285384959186, 2701177075110484070, 6453856448115499033, 6475797457962597458}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{1282566391665688512, 13503640416992806563, 2962240104675990153, 3374904770947067689}), - e: 1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{5716631803409360103, 7859567470082614154, 12747956220853330146, 18434584096087315020}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{16317076441459028418, 12854146980376319601, 2258436689269031143, 9531877130792223752}), - e: 1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{17955191469941083403, 10350326247207200880, 17263512235150705075, 12700328451238078022}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{6767595547459644695, 7146403825494928147, 12269344038346710612, 9122477829383225603}), - e: 1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{17099388671847024438, 6426264987820696548, 10641143464957227405, 7709745403700754098}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{10799154372990268556, 17178492485719929374, 5705777922258988797, 8051037767683567782}), - e: -1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{4567139260680454325, 1629385880182139061, 16607020832317899145, 1261011562621553200}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{13487234491304534488, 17872642955936089265, 17651026784972590233, 9468934643333871559}), - e: -1, - }, - { - a: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{18071070103467571798, 11787850505799426140, 10631355976141928593, 4867785203635092610}), - b: K256FqNew().SetRaw(&[native.FieldLimbs]uint64{12596443599426461624, 10176122686151524591, 17075755296887483439, 6726169532695070719}), - e: -1, - }, - } - - for _, test := range tests { - require.Equal(t, test.e, test.a.Cmp(test.b)) - require.Equal(t, -test.e, test.b.Cmp(test.a)) - require.Equal(t, 0, test.a.Cmp(test.a)) - require.Equal(t, 0, test.b.Cmp(test.b)) - } -} - -func TestFqBigInt(t *testing.T) { - t1 := K256FqNew().SetBigInt(big.NewInt(9999)) - t2 := K256FqNew().SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := K256FqNew().SetRaw(&[native.FieldLimbs]uint64{0xa764d3f6f152f222, 0x3b5dc8aacb9297b7, 0xb015fa9d2b3efdc6, 0x567360cef000f24a}) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Value[0] = 0x186d8a95dee34f1f - e.Value[1] = 0x7f51143be3b60884 - e.Value[2] = 0x4fea0562d4c10238 - e.Value[3] = 0xa98c9f310fff0db5 - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFqSetBytesWide(t *testing.T) { - e := K256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x70620a92b4f2eb7a, 0xd04588eb9c228a3a, 0xccb71ae40a10491c, 0x61cf39d70a8b33b7}) - - a := K256FqNew().SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} - -func TestFpSetBytesWideBigInt(t *testing.T) { - params := getK256FqParams() - var tv2 [64]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, params.BiModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a := K256FqNew().SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} diff --git a/crypto/core/curves/native/k256/fq/secp256k1_fq.go b/crypto/core/curves/native/k256/fq/secp256k1_fq.go deleted file mode 100755 index 9a78dbe99..000000000 --- a/crypto/core/curves/native/k256/fq/secp256k1_fq.go +++ /dev/null @@ -1,2002 +0,0 @@ -// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Go --no-wide-int --relax-primitive-carry-to-bitwidth 32,64 --cmovznz-by-mul --internal-static --package-case flatcase --public-function-case UpperCamelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case camelCase --no-prefix-fiat --doc-newline-in-typedef-bounds --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --doc-text-before-function-name ” --doc-text-before-type-name ” --package-name secp256k1_q ” 64 '2^256 - 432420386565659656852420866394968145599' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp -// -// curve description (via package name): secp256k1_q -// -// machine_wordsize = 64 (from "64") -// -// requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp -// -// m = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 (from "2^256 - 432420386565659656852420866394968145599") -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 -package fq - -import "math/bits" - -type ( - uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -) - -// MontgomeryDomainFieldElement is a field element in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type MontgomeryDomainFieldElement [4]uint64 - -// NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type NonMontgomeryDomainFieldElement [4]uint64 - -// cmovznzU64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func cmovznzU64(out1 *uint64, arg1 uint1, arg2 uint64, arg3 uint64) { - x1 := (uint64(arg1) * 0xffffffffffffffff) - x2 := ((x1 & arg3) | ((^x1) & arg2)) - *out1 = x2 -} - -// Mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Mul( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x4b0dff665588b13f) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffffffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xfffffffffffffffe) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xbaaedce6af48a03b) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xbfd25e8cd0364141) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg2[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg2[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg2[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0x4b0dff665588b13f) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffffffffffff) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xfffffffffffffffe) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xbaaedce6af48a03b) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xbfd25e8cd0364141) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg2[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg2[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg2[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg2[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0x4b0dff665588b13f) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffffffffffff) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xfffffffffffffffe) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xbaaedce6af48a03b) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xbfd25e8cd0364141) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg2[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg2[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg2[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg2[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0x4b0dff665588b13f) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffffffffffff) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xfffffffffffffffe) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xbaaedce6af48a03b) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xbfd25e8cd0364141) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xbfd25e8cd0364141, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xbaaedce6af48a03b, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xfffffffffffffffe, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffffffffffff, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func Square(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x4b0dff665588b13f) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffffffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xfffffffffffffffe) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xbaaedce6af48a03b) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xbfd25e8cd0364141) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg1[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg1[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg1[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg1[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0x4b0dff665588b13f) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffffffffffff) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xfffffffffffffffe) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xbaaedce6af48a03b) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xbfd25e8cd0364141) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg1[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg1[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg1[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg1[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0x4b0dff665588b13f) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffffffffffff) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xfffffffffffffffe) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xbaaedce6af48a03b) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xbfd25e8cd0364141) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg1[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg1[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg1[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg1[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0x4b0dff665588b13f) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffffffffffff) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xfffffffffffffffe) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xbaaedce6af48a03b) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xbfd25e8cd0364141) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xbfd25e8cd0364141, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xbaaedce6af48a03b, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xfffffffffffffffe, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffffffffffff, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Add( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - var x10 uint64 - x9, x10 = bits.Sub64(x1, 0xbfd25e8cd0364141, uint64(0x0)) - var x11 uint64 - var x12 uint64 - x11, x12 = bits.Sub64(x3, 0xbaaedce6af48a03b, uint64(uint1(x10))) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Sub64(x5, 0xfffffffffffffffe, uint64(uint1(x12))) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Sub64(x7, 0xffffffffffffffff, uint64(uint1(x14))) - var x18 uint64 - _, x18 = bits.Sub64(uint64(uint1(x8)), uint64(0x0), uint64(uint1(x16))) - var x19 uint64 - cmovznzU64(&x19, uint1(x18), x9, x1) - var x20 uint64 - cmovznzU64(&x20, uint1(x18), x11, x3) - var x21 uint64 - cmovznzU64(&x21, uint1(x18), x13, x5) - var x22 uint64 - cmovznzU64(&x22, uint1(x18), x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// Sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Sub( - out1 *MontgomeryDomainFieldElement, - arg1 *MontgomeryDomainFieldElement, - arg2 *MontgomeryDomainFieldElement, -) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xbfd25e8cd0364141), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xbaaedce6af48a03b), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, (x9 & 0xfffffffffffffffe), uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, x9, uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// Opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func Opp(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xbfd25e8cd0364141), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xbaaedce6af48a03b), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, (x9 & 0xfffffffffffffffe), uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, x9, uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// FromMontgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func FromMontgomery(out1 *NonMontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0x4b0dff665588b13f) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0xffffffffffffffff) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0xfffffffffffffffe) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0xbaaedce6af48a03b) - var x10 uint64 - var x11 uint64 - x11, x10 = bits.Mul64(x2, 0xbfd25e8cd0364141) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x11, x8, uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x9, x6, uint64(uint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(x7, x4, uint64(uint1(x15))) - var x19 uint64 - _, x19 = bits.Add64(x1, x10, uint64(0x0)) - var x20 uint64 - var x21 uint64 - x20, x21 = bits.Add64(uint64(0x0), x12, uint64(uint1(x19))) - var x22 uint64 - var x23 uint64 - x22, x23 = bits.Add64(uint64(0x0), x14, uint64(uint1(x21))) - var x24 uint64 - var x25 uint64 - x24, x25 = bits.Add64(uint64(0x0), x16, uint64(uint1(x23))) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(uint64(0x0), (uint64(uint1(x17)) + x5), uint64(uint1(x25))) - var x28 uint64 - var x29 uint64 - x28, x29 = bits.Add64(x20, arg1[1], uint64(0x0)) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x22, uint64(0x0), uint64(uint1(x29))) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x24, uint64(0x0), uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x26, uint64(0x0), uint64(uint1(x33))) - var x36 uint64 - _, x36 = bits.Mul64(x28, 0x4b0dff665588b13f) - var x38 uint64 - var x39 uint64 - x39, x38 = bits.Mul64(x36, 0xffffffffffffffff) - var x40 uint64 - var x41 uint64 - x41, x40 = bits.Mul64(x36, 0xfffffffffffffffe) - var x42 uint64 - var x43 uint64 - x43, x42 = bits.Mul64(x36, 0xbaaedce6af48a03b) - var x44 uint64 - var x45 uint64 - x45, x44 = bits.Mul64(x36, 0xbfd25e8cd0364141) - var x46 uint64 - var x47 uint64 - x46, x47 = bits.Add64(x45, x42, uint64(0x0)) - var x48 uint64 - var x49 uint64 - x48, x49 = bits.Add64(x43, x40, uint64(uint1(x47))) - var x50 uint64 - var x51 uint64 - x50, x51 = bits.Add64(x41, x38, uint64(uint1(x49))) - var x53 uint64 - _, x53 = bits.Add64(x28, x44, uint64(0x0)) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x30, x46, uint64(uint1(x53))) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x32, x48, uint64(uint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x34, x50, uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64( - (uint64(uint1(x35)) + uint64(uint1(x27))), - (uint64(uint1(x51)) + x39), - uint64(uint1(x59)), - ) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x54, arg1[2], uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x56, uint64(0x0), uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x58, uint64(0x0), uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x60, uint64(0x0), uint64(uint1(x67))) - var x70 uint64 - _, x70 = bits.Mul64(x62, 0x4b0dff665588b13f) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x70, 0xffffffffffffffff) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x70, 0xfffffffffffffffe) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x70, 0xbaaedce6af48a03b) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x70, 0xbfd25e8cd0364141) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x79, x76, uint64(0x0)) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x77, x74, uint64(uint1(x81))) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x75, x72, uint64(uint1(x83))) - var x87 uint64 - _, x87 = bits.Add64(x62, x78, uint64(0x0)) - var x88 uint64 - var x89 uint64 - x88, x89 = bits.Add64(x64, x80, uint64(uint1(x87))) - var x90 uint64 - var x91 uint64 - x90, x91 = bits.Add64(x66, x82, uint64(uint1(x89))) - var x92 uint64 - var x93 uint64 - x92, x93 = bits.Add64(x68, x84, uint64(uint1(x91))) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64( - (uint64(uint1(x69)) + uint64(uint1(x61))), - (uint64(uint1(x85)) + x73), - uint64(uint1(x93)), - ) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x88, arg1[3], uint64(0x0)) - var x98 uint64 - var x99 uint64 - x98, x99 = bits.Add64(x90, uint64(0x0), uint64(uint1(x97))) - var x100 uint64 - var x101 uint64 - x100, x101 = bits.Add64(x92, uint64(0x0), uint64(uint1(x99))) - var x102 uint64 - var x103 uint64 - x102, x103 = bits.Add64(x94, uint64(0x0), uint64(uint1(x101))) - var x104 uint64 - _, x104 = bits.Mul64(x96, 0x4b0dff665588b13f) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x104, 0xffffffffffffffff) - var x108 uint64 - var x109 uint64 - x109, x108 = bits.Mul64(x104, 0xfffffffffffffffe) - var x110 uint64 - var x111 uint64 - x111, x110 = bits.Mul64(x104, 0xbaaedce6af48a03b) - var x112 uint64 - var x113 uint64 - x113, x112 = bits.Mul64(x104, 0xbfd25e8cd0364141) - var x114 uint64 - var x115 uint64 - x114, x115 = bits.Add64(x113, x110, uint64(0x0)) - var x116 uint64 - var x117 uint64 - x116, x117 = bits.Add64(x111, x108, uint64(uint1(x115))) - var x118 uint64 - var x119 uint64 - x118, x119 = bits.Add64(x109, x106, uint64(uint1(x117))) - var x121 uint64 - _, x121 = bits.Add64(x96, x112, uint64(0x0)) - var x122 uint64 - var x123 uint64 - x122, x123 = bits.Add64(x98, x114, uint64(uint1(x121))) - var x124 uint64 - var x125 uint64 - x124, x125 = bits.Add64(x100, x116, uint64(uint1(x123))) - var x126 uint64 - var x127 uint64 - x126, x127 = bits.Add64(x102, x118, uint64(uint1(x125))) - var x128 uint64 - var x129 uint64 - x128, x129 = bits.Add64( - (uint64(uint1(x103)) + uint64(uint1(x95))), - (uint64(uint1(x119)) + x107), - uint64(uint1(x127)), - ) - var x130 uint64 - var x131 uint64 - x130, x131 = bits.Sub64(x122, 0xbfd25e8cd0364141, uint64(0x0)) - var x132 uint64 - var x133 uint64 - x132, x133 = bits.Sub64(x124, 0xbaaedce6af48a03b, uint64(uint1(x131))) - var x134 uint64 - var x135 uint64 - x134, x135 = bits.Sub64(x126, 0xfffffffffffffffe, uint64(uint1(x133))) - var x136 uint64 - var x137 uint64 - x136, x137 = bits.Sub64(x128, 0xffffffffffffffff, uint64(uint1(x135))) - var x139 uint64 - _, x139 = bits.Sub64(uint64(uint1(x129)), uint64(0x0), uint64(uint1(x137))) - var x140 uint64 - cmovznzU64(&x140, uint1(x139), x130, x122) - var x141 uint64 - cmovznzU64(&x141, uint1(x139), x132, x124) - var x142 uint64 - cmovznzU64(&x142, uint1(x139), x134, x126) - var x143 uint64 - cmovznzU64(&x143, uint1(x139), x136, x128) - out1[0] = x140 - out1[1] = x141 - out1[2] = x142 - out1[3] = x143 -} - -// ToMontgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func ToMontgomery(out1 *MontgomeryDomainFieldElement, arg1 *NonMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x9d671cd581c69bc5) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0xe697f5e45bcd07c6) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0x741496c20e7cf878) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0x896cf21467d7d140) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - var x19 uint64 - _, x19 = bits.Mul64(x11, 0x4b0dff665588b13f) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x19, 0xffffffffffffffff) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x19, 0xfffffffffffffffe) - var x25 uint64 - var x26 uint64 - x26, x25 = bits.Mul64(x19, 0xbaaedce6af48a03b) - var x27 uint64 - var x28 uint64 - x28, x27 = bits.Mul64(x19, 0xbfd25e8cd0364141) - var x29 uint64 - var x30 uint64 - x29, x30 = bits.Add64(x28, x25, uint64(0x0)) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x26, x23, uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x24, x21, uint64(uint1(x32))) - var x36 uint64 - _, x36 = bits.Add64(x11, x27, uint64(0x0)) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x13, x29, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x15, x31, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x17, x33, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64((uint64(uint1(x18)) + x6), (uint64(uint1(x34)) + x22), uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, 0x9d671cd581c69bc5) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, 0xe697f5e45bcd07c6) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, 0x741496c20e7cf878) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, 0x896cf21467d7d140) - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Add64(x52, x49, uint64(0x0)) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x50, x47, uint64(uint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x48, x45, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x37, x51, uint64(0x0)) - var x61 uint64 - var x62 uint64 - x61, x62 = bits.Add64(x39, x53, uint64(uint1(x60))) - var x63 uint64 - var x64 uint64 - x63, x64 = bits.Add64(x41, x55, uint64(uint1(x62))) - var x65 uint64 - var x66 uint64 - x65, x66 = bits.Add64(x43, x57, uint64(uint1(x64))) - var x67 uint64 - _, x67 = bits.Mul64(x59, 0x4b0dff665588b13f) - var x69 uint64 - var x70 uint64 - x70, x69 = bits.Mul64(x67, 0xffffffffffffffff) - var x71 uint64 - var x72 uint64 - x72, x71 = bits.Mul64(x67, 0xfffffffffffffffe) - var x73 uint64 - var x74 uint64 - x74, x73 = bits.Mul64(x67, 0xbaaedce6af48a03b) - var x75 uint64 - var x76 uint64 - x76, x75 = bits.Mul64(x67, 0xbfd25e8cd0364141) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Add64(x76, x73, uint64(0x0)) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x74, x71, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x72, x69, uint64(uint1(x80))) - var x84 uint64 - _, x84 = bits.Add64(x59, x75, uint64(0x0)) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Add64(x61, x77, uint64(uint1(x84))) - var x87 uint64 - var x88 uint64 - x87, x88 = bits.Add64(x63, x79, uint64(uint1(x86))) - var x89 uint64 - var x90 uint64 - x89, x90 = bits.Add64(x65, x81, uint64(uint1(x88))) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64( - ((uint64(uint1(x66)) + uint64(uint1(x44))) + (uint64(uint1(x58)) + x46)), - (uint64(uint1(x82)) + x70), - uint64(uint1(x90)), - ) - var x93 uint64 - var x94 uint64 - x94, x93 = bits.Mul64(x2, 0x9d671cd581c69bc5) - var x95 uint64 - var x96 uint64 - x96, x95 = bits.Mul64(x2, 0xe697f5e45bcd07c6) - var x97 uint64 - var x98 uint64 - x98, x97 = bits.Mul64(x2, 0x741496c20e7cf878) - var x99 uint64 - var x100 uint64 - x100, x99 = bits.Mul64(x2, 0x896cf21467d7d140) - var x101 uint64 - var x102 uint64 - x101, x102 = bits.Add64(x100, x97, uint64(0x0)) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x98, x95, uint64(uint1(x102))) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x96, x93, uint64(uint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x85, x99, uint64(0x0)) - var x109 uint64 - var x110 uint64 - x109, x110 = bits.Add64(x87, x101, uint64(uint1(x108))) - var x111 uint64 - var x112 uint64 - x111, x112 = bits.Add64(x89, x103, uint64(uint1(x110))) - var x113 uint64 - var x114 uint64 - x113, x114 = bits.Add64(x91, x105, uint64(uint1(x112))) - var x115 uint64 - _, x115 = bits.Mul64(x107, 0x4b0dff665588b13f) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x115, 0xffffffffffffffff) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x115, 0xfffffffffffffffe) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x115, 0xbaaedce6af48a03b) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x115, 0xbfd25e8cd0364141) - var x125 uint64 - var x126 uint64 - x125, x126 = bits.Add64(x124, x121, uint64(0x0)) - var x127 uint64 - var x128 uint64 - x127, x128 = bits.Add64(x122, x119, uint64(uint1(x126))) - var x129 uint64 - var x130 uint64 - x129, x130 = bits.Add64(x120, x117, uint64(uint1(x128))) - var x132 uint64 - _, x132 = bits.Add64(x107, x123, uint64(0x0)) - var x133 uint64 - var x134 uint64 - x133, x134 = bits.Add64(x109, x125, uint64(uint1(x132))) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x111, x127, uint64(uint1(x134))) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x113, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64( - ((uint64(uint1(x114)) + uint64(uint1(x92))) + (uint64(uint1(x106)) + x94)), - (uint64(uint1(x130)) + x118), - uint64(uint1(x138)), - ) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, 0x9d671cd581c69bc5) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x3, 0xe697f5e45bcd07c6) - var x145 uint64 - var x146 uint64 - x146, x145 = bits.Mul64(x3, 0x741496c20e7cf878) - var x147 uint64 - var x148 uint64 - x148, x147 = bits.Mul64(x3, 0x896cf21467d7d140) - var x149 uint64 - var x150 uint64 - x149, x150 = bits.Add64(x148, x145, uint64(0x0)) - var x151 uint64 - var x152 uint64 - x151, x152 = bits.Add64(x146, x143, uint64(uint1(x150))) - var x153 uint64 - var x154 uint64 - x153, x154 = bits.Add64(x144, x141, uint64(uint1(x152))) - var x155 uint64 - var x156 uint64 - x155, x156 = bits.Add64(x133, x147, uint64(0x0)) - var x157 uint64 - var x158 uint64 - x157, x158 = bits.Add64(x135, x149, uint64(uint1(x156))) - var x159 uint64 - var x160 uint64 - x159, x160 = bits.Add64(x137, x151, uint64(uint1(x158))) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x139, x153, uint64(uint1(x160))) - var x163 uint64 - _, x163 = bits.Mul64(x155, 0x4b0dff665588b13f) - var x165 uint64 - var x166 uint64 - x166, x165 = bits.Mul64(x163, 0xffffffffffffffff) - var x167 uint64 - var x168 uint64 - x168, x167 = bits.Mul64(x163, 0xfffffffffffffffe) - var x169 uint64 - var x170 uint64 - x170, x169 = bits.Mul64(x163, 0xbaaedce6af48a03b) - var x171 uint64 - var x172 uint64 - x172, x171 = bits.Mul64(x163, 0xbfd25e8cd0364141) - var x173 uint64 - var x174 uint64 - x173, x174 = bits.Add64(x172, x169, uint64(0x0)) - var x175 uint64 - var x176 uint64 - x175, x176 = bits.Add64(x170, x167, uint64(uint1(x174))) - var x177 uint64 - var x178 uint64 - x177, x178 = bits.Add64(x168, x165, uint64(uint1(x176))) - var x180 uint64 - _, x180 = bits.Add64(x155, x171, uint64(0x0)) - var x181 uint64 - var x182 uint64 - x181, x182 = bits.Add64(x157, x173, uint64(uint1(x180))) - var x183 uint64 - var x184 uint64 - x183, x184 = bits.Add64(x159, x175, uint64(uint1(x182))) - var x185 uint64 - var x186 uint64 - x185, x186 = bits.Add64(x161, x177, uint64(uint1(x184))) - var x187 uint64 - var x188 uint64 - x187, x188 = bits.Add64( - ((uint64(uint1(x162)) + uint64(uint1(x140))) + (uint64(uint1(x154)) + x142)), - (uint64(uint1(x178)) + x166), - uint64(uint1(x186)), - ) - var x189 uint64 - var x190 uint64 - x189, x190 = bits.Sub64(x181, 0xbfd25e8cd0364141, uint64(0x0)) - var x191 uint64 - var x192 uint64 - x191, x192 = bits.Sub64(x183, 0xbaaedce6af48a03b, uint64(uint1(x190))) - var x193 uint64 - var x194 uint64 - x193, x194 = bits.Sub64(x185, 0xfffffffffffffffe, uint64(uint1(x192))) - var x195 uint64 - var x196 uint64 - x195, x196 = bits.Sub64(x187, 0xffffffffffffffff, uint64(uint1(x194))) - var x198 uint64 - _, x198 = bits.Sub64(uint64(uint1(x188)), uint64(0x0), uint64(uint1(x196))) - var x199 uint64 - cmovznzU64(&x199, uint1(x198), x189, x181) - var x200 uint64 - cmovznzU64(&x200, uint1(x198), x191, x183) - var x201 uint64 - cmovznzU64(&x201, uint1(x198), x193, x185) - var x202 uint64 - cmovznzU64(&x202, uint1(x198), x195, x187) - out1[0] = x199 - out1[1] = x200 - out1[2] = x201 - out1[3] = x202 -} - -// Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func Nonzero(out1 *uint64, arg1 *[4]uint64) { - x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) - *out1 = x1 -} - -// Selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Selectznz(out1 *[4]uint64, arg1 uint1, arg2 *[4]uint64, arg3 *[4]uint64) { - var x1 uint64 - cmovznzU64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - cmovznzU64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - cmovznzU64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - cmovznzU64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -func ToBytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func FromBytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} - -// SetOne returns the field element one in the Montgomery domain. -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = 1 mod m -// 0 ≤ eval out1 < m -func SetOne(out1 *MontgomeryDomainFieldElement) { - out1[0] = 0x402da1732fc9bebf - out1[1] = 0x4551231950b75fc4 - out1[2] = uint64(0x1) - out1[3] = uint64(0x0) -} - -// Msat returns the saturated representation of the prime modulus. -// -// Postconditions: -// -// twos_complement_eval out1 = m -// 0 ≤ eval out1 < m -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Msat(out1 *[5]uint64) { - out1[0] = 0xbfd25e8cd0364141 - out1[1] = 0xbaaedce6af48a03b - out1[2] = 0xfffffffffffffffe - out1[3] = 0xffffffffffffffff - out1[4] = uint64(0x0) -} - -// Divstep computes a divstep. -// -// Preconditions: -// -// 0 ≤ eval arg4 < m -// 0 ≤ eval arg5 < m -// -// Postconditions: -// -// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) -// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) -// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) -// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) -// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) -// 0 ≤ eval out5 < m -// 0 ≤ eval out5 < m -// 0 ≤ eval out2 < m -// 0 ≤ eval out3 < m -// -// Input Bounds: -// -// arg1: [0x0 ~> 0xffffffffffffffff] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Divstep( - out1 *uint64, - out2 *[5]uint64, - out3 *[5]uint64, - out4 *[4]uint64, - out5 *[4]uint64, - arg1 uint64, - arg2 *[5]uint64, - arg3 *[5]uint64, - arg4 *[4]uint64, - arg5 *[4]uint64, -) { - var x1 uint64 - x1, _ = bits.Add64((^arg1), uint64(0x1), uint64(0x0)) - x3 := (uint1((x1 >> 63)) & (uint1(arg3[0]) & 0x1)) - var x4 uint64 - x4, _ = bits.Add64((^arg1), uint64(0x1), uint64(0x0)) - var x6 uint64 - cmovznzU64(&x6, x3, arg1, x4) - var x7 uint64 - cmovznzU64(&x7, x3, arg2[0], arg3[0]) - var x8 uint64 - cmovznzU64(&x8, x3, arg2[1], arg3[1]) - var x9 uint64 - cmovznzU64(&x9, x3, arg2[2], arg3[2]) - var x10 uint64 - cmovznzU64(&x10, x3, arg2[3], arg3[3]) - var x11 uint64 - cmovznzU64(&x11, x3, arg2[4], arg3[4]) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(uint64(0x1), (^arg2[0]), uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(uint64(0x0), (^arg2[1]), uint64(uint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(uint64(0x0), (^arg2[2]), uint64(uint1(x15))) - var x18 uint64 - var x19 uint64 - x18, x19 = bits.Add64(uint64(0x0), (^arg2[3]), uint64(uint1(x17))) - var x20 uint64 - x20, _ = bits.Add64(uint64(0x0), (^arg2[4]), uint64(uint1(x19))) - var x22 uint64 - cmovznzU64(&x22, x3, arg3[0], x12) - var x23 uint64 - cmovznzU64(&x23, x3, arg3[1], x14) - var x24 uint64 - cmovznzU64(&x24, x3, arg3[2], x16) - var x25 uint64 - cmovznzU64(&x25, x3, arg3[3], x18) - var x26 uint64 - cmovznzU64(&x26, x3, arg3[4], x20) - var x27 uint64 - cmovznzU64(&x27, x3, arg4[0], arg5[0]) - var x28 uint64 - cmovznzU64(&x28, x3, arg4[1], arg5[1]) - var x29 uint64 - cmovznzU64(&x29, x3, arg4[2], arg5[2]) - var x30 uint64 - cmovznzU64(&x30, x3, arg4[3], arg5[3]) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x27, x27, uint64(0x0)) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x28, x28, uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x29, x29, uint64(uint1(x34))) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x30, x30, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Sub64(x31, 0xbfd25e8cd0364141, uint64(0x0)) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Sub64(x33, 0xbaaedce6af48a03b, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Sub64(x35, 0xfffffffffffffffe, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Sub64(x37, 0xffffffffffffffff, uint64(uint1(x44))) - var x48 uint64 - _, x48 = bits.Sub64(uint64(uint1(x38)), uint64(0x0), uint64(uint1(x46))) - x49 := arg4[3] - x50 := arg4[2] - x51 := arg4[1] - x52 := arg4[0] - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Sub64(uint64(0x0), x52, uint64(0x0)) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Sub64(uint64(0x0), x51, uint64(uint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Sub64(uint64(0x0), x50, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Sub64(uint64(0x0), x49, uint64(uint1(x58))) - var x61 uint64 - cmovznzU64(&x61, uint1(x60), uint64(0x0), 0xffffffffffffffff) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x53, (x61 & 0xbfd25e8cd0364141), uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x55, (x61 & 0xbaaedce6af48a03b), uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x57, (x61 & 0xfffffffffffffffe), uint64(uint1(x65))) - var x68 uint64 - x68, _ = bits.Add64(x59, x61, uint64(uint1(x67))) - var x70 uint64 - cmovznzU64(&x70, x3, arg5[0], x62) - var x71 uint64 - cmovznzU64(&x71, x3, arg5[1], x64) - var x72 uint64 - cmovznzU64(&x72, x3, arg5[2], x66) - var x73 uint64 - cmovznzU64(&x73, x3, arg5[3], x68) - x74 := (uint1(x22) & 0x1) - var x75 uint64 - cmovznzU64(&x75, x74, uint64(0x0), x7) - var x76 uint64 - cmovznzU64(&x76, x74, uint64(0x0), x8) - var x77 uint64 - cmovznzU64(&x77, x74, uint64(0x0), x9) - var x78 uint64 - cmovznzU64(&x78, x74, uint64(0x0), x10) - var x79 uint64 - cmovznzU64(&x79, x74, uint64(0x0), x11) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x22, x75, uint64(0x0)) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x23, x76, uint64(uint1(x81))) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x24, x77, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x25, x78, uint64(uint1(x85))) - var x88 uint64 - x88, _ = bits.Add64(x26, x79, uint64(uint1(x87))) - var x90 uint64 - cmovznzU64(&x90, x74, uint64(0x0), x27) - var x91 uint64 - cmovznzU64(&x91, x74, uint64(0x0), x28) - var x92 uint64 - cmovznzU64(&x92, x74, uint64(0x0), x29) - var x93 uint64 - cmovznzU64(&x93, x74, uint64(0x0), x30) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64(x70, x90, uint64(0x0)) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x71, x91, uint64(uint1(x95))) - var x98 uint64 - var x99 uint64 - x98, x99 = bits.Add64(x72, x92, uint64(uint1(x97))) - var x100 uint64 - var x101 uint64 - x100, x101 = bits.Add64(x73, x93, uint64(uint1(x99))) - var x102 uint64 - var x103 uint64 - x102, x103 = bits.Sub64(x94, 0xbfd25e8cd0364141, uint64(0x0)) - var x104 uint64 - var x105 uint64 - x104, x105 = bits.Sub64(x96, 0xbaaedce6af48a03b, uint64(uint1(x103))) - var x106 uint64 - var x107 uint64 - x106, x107 = bits.Sub64(x98, 0xfffffffffffffffe, uint64(uint1(x105))) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Sub64(x100, 0xffffffffffffffff, uint64(uint1(x107))) - var x111 uint64 - _, x111 = bits.Sub64(uint64(uint1(x101)), uint64(0x0), uint64(uint1(x109))) - var x112 uint64 - x112, _ = bits.Add64(x6, uint64(0x1), uint64(0x0)) - x114 := ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)) - x115 := ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)) - x116 := ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)) - x117 := ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)) - x118 := ((x88 & 0x8000000000000000) | (x88 >> 1)) - var x119 uint64 - cmovznzU64(&x119, uint1(x48), x39, x31) - var x120 uint64 - cmovznzU64(&x120, uint1(x48), x41, x33) - var x121 uint64 - cmovznzU64(&x121, uint1(x48), x43, x35) - var x122 uint64 - cmovznzU64(&x122, uint1(x48), x45, x37) - var x123 uint64 - cmovznzU64(&x123, uint1(x111), x102, x94) - var x124 uint64 - cmovznzU64(&x124, uint1(x111), x104, x96) - var x125 uint64 - cmovznzU64(&x125, uint1(x111), x106, x98) - var x126 uint64 - cmovznzU64(&x126, uint1(x111), x108, x100) - *out1 = x112 - out2[0] = x7 - out2[1] = x8 - out2[2] = x9 - out2[3] = x10 - out2[4] = x11 - out3[0] = x114 - out3[1] = x115 - out3[2] = x116 - out3[3] = x117 - out3[4] = x118 - out4[0] = x119 - out4[1] = x120 - out4[2] = x121 - out4[3] = x122 - out5[0] = x123 - out5[1] = x124 - out5[2] = x125 - out5[3] = x126 -} - -// DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). -// -// Postconditions: -// -// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) -// 0 ≤ eval out1 < m -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func DivstepPrecomp(out1 *[4]uint64) { - out1[0] = 0xd7431a4d2b9cb4e9 - out1[1] = 0xab67d35a32d9c503 - out1[2] = 0xadf6c7e5859ce35f - out1[3] = 0x615441451df6c379 -} diff --git a/crypto/core/curves/native/k256/point.go b/crypto/core/curves/native/k256/point.go deleted file mode 100644 index 1ef2225b7..000000000 --- a/crypto/core/curves/native/k256/point.go +++ /dev/null @@ -1,475 +0,0 @@ -package k256 - -import ( - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/k256/fp" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - k256PointInitonce sync.Once - k256PointParams native.EllipticPointParams - k256PointSswuInitOnce sync.Once - k256PointSswuParams native.SswuParams - k256PointIsogenyInitOnce sync.Once - k256PointIsogenyParams native.IsogenyParams -) - -func K256PointNew() *native.EllipticPoint { - return &native.EllipticPoint{ - X: fp.K256FpNew(), - Y: fp.K256FpNew(), - Z: fp.K256FpNew(), - Params: getK256PointParams(), - Arithmetic: &k256PointArithmetic{}, - } -} - -func k256PointParamsInit() { - k256PointParams = native.EllipticPointParams{ - A: fp.K256FpNew(), - B: fp.K256FpNew().SetUint64(7), - Gx: fp.K256FpNew().SetLimbs(&[native.FieldLimbs]uint64{ - 0x59f2815b16f81798, - 0x029bfcdb2dce28d9, - 0x55a06295ce870b07, - 0x79be667ef9dcbbac, - }), - Gy: fp.K256FpNew().SetLimbs(&[native.FieldLimbs]uint64{ - 0x9c47d08ffb10d4b8, - 0xfd17b448a6855419, - 0x5da4fbfc0e1108a8, - 0x483ada7726a3c465, - }), - BitSize: 256, - Name: "secp256k1", - } -} - -func getK256PointParams() *native.EllipticPointParams { - k256PointInitonce.Do(k256PointParamsInit) - return &k256PointParams -} - -func getK256PointSswuParams() *native.SswuParams { - k256PointSswuInitOnce.Do(k256PointSswuParamsInit) - return &k256PointSswuParams -} - -func k256PointSswuParamsInit() { - // Taken from https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.7 - //params := btcec.S256().Params() - // - //// c1 = (q - 3) / 4 - //c1 := new(big.Int).Set(params.P) - //c1.Sub(c1, big.NewInt(3)) - //c1.Rsh(c1, 2) - // - //a, _ := new(big.Int).SetString("3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533", 16) - //b := big.NewInt(1771) - //z := big.NewInt(-11) - //z.Mod(z, params.P) - //// sqrt(-z^3) - //zTmp := new(big.Int).Exp(z, big.NewInt(3), nil) - //zTmp = zTmp.Neg(zTmp) - //zTmp.Mod(zTmp, params.P) - //c2 := new(big.Int).ModSqrt(zTmp, params.P) - // - //var tBytes [32]byte - //c1.FillBytes(tBytes[:]) - //newC1 := [native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(tBytes[24:32]), - // binary.BigEndian.Uint64(tBytes[16:24]), - // binary.BigEndian.Uint64(tBytes[8:16]), - // binary.BigEndian.Uint64(tBytes[:8]), - //} - //fp.K256FpNew().Arithmetic.ToMontgomery(&newC1, &newC1) - //c2.FillBytes(tBytes[:]) - //newC2 := [native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(tBytes[24:32]), - // binary.BigEndian.Uint64(tBytes[16:24]), - // binary.BigEndian.Uint64(tBytes[8:16]), - // binary.BigEndian.Uint64(tBytes[:8]), - //} - //fp.K256FpNew().Arithmetic.ToMontgomery(&newC2, &newC2) - //a.FillBytes(tBytes[:]) - //newA := [native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(tBytes[24:32]), - // binary.BigEndian.Uint64(tBytes[16:24]), - // binary.BigEndian.Uint64(tBytes[8:16]), - // binary.BigEndian.Uint64(tBytes[:8]), - //} - //fp.K256FpNew().Arithmetic.ToMontgomery(&newA, &newA) - //b.FillBytes(tBytes[:]) - //newB := [native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(tBytes[24:32]), - // binary.BigEndian.Uint64(tBytes[16:24]), - // binary.BigEndian.Uint64(tBytes[8:16]), - // binary.BigEndian.Uint64(tBytes[:8]), - //} - //fp.K256FpNew().Arithmetic.ToMontgomery(&newB, &newB) - //z.FillBytes(tBytes[:]) - //newZ := [native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(tBytes[24:32]), - // binary.BigEndian.Uint64(tBytes[16:24]), - // binary.BigEndian.Uint64(tBytes[8:16]), - // binary.BigEndian.Uint64(tBytes[:8]), - //} - //fp.K256FpNew().Arithmetic.ToMontgomery(&newZ, &newZ) - - k256PointSswuParams = native.SswuParams{ - // (q -3) // 4 - C1: [native.FieldLimbs]uint64{ - 0xffffffffbfffff0b, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0x3fffffffffffffff, - }, - // sqrt(-z^3) - C2: [native.FieldLimbs]uint64{ - 0x5b57ba53a30d1520, - 0x908f7cef34a762eb, - 0x190b0ffe068460c8, - 0x98a9828e8f00ff62, - }, - // 0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533 - A: [native.FieldLimbs]uint64{ - 0xdb714ce7b18444a1, - 0x4458ce38a32a19a2, - 0xa0e58ae2837bfbf0, - 0x505aabc49336d959, - }, - // 1771 - B: [native.FieldLimbs]uint64{ - 0x000006eb001a66db, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - // -11 - Z: [native.FieldLimbs]uint64{ - 0xfffffff3ffffd234, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0xffffffffffffffff, - }, - } -} - -func k256PointIsogenyInit() { - k256PointIsogenyParams = native.IsogenyParams{ - XNum: [][native.FieldLimbs]uint64{ - { - 0x0000003b1c72a8b4, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - { - 0xd5bd51a17b2edf46, - 0x2cc06f7c86b86bcd, - 0x50b37e74f3294a00, - 0xeb32314a9da73679, - }, - { - 0x48c18b1b0d2191bd, - 0x5a3f74c29bfccce3, - 0xbe55a02e5e8bd357, - 0x09bf218d11fff905, - }, - { - 0x000000001c71c789, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - XDen: [][native.FieldLimbs]uint64{ - { - 0x8af79c1ffdf1e7fa, - 0xb84bc22235735eb5, - 0x82ee5655a55ace04, - 0xce4b32dea0a2becb, - }, - { - 0x8ecde3f3762e1fa5, - 0x2c3b1ad77be333fd, - 0xb102a1a152ea6e12, - 0x57b82df5a1ffc133, - }, - { - 0x00000001000003d1, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - YNum: [][native.FieldLimbs]uint64{ - { - 0xffffffce425e12c3, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0xffffffffffffffff, - }, - { - 0xba60d5fd6e56922e, - 0x4ec198c898a435f2, - 0x27e77a577b9764ab, - 0xb3b80a1197651d12, - }, - { - 0xa460c58d0690c6f6, - 0xad1fba614dfe6671, - 0xdf2ad0172f45e9ab, - 0x84df90c688fffc82, - }, - { - 0x00000000097b4283, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - YDen: [][native.FieldLimbs]uint64{ - { - 0xfffffd0afff4b6fb, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0xffffffffffffffff, - }, - { - 0xa0e6d461f9d5bf90, - 0x28e34666a05a1c20, - 0x88cb0300f0106a0e, - 0x6ae1989be1e83c62, - }, - { - 0x5634d5edb1453160, - 0x4258a84339d4cdfc, - 0x8983f271fc5fa51b, - 0x039444f072ffa1cd, - }, - { - 0x00000001000003d1, - 0x0000000000000000, - 0x0000000000000000, - 0x0000000000000000, - }, - }, - } -} - -func getK256PointIsogenyParams() *native.IsogenyParams { - k256PointIsogenyInitOnce.Do(k256PointIsogenyInit) - return &k256PointIsogenyParams -} - -type k256PointArithmetic struct{} - -func (k k256PointArithmetic) Hash( - out *native.EllipticPoint, - hash *native.EllipticPointHasher, - msg, dst []byte, -) error { - var u []byte - sswuParams := getK256PointSswuParams() - isoParams := getK256PointIsogenyParams() - - switch hash.Type() { - case native.XMD: - u = native.ExpandMsgXmd(hash, msg, dst, 96) - case native.XOF: - u = native.ExpandMsgXof(hash, msg, dst, 96) - } - var buf [64]byte - copy(buf[:48], internal.ReverseScalarBytes(u[:48])) - u0 := fp.K256FpNew().SetBytesWide(&buf) - copy(buf[:48], internal.ReverseScalarBytes(u[48:])) - u1 := fp.K256FpNew().SetBytesWide(&buf) - - r0x, r0y := sswuParams.Osswu3mod4(u0) - r1x, r1y := sswuParams.Osswu3mod4(u1) - q0x, q0y := isoParams.Map(r0x, r0y) - q1x, q1y := isoParams.Map(r1x, r1y) - out.X = q0x - out.Y = q0y - out.Z.SetOne() - tv := &native.EllipticPoint{ - X: q1x, - Y: q1y, - Z: fp.K256FpNew().SetOne(), - } - k.Add(out, out, tv) - return nil -} - -func (k k256PointArithmetic) Double(out, arg *native.EllipticPoint) { - // Addition formula from Renes-Costello-Batina 2015 - // (https://eprint.iacr.org/2015/1060 Algorithm 9) - var yy, zz, xy2, bzz, bzz3, bzz9 [native.FieldLimbs]uint64 - var yyMBzz9, yyPBzz3, yyzz, yyzz8, t [native.FieldLimbs]uint64 - var x, y, z [native.FieldLimbs]uint64 - f := arg.X.Arithmetic - - f.Square(&yy, &arg.Y.Value) - f.Square(&zz, &arg.Z.Value) - f.Mul(&xy2, &arg.X.Value, &arg.Y.Value) - f.Add(&xy2, &xy2, &xy2) - f.Mul(&bzz, &zz, &arg.Params.B.Value) - f.Add(&bzz3, &bzz, &bzz) - f.Add(&bzz3, &bzz3, &bzz) - f.Add(&bzz9, &bzz3, &bzz3) - f.Add(&bzz9, &bzz9, &bzz3) - f.Neg(&yyMBzz9, &bzz9) - f.Add(&yyMBzz9, &yyMBzz9, &yy) - f.Add(&yyPBzz3, &yy, &bzz3) - f.Mul(&yyzz, &yy, &zz) - f.Add(&yyzz8, &yyzz, &yyzz) - f.Add(&yyzz8, &yyzz8, &yyzz8) - f.Add(&yyzz8, &yyzz8, &yyzz8) - f.Add(&t, &yyzz8, &yyzz8) - f.Add(&t, &t, &yyzz8) - f.Mul(&t, &t, &arg.Params.B.Value) - - f.Mul(&x, &xy2, &yyMBzz9) - - f.Mul(&y, &yyMBzz9, &yyPBzz3) - f.Add(&y, &y, &t) - - f.Mul(&z, &yy, &arg.Y.Value) - f.Mul(&z, &z, &arg.Z.Value) - f.Add(&z, &z, &z) - f.Add(&z, &z, &z) - f.Add(&z, &z, &z) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z -} - -func (k k256PointArithmetic) Add(out, arg1, arg2 *native.EllipticPoint) { - // Addition formula from Renes-Costello-Batina 2015 - // (https://eprint.iacr.org/2015/1060 Algorithm 7). - var xx, yy, zz, nXxYy, nYyZz, nXxZz [native.FieldLimbs]uint64 - var tv1, tv2, xyPairs, yzPairs, xzPairs [native.FieldLimbs]uint64 - var bzz, bzz3, yyMBzz3, yyPBzz3, byz [native.FieldLimbs]uint64 - var byz3, xx3, bxx9, x, y, z [native.FieldLimbs]uint64 - f := arg1.X.Arithmetic - - f.Mul(&xx, &arg1.X.Value, &arg2.X.Value) - f.Mul(&yy, &arg1.Y.Value, &arg2.Y.Value) - f.Mul(&zz, &arg1.Z.Value, &arg2.Z.Value) - - f.Add(&nXxYy, &xx, &yy) - f.Neg(&nXxYy, &nXxYy) - - f.Add(&nYyZz, &yy, &zz) - f.Neg(&nYyZz, &nYyZz) - - f.Add(&nXxZz, &xx, &zz) - f.Neg(&nXxZz, &nXxZz) - - f.Add(&tv1, &arg1.X.Value, &arg1.Y.Value) - f.Add(&tv2, &arg2.X.Value, &arg2.Y.Value) - f.Mul(&xyPairs, &tv1, &tv2) - f.Add(&xyPairs, &xyPairs, &nXxYy) - - f.Add(&tv1, &arg1.Y.Value, &arg1.Z.Value) - f.Add(&tv2, &arg2.Y.Value, &arg2.Z.Value) - f.Mul(&yzPairs, &tv1, &tv2) - f.Add(&yzPairs, &yzPairs, &nYyZz) - - f.Add(&tv1, &arg1.X.Value, &arg1.Z.Value) - f.Add(&tv2, &arg2.X.Value, &arg2.Z.Value) - f.Mul(&xzPairs, &tv1, &tv2) - f.Add(&xzPairs, &xzPairs, &nXxZz) - - f.Mul(&bzz, &zz, &arg1.Params.B.Value) - f.Add(&bzz3, &bzz, &bzz) - f.Add(&bzz3, &bzz3, &bzz) - - f.Neg(&yyMBzz3, &bzz3) - f.Add(&yyMBzz3, &yyMBzz3, &yy) - - f.Add(&yyPBzz3, &yy, &bzz3) - - f.Mul(&byz, &yzPairs, &arg1.Params.B.Value) - f.Add(&byz3, &byz, &byz) - f.Add(&byz3, &byz3, &byz) - - f.Add(&xx3, &xx, &xx) - f.Add(&xx3, &xx3, &xx) - - f.Add(&bxx9, &xx3, &xx3) - f.Add(&bxx9, &bxx9, &xx3) - f.Mul(&bxx9, &bxx9, &arg1.Params.B.Value) - - f.Mul(&tv1, &xyPairs, &yyMBzz3) - f.Mul(&tv2, &byz3, &xzPairs) - f.Neg(&tv2, &tv2) - f.Add(&x, &tv1, &tv2) - - f.Mul(&tv1, &yyPBzz3, &yyMBzz3) - f.Mul(&tv2, &bxx9, &xzPairs) - f.Add(&y, &tv1, &tv2) - - f.Mul(&tv1, &yzPairs, &yyPBzz3) - f.Mul(&tv2, &xx3, &xyPairs) - f.Add(&z, &tv1, &tv2) - - e1 := arg1.Z.IsZero() - e2 := arg2.Z.IsZero() - - // If arg1 is identity set it to arg2 - f.Selectznz(&z, &z, &arg2.Z.Value, e1) - f.Selectznz(&y, &y, &arg2.Y.Value, e1) - f.Selectznz(&x, &x, &arg2.X.Value, e1) - // If arg2 is identity set it to arg1 - f.Selectznz(&z, &z, &arg1.Z.Value, e2) - f.Selectznz(&y, &y, &arg1.Y.Value, e2) - f.Selectznz(&x, &x, &arg1.X.Value, e2) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z -} - -func (k k256PointArithmetic) IsOnCurve(arg *native.EllipticPoint) bool { - affine := K256PointNew() - k.ToAffine(affine, arg) - lhs := fp.K256FpNew().Square(affine.Y) - rhs := fp.K256FpNew() - k.RhsEq(rhs, affine.X) - return lhs.Equal(rhs) == 1 -} - -func (k k256PointArithmetic) ToAffine(out, arg *native.EllipticPoint) { - var wasInverted int - var zero, x, y, z [native.FieldLimbs]uint64 - f := arg.X.Arithmetic - - f.Invert(&wasInverted, &z, &arg.Z.Value) - f.Mul(&x, &arg.X.Value, &z) - f.Mul(&y, &arg.Y.Value, &z) - - out.Z.SetOne() - // If point at infinity this does nothing - f.Selectznz(&x, &zero, &x, wasInverted) - f.Selectznz(&y, &zero, &y, wasInverted) - f.Selectznz(&z, &zero, &out.Z.Value, wasInverted) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z - out.Params = arg.Params - out.Arithmetic = arg.Arithmetic -} - -func (k k256PointArithmetic) RhsEq(out, x *native.Field) { - // Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7 - out.Square(x) - out.Mul(out, x) - out.Add(out, getK256PointParams().B) -} diff --git a/crypto/core/curves/native/k256/point_test.go b/crypto/core/curves/native/k256/point_test.go deleted file mode 100644 index 8a7f52da8..000000000 --- a/crypto/core/curves/native/k256/point_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package k256_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/k256" -) - -func TestK256PointArithmetic_Hash(t *testing.T) { - var b [32]byte - sc, err := k256.K256PointNew().Hash(b[:], native.EllipticPointHasherSha256()) - - require.NoError(t, err) - require.True(t, !sc.IsIdentity()) - require.True(t, sc.IsOnCurve()) -} diff --git a/crypto/core/curves/native/osswu.go b/crypto/core/curves/native/osswu.go deleted file mode 100755 index 2ea67439f..000000000 --- a/crypto/core/curves/native/osswu.go +++ /dev/null @@ -1,82 +0,0 @@ -package native - -// SswuParams for computing the Simplified SWU mapping -// for hash to curve implementations -type SswuParams struct { - C1, C2, A, B, Z [FieldLimbs]uint64 -} - -// Osswu3mod4 computes the simplified map optmized for 3 mod 4 primes -// https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-11#appendix-G.2.1 -func (p *SswuParams) Osswu3mod4(u *Field) (x, y *Field) { - var tv1, tv2, tv3, tv4, xd, x1n, x2n, gxd, gx1, aNeg, zA, y1, y2 [FieldLimbs]uint64 - var wasInverted int - u.Arithmetic.Mul(&tv1, &u.Value, &u.Value) // tv1 = u^2 - u.Arithmetic.Mul(&tv3, &p.Z, &tv1) // tv3 = z * tv1 - u.Arithmetic.Square(&tv2, &tv3) // tv2 = tv3^2 - u.Arithmetic.Add(&xd, &tv2, &tv3) // xd = tv2 + tv3 - u.Arithmetic.Add(&x1n, &u.Params.R, &xd) // x1n = (xd + 1) - u.Arithmetic.Mul(&x1n, &x1n, &p.B) // x1n * B - u.Arithmetic.Neg(&aNeg, &p.A) - u.Arithmetic.Mul(&xd, &xd, &aNeg) // xd = -A * xd - - xdIsZero := (&Field{ - Value: xd, - }).IsZero() - u.Arithmetic.Mul(&zA, &p.Z, &p.A) - u.Arithmetic.Selectznz(&xd, &xd, &zA, xdIsZero) // xd = z * A if xd == 0 - - u.Arithmetic.Square(&tv2, &xd) // tv2 = xd^2 - u.Arithmetic.Mul(&gxd, &tv2, &xd) // gxd = tv2 * xd - u.Arithmetic.Mul(&tv2, &tv2, &p.A) // tv2 = A * tv2 - - u.Arithmetic.Square(&gx1, &x1n) // gx1 = x1n^2 - u.Arithmetic.Add(&gx1, &gx1, &tv2) // gx1 = gx1 + tv2 - u.Arithmetic.Mul(&gx1, &gx1, &x1n) // gx1 = gx1 * x1n - u.Arithmetic.Mul(&tv2, &gxd, &p.B) // tv2 = B * gxd - u.Arithmetic.Add(&gx1, &gx1, &tv2) // gx1 = gx1 + tv2 - - u.Arithmetic.Square(&tv4, &gxd) // tv4 = gxd^2 - u.Arithmetic.Mul(&tv2, &gx1, &gxd) // tv2 = gx1 * gxd - u.Arithmetic.Mul(&tv4, &tv4, &tv2) // tv4 = tv4 * tv2 - - Pow(&y1, &tv4, &p.C1, u.Params, u.Arithmetic) // y1 = tv4^C1 - u.Arithmetic.Mul(&y1, &y1, &tv2) // y1 = y1 * tv2 - u.Arithmetic.Mul(&x2n, &tv3, &x1n) // x2n = tv3 * x1n - - u.Arithmetic.Mul(&y2, &y1, &p.C2) // y2 = y1 * c2 - u.Arithmetic.Mul(&y2, &y2, &tv1) // y2 = y2 * tv1 - u.Arithmetic.Mul(&y2, &y2, &u.Value) // y2 = y2 * u - - u.Arithmetic.Square(&tv2, &y1) // tv2 = y1^2 - u.Arithmetic.Mul(&tv2, &tv2, &gxd) // tv2 = tv2 * gxd - - e2 := (&Field{Value: tv2}).Equal(&Field{Value: gx1}) - - x = new(Field).Set(u) - y = new(Field).Set(u) - - // If e2, x = x1, else x = x2 - u.Arithmetic.Selectznz(&x.Value, &x2n, &x1n, e2) - - // xn / xd - u.Arithmetic.Invert(&wasInverted, &tv1, &xd) - u.Arithmetic.Mul(&tv1, &x.Value, &tv1) - u.Arithmetic.Selectznz(&x.Value, &x.Value, &tv1, wasInverted) - - // If e2, y = y1, else y = y2 - u.Arithmetic.Selectznz(&y.Value, &y2, &y1, e2) - - uBytes := u.Bytes() - yBytes := y.Bytes() - - usign := uBytes[0] & 1 - ysign := yBytes[0] & 1 - - // Fix sign of y - if usign != ysign { - y.Neg(y) - } - - return x, y -} diff --git a/crypto/core/curves/native/p256/fp/fp.go b/crypto/core/curves/native/p256/fp/fp.go deleted file mode 100644 index 5559b39fb..000000000 --- a/crypto/core/curves/native/p256/fp/fp.go +++ /dev/null @@ -1,206 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -var ( - p256FpInitonce sync.Once - p256FpParams native.FieldParams -) - -func P256FpNew() *native.Field { - return &native.Field{ - Value: [native.FieldLimbs]uint64{}, - Params: getP256FpParams(), - Arithmetic: p256FpArithmetic{}, - } -} - -func p256FpParamsInit() { - // See FIPS 186-3, section D.2.3 - p256FpParams = native.FieldParams{ - R: [native.FieldLimbs]uint64{ - 0x0000000000000001, - 0xffffffff00000000, - 0xffffffffffffffff, - 0x00000000fffffffe, - }, - R2: [native.FieldLimbs]uint64{ - 0x0000000000000003, - 0xfffffffbffffffff, - 0xfffffffffffffffe, - 0x00000004fffffffd, - }, - R3: [native.FieldLimbs]uint64{ - 0xfffffffd0000000a, - 0xffffffedfffffff7, - 0x00000005fffffffc, - 0x0000001800000001, - }, - Modulus: [native.FieldLimbs]uint64{ - 0xffffffffffffffff, - 0x00000000ffffffff, - 0x0000000000000000, - 0xffffffff00000001, - }, - BiModulus: new(big.Int).SetBytes([]byte{ - 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - }), - } -} - -func getP256FpParams() *native.FieldParams { - p256FpInitonce.Do(p256FpParamsInit) - return &p256FpParams -} - -// p256FpArithmetic is a struct with all the methods needed for working -// in mod q -type p256FpArithmetic struct{} - -// ToMontgomery converts this field to montgomery form -func (f p256FpArithmetic) ToMontgomery(out, arg *[native.FieldLimbs]uint64) { - ToMontgomery((*MontgomeryDomainFieldElement)(out), (*NonMontgomeryDomainFieldElement)(arg)) -} - -// FromMontgomery converts this field from montgomery form -func (f p256FpArithmetic) FromMontgomery(out, arg *[native.FieldLimbs]uint64) { - FromMontgomery((*NonMontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Neg performs modular negation -func (f p256FpArithmetic) Neg(out, arg *[native.FieldLimbs]uint64) { - Opp((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Square performs modular square -func (f p256FpArithmetic) Square(out, arg *[native.FieldLimbs]uint64) { - Square((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Mul performs modular multiplication -func (f p256FpArithmetic) Mul(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Mul( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Add performs modular addition -func (f p256FpArithmetic) Add(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Add( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sub performs modular subtraction -func (f p256FpArithmetic) Sub(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Sub( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sqrt performs modular square root -func (f p256FpArithmetic) Sqrt(wasSquare *int, out, arg *[native.FieldLimbs]uint64) { - // Use p = 3 mod 4 by Euler's criterion means - // arg^((p+1)/4 mod p - var t, c [native.FieldLimbs]uint64 - c1 := [native.FieldLimbs]uint64{ - 0x0000_0000_0000_0000, - 0x0000_0000_4000_0000, - 0x4000_0000_0000_0000, - 0x3fff_ffff_c000_0000, - } - native.Pow(&t, arg, &c1, getP256FpParams(), f) - Square((*MontgomeryDomainFieldElement)(&c), (*MontgomeryDomainFieldElement)(&t)) - *wasSquare = (&native.Field{Value: c, Params: getP256FpParams(), Arithmetic: f}).Equal( - &native.Field{ - Value: *arg, Params: getP256FpParams(), Arithmetic: f, - }, - ) - Selectznz(out, uint1(*wasSquare), out, &t) -} - -// Invert performs modular inverse -func (f p256FpArithmetic) Invert(wasInverted *int, out, arg *[native.FieldLimbs]uint64) { - // Fermat's Little Theorem - // a ^ (p - 2) mod p - // - // The exponent pattern (from high to low) is: - // - 32 bits of value 1 - // - 31 bits of value 0 - // - 1 bit of value 1 - // - 96 bits of value 0 - // - 94 bits of value 1 - // - 1 bit of value 0 - // - 1 bit of value 1 - // To speed up the square-and-multiply algorithm, precompute a^(2^31-1). - // - // Courtesy of Thomas Pornin - // - var t, r [native.FieldLimbs]uint64 - copy(t[:], arg[:]) - - for i := 0; i < 30; i++ { - f.Square(&t, &t) - f.Mul(&t, &t, arg) - } - copy(r[:], t[:]) - for i := 224; i >= 0; i-- { - f.Square(&r, &r) - switch i { - case 0: - fallthrough - case 2: - fallthrough - case 192: - fallthrough - case 224: - f.Mul(&r, &r, arg) - case 3: - fallthrough - case 34: - fallthrough - case 65: - f.Mul(&r, &r, &t) - } - } - - *wasInverted = (&native.Field{ - Value: *arg, - Params: getP256FpParams(), - Arithmetic: f, - }).IsNonZero() - Selectznz(out, uint1(*wasInverted), out, &r) -} - -// FromBytes converts a little endian byte array into a field element -func (f p256FpArithmetic) FromBytes(out *[native.FieldLimbs]uint64, arg *[native.FieldBytes]byte) { - FromBytes(out, arg) -} - -// ToBytes converts a field element to a little endian byte array -func (f p256FpArithmetic) ToBytes(out *[native.FieldBytes]byte, arg *[native.FieldLimbs]uint64) { - ToBytes(out, arg) -} - -// Selectznz performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f p256FpArithmetic) Selectznz(out, arg1, arg2 *[native.FieldLimbs]uint64, choice int) { - Selectznz(out, uint1(choice), arg1, arg2) -} diff --git a/crypto/core/curves/native/p256/fp/fp_test.go b/crypto/core/curves/native/p256/fp/fp_test.go deleted file mode 100644 index 7ccfb13df..000000000 --- a/crypto/core/curves/native/p256/fp/fp_test.go +++ /dev/null @@ -1,330 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFpSetOne(t *testing.T) { - fq := P256FpNew().SetOne() - require.NotNil(t, fq) - require.Equal(t, fq.Value, getP256FpParams().R) -} - -func TestFpSetUint64(t *testing.T) { - act := P256FpNew().SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act.Value[0], uint64(0x100000000fffffff)) -} - -func TestFpAdd(t *testing.T) { - lhs := P256FpNew().SetOne() - rhs := P256FpNew().SetOne() - exp := P256FpNew().SetUint64(2) - res := P256FpNew().Add(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := P256FpNew().Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpSub(t *testing.T) { - lhs := P256FpNew().SetOne() - rhs := P256FpNew().SetOne() - exp := P256FpNew().SetZero() - res := P256FpNew().Sub(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := P256FpNew().Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpMul(t *testing.T) { - lhs := P256FpNew().SetOne() - rhs := P256FpNew().SetOne() - exp := P256FpNew().SetOne() - res := P256FpNew().Mul(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := P256FpNew().Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpDouble(t *testing.T) { - a := P256FpNew().SetUint64(2) - e := P256FpNew().SetUint64(4) - require.Equal(t, e, P256FpNew().Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = P256FpNew().SetUint64(uint64(tv)) - e = P256FpNew().SetUint64(ttv) - require.Equal(t, e, P256FpNew().Double(a)) - } -} - -func TestFpSquare(t *testing.T) { - a := P256FpNew().SetUint64(4) - e := P256FpNew().SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFpNeg(t *testing.T) { - g := P256FpNew().SetUint64(7) - a := P256FpNew().SetOne() - a.Neg(a) - e := P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xfffffffffffffffe, 0x00000001ffffffff, 0x0000000000000000, 0xfffffffe00000002}) - require.Equal(t, e, a) - a.Neg(g) - e = P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xfffffffffffffff8, 0x00000007ffffffff, 0x0000000000000000, 0xfffffff800000008}) - require.Equal(t, e, a) -} - -func TestFpExp(t *testing.T) { - e := P256FpNew().SetUint64(8) - a := P256FpNew().SetUint64(2) - by := P256FpNew().SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFpSqrt(t *testing.T) { - t1 := P256FpNew().SetUint64(2) - t2 := P256FpNew().Neg(t1) - t3 := P256FpNew().Square(t1) - _, wasSquare := t3.Sqrt(t3) - - require.True(t, wasSquare) - require.Equal(t, 1, t1.Equal(t3)|t2.Equal(t3)) - t1.SetUint64(3) - _, wasSquare = P256FpNew().Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFpInvert(t *testing.T) { - twoInv := P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x8000000000000000}) - two := P256FpNew().SetUint64(2) - a, inverted := P256FpNew().Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnity := P256FpNew().SetLimbs(&[native.FieldLimbs]uint64{0x8619a9e760c01d0c, 0xa883c4fba37998df, 0x45607580b6eabd98, 0xf252b002544b2f99}) - rootOfUnityInv := P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0x2609d8ab477f96d1, 0x6e5f128fb20a0f24, 0xe4d636874d99643b, 0x376080cc1f2a3735}) - a, inverted = P256FpNew().Invert(rootOfUnity) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := P256FpNew().SetUint64(9) - rhs := P256FpNew().SetUint64(3) - rhsInv, inverted := P256FpNew().Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, P256FpNew().Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = P256FpNew().Invert(rhs) - require.False(t, inverted) -} - -func TestFpCMove(t *testing.T) { - t1 := P256FpNew().SetUint64(5) - t2 := P256FpNew().SetUint64(10) - require.Equal(t, t1, P256FpNew().CMove(t1, t2, 0)) - require.Equal(t, t2, P256FpNew().CMove(t1, t2, 1)) -} - -func TestFpBytes(t *testing.T) { - t1 := P256FpNew().SetUint64(99) - seq := t1.Bytes() - t2, err := P256FpNew().SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFpCmp(t *testing.T) { - tests := []struct { - a *native.Field - b *native.Field - e int - }{ - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{2731658267414164836, 14655288906067898431, 6537465423330262322, 8306191141697566219}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{6472764012681988529, 10848812988401906064, 2961825807536828898, 4282183981941645679}), - e: 1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{8023004109510539223, 4652004072850285717, 1877219145646046927, 383214385093921911}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{10099384440823804262, 16139476942229308465, 8636966320777393798, 5435928725024696785}), - e: -1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{3741840066202388211, 12165774400417314871, 16619312580230515379, 16195032234110087705}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{3905865991286066744, 543690822309071825, 17963103015950210055, 3745476720756119742}), - e: 1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{16660853697936147788, 7799793619412111108, 13515141085171033220, 2641079731236069032}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{17790588295388238399, 571847801379669440, 14537208974498222469, 12792570372087452754}), - e: -1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{3912839285384959186, 2701177075110484070, 6453856448115499033, 6475797457962597458}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{1282566391665688512, 13503640416992806563, 2962240104675990153, 3374904770947067689}), - e: 1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{5716631803409360103, 7859567470082614154, 12747956220853330146, 18434584096087315020}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{16317076441459028418, 12854146980376319601, 2258436689269031143, 9531877130792223752}), - e: 1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{17955191469941083403, 10350326247207200880, 17263512235150705075, 12700328451238078022}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{6767595547459644695, 7146403825494928147, 12269344038346710612, 9122477829383225603}), - e: 1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{17099388671847024438, 6426264987820696548, 10641143464957227405, 7709745403700754098}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{10799154372990268556, 17178492485719929374, 5705777922258988797, 8051037767683567782}), - e: -1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{4567139260680454325, 1629385880182139061, 16607020832317899145, 1261011562621553200}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{13487234491304534488, 17872642955936089265, 17651026784972590233, 9468934643333871559}), - e: -1, - }, - { - a: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{18071070103467571798, 11787850505799426140, 10631355976141928593, 4867785203635092610}), - b: P256FpNew().SetRaw(&[native.FieldLimbs]uint64{12596443599426461624, 10176122686151524591, 17075755296887483439, 6726169532695070719}), - e: -1, - }, - } - - for _, test := range tests { - require.Equal(t, test.e, test.a.Cmp(test.b)) - require.Equal(t, -test.e, test.b.Cmp(test.a)) - require.Equal(t, 0, test.a.Cmp(test.a)) - require.Equal(t, 0, test.b.Cmp(test.b)) - } -} - -func TestFpBigInt(t *testing.T) { - t1 := P256FpNew().SetBigInt(big.NewInt(9999)) - t2 := P256FpNew().SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0x515151513f3f3f3e, 0xc9c9c9cb36363636, 0xb7b7b7b79c9c9c9c, 0xfffffffeaeaeaeaf}) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Value[0] = 0xaeaeaeaec0c0c0c1 - e.Value[1] = 0x36363635c9c9c9c9 - e.Value[2] = 0x4848484863636363 - e.Value[3] = 0x0000000051515151 - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFpSetBytesWide(t *testing.T) { - e := P256FpNew().SetRaw(&[native.FieldLimbs]uint64{0xccdefd48c77805bc, 0xe935dc2db86364d6, 0xca8ee6e5870a020e, 0x4c94bf4467f3b5bf}) - - a := P256FpNew().SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} - -func TestFpSetBytesWideBigInt(t *testing.T) { - params := getP256FpParams() - var tv2 [64]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, params.BiModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a := P256FpNew().SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} diff --git a/crypto/core/curves/native/p256/fp/p256_fp.go b/crypto/core/curves/native/p256/fp/p256_fp.go deleted file mode 100755 index 6931a0688..000000000 --- a/crypto/core/curves/native/p256/fp/p256_fp.go +++ /dev/null @@ -1,1463 +0,0 @@ -// Code generated by Fiat Cryptography. DO NOT EDIT. -// -// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Go --no-wide-int --relax-primitive-carry-to-bitwidth 32,64 --cmovznz-by-mul --internal-static --package-case flatcase --public-function-case UpperCamelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case camelCase --no-prefix-fiat --doc-newline-in-typedef-bounds --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --doc-text-before-function-name ” --doc-text-before-type-name ” --package-name p256 ” 64 '2^256 - 2^224 + 2^192 + 2^96 - 1' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one -// -// curve description (via package name): p256 -// -// machine_wordsize = 64 (from "64") -// -// requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp -// -// m = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff (from "2^256 - 2^224 + 2^192 + 2^96 - 1") -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 -package fp - -import "math/bits" - -type uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -type int1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 - -// MontgomeryDomainFieldElement is a field element in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type MontgomeryDomainFieldElement [4]uint64 - -// NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type NonMontgomeryDomainFieldElement [4]uint64 - -// cmovznzU64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func cmovznzU64(out1 *uint64, arg1 uint1, arg2 uint64, arg3 uint64) { - x1 := (uint64(arg1) * 0xffffffffffffffff) - x2 := ((x1 & arg3) | ((^x1) & arg2)) - *out1 = x2 -} - -// Mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Mul(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x11, 0xffffffff00000001) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x11, 0xffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x11, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(x25, x22, uint64(0x0)) - x28 := (uint64(uint1(x27)) + x23) - var x30 uint64 - _, x30 = bits.Add64(x11, x24, uint64(0x0)) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x13, x26, uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x15, x28, uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x17, x20, uint64(uint1(x34))) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x19, x21, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, arg2[3]) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg2[2]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg2[1]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg2[0]) - var x47 uint64 - var x48 uint64 - x47, x48 = bits.Add64(x46, x43, uint64(0x0)) - var x49 uint64 - var x50 uint64 - x49, x50 = bits.Add64(x44, x41, uint64(uint1(x48))) - var x51 uint64 - var x52 uint64 - x51, x52 = bits.Add64(x42, x39, uint64(uint1(x50))) - x53 := (uint64(uint1(x52)) + x40) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x31, x45, uint64(0x0)) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x33, x47, uint64(uint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x35, x49, uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64(x37, x51, uint64(uint1(x59))) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(uint64(uint1(x38)), x53, uint64(uint1(x61))) - var x64 uint64 - var x65 uint64 - x65, x64 = bits.Mul64(x54, 0xffffffff00000001) - var x66 uint64 - var x67 uint64 - x67, x66 = bits.Mul64(x54, 0xffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x54, 0xffffffffffffffff) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(x69, x66, uint64(0x0)) - x72 := (uint64(uint1(x71)) + x67) - var x74 uint64 - _, x74 = bits.Add64(x54, x68, uint64(0x0)) - var x75 uint64 - var x76 uint64 - x75, x76 = bits.Add64(x56, x70, uint64(uint1(x74))) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Add64(x58, x72, uint64(uint1(x76))) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x60, x64, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x62, x65, uint64(uint1(x80))) - x83 := (uint64(uint1(x82)) + uint64(uint1(x63))) - var x84 uint64 - var x85 uint64 - x85, x84 = bits.Mul64(x2, arg2[3]) - var x86 uint64 - var x87 uint64 - x87, x86 = bits.Mul64(x2, arg2[2]) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg2[1]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg2[0]) - var x92 uint64 - var x93 uint64 - x92, x93 = bits.Add64(x91, x88, uint64(0x0)) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64(x89, x86, uint64(uint1(x93))) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x87, x84, uint64(uint1(x95))) - x98 := (uint64(uint1(x97)) + x85) - var x99 uint64 - var x100 uint64 - x99, x100 = bits.Add64(x75, x90, uint64(0x0)) - var x101 uint64 - var x102 uint64 - x101, x102 = bits.Add64(x77, x92, uint64(uint1(x100))) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x79, x94, uint64(uint1(x102))) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x81, x96, uint64(uint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x83, x98, uint64(uint1(x106))) - var x109 uint64 - var x110 uint64 - x110, x109 = bits.Mul64(x99, 0xffffffff00000001) - var x111 uint64 - var x112 uint64 - x112, x111 = bits.Mul64(x99, 0xffffffff) - var x113 uint64 - var x114 uint64 - x114, x113 = bits.Mul64(x99, 0xffffffffffffffff) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x114, x111, uint64(0x0)) - x117 := (uint64(uint1(x116)) + x112) - var x119 uint64 - _, x119 = bits.Add64(x99, x113, uint64(0x0)) - var x120 uint64 - var x121 uint64 - x120, x121 = bits.Add64(x101, x115, uint64(uint1(x119))) - var x122 uint64 - var x123 uint64 - x122, x123 = bits.Add64(x103, x117, uint64(uint1(x121))) - var x124 uint64 - var x125 uint64 - x124, x125 = bits.Add64(x105, x109, uint64(uint1(x123))) - var x126 uint64 - var x127 uint64 - x126, x127 = bits.Add64(x107, x110, uint64(uint1(x125))) - x128 := (uint64(uint1(x127)) + uint64(uint1(x108))) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x3, arg2[3]) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x3, arg2[2]) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x3, arg2[1]) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg2[0]) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x136, x133, uint64(0x0)) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x134, x131, uint64(uint1(x138))) - var x141 uint64 - var x142 uint64 - x141, x142 = bits.Add64(x132, x129, uint64(uint1(x140))) - x143 := (uint64(uint1(x142)) + x130) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x120, x135, uint64(0x0)) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x122, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x124, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x126, x141, uint64(uint1(x149))) - var x152 uint64 - var x153 uint64 - x152, x153 = bits.Add64(x128, x143, uint64(uint1(x151))) - var x154 uint64 - var x155 uint64 - x155, x154 = bits.Mul64(x144, 0xffffffff00000001) - var x156 uint64 - var x157 uint64 - x157, x156 = bits.Mul64(x144, 0xffffffff) - var x158 uint64 - var x159 uint64 - x159, x158 = bits.Mul64(x144, 0xffffffffffffffff) - var x160 uint64 - var x161 uint64 - x160, x161 = bits.Add64(x159, x156, uint64(0x0)) - x162 := (uint64(uint1(x161)) + x157) - var x164 uint64 - _, x164 = bits.Add64(x144, x158, uint64(0x0)) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x146, x160, uint64(uint1(x164))) - var x167 uint64 - var x168 uint64 - x167, x168 = bits.Add64(x148, x162, uint64(uint1(x166))) - var x169 uint64 - var x170 uint64 - x169, x170 = bits.Add64(x150, x154, uint64(uint1(x168))) - var x171 uint64 - var x172 uint64 - x171, x172 = bits.Add64(x152, x155, uint64(uint1(x170))) - x173 := (uint64(uint1(x172)) + uint64(uint1(x153))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Sub64(x165, 0xffffffffffffffff, uint64(0x0)) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Sub64(x167, 0xffffffff, uint64(uint1(x175))) - var x178 uint64 - var x179 uint64 - x178, x179 = bits.Sub64(x169, uint64(0x0), uint64(uint1(x177))) - var x180 uint64 - var x181 uint64 - x180, x181 = bits.Sub64(x171, 0xffffffff00000001, uint64(uint1(x179))) - var x183 uint64 - _, x183 = bits.Sub64(x173, uint64(0x0), uint64(uint1(x181))) - var x184 uint64 - cmovznzU64(&x184, uint1(x183), x174, x165) - var x185 uint64 - cmovznzU64(&x185, uint1(x183), x176, x167) - var x186 uint64 - cmovznzU64(&x186, uint1(x183), x178, x169) - var x187 uint64 - cmovznzU64(&x187, uint1(x183), x180, x171) - out1[0] = x184 - out1[1] = x185 - out1[2] = x186 - out1[3] = x187 -} - -// Square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func Square(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x11, 0xffffffff00000001) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x11, 0xffffffff) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x11, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(x25, x22, uint64(0x0)) - x28 := (uint64(uint1(x27)) + x23) - var x30 uint64 - _, x30 = bits.Add64(x11, x24, uint64(0x0)) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x13, x26, uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x15, x28, uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64(x17, x20, uint64(uint1(x34))) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x19, x21, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, arg1[3]) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg1[2]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg1[1]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg1[0]) - var x47 uint64 - var x48 uint64 - x47, x48 = bits.Add64(x46, x43, uint64(0x0)) - var x49 uint64 - var x50 uint64 - x49, x50 = bits.Add64(x44, x41, uint64(uint1(x48))) - var x51 uint64 - var x52 uint64 - x51, x52 = bits.Add64(x42, x39, uint64(uint1(x50))) - x53 := (uint64(uint1(x52)) + x40) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x31, x45, uint64(0x0)) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x33, x47, uint64(uint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x35, x49, uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64(x37, x51, uint64(uint1(x59))) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(uint64(uint1(x38)), x53, uint64(uint1(x61))) - var x64 uint64 - var x65 uint64 - x65, x64 = bits.Mul64(x54, 0xffffffff00000001) - var x66 uint64 - var x67 uint64 - x67, x66 = bits.Mul64(x54, 0xffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x54, 0xffffffffffffffff) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(x69, x66, uint64(0x0)) - x72 := (uint64(uint1(x71)) + x67) - var x74 uint64 - _, x74 = bits.Add64(x54, x68, uint64(0x0)) - var x75 uint64 - var x76 uint64 - x75, x76 = bits.Add64(x56, x70, uint64(uint1(x74))) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Add64(x58, x72, uint64(uint1(x76))) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x60, x64, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x62, x65, uint64(uint1(x80))) - x83 := (uint64(uint1(x82)) + uint64(uint1(x63))) - var x84 uint64 - var x85 uint64 - x85, x84 = bits.Mul64(x2, arg1[3]) - var x86 uint64 - var x87 uint64 - x87, x86 = bits.Mul64(x2, arg1[2]) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg1[1]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg1[0]) - var x92 uint64 - var x93 uint64 - x92, x93 = bits.Add64(x91, x88, uint64(0x0)) - var x94 uint64 - var x95 uint64 - x94, x95 = bits.Add64(x89, x86, uint64(uint1(x93))) - var x96 uint64 - var x97 uint64 - x96, x97 = bits.Add64(x87, x84, uint64(uint1(x95))) - x98 := (uint64(uint1(x97)) + x85) - var x99 uint64 - var x100 uint64 - x99, x100 = bits.Add64(x75, x90, uint64(0x0)) - var x101 uint64 - var x102 uint64 - x101, x102 = bits.Add64(x77, x92, uint64(uint1(x100))) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x79, x94, uint64(uint1(x102))) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x81, x96, uint64(uint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x83, x98, uint64(uint1(x106))) - var x109 uint64 - var x110 uint64 - x110, x109 = bits.Mul64(x99, 0xffffffff00000001) - var x111 uint64 - var x112 uint64 - x112, x111 = bits.Mul64(x99, 0xffffffff) - var x113 uint64 - var x114 uint64 - x114, x113 = bits.Mul64(x99, 0xffffffffffffffff) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x114, x111, uint64(0x0)) - x117 := (uint64(uint1(x116)) + x112) - var x119 uint64 - _, x119 = bits.Add64(x99, x113, uint64(0x0)) - var x120 uint64 - var x121 uint64 - x120, x121 = bits.Add64(x101, x115, uint64(uint1(x119))) - var x122 uint64 - var x123 uint64 - x122, x123 = bits.Add64(x103, x117, uint64(uint1(x121))) - var x124 uint64 - var x125 uint64 - x124, x125 = bits.Add64(x105, x109, uint64(uint1(x123))) - var x126 uint64 - var x127 uint64 - x126, x127 = bits.Add64(x107, x110, uint64(uint1(x125))) - x128 := (uint64(uint1(x127)) + uint64(uint1(x108))) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x3, arg1[3]) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x3, arg1[2]) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x3, arg1[1]) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg1[0]) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x136, x133, uint64(0x0)) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x134, x131, uint64(uint1(x138))) - var x141 uint64 - var x142 uint64 - x141, x142 = bits.Add64(x132, x129, uint64(uint1(x140))) - x143 := (uint64(uint1(x142)) + x130) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x120, x135, uint64(0x0)) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x122, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x124, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x126, x141, uint64(uint1(x149))) - var x152 uint64 - var x153 uint64 - x152, x153 = bits.Add64(x128, x143, uint64(uint1(x151))) - var x154 uint64 - var x155 uint64 - x155, x154 = bits.Mul64(x144, 0xffffffff00000001) - var x156 uint64 - var x157 uint64 - x157, x156 = bits.Mul64(x144, 0xffffffff) - var x158 uint64 - var x159 uint64 - x159, x158 = bits.Mul64(x144, 0xffffffffffffffff) - var x160 uint64 - var x161 uint64 - x160, x161 = bits.Add64(x159, x156, uint64(0x0)) - x162 := (uint64(uint1(x161)) + x157) - var x164 uint64 - _, x164 = bits.Add64(x144, x158, uint64(0x0)) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x146, x160, uint64(uint1(x164))) - var x167 uint64 - var x168 uint64 - x167, x168 = bits.Add64(x148, x162, uint64(uint1(x166))) - var x169 uint64 - var x170 uint64 - x169, x170 = bits.Add64(x150, x154, uint64(uint1(x168))) - var x171 uint64 - var x172 uint64 - x171, x172 = bits.Add64(x152, x155, uint64(uint1(x170))) - x173 := (uint64(uint1(x172)) + uint64(uint1(x153))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Sub64(x165, 0xffffffffffffffff, uint64(0x0)) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Sub64(x167, 0xffffffff, uint64(uint1(x175))) - var x178 uint64 - var x179 uint64 - x178, x179 = bits.Sub64(x169, uint64(0x0), uint64(uint1(x177))) - var x180 uint64 - var x181 uint64 - x180, x181 = bits.Sub64(x171, 0xffffffff00000001, uint64(uint1(x179))) - var x183 uint64 - _, x183 = bits.Sub64(x173, uint64(0x0), uint64(uint1(x181))) - var x184 uint64 - cmovznzU64(&x184, uint1(x183), x174, x165) - var x185 uint64 - cmovznzU64(&x185, uint1(x183), x176, x167) - var x186 uint64 - cmovznzU64(&x186, uint1(x183), x178, x169) - var x187 uint64 - cmovznzU64(&x187, uint1(x183), x180, x171) - out1[0] = x184 - out1[1] = x185 - out1[2] = x186 - out1[3] = x187 -} - -// Add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Add(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - var x10 uint64 - x9, x10 = bits.Sub64(x1, 0xffffffffffffffff, uint64(0x0)) - var x11 uint64 - var x12 uint64 - x11, x12 = bits.Sub64(x3, 0xffffffff, uint64(uint1(x10))) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Sub64(x5, uint64(0x0), uint64(uint1(x12))) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Sub64(x7, 0xffffffff00000001, uint64(uint1(x14))) - var x18 uint64 - _, x18 = bits.Sub64(uint64(uint1(x8)), uint64(0x0), uint64(uint1(x16))) - var x19 uint64 - cmovznzU64(&x19, uint1(x18), x9, x1) - var x20 uint64 - cmovznzU64(&x20, uint1(x18), x11, x3) - var x21 uint64 - cmovznzU64(&x21, uint1(x18), x13, x5) - var x22 uint64 - cmovznzU64(&x22, uint1(x18), x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// Sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Sub(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, x9, uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xffffffff), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, uint64(0x0), uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0xffffffff00000001), uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// Opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func Opp(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, x9, uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xffffffff), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, uint64(0x0), uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0xffffffff00000001), uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// FromMontgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func FromMontgomery(out1 *NonMontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[0] - var x2 uint64 - var x3 uint64 - x3, x2 = bits.Mul64(x1, 0xffffffff00000001) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x1, 0xffffffff) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x1, 0xffffffffffffffff) - var x8 uint64 - var x9 uint64 - x8, x9 = bits.Add64(x7, x4, uint64(0x0)) - var x11 uint64 - _, x11 = bits.Add64(x1, x6, uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(uint64(0x0), x8, uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x12, arg1[1], uint64(0x0)) - var x16 uint64 - var x17 uint64 - x17, x16 = bits.Mul64(x14, 0xffffffff00000001) - var x18 uint64 - var x19 uint64 - x19, x18 = bits.Mul64(x14, 0xffffffff) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x14, 0xffffffffffffffff) - var x22 uint64 - var x23 uint64 - x22, x23 = bits.Add64(x21, x18, uint64(0x0)) - var x25 uint64 - _, x25 = bits.Add64(x14, x20, uint64(0x0)) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64((uint64(uint1(x15)) + (uint64(uint1(x13)) + (uint64(uint1(x9)) + x5))), x22, uint64(uint1(x25))) - var x28 uint64 - var x29 uint64 - x28, x29 = bits.Add64(x2, (uint64(uint1(x23)) + x19), uint64(uint1(x27))) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x3, x16, uint64(uint1(x29))) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x26, arg1[2], uint64(0x0)) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x28, uint64(0x0), uint64(uint1(x33))) - var x36 uint64 - var x37 uint64 - x36, x37 = bits.Add64(x30, uint64(0x0), uint64(uint1(x35))) - var x38 uint64 - var x39 uint64 - x39, x38 = bits.Mul64(x32, 0xffffffff00000001) - var x40 uint64 - var x41 uint64 - x41, x40 = bits.Mul64(x32, 0xffffffff) - var x42 uint64 - var x43 uint64 - x43, x42 = bits.Mul64(x32, 0xffffffffffffffff) - var x44 uint64 - var x45 uint64 - x44, x45 = bits.Add64(x43, x40, uint64(0x0)) - var x47 uint64 - _, x47 = bits.Add64(x32, x42, uint64(0x0)) - var x48 uint64 - var x49 uint64 - x48, x49 = bits.Add64(x34, x44, uint64(uint1(x47))) - var x50 uint64 - var x51 uint64 - x50, x51 = bits.Add64(x36, (uint64(uint1(x45)) + x41), uint64(uint1(x49))) - var x52 uint64 - var x53 uint64 - x52, x53 = bits.Add64((uint64(uint1(x37)) + (uint64(uint1(x31)) + x17)), x38, uint64(uint1(x51))) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64(x48, arg1[3], uint64(0x0)) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x50, uint64(0x0), uint64(uint1(x55))) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x52, uint64(0x0), uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x61, x60 = bits.Mul64(x54, 0xffffffff00000001) - var x62 uint64 - var x63 uint64 - x63, x62 = bits.Mul64(x54, 0xffffffff) - var x64 uint64 - var x65 uint64 - x65, x64 = bits.Mul64(x54, 0xffffffffffffffff) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x65, x62, uint64(0x0)) - var x69 uint64 - _, x69 = bits.Add64(x54, x64, uint64(0x0)) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(x56, x66, uint64(uint1(x69))) - var x72 uint64 - var x73 uint64 - x72, x73 = bits.Add64(x58, (uint64(uint1(x67)) + x63), uint64(uint1(x71))) - var x74 uint64 - var x75 uint64 - x74, x75 = bits.Add64((uint64(uint1(x59)) + (uint64(uint1(x53)) + x39)), x60, uint64(uint1(x73))) - x76 := (uint64(uint1(x75)) + x61) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Sub64(x70, 0xffffffffffffffff, uint64(0x0)) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Sub64(x72, 0xffffffff, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Sub64(x74, uint64(0x0), uint64(uint1(x80))) - var x83 uint64 - var x84 uint64 - x83, x84 = bits.Sub64(x76, 0xffffffff00000001, uint64(uint1(x82))) - var x86 uint64 - _, x86 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(uint1(x84))) - var x87 uint64 - cmovznzU64(&x87, uint1(x86), x77, x70) - var x88 uint64 - cmovznzU64(&x88, uint1(x86), x79, x72) - var x89 uint64 - cmovznzU64(&x89, uint1(x86), x81, x74) - var x90 uint64 - cmovznzU64(&x90, uint1(x86), x83, x76) - out1[0] = x87 - out1[1] = x88 - out1[2] = x89 - out1[3] = x90 -} - -// ToMontgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func ToMontgomery(out1 *MontgomeryDomainFieldElement, arg1 *NonMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x4fffffffd) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0xfffffffffffffffe) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0xfffffffbffffffff) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0x3) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - var x19 uint64 - var x20 uint64 - x20, x19 = bits.Mul64(x11, 0xffffffff00000001) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x11, 0xffffffff) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x11, 0xffffffffffffffff) - var x25 uint64 - var x26 uint64 - x25, x26 = bits.Add64(x24, x21, uint64(0x0)) - var x28 uint64 - _, x28 = bits.Add64(x11, x23, uint64(0x0)) - var x29 uint64 - var x30 uint64 - x29, x30 = bits.Add64(x13, x25, uint64(uint1(x28))) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x15, (uint64(uint1(x26)) + x22), uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x17, x19, uint64(uint1(x32))) - var x35 uint64 - var x36 uint64 - x35, x36 = bits.Add64((uint64(uint1(x18)) + x6), x20, uint64(uint1(x34))) - var x37 uint64 - var x38 uint64 - x38, x37 = bits.Mul64(x1, 0x4fffffffd) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, 0xfffffffffffffffe) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, 0xfffffffbffffffff) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, 0x3) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x44, x41, uint64(0x0)) - var x47 uint64 - var x48 uint64 - x47, x48 = bits.Add64(x42, x39, uint64(uint1(x46))) - var x49 uint64 - var x50 uint64 - x49, x50 = bits.Add64(x40, x37, uint64(uint1(x48))) - var x51 uint64 - var x52 uint64 - x51, x52 = bits.Add64(x29, x43, uint64(0x0)) - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Add64(x31, x45, uint64(uint1(x52))) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x33, x47, uint64(uint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x35, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x60, x59 = bits.Mul64(x51, 0xffffffff00000001) - var x61 uint64 - var x62 uint64 - x62, x61 = bits.Mul64(x51, 0xffffffff) - var x63 uint64 - var x64 uint64 - x64, x63 = bits.Mul64(x51, 0xffffffffffffffff) - var x65 uint64 - var x66 uint64 - x65, x66 = bits.Add64(x64, x61, uint64(0x0)) - var x68 uint64 - _, x68 = bits.Add64(x51, x63, uint64(0x0)) - var x69 uint64 - var x70 uint64 - x69, x70 = bits.Add64(x53, x65, uint64(uint1(x68))) - var x71 uint64 - var x72 uint64 - x71, x72 = bits.Add64(x55, (uint64(uint1(x66)) + x62), uint64(uint1(x70))) - var x73 uint64 - var x74 uint64 - x73, x74 = bits.Add64(x57, x59, uint64(uint1(x72))) - var x75 uint64 - var x76 uint64 - x75, x76 = bits.Add64(((uint64(uint1(x58)) + uint64(uint1(x36))) + (uint64(uint1(x50)) + x38)), x60, uint64(uint1(x74))) - var x77 uint64 - var x78 uint64 - x78, x77 = bits.Mul64(x2, 0x4fffffffd) - var x79 uint64 - var x80 uint64 - x80, x79 = bits.Mul64(x2, 0xfffffffffffffffe) - var x81 uint64 - var x82 uint64 - x82, x81 = bits.Mul64(x2, 0xfffffffbffffffff) - var x83 uint64 - var x84 uint64 - x84, x83 = bits.Mul64(x2, 0x3) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Add64(x84, x81, uint64(0x0)) - var x87 uint64 - var x88 uint64 - x87, x88 = bits.Add64(x82, x79, uint64(uint1(x86))) - var x89 uint64 - var x90 uint64 - x89, x90 = bits.Add64(x80, x77, uint64(uint1(x88))) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x69, x83, uint64(0x0)) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x71, x85, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x73, x87, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x75, x89, uint64(uint1(x96))) - var x99 uint64 - var x100 uint64 - x100, x99 = bits.Mul64(x91, 0xffffffff00000001) - var x101 uint64 - var x102 uint64 - x102, x101 = bits.Mul64(x91, 0xffffffff) - var x103 uint64 - var x104 uint64 - x104, x103 = bits.Mul64(x91, 0xffffffffffffffff) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x104, x101, uint64(0x0)) - var x108 uint64 - _, x108 = bits.Add64(x91, x103, uint64(0x0)) - var x109 uint64 - var x110 uint64 - x109, x110 = bits.Add64(x93, x105, uint64(uint1(x108))) - var x111 uint64 - var x112 uint64 - x111, x112 = bits.Add64(x95, (uint64(uint1(x106)) + x102), uint64(uint1(x110))) - var x113 uint64 - var x114 uint64 - x113, x114 = bits.Add64(x97, x99, uint64(uint1(x112))) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(((uint64(uint1(x98)) + uint64(uint1(x76))) + (uint64(uint1(x90)) + x78)), x100, uint64(uint1(x114))) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x3, 0x4fffffffd) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x3, 0xfffffffffffffffe) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x3, 0xfffffffbffffffff) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x3, 0x3) - var x125 uint64 - var x126 uint64 - x125, x126 = bits.Add64(x124, x121, uint64(0x0)) - var x127 uint64 - var x128 uint64 - x127, x128 = bits.Add64(x122, x119, uint64(uint1(x126))) - var x129 uint64 - var x130 uint64 - x129, x130 = bits.Add64(x120, x117, uint64(uint1(x128))) - var x131 uint64 - var x132 uint64 - x131, x132 = bits.Add64(x109, x123, uint64(0x0)) - var x133 uint64 - var x134 uint64 - x133, x134 = bits.Add64(x111, x125, uint64(uint1(x132))) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x113, x127, uint64(uint1(x134))) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x115, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x131, 0xffffffff00000001) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x131, 0xffffffff) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x131, 0xffffffffffffffff) - var x145 uint64 - var x146 uint64 - x145, x146 = bits.Add64(x144, x141, uint64(0x0)) - var x148 uint64 - _, x148 = bits.Add64(x131, x143, uint64(0x0)) - var x149 uint64 - var x150 uint64 - x149, x150 = bits.Add64(x133, x145, uint64(uint1(x148))) - var x151 uint64 - var x152 uint64 - x151, x152 = bits.Add64(x135, (uint64(uint1(x146)) + x142), uint64(uint1(x150))) - var x153 uint64 - var x154 uint64 - x153, x154 = bits.Add64(x137, x139, uint64(uint1(x152))) - var x155 uint64 - var x156 uint64 - x155, x156 = bits.Add64(((uint64(uint1(x138)) + uint64(uint1(x116))) + (uint64(uint1(x130)) + x118)), x140, uint64(uint1(x154))) - var x157 uint64 - var x158 uint64 - x157, x158 = bits.Sub64(x149, 0xffffffffffffffff, uint64(0x0)) - var x159 uint64 - var x160 uint64 - x159, x160 = bits.Sub64(x151, 0xffffffff, uint64(uint1(x158))) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Sub64(x153, uint64(0x0), uint64(uint1(x160))) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Sub64(x155, 0xffffffff00000001, uint64(uint1(x162))) - var x166 uint64 - _, x166 = bits.Sub64(uint64(uint1(x156)), uint64(0x0), uint64(uint1(x164))) - var x167 uint64 - cmovznzU64(&x167, uint1(x166), x157, x149) - var x168 uint64 - cmovznzU64(&x168, uint1(x166), x159, x151) - var x169 uint64 - cmovznzU64(&x169, uint1(x166), x161, x153) - var x170 uint64 - cmovznzU64(&x170, uint1(x166), x163, x155) - out1[0] = x167 - out1[1] = x168 - out1[2] = x169 - out1[3] = x170 -} - -// Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func Nonzero(out1 *uint64, arg1 *[4]uint64) { - x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) - *out1 = x1 -} - -// Selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Selectznz(out1 *[4]uint64, arg1 uint1, arg2 *[4]uint64, arg3 *[4]uint64) { - var x1 uint64 - cmovznzU64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - cmovznzU64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - cmovznzU64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - cmovznzU64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -func ToBytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func FromBytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} - -// SetOne returns the field element one in the Montgomery domain. -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = 1 mod m -// 0 ≤ eval out1 < m -func SetOne(out1 *MontgomeryDomainFieldElement) { - out1[0] = uint64(0x1) - out1[1] = 0xffffffff00000000 - out1[2] = 0xffffffffffffffff - out1[3] = 0xfffffffe -} diff --git a/crypto/core/curves/native/p256/fq/fq.go b/crypto/core/curves/native/p256/fq/fq.go deleted file mode 100644 index 7d95e944e..000000000 --- a/crypto/core/curves/native/p256/fq/fq.go +++ /dev/null @@ -1,510 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" -) - -var ( - p256FqInitonce sync.Once - p256FqParams native.FieldParams -) - -func P256FqNew() *native.Field { - return &native.Field{ - Value: [native.FieldLimbs]uint64{}, - Params: getP256FqParams(), - Arithmetic: p256FqArithmetic{}, - } -} - -func p256FqParamsInit() { - // See FIPS 186-3, section D.2.3 - p256FqParams = native.FieldParams{ - R: [native.FieldLimbs]uint64{ - 0x0c46353d039cdaaf, - 0x4319055258e8617b, - 0x0000000000000000, - 0x00000000ffffffff, - }, - R2: [native.FieldLimbs]uint64{ - 0x83244c95be79eea2, - 0x4699799c49bd6fa6, - 0x2845b2392b6bec59, - 0x66e12d94f3d95620, - }, - R3: [native.FieldLimbs]uint64{ - 0xac8ebec90b65a624, - 0x111f28ae0c0555c9, - 0x2543b9246ba5e93f, - 0x503a54e76407be65, - }, - Modulus: [native.FieldLimbs]uint64{ - 0xf3b9cac2fc632551, - 0xbce6faada7179e84, - 0xffffffffffffffff, - 0xffffffff00000000, - }, - BiModulus: new(big.Int).SetBytes([]byte{ - 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, - }), - } -} - -func getP256FqParams() *native.FieldParams { - p256FqInitonce.Do(p256FqParamsInit) - return &p256FqParams -} - -// p256FqArithmetic is a struct with all the methods needed for working -// in mod q -type p256FqArithmetic struct{} - -// ToMontgomery converts this field to montgomery form -func (f p256FqArithmetic) ToMontgomery(out, arg *[native.FieldLimbs]uint64) { - ToMontgomery((*MontgomeryDomainFieldElement)(out), (*NonMontgomeryDomainFieldElement)(arg)) -} - -// FromMontgomery converts this field from montgomery form -func (f p256FqArithmetic) FromMontgomery(out, arg *[native.FieldLimbs]uint64) { - FromMontgomery((*NonMontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Neg performs modular negation -func (f p256FqArithmetic) Neg(out, arg *[native.FieldLimbs]uint64) { - Opp((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Square performs modular square -func (f p256FqArithmetic) Square(out, arg *[native.FieldLimbs]uint64) { - Square((*MontgomeryDomainFieldElement)(out), (*MontgomeryDomainFieldElement)(arg)) -} - -// Mul performs modular multiplication -func (f p256FqArithmetic) Mul(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Mul( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Add performs modular addition -func (f p256FqArithmetic) Add(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Add( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sub performs modular subtraction -func (f p256FqArithmetic) Sub(out, arg1, arg2 *[native.FieldLimbs]uint64) { - Sub( - (*MontgomeryDomainFieldElement)(out), - (*MontgomeryDomainFieldElement)(arg1), - (*MontgomeryDomainFieldElement)(arg2), - ) -} - -// Sqrt performs modular square root -func (f p256FqArithmetic) Sqrt(wasSquare *int, out, arg *[native.FieldLimbs]uint64) { - // See sqrt_ts_ct at - // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.4 - // c1 := s - // c2 := (q - 1) / (2^c1) - // c2 := [4]uint64{ - // 0x4f3b9cac2fc63255, - // 0xfbce6faada7179e8, - // 0x0fffffffffffffff, - // 0x0ffffffff0000000, - // } - // c3 := (c2 - 1) / 2 - c3 := [native.FieldLimbs]uint64{ - 0x279dce5617e3192a, - 0xfde737d56d38bcf4, - 0x07ffffffffffffff, - 0x07fffffff8000000, - } - // c4 := generator - // c5 := new(Fq).pow(generator, c2) - c5 := [native.FieldLimbs]uint64{ - 0x1015708f7e368fe1, - 0x31c6c5456ecc4511, - 0x5281fe8998a19ea1, - 0x0279089e10c63fe8, - } - var z, t, b, c, tv [native.FieldLimbs]uint64 - - native.Pow(&z, arg, &c3, getP256FqParams(), f) - Square((*MontgomeryDomainFieldElement)(&t), (*MontgomeryDomainFieldElement)(&z)) - Mul( - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(arg), - ) - Mul( - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(arg), - ) - - copy(b[:], t[:]) - copy(c[:], c5[:]) - - for i := s; i >= 2; i-- { - for j := 1; j <= i-2; j++ { - Square((*MontgomeryDomainFieldElement)(&b), (*MontgomeryDomainFieldElement)(&b)) - } - // if b == 1 flag = 0 else flag = 1 - flag := -(&native.Field{ - Value: b, - Params: getP256FqParams(), - Arithmetic: f, - }).IsOne() + 1 - Mul( - (*MontgomeryDomainFieldElement)(&tv), - (*MontgomeryDomainFieldElement)(&z), - (*MontgomeryDomainFieldElement)(&c), - ) - Selectznz(&z, uint1(flag), &z, &tv) - Square((*MontgomeryDomainFieldElement)(&c), (*MontgomeryDomainFieldElement)(&c)) - Mul( - (*MontgomeryDomainFieldElement)(&tv), - (*MontgomeryDomainFieldElement)(&t), - (*MontgomeryDomainFieldElement)(&c), - ) - Selectznz(&t, uint1(flag), &t, &tv) - copy(b[:], t[:]) - } - Square((*MontgomeryDomainFieldElement)(&c), (*MontgomeryDomainFieldElement)(&z)) - *wasSquare = (&native.Field{ - Value: c, - Params: getP256FqParams(), - Arithmetic: f, - }).Equal(&native.Field{ - Value: *arg, - Params: getP256FqParams(), - Arithmetic: f, - }) - Selectznz(out, uint1(*wasSquare), out, &z) -} - -// Invert performs modular inverse -func (f p256FqArithmetic) Invert(wasInverted *int, out, arg *[native.FieldLimbs]uint64) { - // Using an addition chain from - // https://briansmith.org/ecc-inversion-addition-chains-01#p256_field_inversion - var x1, x10, x11, x101, x111, x1010, x1111, x10101, x101010, x101111 [native.FieldLimbs]uint64 - var x6, x8, x16, x32, tmp [native.FieldLimbs]uint64 - - copy(x1[:], arg[:]) - native.Pow2k(&x10, arg, 1, f) - Mul( - (*MontgomeryDomainFieldElement)(&x11), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x1), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x101), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x11), - ) - Mul( - (*MontgomeryDomainFieldElement)(&x111), - (*MontgomeryDomainFieldElement)(&x10), - (*MontgomeryDomainFieldElement)(&x101), - ) - native.Pow2k(&x1010, &x101, 1, f) - Mul( - (*MontgomeryDomainFieldElement)(&x1111), - (*MontgomeryDomainFieldElement)(&x101), - (*MontgomeryDomainFieldElement)(&x1010), - ) - native.Pow2k(&x10101, &x1010, 1, f) - Mul( - (*MontgomeryDomainFieldElement)(&x10101), - (*MontgomeryDomainFieldElement)(&x10101), - (*MontgomeryDomainFieldElement)(&x1), - ) - native.Pow2k(&x101010, &x10101, 1, f) - Mul( - (*MontgomeryDomainFieldElement)(&x101111), - (*MontgomeryDomainFieldElement)(&x101), - (*MontgomeryDomainFieldElement)(&x101010), - ) - - Mul( - (*MontgomeryDomainFieldElement)(&x6), - (*MontgomeryDomainFieldElement)(&x10101), - (*MontgomeryDomainFieldElement)(&x101010), - ) - - native.Pow2k(&x8, &x6, 2, f) - Mul( - (*MontgomeryDomainFieldElement)(&x8), - (*MontgomeryDomainFieldElement)(&x8), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&x16, &x8, 8, f) - Mul( - (*MontgomeryDomainFieldElement)(&x16), - (*MontgomeryDomainFieldElement)(&x16), - (*MontgomeryDomainFieldElement)(&x8), - ) - - native.Pow2k(&x32, &x16, 16, f) - Mul( - (*MontgomeryDomainFieldElement)(&x32), - (*MontgomeryDomainFieldElement)(&x32), - (*MontgomeryDomainFieldElement)(&x16), - ) - - native.Pow2k(&tmp, &x32, 64, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x32), - ) - - native.Pow2k(&tmp, &tmp, 32, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x32), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x10101), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 9, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101111), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1111), - ) - - native.Pow2k(&tmp, &tmp, 2, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 4, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x111), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 10, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x101111), - ) - - native.Pow2k(&tmp, &tmp, 2, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 5, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x11), - ) - - native.Pow2k(&tmp, &tmp, 3, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1), - ) - - native.Pow2k(&tmp, &tmp, 7, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x10101), - ) - - native.Pow2k(&tmp, &tmp, 6, f) - Mul( - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&tmp), - (*MontgomeryDomainFieldElement)(&x1111), - ) - - *wasInverted = (&native.Field{ - Value: *arg, - Params: getP256FqParams(), - Arithmetic: f, - }).IsNonZero() - Selectznz(out, uint1(*wasInverted), out, &tmp) -} - -// FromBytes converts a little endian byte array into a field element -func (f p256FqArithmetic) FromBytes(out *[native.FieldLimbs]uint64, arg *[native.FieldBytes]byte) { - FromBytes(out, arg) -} - -// ToBytes converts a field element to a little endian byte array -func (f p256FqArithmetic) ToBytes(out *[native.FieldBytes]byte, arg *[native.FieldLimbs]uint64) { - ToBytes(out, arg) -} - -// Selectznz performs conditional select. -// selects arg1 if choice == 0 and arg2 if choice == 1 -func (f p256FqArithmetic) Selectznz(out, arg1, arg2 *[native.FieldLimbs]uint64, choice int) { - Selectznz(out, uint1(choice), arg1, arg2) -} - -// generator = 7 mod q is a generator of the `q - 1` order multiplicative -// subgroup, or in other words a primitive element of the field. -// generator^t where t * 2^s + 1 = q -var generator = &[native.FieldLimbs]uint64{ - 0x55eb74ab1949fac9, - 0xd5af25406e5aaa5d, - 0x0000000000000001, - 0x00000006fffffff9, -} - -// s satisfies the equation 2^s * t = q - 1 with t odd. -var s = 4 - -// rootOfUnity -var rootOfUnity = &[native.FieldLimbs]uint64{ - 0x0592d7fbb41e6602, - 0x1546cad004378daf, - 0xba807ace842a3dfc, - 0xffc97f062a770992, -} diff --git a/crypto/core/curves/native/p256/fq/fq_test.go b/crypto/core/curves/native/p256/fq/fq_test.go deleted file mode 100644 index 4449ec872..000000000 --- a/crypto/core/curves/native/p256/fq/fq_test.go +++ /dev/null @@ -1,330 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - crand "crypto/rand" - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/internal" -) - -func TestFqSetOne(t *testing.T) { - fq := P256FqNew().SetOne() - require.NotNil(t, fq) - require.Equal(t, fq.Value, getP256FqParams().R) -} - -func TestFqSetUint64(t *testing.T) { - act := P256FqNew().SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, act.Value[0], uint64(0xb3f3986dec632551)) -} - -func TestFqAdd(t *testing.T) { - lhs := P256FqNew().SetOne() - rhs := P256FqNew().SetOne() - exp := P256FqNew().SetUint64(2) - res := P256FqNew().Add(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := P256FqNew().Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqSub(t *testing.T) { - lhs := P256FqNew().SetOne() - rhs := P256FqNew().SetOne() - exp := P256FqNew().SetZero() - res := P256FqNew().Sub(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := P256FqNew().Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqMul(t *testing.T) { - lhs := P256FqNew().SetOne() - rhs := P256FqNew().SetOne() - exp := P256FqNew().SetOne() - res := P256FqNew().Mul(lhs, rhs) - require.NotNil(t, res) - require.Equal(t, 1, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := P256FqNew().Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqDouble(t *testing.T) { - a := P256FqNew().SetUint64(2) - e := P256FqNew().SetUint64(4) - require.Equal(t, e, P256FqNew().Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = P256FqNew().SetUint64(uint64(tv)) - e = P256FqNew().SetUint64(ttv) - require.Equal(t, e, P256FqNew().Double(a)) - } -} - -func TestFqSquare(t *testing.T) { - a := P256FqNew().SetUint64(4) - e := P256FqNew().SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFqNeg(t *testing.T) { - g := P256FqNew().SetRaw(generator) - a := P256FqNew().SetOne() - a.Neg(a) - e := P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0xe7739585f8c64aa2, 0x79cdf55b4e2f3d09, 0xffffffffffffffff, 0xfffffffe00000001}) - require.Equal(t, e, a) - a.Neg(g) - e = P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x9dce5617e3192a88, 0xe737d56d38bcf427, 0xfffffffffffffffd, 0xfffffff800000007}) - require.Equal(t, e, a) -} - -func TestFqExp(t *testing.T) { - e := P256FqNew().SetUint64(8) - a := P256FqNew().SetUint64(2) - by := P256FqNew().SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFqSqrt(t *testing.T) { - t1 := P256FqNew().SetUint64(2) - t2 := P256FqNew().Neg(t1) - t3 := P256FqNew().Square(t1) - _, wasSquare := t3.Sqrt(t3) - - require.True(t, wasSquare) - require.Equal(t, 1, t1.Equal(t3)|t2.Equal(t3)) - t1.SetUint64(7) - _, wasSquare = t3.Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFqInvert(t *testing.T) { - twoInv := P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x8000000000000000}) - two := P256FqNew().SetUint64(2) - a, inverted := P256FqNew().Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnityInv := P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0xcfbf53b9618acf96, 0xf17e5c39df7bd05b, 0xc7acb1f83e3ad9ad, 0x4659a42b394ff7df}) - rootOU := P256FqNew().SetRaw(rootOfUnity) - a, inverted = P256FqNew().Invert(rootOU) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := P256FqNew().SetUint64(9) - rhs := P256FqNew().SetUint64(3) - rhsInv, inverted := P256FqNew().Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, P256FqNew().Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = P256FqNew().Invert(rhs) - require.False(t, inverted) -} - -func TestFqCMove(t *testing.T) { - t1 := P256FqNew().SetUint64(5) - t2 := P256FqNew().SetUint64(10) - require.Equal(t, t1, P256FqNew().CMove(t1, t2, 0)) - require.Equal(t, t2, P256FqNew().CMove(t1, t2, 1)) -} - -func TestFqBytes(t *testing.T) { - t1 := P256FqNew().SetUint64(99) - seq := t1.Bytes() - t2, err := P256FqNew().SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFqCmp(t *testing.T) { - tests := []struct { - a *native.Field - b *native.Field - e int - }{ - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{2731658267414164836, 14655288906067898431, 6537465423330262322, 8306191141697566219}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{6472764012681988529, 10848812988401906064, 2961825807536828898, 4282183981941645679}), - e: 1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{8023004109510539223, 4652004072850285717, 1877219145646046927, 383214385093921911}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{10099384440823804262, 16139476942229308465, 8636966320777393798, 5435928725024696785}), - e: -1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{3741840066202388211, 12165774400417314871, 16619312580230515379, 16195032234110087705}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{3905865991286066744, 543690822309071825, 17963103015950210055, 3745476720756119742}), - e: 1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{16660853697936147788, 7799793619412111108, 13515141085171033220, 2641079731236069032}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{17790588295388238399, 571847801379669440, 14537208974498222469, 12792570372087452754}), - e: -1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{3912839285384959186, 2701177075110484070, 6453856448115499033, 6475797457962597458}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{1282566391665688512, 13503640416992806563, 2962240104675990153, 3374904770947067689}), - e: 1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{5716631803409360103, 7859567470082614154, 12747956220853330146, 18434584096087315020}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{16317076441459028418, 12854146980376319601, 2258436689269031143, 9531877130792223752}), - e: 1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{17955191469941083403, 10350326247207200880, 17263512235150705075, 12700328451238078022}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{6767595547459644695, 7146403825494928147, 12269344038346710612, 9122477829383225603}), - e: 1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{17099388671847024438, 6426264987820696548, 10641143464957227405, 7709745403700754098}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{10799154372990268556, 17178492485719929374, 5705777922258988797, 8051037767683567782}), - e: -1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{4567139260680454325, 1629385880182139061, 16607020832317899145, 1261011562621553200}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{13487234491304534488, 17872642955936089265, 17651026784972590233, 9468934643333871559}), - e: -1, - }, - { - a: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{18071070103467571798, 11787850505799426140, 10631355976141928593, 4867785203635092610}), - b: P256FqNew().SetRaw(&[native.FieldLimbs]uint64{12596443599426461624, 10176122686151524591, 17075755296887483439, 6726169532695070719}), - e: -1, - }, - } - - for _, test := range tests { - require.Equal(t, test.e, test.a.Cmp(test.b)) - require.Equal(t, -test.e, test.b.Cmp(test.a)) - require.Equal(t, 0, test.a.Cmp(test.a)) - require.Equal(t, 0, test.b.Cmp(test.b)) - } -} - -func TestFqBigInt(t *testing.T) { - t1 := P256FqNew().SetBigInt(big.NewInt(9999)) - t2 := P256FqNew().SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0x21dcaaadf1cb6aa0, 0x568de5f5990a98d7, 0x354f43b0d837fac5, 0x3e02532cb23f481a}) - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e.Value[0] = 0xd1dd20150a97bab1 - e.Value[1] = 0x665914b80e0d05ad - e.Value[2] = 0xcab0bc4f27c8053a - e.Value[3] = 0xc1fdacd24dc0b7e6 - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFqSetBytesWide(t *testing.T) { - e := P256FqNew().SetRaw(&[native.FieldLimbs]uint64{0xe2b8d4b0e576c8fa, 0x9d2b215f85d3bdf7, 0xf6070a872442640c, 0xcf15d1e49c990b88}) - - a := P256FqNew().SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} - -func TestFpSetBytesWideBigInt(t *testing.T) { - params := getP256FqParams() - var tv2 [64]byte - for i := 0; i < 25; i++ { - _, _ = crand.Read(tv2[:]) - e := new(big.Int).SetBytes(tv2[:]) - e.Mod(e, params.BiModulus) - - tv := internal.ReverseScalarBytes(tv2[:]) - copy(tv2[:], tv) - a := P256FqNew().SetBytesWide(&tv2) - require.Equal(t, 0, e.Cmp(a.BigInt())) - } -} diff --git a/crypto/core/curves/native/p256/fq/p256_fq.go b/crypto/core/curves/native/p256/fq/p256_fq.go deleted file mode 100755 index 728e58b1f..000000000 --- a/crypto/core/curves/native/p256/fq/p256_fq.go +++ /dev/null @@ -1,1651 +0,0 @@ -// Code generated by Fiat Cryptography. DO NOT EDIT. -// -// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Go --no-wide-int --relax-primitive-carry-to-bitwidth 32,64 --cmovznz-by-mul --internal-static --package-case flatcase --public-function-case UpperCamelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case camelCase --no-prefix-fiat --doc-newline-in-typedef-bounds --doc-prepend-header 'Code generated by Fiat Cryptography. DO NOT EDIT.' --doc-text-before-function-name ” --doc-text-before-type-name ” --package-name fq ” 64 '2^256 - 2^224 + 2^192 - 89188191075325690597107910205041859247' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one -// -// curve description (via package name): fq -// -// machine_wordsize = 64 (from "64") -// -// requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one -// -// m = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 (from "2^256 - 2^224 + 2^192 - 89188191075325690597107910205041859247") -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 -package fq - -import "math/bits" - -type uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -type int1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 - -// MontgomeryDomainFieldElement is a field element in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type MontgomeryDomainFieldElement [4]uint64 - -// NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. -// -// Bounds: -// -// [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type NonMontgomeryDomainFieldElement [4]uint64 - -// cmovznzU64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func cmovznzU64(out1 *uint64, arg1 uint1, arg2 uint64, arg3 uint64) { - x1 := (uint64(arg1) * 0xffffffffffffffff) - x2 := ((x1 & arg3) | ((^x1) & arg2)) - *out1 = x2 -} - -// Mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Mul(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0xccd1c8aaee00bc4f) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffff00000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xbce6faada7179e84) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xf3b9cac2fc632551) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg2[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg2[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg2[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0xccd1c8aaee00bc4f) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffff00000000) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xffffffffffffffff) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xbce6faada7179e84) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xf3b9cac2fc632551) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg2[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg2[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg2[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg2[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0xccd1c8aaee00bc4f) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffff00000000) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xffffffffffffffff) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xbce6faada7179e84) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xf3b9cac2fc632551) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg2[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg2[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg2[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg2[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0xccd1c8aaee00bc4f) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffff00000000) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xffffffffffffffff) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xbce6faada7179e84) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xf3b9cac2fc632551) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xf3b9cac2fc632551, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xbce6faada7179e84, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xffffffffffffffff, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffff00000000, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func Square(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - x19 := (uint64(uint1(x18)) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0xccd1c8aaee00bc4f) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0xffffffff00000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0xffffffffffffffff) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0xbce6faada7179e84) - var x28 uint64 - var x29 uint64 - x29, x28 = bits.Mul64(x20, 0xf3b9cac2fc632551) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x29, x26, uint64(0x0)) - var x32 uint64 - var x33 uint64 - x32, x33 = bits.Add64(x27, x24, uint64(uint1(x31))) - var x34 uint64 - var x35 uint64 - x34, x35 = bits.Add64(x25, x22, uint64(uint1(x33))) - x36 := (uint64(uint1(x35)) + x23) - var x38 uint64 - _, x38 = bits.Add64(x11, x28, uint64(0x0)) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x13, x30, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x15, x32, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64(x17, x34, uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x45, x46 = bits.Add64(x19, x36, uint64(uint1(x44))) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg1[3]) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, arg1[2]) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, arg1[1]) - var x53 uint64 - var x54 uint64 - x54, x53 = bits.Mul64(x1, arg1[0]) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x54, x51, uint64(0x0)) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x52, x49, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x50, x47, uint64(uint1(x58))) - x61 := (uint64(uint1(x60)) + x48) - var x62 uint64 - var x63 uint64 - x62, x63 = bits.Add64(x39, x53, uint64(0x0)) - var x64 uint64 - var x65 uint64 - x64, x65 = bits.Add64(x41, x55, uint64(uint1(x63))) - var x66 uint64 - var x67 uint64 - x66, x67 = bits.Add64(x43, x57, uint64(uint1(x65))) - var x68 uint64 - var x69 uint64 - x68, x69 = bits.Add64(x45, x59, uint64(uint1(x67))) - var x70 uint64 - var x71 uint64 - x70, x71 = bits.Add64(uint64(uint1(x46)), x61, uint64(uint1(x69))) - var x72 uint64 - _, x72 = bits.Mul64(x62, 0xccd1c8aaee00bc4f) - var x74 uint64 - var x75 uint64 - x75, x74 = bits.Mul64(x72, 0xffffffff00000000) - var x76 uint64 - var x77 uint64 - x77, x76 = bits.Mul64(x72, 0xffffffffffffffff) - var x78 uint64 - var x79 uint64 - x79, x78 = bits.Mul64(x72, 0xbce6faada7179e84) - var x80 uint64 - var x81 uint64 - x81, x80 = bits.Mul64(x72, 0xf3b9cac2fc632551) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x81, x78, uint64(0x0)) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64(x79, x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x77, x74, uint64(uint1(x85))) - x88 := (uint64(uint1(x87)) + x75) - var x90 uint64 - _, x90 = bits.Add64(x62, x80, uint64(0x0)) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(x64, x82, uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x93, x94 = bits.Add64(x66, x84, uint64(uint1(x92))) - var x95 uint64 - var x96 uint64 - x95, x96 = bits.Add64(x68, x86, uint64(uint1(x94))) - var x97 uint64 - var x98 uint64 - x97, x98 = bits.Add64(x70, x88, uint64(uint1(x96))) - x99 := (uint64(uint1(x98)) + uint64(uint1(x71))) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x2, arg1[3]) - var x102 uint64 - var x103 uint64 - x103, x102 = bits.Mul64(x2, arg1[2]) - var x104 uint64 - var x105 uint64 - x105, x104 = bits.Mul64(x2, arg1[1]) - var x106 uint64 - var x107 uint64 - x107, x106 = bits.Mul64(x2, arg1[0]) - var x108 uint64 - var x109 uint64 - x108, x109 = bits.Add64(x107, x104, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x105, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x103, x100, uint64(uint1(x111))) - x114 := (uint64(uint1(x113)) + x101) - var x115 uint64 - var x116 uint64 - x115, x116 = bits.Add64(x91, x106, uint64(0x0)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Add64(x93, x108, uint64(uint1(x116))) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Add64(x95, x110, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Add64(x97, x112, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Add64(x99, x114, uint64(uint1(x122))) - var x125 uint64 - _, x125 = bits.Mul64(x115, 0xccd1c8aaee00bc4f) - var x127 uint64 - var x128 uint64 - x128, x127 = bits.Mul64(x125, 0xffffffff00000000) - var x129 uint64 - var x130 uint64 - x130, x129 = bits.Mul64(x125, 0xffffffffffffffff) - var x131 uint64 - var x132 uint64 - x132, x131 = bits.Mul64(x125, 0xbce6faada7179e84) - var x133 uint64 - var x134 uint64 - x134, x133 = bits.Mul64(x125, 0xf3b9cac2fc632551) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x134, x131, uint64(0x0)) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x132, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(x130, x127, uint64(uint1(x138))) - x141 := (uint64(uint1(x140)) + x128) - var x143 uint64 - _, x143 = bits.Add64(x115, x133, uint64(0x0)) - var x144 uint64 - var x145 uint64 - x144, x145 = bits.Add64(x117, x135, uint64(uint1(x143))) - var x146 uint64 - var x147 uint64 - x146, x147 = bits.Add64(x119, x137, uint64(uint1(x145))) - var x148 uint64 - var x149 uint64 - x148, x149 = bits.Add64(x121, x139, uint64(uint1(x147))) - var x150 uint64 - var x151 uint64 - x150, x151 = bits.Add64(x123, x141, uint64(uint1(x149))) - x152 := (uint64(uint1(x151)) + uint64(uint1(x124))) - var x153 uint64 - var x154 uint64 - x154, x153 = bits.Mul64(x3, arg1[3]) - var x155 uint64 - var x156 uint64 - x156, x155 = bits.Mul64(x3, arg1[2]) - var x157 uint64 - var x158 uint64 - x158, x157 = bits.Mul64(x3, arg1[1]) - var x159 uint64 - var x160 uint64 - x160, x159 = bits.Mul64(x3, arg1[0]) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x160, x157, uint64(0x0)) - var x163 uint64 - var x164 uint64 - x163, x164 = bits.Add64(x158, x155, uint64(uint1(x162))) - var x165 uint64 - var x166 uint64 - x165, x166 = bits.Add64(x156, x153, uint64(uint1(x164))) - x167 := (uint64(uint1(x166)) + x154) - var x168 uint64 - var x169 uint64 - x168, x169 = bits.Add64(x144, x159, uint64(0x0)) - var x170 uint64 - var x171 uint64 - x170, x171 = bits.Add64(x146, x161, uint64(uint1(x169))) - var x172 uint64 - var x173 uint64 - x172, x173 = bits.Add64(x148, x163, uint64(uint1(x171))) - var x174 uint64 - var x175 uint64 - x174, x175 = bits.Add64(x150, x165, uint64(uint1(x173))) - var x176 uint64 - var x177 uint64 - x176, x177 = bits.Add64(x152, x167, uint64(uint1(x175))) - var x178 uint64 - _, x178 = bits.Mul64(x168, 0xccd1c8aaee00bc4f) - var x180 uint64 - var x181 uint64 - x181, x180 = bits.Mul64(x178, 0xffffffff00000000) - var x182 uint64 - var x183 uint64 - x183, x182 = bits.Mul64(x178, 0xffffffffffffffff) - var x184 uint64 - var x185 uint64 - x185, x184 = bits.Mul64(x178, 0xbce6faada7179e84) - var x186 uint64 - var x187 uint64 - x187, x186 = bits.Mul64(x178, 0xf3b9cac2fc632551) - var x188 uint64 - var x189 uint64 - x188, x189 = bits.Add64(x187, x184, uint64(0x0)) - var x190 uint64 - var x191 uint64 - x190, x191 = bits.Add64(x185, x182, uint64(uint1(x189))) - var x192 uint64 - var x193 uint64 - x192, x193 = bits.Add64(x183, x180, uint64(uint1(x191))) - x194 := (uint64(uint1(x193)) + x181) - var x196 uint64 - _, x196 = bits.Add64(x168, x186, uint64(0x0)) - var x197 uint64 - var x198 uint64 - x197, x198 = bits.Add64(x170, x188, uint64(uint1(x196))) - var x199 uint64 - var x200 uint64 - x199, x200 = bits.Add64(x172, x190, uint64(uint1(x198))) - var x201 uint64 - var x202 uint64 - x201, x202 = bits.Add64(x174, x192, uint64(uint1(x200))) - var x203 uint64 - var x204 uint64 - x203, x204 = bits.Add64(x176, x194, uint64(uint1(x202))) - x205 := (uint64(uint1(x204)) + uint64(uint1(x177))) - var x206 uint64 - var x207 uint64 - x206, x207 = bits.Sub64(x197, 0xf3b9cac2fc632551, uint64(0x0)) - var x208 uint64 - var x209 uint64 - x208, x209 = bits.Sub64(x199, 0xbce6faada7179e84, uint64(uint1(x207))) - var x210 uint64 - var x211 uint64 - x210, x211 = bits.Sub64(x201, 0xffffffffffffffff, uint64(uint1(x209))) - var x212 uint64 - var x213 uint64 - x212, x213 = bits.Sub64(x203, 0xffffffff00000000, uint64(uint1(x211))) - var x215 uint64 - _, x215 = bits.Sub64(x205, uint64(0x0), uint64(uint1(x213))) - var x216 uint64 - cmovznzU64(&x216, uint1(x215), x206, x197) - var x217 uint64 - cmovznzU64(&x217, uint1(x215), x208, x199) - var x218 uint64 - cmovznzU64(&x218, uint1(x215), x210, x201) - var x219 uint64 - cmovznzU64(&x219, uint1(x215), x212, x203) - out1[0] = x216 - out1[1] = x217 - out1[2] = x218 - out1[3] = x219 -} - -// Add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Add(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Add64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Add64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Add64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Add64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - var x10 uint64 - x9, x10 = bits.Sub64(x1, 0xf3b9cac2fc632551, uint64(0x0)) - var x11 uint64 - var x12 uint64 - x11, x12 = bits.Sub64(x3, 0xbce6faada7179e84, uint64(uint1(x10))) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Sub64(x5, 0xffffffffffffffff, uint64(uint1(x12))) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Sub64(x7, 0xffffffff00000000, uint64(uint1(x14))) - var x18 uint64 - _, x18 = bits.Sub64(uint64(uint1(x8)), uint64(0x0), uint64(uint1(x16))) - var x19 uint64 - cmovznzU64(&x19, uint1(x18), x9, x1) - var x20 uint64 - cmovznzU64(&x20, uint1(x18), x11, x3) - var x21 uint64 - cmovznzU64(&x21, uint1(x18), x13, x5) - var x22 uint64 - cmovznzU64(&x22, uint1(x18), x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// Sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func Sub(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement, arg2 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(arg1[0], arg2[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(arg1[1], arg2[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(arg1[2], arg2[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(arg1[3], arg2[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xf3b9cac2fc632551), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xbce6faada7179e84), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, x9, uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0xffffffff00000000), uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// Opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func Opp(out1 *MontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - var x1 uint64 - var x2 uint64 - x1, x2 = bits.Sub64(uint64(0x0), arg1[0], uint64(0x0)) - var x3 uint64 - var x4 uint64 - x3, x4 = bits.Sub64(uint64(0x0), arg1[1], uint64(uint1(x2))) - var x5 uint64 - var x6 uint64 - x5, x6 = bits.Sub64(uint64(0x0), arg1[2], uint64(uint1(x4))) - var x7 uint64 - var x8 uint64 - x7, x8 = bits.Sub64(uint64(0x0), arg1[3], uint64(uint1(x6))) - var x9 uint64 - cmovznzU64(&x9, uint1(x8), uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 uint64 - x10, x11 = bits.Add64(x1, (x9 & 0xf3b9cac2fc632551), uint64(0x0)) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x3, (x9 & 0xbce6faada7179e84), uint64(uint1(x11))) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x5, x9, uint64(uint1(x13))) - var x16 uint64 - x16, _ = bits.Add64(x7, (x9 & 0xffffffff00000000), uint64(uint1(x15))) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// FromMontgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func FromMontgomery(out1 *NonMontgomeryDomainFieldElement, arg1 *MontgomeryDomainFieldElement) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0xccd1c8aaee00bc4f) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0xffffffff00000000) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0xffffffffffffffff) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0xbce6faada7179e84) - var x10 uint64 - var x11 uint64 - x11, x10 = bits.Mul64(x2, 0xf3b9cac2fc632551) - var x12 uint64 - var x13 uint64 - x12, x13 = bits.Add64(x11, x8, uint64(0x0)) - var x14 uint64 - var x15 uint64 - x14, x15 = bits.Add64(x9, x6, uint64(uint1(x13))) - var x16 uint64 - var x17 uint64 - x16, x17 = bits.Add64(x7, x4, uint64(uint1(x15))) - var x19 uint64 - _, x19 = bits.Add64(x1, x10, uint64(0x0)) - var x20 uint64 - var x21 uint64 - x20, x21 = bits.Add64(uint64(0x0), x12, uint64(uint1(x19))) - var x22 uint64 - var x23 uint64 - x22, x23 = bits.Add64(uint64(0x0), x14, uint64(uint1(x21))) - var x24 uint64 - var x25 uint64 - x24, x25 = bits.Add64(uint64(0x0), x16, uint64(uint1(x23))) - var x26 uint64 - var x27 uint64 - x26, x27 = bits.Add64(x20, arg1[1], uint64(0x0)) - var x28 uint64 - var x29 uint64 - x28, x29 = bits.Add64(x22, uint64(0x0), uint64(uint1(x27))) - var x30 uint64 - var x31 uint64 - x30, x31 = bits.Add64(x24, uint64(0x0), uint64(uint1(x29))) - var x32 uint64 - _, x32 = bits.Mul64(x26, 0xccd1c8aaee00bc4f) - var x34 uint64 - var x35 uint64 - x35, x34 = bits.Mul64(x32, 0xffffffff00000000) - var x36 uint64 - var x37 uint64 - x37, x36 = bits.Mul64(x32, 0xffffffffffffffff) - var x38 uint64 - var x39 uint64 - x39, x38 = bits.Mul64(x32, 0xbce6faada7179e84) - var x40 uint64 - var x41 uint64 - x41, x40 = bits.Mul64(x32, 0xf3b9cac2fc632551) - var x42 uint64 - var x43 uint64 - x42, x43 = bits.Add64(x41, x38, uint64(0x0)) - var x44 uint64 - var x45 uint64 - x44, x45 = bits.Add64(x39, x36, uint64(uint1(x43))) - var x46 uint64 - var x47 uint64 - x46, x47 = bits.Add64(x37, x34, uint64(uint1(x45))) - var x49 uint64 - _, x49 = bits.Add64(x26, x40, uint64(0x0)) - var x50 uint64 - var x51 uint64 - x50, x51 = bits.Add64(x28, x42, uint64(uint1(x49))) - var x52 uint64 - var x53 uint64 - x52, x53 = bits.Add64(x30, x44, uint64(uint1(x51))) - var x54 uint64 - var x55 uint64 - x54, x55 = bits.Add64((uint64(uint1(x31)) + (uint64(uint1(x25)) + (uint64(uint1(x17)) + x5))), x46, uint64(uint1(x53))) - var x56 uint64 - var x57 uint64 - x56, x57 = bits.Add64(x50, arg1[2], uint64(0x0)) - var x58 uint64 - var x59 uint64 - x58, x59 = bits.Add64(x52, uint64(0x0), uint64(uint1(x57))) - var x60 uint64 - var x61 uint64 - x60, x61 = bits.Add64(x54, uint64(0x0), uint64(uint1(x59))) - var x62 uint64 - _, x62 = bits.Mul64(x56, 0xccd1c8aaee00bc4f) - var x64 uint64 - var x65 uint64 - x65, x64 = bits.Mul64(x62, 0xffffffff00000000) - var x66 uint64 - var x67 uint64 - x67, x66 = bits.Mul64(x62, 0xffffffffffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x62, 0xbce6faada7179e84) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x62, 0xf3b9cac2fc632551) - var x72 uint64 - var x73 uint64 - x72, x73 = bits.Add64(x71, x68, uint64(0x0)) - var x74 uint64 - var x75 uint64 - x74, x75 = bits.Add64(x69, x66, uint64(uint1(x73))) - var x76 uint64 - var x77 uint64 - x76, x77 = bits.Add64(x67, x64, uint64(uint1(x75))) - var x79 uint64 - _, x79 = bits.Add64(x56, x70, uint64(0x0)) - var x80 uint64 - var x81 uint64 - x80, x81 = bits.Add64(x58, x72, uint64(uint1(x79))) - var x82 uint64 - var x83 uint64 - x82, x83 = bits.Add64(x60, x74, uint64(uint1(x81))) - var x84 uint64 - var x85 uint64 - x84, x85 = bits.Add64((uint64(uint1(x61)) + (uint64(uint1(x55)) + (uint64(uint1(x47)) + x35))), x76, uint64(uint1(x83))) - var x86 uint64 - var x87 uint64 - x86, x87 = bits.Add64(x80, arg1[3], uint64(0x0)) - var x88 uint64 - var x89 uint64 - x88, x89 = bits.Add64(x82, uint64(0x0), uint64(uint1(x87))) - var x90 uint64 - var x91 uint64 - x90, x91 = bits.Add64(x84, uint64(0x0), uint64(uint1(x89))) - var x92 uint64 - _, x92 = bits.Mul64(x86, 0xccd1c8aaee00bc4f) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x92, 0xffffffff00000000) - var x96 uint64 - var x97 uint64 - x97, x96 = bits.Mul64(x92, 0xffffffffffffffff) - var x98 uint64 - var x99 uint64 - x99, x98 = bits.Mul64(x92, 0xbce6faada7179e84) - var x100 uint64 - var x101 uint64 - x101, x100 = bits.Mul64(x92, 0xf3b9cac2fc632551) - var x102 uint64 - var x103 uint64 - x102, x103 = bits.Add64(x101, x98, uint64(0x0)) - var x104 uint64 - var x105 uint64 - x104, x105 = bits.Add64(x99, x96, uint64(uint1(x103))) - var x106 uint64 - var x107 uint64 - x106, x107 = bits.Add64(x97, x94, uint64(uint1(x105))) - var x109 uint64 - _, x109 = bits.Add64(x86, x100, uint64(0x0)) - var x110 uint64 - var x111 uint64 - x110, x111 = bits.Add64(x88, x102, uint64(uint1(x109))) - var x112 uint64 - var x113 uint64 - x112, x113 = bits.Add64(x90, x104, uint64(uint1(x111))) - var x114 uint64 - var x115 uint64 - x114, x115 = bits.Add64((uint64(uint1(x91)) + (uint64(uint1(x85)) + (uint64(uint1(x77)) + x65))), x106, uint64(uint1(x113))) - x116 := (uint64(uint1(x115)) + (uint64(uint1(x107)) + x95)) - var x117 uint64 - var x118 uint64 - x117, x118 = bits.Sub64(x110, 0xf3b9cac2fc632551, uint64(0x0)) - var x119 uint64 - var x120 uint64 - x119, x120 = bits.Sub64(x112, 0xbce6faada7179e84, uint64(uint1(x118))) - var x121 uint64 - var x122 uint64 - x121, x122 = bits.Sub64(x114, 0xffffffffffffffff, uint64(uint1(x120))) - var x123 uint64 - var x124 uint64 - x123, x124 = bits.Sub64(x116, 0xffffffff00000000, uint64(uint1(x122))) - var x126 uint64 - _, x126 = bits.Sub64(uint64(0x0), uint64(0x0), uint64(uint1(x124))) - var x127 uint64 - cmovznzU64(&x127, uint1(x126), x117, x110) - var x128 uint64 - cmovznzU64(&x128, uint1(x126), x119, x112) - var x129 uint64 - cmovznzU64(&x129, uint1(x126), x121, x114) - var x130 uint64 - cmovznzU64(&x130, uint1(x126), x123, x116) - out1[0] = x127 - out1[1] = x128 - out1[2] = x129 - out1[3] = x130 -} - -// ToMontgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func ToMontgomery(out1 *MontgomeryDomainFieldElement, arg1 *NonMontgomeryDomainFieldElement) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x66e12d94f3d95620) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0x2845b2392b6bec59) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0x4699799c49bd6fa6) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0x83244c95be79eea2) - var x13 uint64 - var x14 uint64 - x13, x14 = bits.Add64(x12, x9, uint64(0x0)) - var x15 uint64 - var x16 uint64 - x15, x16 = bits.Add64(x10, x7, uint64(uint1(x14))) - var x17 uint64 - var x18 uint64 - x17, x18 = bits.Add64(x8, x5, uint64(uint1(x16))) - var x19 uint64 - _, x19 = bits.Mul64(x11, 0xccd1c8aaee00bc4f) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x19, 0xffffffff00000000) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x19, 0xffffffffffffffff) - var x25 uint64 - var x26 uint64 - x26, x25 = bits.Mul64(x19, 0xbce6faada7179e84) - var x27 uint64 - var x28 uint64 - x28, x27 = bits.Mul64(x19, 0xf3b9cac2fc632551) - var x29 uint64 - var x30 uint64 - x29, x30 = bits.Add64(x28, x25, uint64(0x0)) - var x31 uint64 - var x32 uint64 - x31, x32 = bits.Add64(x26, x23, uint64(uint1(x30))) - var x33 uint64 - var x34 uint64 - x33, x34 = bits.Add64(x24, x21, uint64(uint1(x32))) - var x36 uint64 - _, x36 = bits.Add64(x11, x27, uint64(0x0)) - var x37 uint64 - var x38 uint64 - x37, x38 = bits.Add64(x13, x29, uint64(uint1(x36))) - var x39 uint64 - var x40 uint64 - x39, x40 = bits.Add64(x15, x31, uint64(uint1(x38))) - var x41 uint64 - var x42 uint64 - x41, x42 = bits.Add64(x17, x33, uint64(uint1(x40))) - var x43 uint64 - var x44 uint64 - x43, x44 = bits.Add64((uint64(uint1(x18)) + x6), (uint64(uint1(x34)) + x22), uint64(uint1(x42))) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, 0x66e12d94f3d95620) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, 0x2845b2392b6bec59) - var x49 uint64 - var x50 uint64 - x50, x49 = bits.Mul64(x1, 0x4699799c49bd6fa6) - var x51 uint64 - var x52 uint64 - x52, x51 = bits.Mul64(x1, 0x83244c95be79eea2) - var x53 uint64 - var x54 uint64 - x53, x54 = bits.Add64(x52, x49, uint64(0x0)) - var x55 uint64 - var x56 uint64 - x55, x56 = bits.Add64(x50, x47, uint64(uint1(x54))) - var x57 uint64 - var x58 uint64 - x57, x58 = bits.Add64(x48, x45, uint64(uint1(x56))) - var x59 uint64 - var x60 uint64 - x59, x60 = bits.Add64(x37, x51, uint64(0x0)) - var x61 uint64 - var x62 uint64 - x61, x62 = bits.Add64(x39, x53, uint64(uint1(x60))) - var x63 uint64 - var x64 uint64 - x63, x64 = bits.Add64(x41, x55, uint64(uint1(x62))) - var x65 uint64 - var x66 uint64 - x65, x66 = bits.Add64(x43, x57, uint64(uint1(x64))) - var x67 uint64 - _, x67 = bits.Mul64(x59, 0xccd1c8aaee00bc4f) - var x69 uint64 - var x70 uint64 - x70, x69 = bits.Mul64(x67, 0xffffffff00000000) - var x71 uint64 - var x72 uint64 - x72, x71 = bits.Mul64(x67, 0xffffffffffffffff) - var x73 uint64 - var x74 uint64 - x74, x73 = bits.Mul64(x67, 0xbce6faada7179e84) - var x75 uint64 - var x76 uint64 - x76, x75 = bits.Mul64(x67, 0xf3b9cac2fc632551) - var x77 uint64 - var x78 uint64 - x77, x78 = bits.Add64(x76, x73, uint64(0x0)) - var x79 uint64 - var x80 uint64 - x79, x80 = bits.Add64(x74, x71, uint64(uint1(x78))) - var x81 uint64 - var x82 uint64 - x81, x82 = bits.Add64(x72, x69, uint64(uint1(x80))) - var x84 uint64 - _, x84 = bits.Add64(x59, x75, uint64(0x0)) - var x85 uint64 - var x86 uint64 - x85, x86 = bits.Add64(x61, x77, uint64(uint1(x84))) - var x87 uint64 - var x88 uint64 - x87, x88 = bits.Add64(x63, x79, uint64(uint1(x86))) - var x89 uint64 - var x90 uint64 - x89, x90 = bits.Add64(x65, x81, uint64(uint1(x88))) - var x91 uint64 - var x92 uint64 - x91, x92 = bits.Add64(((uint64(uint1(x66)) + uint64(uint1(x44))) + (uint64(uint1(x58)) + x46)), (uint64(uint1(x82)) + x70), uint64(uint1(x90))) - var x93 uint64 - var x94 uint64 - x94, x93 = bits.Mul64(x2, 0x66e12d94f3d95620) - var x95 uint64 - var x96 uint64 - x96, x95 = bits.Mul64(x2, 0x2845b2392b6bec59) - var x97 uint64 - var x98 uint64 - x98, x97 = bits.Mul64(x2, 0x4699799c49bd6fa6) - var x99 uint64 - var x100 uint64 - x100, x99 = bits.Mul64(x2, 0x83244c95be79eea2) - var x101 uint64 - var x102 uint64 - x101, x102 = bits.Add64(x100, x97, uint64(0x0)) - var x103 uint64 - var x104 uint64 - x103, x104 = bits.Add64(x98, x95, uint64(uint1(x102))) - var x105 uint64 - var x106 uint64 - x105, x106 = bits.Add64(x96, x93, uint64(uint1(x104))) - var x107 uint64 - var x108 uint64 - x107, x108 = bits.Add64(x85, x99, uint64(0x0)) - var x109 uint64 - var x110 uint64 - x109, x110 = bits.Add64(x87, x101, uint64(uint1(x108))) - var x111 uint64 - var x112 uint64 - x111, x112 = bits.Add64(x89, x103, uint64(uint1(x110))) - var x113 uint64 - var x114 uint64 - x113, x114 = bits.Add64(x91, x105, uint64(uint1(x112))) - var x115 uint64 - _, x115 = bits.Mul64(x107, 0xccd1c8aaee00bc4f) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x115, 0xffffffff00000000) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x115, 0xffffffffffffffff) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x115, 0xbce6faada7179e84) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x115, 0xf3b9cac2fc632551) - var x125 uint64 - var x126 uint64 - x125, x126 = bits.Add64(x124, x121, uint64(0x0)) - var x127 uint64 - var x128 uint64 - x127, x128 = bits.Add64(x122, x119, uint64(uint1(x126))) - var x129 uint64 - var x130 uint64 - x129, x130 = bits.Add64(x120, x117, uint64(uint1(x128))) - var x132 uint64 - _, x132 = bits.Add64(x107, x123, uint64(0x0)) - var x133 uint64 - var x134 uint64 - x133, x134 = bits.Add64(x109, x125, uint64(uint1(x132))) - var x135 uint64 - var x136 uint64 - x135, x136 = bits.Add64(x111, x127, uint64(uint1(x134))) - var x137 uint64 - var x138 uint64 - x137, x138 = bits.Add64(x113, x129, uint64(uint1(x136))) - var x139 uint64 - var x140 uint64 - x139, x140 = bits.Add64(((uint64(uint1(x114)) + uint64(uint1(x92))) + (uint64(uint1(x106)) + x94)), (uint64(uint1(x130)) + x118), uint64(uint1(x138))) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, 0x66e12d94f3d95620) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x3, 0x2845b2392b6bec59) - var x145 uint64 - var x146 uint64 - x146, x145 = bits.Mul64(x3, 0x4699799c49bd6fa6) - var x147 uint64 - var x148 uint64 - x148, x147 = bits.Mul64(x3, 0x83244c95be79eea2) - var x149 uint64 - var x150 uint64 - x149, x150 = bits.Add64(x148, x145, uint64(0x0)) - var x151 uint64 - var x152 uint64 - x151, x152 = bits.Add64(x146, x143, uint64(uint1(x150))) - var x153 uint64 - var x154 uint64 - x153, x154 = bits.Add64(x144, x141, uint64(uint1(x152))) - var x155 uint64 - var x156 uint64 - x155, x156 = bits.Add64(x133, x147, uint64(0x0)) - var x157 uint64 - var x158 uint64 - x157, x158 = bits.Add64(x135, x149, uint64(uint1(x156))) - var x159 uint64 - var x160 uint64 - x159, x160 = bits.Add64(x137, x151, uint64(uint1(x158))) - var x161 uint64 - var x162 uint64 - x161, x162 = bits.Add64(x139, x153, uint64(uint1(x160))) - var x163 uint64 - _, x163 = bits.Mul64(x155, 0xccd1c8aaee00bc4f) - var x165 uint64 - var x166 uint64 - x166, x165 = bits.Mul64(x163, 0xffffffff00000000) - var x167 uint64 - var x168 uint64 - x168, x167 = bits.Mul64(x163, 0xffffffffffffffff) - var x169 uint64 - var x170 uint64 - x170, x169 = bits.Mul64(x163, 0xbce6faada7179e84) - var x171 uint64 - var x172 uint64 - x172, x171 = bits.Mul64(x163, 0xf3b9cac2fc632551) - var x173 uint64 - var x174 uint64 - x173, x174 = bits.Add64(x172, x169, uint64(0x0)) - var x175 uint64 - var x176 uint64 - x175, x176 = bits.Add64(x170, x167, uint64(uint1(x174))) - var x177 uint64 - var x178 uint64 - x177, x178 = bits.Add64(x168, x165, uint64(uint1(x176))) - var x180 uint64 - _, x180 = bits.Add64(x155, x171, uint64(0x0)) - var x181 uint64 - var x182 uint64 - x181, x182 = bits.Add64(x157, x173, uint64(uint1(x180))) - var x183 uint64 - var x184 uint64 - x183, x184 = bits.Add64(x159, x175, uint64(uint1(x182))) - var x185 uint64 - var x186 uint64 - x185, x186 = bits.Add64(x161, x177, uint64(uint1(x184))) - var x187 uint64 - var x188 uint64 - x187, x188 = bits.Add64(((uint64(uint1(x162)) + uint64(uint1(x140))) + (uint64(uint1(x154)) + x142)), (uint64(uint1(x178)) + x166), uint64(uint1(x186))) - var x189 uint64 - var x190 uint64 - x189, x190 = bits.Sub64(x181, 0xf3b9cac2fc632551, uint64(0x0)) - var x191 uint64 - var x192 uint64 - x191, x192 = bits.Sub64(x183, 0xbce6faada7179e84, uint64(uint1(x190))) - var x193 uint64 - var x194 uint64 - x193, x194 = bits.Sub64(x185, 0xffffffffffffffff, uint64(uint1(x192))) - var x195 uint64 - var x196 uint64 - x195, x196 = bits.Sub64(x187, 0xffffffff00000000, uint64(uint1(x194))) - var x198 uint64 - _, x198 = bits.Sub64(uint64(uint1(x188)), uint64(0x0), uint64(uint1(x196))) - var x199 uint64 - cmovznzU64(&x199, uint1(x198), x189, x181) - var x200 uint64 - cmovznzU64(&x200, uint1(x198), x191, x183) - var x201 uint64 - cmovznzU64(&x201, uint1(x198), x193, x185) - var x202 uint64 - cmovznzU64(&x202, uint1(x198), x195, x187) - out1[0] = x199 - out1[1] = x200 - out1[2] = x201 - out1[3] = x202 -} - -// Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func Nonzero(out1 *uint64, arg1 *[4]uint64) { - x1 := (arg1[0] | (arg1[1] | (arg1[2] | arg1[3]))) - *out1 = x1 -} - -// Selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func Selectznz(out1 *[4]uint64, arg1 uint1, arg2 *[4]uint64, arg3 *[4]uint64) { - var x1 uint64 - cmovznzU64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - cmovznzU64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - cmovznzU64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - cmovznzU64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -func ToBytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func FromBytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} - -// SetOne returns the field element one in the Montgomery domain. -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = 1 mod m -// 0 ≤ eval out1 < m -func SetOne(out1 *MontgomeryDomainFieldElement) { - out1[0] = 0xc46353d039cdaaf - out1[1] = 0x4319055258e8617b - out1[2] = uint64(0x0) - out1[3] = 0xffffffff -} diff --git a/crypto/core/curves/native/p256/point.go b/crypto/core/curves/native/p256/point.go deleted file mode 100644 index e8e14a49b..000000000 --- a/crypto/core/curves/native/p256/point.go +++ /dev/null @@ -1,350 +0,0 @@ -package p256 - -import ( - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/p256/fp" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - p256PointInitonce sync.Once - p256PointParams native.EllipticPointParams - p256PointSswuInitOnce sync.Once - p256PointSswuParams native.SswuParams -) - -func P256PointNew() *native.EllipticPoint { - return &native.EllipticPoint{ - X: fp.P256FpNew(), - Y: fp.P256FpNew(), - Z: fp.P256FpNew(), - Params: getP256PointParams(), - Arithmetic: &p256PointArithmetic{}, - } -} - -func p256PointParamsInit() { - // How these values were derived - // left for informational purposes - // params := elliptic.P256().Params() - // a := big.NewInt(-3) - // a.Mod(a, params.P) - // capA := fp.P256FpNew().SetBigInt(a) - // capB := fp.P256FpNew().SetBigInt(params.B) - // gx := fp.P256FpNew().SetBigInt(params.Gx) - // gy := fp.P256FpNew().SetBigInt(params.Gy) - - p256PointParams = native.EllipticPointParams{ - A: fp.P256FpNew(). - SetRaw(&[native.FieldLimbs]uint64{0xfffffffffffffffc, 0x00000003ffffffff, 0x0000000000000000, 0xfffffffc00000004}), - B: fp.P256FpNew(). - SetRaw(&[native.FieldLimbs]uint64{0xd89cdf6229c4bddf, 0xacf005cd78843090, 0xe5a220abf7212ed6, 0xdc30061d04874834}), - Gx: fp.P256FpNew(). - SetRaw(&[native.FieldLimbs]uint64{0x79e730d418a9143c, 0x75ba95fc5fedb601, 0x79fb732b77622510, 0x18905f76a53755c6}), - Gy: fp.P256FpNew(). - SetRaw(&[native.FieldLimbs]uint64{0xddf25357ce95560a, 0x8b4ab8e4ba19e45c, 0xd2e88688dd21f325, 0x8571ff1825885d85}), - BitSize: 256, - Name: "P256", - } -} - -func getP256PointParams() *native.EllipticPointParams { - p256PointInitonce.Do(p256PointParamsInit) - return &p256PointParams -} - -func getP256PointSswuParams() *native.SswuParams { - p256PointSswuInitOnce.Do(p256PointSswuParamsInit) - return &p256PointSswuParams -} - -func p256PointSswuParamsInit() { - // How these values were derived - // left for informational purposes - //params := elliptic.P256().Params() - // - //// c1 = (q - 3) / 4 - //c1 := new(big.Int).Set(params.P) - //c1.Sub(c1, big.NewInt(3)) - //c1.Rsh(c1, 2) - // - //a := big.NewInt(-3) - //a.Mod(a, params.P) - //b := new(big.Int).Set(params.B) - //z := big.NewInt(-10) - //z.Mod(z, params.P) - //// sqrt(-Z^3) - //zTmp := new(big.Int).Exp(z, big.NewInt(3), nil) - //zTmp = zTmp.Neg(zTmp) - //zTmp.Mod(zTmp, params.P) - //c2 := new(big.Int).ModSqrt(zTmp, params.P) - // - //var capC1Bytes [32]byte - //c1.FillBytes(capC1Bytes[:]) - //capC1 := fp.P256FpNew().SetRaw(&[native.FieldLimbs]uint64{ - // binary.BigEndian.Uint64(capC1Bytes[24:]), - // binary.BigEndian.Uint64(capC1Bytes[16:24]), - // binary.BigEndian.Uint64(capC1Bytes[8:16]), - // binary.BigEndian.Uint64(capC1Bytes[:8]), - //}) - //capC2 := fp.P256FpNew().SetBigInt(c2) - //capA := fp.P256FpNew().SetBigInt(a) - //capB := fp.P256FpNew().SetBigInt(b) - //capZ := fp.P256FpNew().SetBigInt(z) - - p256PointSswuParams = native.SswuParams{ - C1: [native.FieldLimbs]uint64{ - 0xffffffffffffffff, - 0x000000003fffffff, - 0x4000000000000000, - 0x3fffffffc0000000, - }, - C2: [native.FieldLimbs]uint64{ - 0x53e43951f64fdbe7, - 0xb2806c63966a1a66, - 0x1ac5d59c3298bf50, - 0xa3323851ba997e27, - }, - A: [native.FieldLimbs]uint64{ - 0xfffffffffffffffc, - 0x00000003ffffffff, - 0x0000000000000000, - 0xfffffffc00000004, - }, - B: [native.FieldLimbs]uint64{ - 0xd89cdf6229c4bddf, - 0xacf005cd78843090, - 0xe5a220abf7212ed6, - 0xdc30061d04874834, - }, - Z: [native.FieldLimbs]uint64{ - 0xfffffffffffffff5, - 0x0000000affffffff, - 0x0000000000000000, - 0xfffffff50000000b, - }, - } -} - -type p256PointArithmetic struct{} - -func (k p256PointArithmetic) Hash( - out *native.EllipticPoint, - hash *native.EllipticPointHasher, - msg, dst []byte, -) error { - var u []byte - sswuParams := getP256PointSswuParams() - - switch hash.Type() { - case native.XMD: - u = native.ExpandMsgXmd(hash, msg, dst, 96) - case native.XOF: - u = native.ExpandMsgXof(hash, msg, dst, 96) - } - var buf [64]byte - copy(buf[:48], internal.ReverseScalarBytes(u[:48])) - u0 := fp.P256FpNew().SetBytesWide(&buf) - copy(buf[:48], internal.ReverseScalarBytes(u[48:])) - u1 := fp.P256FpNew().SetBytesWide(&buf) - - q0x, q0y := sswuParams.Osswu3mod4(u0) - q1x, q1y := sswuParams.Osswu3mod4(u1) - out.X = q0x - out.Y = q0y - out.Z.SetOne() - tv := &native.EllipticPoint{ - X: q1x, - Y: q1y, - Z: fp.P256FpNew().SetOne(), - } - k.Add(out, out, tv) - return nil -} - -func (k p256PointArithmetic) Double(out, arg *native.EllipticPoint) { - // Addition formula from Renes-Costello-Batina 2015 - // (https://eprint.iacr.org/2015/1060 Algorithm 6) - var xx, yy, zz, xy2, yz2, xz2, bzz, bzz3 [native.FieldLimbs]uint64 - var yyMBzz3, yyPBzz3, yFrag, xFrag, zz3 [native.FieldLimbs]uint64 - var bxz2, bxz6, xx3Mzz3, x, y, z [native.FieldLimbs]uint64 - b := getP256PointParams().B.Value - f := arg.X.Arithmetic - - f.Square(&xx, &arg.X.Value) - f.Square(&yy, &arg.Y.Value) - f.Square(&zz, &arg.Z.Value) - - f.Mul(&xy2, &arg.X.Value, &arg.Y.Value) - f.Add(&xy2, &xy2, &xy2) - - f.Mul(&yz2, &arg.Y.Value, &arg.Z.Value) - f.Add(&yz2, &yz2, &yz2) - - f.Mul(&xz2, &arg.X.Value, &arg.Z.Value) - f.Add(&xz2, &xz2, &xz2) - - f.Mul(&bzz, &b, &zz) - f.Sub(&bzz, &bzz, &xz2) - - f.Add(&bzz3, &bzz, &bzz) - f.Add(&bzz3, &bzz3, &bzz) - - f.Sub(&yyMBzz3, &yy, &bzz3) - f.Add(&yyPBzz3, &yy, &bzz3) - f.Mul(&yFrag, &yyPBzz3, &yyMBzz3) - f.Mul(&xFrag, &yyMBzz3, &xy2) - - f.Add(&zz3, &zz, &zz) - f.Add(&zz3, &zz3, &zz) - - f.Mul(&bxz2, &b, &xz2) - f.Sub(&bxz2, &bxz2, &zz3) - f.Sub(&bxz2, &bxz2, &xx) - - f.Add(&bxz6, &bxz2, &bxz2) - f.Add(&bxz6, &bxz6, &bxz2) - - f.Add(&xx3Mzz3, &xx, &xx) - f.Add(&xx3Mzz3, &xx3Mzz3, &xx) - f.Sub(&xx3Mzz3, &xx3Mzz3, &zz3) - - f.Mul(&x, &bxz6, &yz2) - f.Sub(&x, &xFrag, &x) - - f.Mul(&y, &xx3Mzz3, &bxz6) - f.Add(&y, &yFrag, &y) - - f.Mul(&z, &yz2, &yy) - f.Add(&z, &z, &z) - f.Add(&z, &z, &z) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z -} - -func (k p256PointArithmetic) Add(out, arg1, arg2 *native.EllipticPoint) { - // Addition formula from Renes-Costello-Batina 2015 - // (https://eprint.iacr.org/2015/1060 Algorithm 4). - var xx, yy, zz, zz3, bxz, bxz3 [native.FieldLimbs]uint64 - var tv1, xyPairs, yzPairs, xzPairs [native.FieldLimbs]uint64 - var bzz, bzz3, yyMBzz3, yyPBzz3 [native.FieldLimbs]uint64 - var xx3Mzz3, x, y, z [native.FieldLimbs]uint64 - f := arg1.X.Arithmetic - b := getP256PointParams().B.Value - - f.Mul(&xx, &arg1.X.Value, &arg2.X.Value) - f.Mul(&yy, &arg1.Y.Value, &arg2.Y.Value) - f.Mul(&zz, &arg1.Z.Value, &arg2.Z.Value) - - f.Add(&tv1, &arg2.X.Value, &arg2.Y.Value) - f.Add(&xyPairs, &arg1.X.Value, &arg1.Y.Value) - f.Mul(&xyPairs, &xyPairs, &tv1) - f.Sub(&xyPairs, &xyPairs, &xx) - f.Sub(&xyPairs, &xyPairs, &yy) - - f.Add(&tv1, &arg2.Y.Value, &arg2.Z.Value) - f.Add(&yzPairs, &arg1.Y.Value, &arg1.Z.Value) - f.Mul(&yzPairs, &yzPairs, &tv1) - f.Sub(&yzPairs, &yzPairs, &yy) - f.Sub(&yzPairs, &yzPairs, &zz) - - f.Add(&tv1, &arg2.X.Value, &arg2.Z.Value) - f.Add(&xzPairs, &arg1.X.Value, &arg1.Z.Value) - f.Mul(&xzPairs, &xzPairs, &tv1) - f.Sub(&xzPairs, &xzPairs, &xx) - f.Sub(&xzPairs, &xzPairs, &zz) - - f.Mul(&bzz, &b, &zz) - f.Sub(&bzz, &xzPairs, &bzz) - - f.Add(&bzz3, &bzz, &bzz) - f.Add(&bzz3, &bzz3, &bzz) - - f.Sub(&yyMBzz3, &yy, &bzz3) - f.Add(&yyPBzz3, &yy, &bzz3) - - f.Add(&zz3, &zz, &zz) - f.Add(&zz3, &zz3, &zz) - - f.Mul(&bxz, &b, &xzPairs) - f.Sub(&bxz, &bxz, &zz3) - f.Sub(&bxz, &bxz, &xx) - - f.Add(&bxz3, &bxz, &bxz) - f.Add(&bxz3, &bxz3, &bxz) - - f.Add(&xx3Mzz3, &xx, &xx) - f.Add(&xx3Mzz3, &xx3Mzz3, &xx) - f.Sub(&xx3Mzz3, &xx3Mzz3, &zz3) - - f.Mul(&tv1, &yzPairs, &bxz3) - f.Mul(&x, &yyPBzz3, &xyPairs) - f.Sub(&x, &x, &tv1) - - f.Mul(&tv1, &xx3Mzz3, &bxz3) - f.Mul(&y, &yyPBzz3, &yyMBzz3) - f.Add(&y, &y, &tv1) - - f.Mul(&tv1, &xyPairs, &xx3Mzz3) - f.Mul(&z, &yyMBzz3, &yzPairs) - f.Add(&z, &z, &tv1) - - e1 := arg1.Z.IsZero() - e2 := arg2.Z.IsZero() - - // If arg1 is identity set it to arg2 - f.Selectznz(&z, &z, &arg2.Z.Value, e1) - f.Selectznz(&y, &y, &arg2.Y.Value, e1) - f.Selectznz(&x, &x, &arg2.X.Value, e1) - // If arg2 is identity set it to arg1 - f.Selectznz(&z, &z, &arg1.Z.Value, e2) - f.Selectznz(&y, &y, &arg1.Y.Value, e2) - f.Selectznz(&x, &x, &arg1.X.Value, e2) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z -} - -func (k p256PointArithmetic) IsOnCurve(arg *native.EllipticPoint) bool { - affine := P256PointNew() - k.ToAffine(affine, arg) - lhs := fp.P256FpNew().Square(affine.Y) - rhs := fp.P256FpNew() - k.RhsEq(rhs, affine.X) - return lhs.Equal(rhs) == 1 -} - -func (k p256PointArithmetic) ToAffine(out, arg *native.EllipticPoint) { - var wasInverted int - var zero, x, y, z [native.FieldLimbs]uint64 - f := arg.X.Arithmetic - - f.Invert(&wasInverted, &z, &arg.Z.Value) - f.Mul(&x, &arg.X.Value, &z) - f.Mul(&y, &arg.Y.Value, &z) - - out.Z.SetOne() - // If point at infinity this does nothing - f.Selectznz(&x, &zero, &x, wasInverted) - f.Selectznz(&y, &zero, &y, wasInverted) - f.Selectznz(&z, &zero, &out.Z.Value, wasInverted) - - out.X.Value = x - out.Y.Value = y - out.Z.Value = z - out.Params = arg.Params - out.Arithmetic = arg.Arithmetic -} - -func (k p256PointArithmetic) RhsEq(out, x *native.Field) { - // Elliptic curve equation for p256 is: y^2 = x^3 ax + b - out.Square(x) - out.Mul(out, x) - out.Add(out, getP256PointParams().B) - out.Add(out, fp.P256FpNew().Mul(getP256PointParams().A, x)) -} diff --git a/crypto/core/curves/native/p256/point_test.go b/crypto/core/curves/native/p256/point_test.go deleted file mode 100644 index da545312a..000000000 --- a/crypto/core/curves/native/p256/point_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package p256_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/p256" - "github.com/sonr-io/sonr/crypto/core/curves/native/p256/fp" -) - -func TestP256PointArithmetic_Double(t *testing.T) { - g := p256.P256PointNew().Generator() - pt1 := p256.P256PointNew().Double(g) - pt2 := p256.P256PointNew().Add(g, g) - pt3 := p256.P256PointNew().Mul(g, fp.P256FpNew().SetUint64(2)) - - e1 := pt1.Equal(pt2) - e2 := pt1.Equal(pt3) - e3 := pt2.Equal(pt3) - require.Equal(t, 1, e1) - require.Equal(t, 1, e2) - require.Equal(t, 1, e3) -} - -func TestP256PointArithmetic_Hash(t *testing.T) { - var b [32]byte - sc, err := p256.P256PointNew().Hash(b[:], native.EllipticPointHasherSha256()) - sc1 := curves.P256().NewIdentityPoint().Hash(b[:]) - fmt.Printf("%v\n", sc1) - - require.NoError(t, err) - require.True(t, !sc.IsIdentity()) - require.True(t, sc.IsOnCurve()) -} diff --git a/crypto/core/curves/native/pasta/README.md b/crypto/core/curves/native/pasta/README.md deleted file mode 100755 index e0785f20f..000000000 --- a/crypto/core/curves/native/pasta/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Pallas and Pasta Curve diff --git a/crypto/core/curves/native/pasta/fp/fp.go b/crypto/core/curves/native/pasta/fp/fp.go deleted file mode 100644 index 2a025e862..000000000 --- a/crypto/core/curves/native/pasta/fp/fp.go +++ /dev/null @@ -1,375 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - "encoding/binary" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/internal" -) - -type Fp fiat_pasta_fp_montgomery_domain_field_element - -// r = 2^256 mod p -var r = &Fp{0x34786d38fffffffd, 0x992c350be41914ad, 0xffffffffffffffff, 0x3fffffffffffffff} - -// r2 = 2^512 mod p -var r2 = &Fp{0x8c78ecb30000000f, 0xd7d30dbd8b0de0e7, 0x7797a99bc3c95d18, 0x096d41af7b9cb714} - -// r3 = 2^768 mod p -var r3 = &Fp{0xf185a5993a9e10f9, 0xf6a68f3b6ac5b1d1, 0xdf8d1014353fd42c, 0x2ae309222d2d9910} - -// generator = 5 mod p is a generator of the `p - 1` order multiplicative -// subgroup, or in other words a primitive element of the field. -var generator = &Fp{0xa1a55e68ffffffed, 0x74c2a54b4f4982f3, 0xfffffffffffffffd, 0x3fffffffffffffff} - -var s = 32 - -// modulus representation -// p = 0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001 -var modulus = &Fp{0x992d30ed00000001, 0x224698fc094cf91b, 0x0000000000000000, 0x4000000000000000} - -var biModulus = new(big.Int).SetBytes([]byte{ - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x46, 0x98, 0xfc, 0x09, 0x4c, 0xf9, 0x1b, - 0x99, 0x2d, 0x30, 0xed, 0x00, 0x00, 0x00, 0x01, -}) - -// Cmp returns -1 if fp < rhs -// 0 if fp == rhs -// 1 if fp > rhs -func (fp *Fp) Cmp(rhs *Fp) int { - gt := 0 - lt := 0 - for i := len(fp) - 1; i >= 0; i-- { - gt |= int((rhs[i]-fp[i])>>63) &^ lt - lt |= int((fp[i]-rhs[i])>>63) &^ gt - } - return gt - lt -} - -// Equal returns true if fp == rhs -func (fp *Fp) Equal(rhs *Fp) bool { - t := fp[0] ^ rhs[0] - t |= fp[1] ^ rhs[1] - t |= fp[2] ^ rhs[2] - t |= fp[3] ^ rhs[3] - return t == 0 -} - -// IsZero returns true if fp == 0 -func (fp *Fp) IsZero() bool { - t := fp[0] - t |= fp[1] - t |= fp[2] - t |= fp[3] - return t == 0 -} - -// IsOne returns true if fp == R -func (fp *Fp) IsOne() bool { - return fp.Equal(r) -} - -func (fp *Fp) IsOdd() bool { - tv := new(fiat_pasta_fp_non_montgomery_domain_field_element) - fiat_pasta_fp_from_montgomery(tv, (*fiat_pasta_fp_montgomery_domain_field_element)(fp)) - return tv[0]&0x01 == 0x01 -} - -// Set fp == rhs -func (fp *Fp) Set(rhs *Fp) *Fp { - fp[0] = rhs[0] - fp[1] = rhs[1] - fp[2] = rhs[2] - fp[3] = rhs[3] - return fp -} - -// SetUint64 sets fp == rhs -func (fp *Fp) SetUint64(rhs uint64) *Fp { - r := &fiat_pasta_fp_non_montgomery_domain_field_element{rhs, 0, 0, 0} - fiat_pasta_fp_to_montgomery((*fiat_pasta_fp_montgomery_domain_field_element)(fp), r) - return fp -} - -func (fp *Fp) SetBool(rhs bool) *Fp { - if rhs { - fp.SetOne() - } else { - fp.SetZero() - } - return fp -} - -// SetOne fp == R -func (fp *Fp) SetOne() *Fp { - return fp.Set(r) -} - -// SetZero fp == 0 -func (fp *Fp) SetZero() *Fp { - fp[0] = 0 - fp[1] = 0 - fp[2] = 0 - fp[3] = 0 - return fp -} - -// SetBytesWide takes 64 bytes as input and treats them as a 512-bit number. -// Attributed to https://github.com/zcash/pasta_curves/blob/main/src/fields/fp.rs#L255 -// We reduce an arbitrary 512-bit number by decomposing it into two 256-bit digits -// with the higher bits multiplied by 2^256. Thus, we perform two reductions -// -// 1. the lower bits are multiplied by R^2, as normal -// 2. the upper bits are multiplied by R^2 * 2^256 = R^3 -// -// and computing their sum in the field. It remains to see that arbitrary 256-bit -// numbers can be placed into Montgomery form safely using the reduction. The -// reduction works so long as the product is less than R=2^256 multiplied by -// the modulus. This holds because for any `c` smaller than the modulus, we have -// that (2^256 - 1)*c is an acceptable product for the reduction. Therefore, the -// reduction always works so long as `c` is in the field; in this case it is either the -// constant `r2` or `r3`. -func (fp *Fp) SetBytesWide(input *[64]byte) *Fp { - d0 := fiat_pasta_fp_montgomery_domain_field_element{ - binary.LittleEndian.Uint64(input[:8]), - binary.LittleEndian.Uint64(input[8:16]), - binary.LittleEndian.Uint64(input[16:24]), - binary.LittleEndian.Uint64(input[24:32]), - } - d1 := fiat_pasta_fp_montgomery_domain_field_element{ - binary.LittleEndian.Uint64(input[32:40]), - binary.LittleEndian.Uint64(input[40:48]), - binary.LittleEndian.Uint64(input[48:56]), - binary.LittleEndian.Uint64(input[56:64]), - } - // Convert to Montgomery form - tv1 := new(fiat_pasta_fp_montgomery_domain_field_element) - tv2 := new(fiat_pasta_fp_montgomery_domain_field_element) - // d0 * r2 + d1 * r3 - fiat_pasta_fp_mul(tv1, &d0, (*fiat_pasta_fp_montgomery_domain_field_element)(r2)) - fiat_pasta_fp_mul(tv2, &d1, (*fiat_pasta_fp_montgomery_domain_field_element)(r3)) - fiat_pasta_fp_add((*fiat_pasta_fp_montgomery_domain_field_element)(fp), tv1, tv2) - return fp -} - -// SetBytes attempts to convert a little endian byte representation -// of a scalar into a `Fp`, failing if input is not canonical -func (fp *Fp) SetBytes(input *[32]byte) (*Fp, error) { - d0 := &Fp{ - binary.LittleEndian.Uint64(input[:8]), - binary.LittleEndian.Uint64(input[8:16]), - binary.LittleEndian.Uint64(input[16:24]), - binary.LittleEndian.Uint64(input[24:32]), - } - if d0.Cmp(modulus) != -1 { - return nil, fmt.Errorf("invalid byte sequence") - } - fiat_pasta_fp_from_bytes((*[4]uint64)(fp), input) - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(fp), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(fp), - ) - return fp, nil -} - -// SetBigInt initializes an element from big.Int -// The value is reduced by the modulus -func (fp *Fp) SetBigInt(bi *big.Int) *Fp { - var buffer [32]byte - r := new(big.Int).Set(bi) - r.Mod(r, biModulus) - r.FillBytes(buffer[:]) - copy(buffer[:], internal.ReverseScalarBytes(buffer[:])) - _, _ = fp.SetBytes(&buffer) - return fp -} - -// SetRaw converts a raw array into a field element -func (fp *Fp) SetRaw(array *[4]uint64) *Fp { - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(fp), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(array), - ) - return fp -} - -// Bytes converts this element into a byte representation -// in little endian byte order -func (fp *Fp) Bytes() [32]byte { - var output [32]byte - tv := new(fiat_pasta_fp_non_montgomery_domain_field_element) - fiat_pasta_fp_from_montgomery(tv, (*fiat_pasta_fp_montgomery_domain_field_element)(fp)) - fiat_pasta_fp_to_bytes(&output, (*[4]uint64)(tv)) - return output -} - -// BigInt converts this element into the big.Int struct -func (fp *Fp) BigInt() *big.Int { - buffer := fp.Bytes() - return new(big.Int).SetBytes(internal.ReverseScalarBytes(buffer[:])) -} - -// Double this element -func (fp *Fp) Double(elem *Fp) *Fp { - delem := (*fiat_pasta_fp_montgomery_domain_field_element)(elem) - fiat_pasta_fp_add((*fiat_pasta_fp_montgomery_domain_field_element)(fp), delem, delem) - return fp -} - -// Square this element -func (fp *Fp) Square(elem *Fp) *Fp { - delem := (*fiat_pasta_fp_montgomery_domain_field_element)(elem) - fiat_pasta_fp_square((*fiat_pasta_fp_montgomery_domain_field_element)(fp), delem) - return fp -} - -// Sqrt this element, if it exists. If true, then value -// is a square root. If false, value is a QNR -func (fp *Fp) Sqrt(elem *Fp) (*Fp, bool) { - return fp.tonelliShanks(elem) -} - -// See sqrt_ts_ct at -// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.4 -func (fp *Fp) tonelliShanks(elem *Fp) (*Fp, bool) { - // c1 := 32 - // c2 := (q - 1) / (2^c1) - // c2 := [4]uint64{ - // 0x094cf91b992d30ed, - // 0x00000000224698fc, - // 0x0000000000000000, - // 0x0000000040000000, - // } - // c3 := (c2 - 1) / 2 - c3 := [4]uint64{ - 0x04a67c8dcc969876, - 0x0000000011234c7e, - 0x0000000000000000, - 0x0000000020000000, - } - // c4 := generator - // c5 := new(Fp).pow(&generator, c2) - c5 := &Fp{ - 0xa28db849bad6dbf0, - 0x9083cd03d3b539df, - 0xfba6b9ca9dc8448e, - 0x3ec928747b89c6da, - } - - z := new(Fp).pow(elem, c3) - t := new(Fp).Square(z) - t.Mul(t, elem) - - z.Mul(z, elem) - - b := new(Fp).Set(t) - c := new(Fp).Set(c5) - flags := map[bool]int{ - true: 1, - false: 0, - } - - for i := s; i >= 2; i-- { - for j := 1; j <= i-2; j++ { - b.Square(b) - } - z.CMove(z, new(Fp).Mul(z, c), flags[!b.IsOne()]) - c.Square(c) - t.CMove(t, new(Fp).Mul(t, c), flags[!b.IsOne()]) - b.Set(t) - } - wasSquare := c.Square(z).Equal(elem) - return fp.Set(z), wasSquare -} - -// Invert this element i.e. compute the multiplicative inverse -// return false, zero if this element is zero -func (fp *Fp) Invert(elem *Fp) (*Fp, bool) { - // computes elem^(p - 2) mod p - exp := [4]uint64{ - 0x992d30ecffffffff, - 0x224698fc094cf91b, - 0x0000000000000000, - 0x4000000000000000, - } - return fp.pow(elem, exp), !elem.IsZero() -} - -// Mul returns the result from multiplying this element by rhs -func (fp *Fp) Mul(lhs, rhs *Fp) *Fp { - dlhs := (*fiat_pasta_fp_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fp_montgomery_domain_field_element)(rhs) - fiat_pasta_fp_mul((*fiat_pasta_fp_montgomery_domain_field_element)(fp), dlhs, drhs) - return fp -} - -// Sub returns the result from subtracting rhs from this element -func (fp *Fp) Sub(lhs, rhs *Fp) *Fp { - dlhs := (*fiat_pasta_fp_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fp_montgomery_domain_field_element)(rhs) - fiat_pasta_fp_sub((*fiat_pasta_fp_montgomery_domain_field_element)(fp), dlhs, drhs) - return fp -} - -// Add returns the result from adding rhs to this element -func (fp *Fp) Add(lhs, rhs *Fp) *Fp { - dlhs := (*fiat_pasta_fp_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fp_montgomery_domain_field_element)(rhs) - fiat_pasta_fp_add((*fiat_pasta_fp_montgomery_domain_field_element)(fp), dlhs, drhs) - return fp -} - -// Neg returns negation of this element -func (fp *Fp) Neg(elem *Fp) *Fp { - delem := (*fiat_pasta_fp_montgomery_domain_field_element)(elem) - fiat_pasta_fp_opp((*fiat_pasta_fp_montgomery_domain_field_element)(fp), delem) - return fp -} - -// Exp exponentiates this element by exp -func (fp *Fp) Exp(base, exp *Fp) *Fp { - // convert exponent to integer form - tv := &fiat_pasta_fp_non_montgomery_domain_field_element{} - fiat_pasta_fp_from_montgomery(tv, (*fiat_pasta_fp_montgomery_domain_field_element)(exp)) - - e := (*[4]uint64)(tv) - return fp.pow(base, *e) -} - -func (fp *Fp) pow(base *Fp, exp [4]uint64) *Fp { - res := new(Fp).SetOne() - tmp := new(Fp) - - for i := len(exp) - 1; i >= 0; i-- { - for j := 63; j >= 0; j-- { - res.Square(res) - tmp.Mul(res, base) - res.CMove(res, tmp, int(exp[i]>>j)&1) - } - } - return fp.Set(res) -} - -// CMove selects lhs if choice == 0 and rhs if choice == 1 -func (fp *Fp) CMove(lhs, rhs *Fp, choice int) *Fp { - dlhs := (*[4]uint64)(lhs) - drhs := (*[4]uint64)(rhs) - fiat_pasta_fp_selectznz((*[4]uint64)(fp), fiat_pasta_fp_uint1(choice), dlhs, drhs) - return fp -} - -// ToRaw converts this element into the a [4]uint64 -func (fp *Fp) ToRaw() [4]uint64 { - res := &fiat_pasta_fp_non_montgomery_domain_field_element{} - fiat_pasta_fp_from_montgomery(res, (*fiat_pasta_fp_montgomery_domain_field_element)(fp)) - return *(*[4]uint64)(res) -} diff --git a/crypto/core/curves/native/pasta/fp/fp_test.go b/crypto/core/curves/native/pasta/fp/fp_test.go deleted file mode 100755 index b88285069..000000000 --- a/crypto/core/curves/native/pasta/fp/fp_test.go +++ /dev/null @@ -1,273 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fp - -import ( - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFpSetOne(t *testing.T) { - fp := new(Fp).SetOne() - require.NotNil(t, fp) - require.True(t, fp.Equal(r)) -} - -func TestFpSetUint64(t *testing.T) { - act := new(Fp).SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, int(act[0]), 0x592d30ed00000001) -} - -func TestFpAdd(t *testing.T) { - lhs := new(Fp).SetOne() - rhs := new(Fp).SetOne() - exp := new(Fp).SetUint64(2) - res := new(Fp).Add(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := new(Fp).Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpSub(t *testing.T) { - lhs := new(Fp).SetOne() - rhs := new(Fp).SetOne() - exp := new(Fp).SetZero() - res := new(Fp).Sub(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := new(Fp).Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpMul(t *testing.T) { - lhs := new(Fp).SetOne() - rhs := new(Fp).SetOne() - exp := new(Fp).SetOne() - res := new(Fp).Mul(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := new(Fp).Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFpDouble(t *testing.T) { - a := new(Fp).SetUint64(2) - e := new(Fp).SetUint64(4) - require.Equal(t, e, new(Fp).Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = new(Fp).SetUint64(uint64(tv)) - e = new(Fp).SetUint64(ttv) - require.Equal(t, e, new(Fp).Double(a)) - } -} - -func TestFpSquare(t *testing.T) { - a := new(Fp).SetUint64(4) - e := new(Fp).SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFpNeg(t *testing.T) { - a := new(Fp).SetOne() - a.Neg(a) - e := &Fp{7256640077462241284, 9879318615658062958, 0, 0} - require.Equal(t, e, a) - a.Neg(generator) - e = &Fp{0xf787d28400000014, 0xad83f3b0ba037627, 0x2, 0x0} - require.Equal(t, e, a) -} - -func TestFpExp(t *testing.T) { - e := new(Fp).SetUint64(8) - a := new(Fp).SetUint64(2) - by := new(Fp).SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFpSqrt(t *testing.T) { - t1 := new(Fp).SetUint64(2) - t2 := new(Fp).Neg(t1) - t3 := new(Fp).Square(t1) - _, wasSquare := t3.Sqrt(t3) - require.True(t, wasSquare) - require.True(t, t1.Equal(t3) || t2.Equal(t3)) - t1.SetUint64(5) - _, wasSquare = new(Fp).Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFpInvert(t *testing.T) { - twoInv := &Fp{0xcc96987680000001, 0x11234c7e04a67c8d, 0x0000000000000000, 0x2000000000000000} - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(twoInv), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(twoInv), - ) - two := new(Fp).SetUint64(2) - a, inverted := new(Fp).Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnity := &Fp{ - 0xbdad6fabd87ea32f, - 0xea322bf2b7bb7584, - 0x362120830561f81a, - 0x2bce74deac30ebda, - } - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(rootOfUnity), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(rootOfUnity), - ) - rootOfUnityInv := &Fp{ - 0xf0b87c7db2ce91f6, - 0x84a0a1d8859f066f, - 0xb4ed8e647196dad1, - 0x2cd5282c53116b5c, - } - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(rootOfUnityInv), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(rootOfUnityInv), - ) - a, inverted = new(Fp).Invert(rootOfUnity) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := new(Fp).SetUint64(9) - rhs := new(Fp).SetUint64(3) - rhsInv, inverted := new(Fp).Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, new(Fp).Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = new(Fp).Invert(rhs) - require.False(t, inverted) -} - -func TestFpCMove(t *testing.T) { - t1 := new(Fp).SetUint64(5) - t2 := new(Fp).SetUint64(10) - require.Equal(t, t1, new(Fp).CMove(t1, t2, 0)) - require.Equal(t, t2, new(Fp).CMove(t1, t2, 1)) -} - -func TestFpBytes(t *testing.T) { - t1 := new(Fp).SetUint64(99) - seq := t1.Bytes() - t2, err := new(Fp).SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFpBigInt(t *testing.T) { - t1 := new(Fp).SetBigInt(big.NewInt(9999)) - t2 := new(Fp).SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := &Fp{0x8c6bc70550c87761, 0xce2c6c48e7063731, 0xf1275fd1e4607cd6, 0x3e6762e63501edbd} - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e[0] = 0xcc169e7af3788a0 - e[1] = 0x541a2cb32246c1ea - e[2] = 0xed8a02e1b9f8329 - e[3] = 0x1989d19cafe1242 - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFpSetBool(t *testing.T) { - require.Equal(t, new(Fp).SetOne(), new(Fp).SetBool(true)) - require.Equal(t, new(Fp).SetZero(), new(Fp).SetBool(false)) -} - -func TestFpSetBytesWide(t *testing.T) { - e := &Fp{0x3daec14d565241d9, 0x0b7af45b6073944b, 0xea5b8bd611a5bd4c, 0x150160330625db3d} - fiat_pasta_fp_to_montgomery( - (*fiat_pasta_fp_montgomery_domain_field_element)(e), - (*fiat_pasta_fp_non_montgomery_domain_field_element)(e), - ) - a := new(Fp).SetBytesWide(&[64]byte{ - 0xa1, 0x78, 0x76, 0x29, 0x41, 0x56, 0x15, 0xee, - 0x65, 0xbe, 0xfd, 0xdb, 0x6b, 0x15, 0x3e, 0xd8, - 0xb5, 0xa0, 0x8b, 0xc6, 0x34, 0xd8, 0xcc, 0xd9, - 0x58, 0x27, 0x27, 0x12, 0xe3, 0xed, 0x08, 0xf5, - 0x89, 0x8e, 0x22, 0xf8, 0xcb, 0xf7, 0x8d, 0x03, - 0x41, 0x4b, 0xc7, 0xa3, 0xe4, 0xa1, 0x05, 0x35, - 0xb3, 0x2d, 0xb8, 0x5e, 0x77, 0x6f, 0xa4, 0xbf, - 0x1d, 0x47, 0x2f, 0x26, 0x7e, 0xe2, 0xeb, 0x26, - }) - require.Equal(t, e, a) -} diff --git a/crypto/core/curves/native/pasta/fp/pasta_fp.go b/crypto/core/curves/native/pasta/fp/pasta_fp.go deleted file mode 100755 index 6735d8c5a..000000000 --- a/crypto/core/curves/native/pasta/fp/pasta_fp.go +++ /dev/null @@ -1,1518 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Autogenerated: './src/ExtractionOCaml/word_by_word_montgomery' --lang Go pasta_fp 64 '2^254 + 45560315531419706090280762371685220353' -// -// curve description: pasta_fp -// -// machine_wordsize = 64 (from "64") -// -// requested operations: (all) -// -// m = 0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001 (from "2^254 + 45560315531419706090280762371685220353") -// -// -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 - -package fp - -import "math/bits" - -type ( - fiat_pasta_fp_uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 - fiat_pasta_fp_int1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -) - -// The type fiat_pasta_fp_montgomery_domain_field_element is a field element in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiat_pasta_fp_montgomery_domain_field_element [4]uint64 - -// The type fiat_pasta_fp_non_montgomery_domain_field_element is a field element NOT in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiat_pasta_fp_non_montgomery_domain_field_element [4]uint64 - -// The function fiat_pasta_fp_addcarryx_u64 is a thin wrapper around bits.Add64 that uses fiat_pasta_fp_uint1 rather than uint64 -func fiat_pasta_fp_addcarryx_u64( - x uint64, - y uint64, - carry fiat_pasta_fp_uint1, -) (uint64, fiat_pasta_fp_uint1) { - sum, carryOut := bits.Add64(x, y, uint64(carry)) - return sum, fiat_pasta_fp_uint1(carryOut) -} - -// The function fiat_pasta_fp_subborrowx_u64 is a thin wrapper around bits.Sub64 that uses fiat_pasta_fp_uint1 rather than uint64 -func fiat_pasta_fp_subborrowx_u64( - x uint64, - y uint64, - carry fiat_pasta_fp_uint1, -) (uint64, fiat_pasta_fp_uint1) { - sum, carryOut := bits.Sub64(x, y, uint64(carry)) - return sum, fiat_pasta_fp_uint1(carryOut) -} - -// The function fiat_pasta_fp_cmovznz_u64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func fiat_pasta_fp_cmovznz_u64(out1 *uint64, arg1 fiat_pasta_fp_uint1, arg2 uint64, arg3 uint64) { - x1 := arg1 - x2 := (uint64((fiat_pasta_fp_int1(0x0) - fiat_pasta_fp_int1(x1))) & 0xffffffffffffffff) - x3 := ((x2 & arg3) | ((^x2) & arg2)) - *out1 = x3 -} - -// The function fiat_pasta_fp_mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_mul( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, - arg2 *fiat_pasta_fp_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 fiat_pasta_fp_uint1 - x13, x14 = fiat_pasta_fp_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fp_uint1 - x15, x16 = fiat_pasta_fp_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fp_uint1 - x17, x18 = fiat_pasta_fp_addcarryx_u64(x8, x5, x16) - x19 := (uint64(x18) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x992d30ecffffffff) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0x4000000000000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0x224698fc094cf91b) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0x992d30ed00000001) - var x28 uint64 - var x29 fiat_pasta_fp_uint1 - x28, x29 = fiat_pasta_fp_addcarryx_u64(x27, x24, 0x0) - x30 := (uint64(x29) + x25) - var x32 fiat_pasta_fp_uint1 - _, x32 = fiat_pasta_fp_addcarryx_u64(x11, x26, 0x0) - var x33 uint64 - var x34 fiat_pasta_fp_uint1 - x33, x34 = fiat_pasta_fp_addcarryx_u64(x13, x28, x32) - var x35 uint64 - var x36 fiat_pasta_fp_uint1 - x35, x36 = fiat_pasta_fp_addcarryx_u64(x15, x30, x34) - var x37 uint64 - var x38 fiat_pasta_fp_uint1 - x37, x38 = fiat_pasta_fp_addcarryx_u64(x17, x22, x36) - var x39 uint64 - var x40 fiat_pasta_fp_uint1 - x39, x40 = fiat_pasta_fp_addcarryx_u64(x19, x23, x38) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg2[3]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg2[2]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg2[1]) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[0]) - var x49 uint64 - var x50 fiat_pasta_fp_uint1 - x49, x50 = fiat_pasta_fp_addcarryx_u64(x48, x45, 0x0) - var x51 uint64 - var x52 fiat_pasta_fp_uint1 - x51, x52 = fiat_pasta_fp_addcarryx_u64(x46, x43, x50) - var x53 uint64 - var x54 fiat_pasta_fp_uint1 - x53, x54 = fiat_pasta_fp_addcarryx_u64(x44, x41, x52) - x55 := (uint64(x54) + x42) - var x56 uint64 - var x57 fiat_pasta_fp_uint1 - x56, x57 = fiat_pasta_fp_addcarryx_u64(x33, x47, 0x0) - var x58 uint64 - var x59 fiat_pasta_fp_uint1 - x58, x59 = fiat_pasta_fp_addcarryx_u64(x35, x49, x57) - var x60 uint64 - var x61 fiat_pasta_fp_uint1 - x60, x61 = fiat_pasta_fp_addcarryx_u64(x37, x51, x59) - var x62 uint64 - var x63 fiat_pasta_fp_uint1 - x62, x63 = fiat_pasta_fp_addcarryx_u64(x39, x53, x61) - var x64 uint64 - var x65 fiat_pasta_fp_uint1 - x64, x65 = fiat_pasta_fp_addcarryx_u64(uint64(x40), x55, x63) - var x66 uint64 - _, x66 = bits.Mul64(x56, 0x992d30ecffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc094cf91b) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x992d30ed00000001) - var x74 uint64 - var x75 fiat_pasta_fp_uint1 - x74, x75 = fiat_pasta_fp_addcarryx_u64(x73, x70, 0x0) - x76 := (uint64(x75) + x71) - var x78 fiat_pasta_fp_uint1 - _, x78 = fiat_pasta_fp_addcarryx_u64(x56, x72, 0x0) - var x79 uint64 - var x80 fiat_pasta_fp_uint1 - x79, x80 = fiat_pasta_fp_addcarryx_u64(x58, x74, x78) - var x81 uint64 - var x82 fiat_pasta_fp_uint1 - x81, x82 = fiat_pasta_fp_addcarryx_u64(x60, x76, x80) - var x83 uint64 - var x84 fiat_pasta_fp_uint1 - x83, x84 = fiat_pasta_fp_addcarryx_u64(x62, x68, x82) - var x85 uint64 - var x86 fiat_pasta_fp_uint1 - x85, x86 = fiat_pasta_fp_addcarryx_u64(x64, x69, x84) - x87 := (uint64(x86) + uint64(x65)) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg2[3]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg2[2]) - var x92 uint64 - var x93 uint64 - x93, x92 = bits.Mul64(x2, arg2[1]) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x2, arg2[0]) - var x96 uint64 - var x97 fiat_pasta_fp_uint1 - x96, x97 = fiat_pasta_fp_addcarryx_u64(x95, x92, 0x0) - var x98 uint64 - var x99 fiat_pasta_fp_uint1 - x98, x99 = fiat_pasta_fp_addcarryx_u64(x93, x90, x97) - var x100 uint64 - var x101 fiat_pasta_fp_uint1 - x100, x101 = fiat_pasta_fp_addcarryx_u64(x91, x88, x99) - x102 := (uint64(x101) + x89) - var x103 uint64 - var x104 fiat_pasta_fp_uint1 - x103, x104 = fiat_pasta_fp_addcarryx_u64(x79, x94, 0x0) - var x105 uint64 - var x106 fiat_pasta_fp_uint1 - x105, x106 = fiat_pasta_fp_addcarryx_u64(x81, x96, x104) - var x107 uint64 - var x108 fiat_pasta_fp_uint1 - x107, x108 = fiat_pasta_fp_addcarryx_u64(x83, x98, x106) - var x109 uint64 - var x110 fiat_pasta_fp_uint1 - x109, x110 = fiat_pasta_fp_addcarryx_u64(x85, x100, x108) - var x111 uint64 - var x112 fiat_pasta_fp_uint1 - x111, x112 = fiat_pasta_fp_addcarryx_u64(x87, x102, x110) - var x113 uint64 - _, x113 = bits.Mul64(x103, 0x992d30ecffffffff) - var x115 uint64 - var x116 uint64 - x116, x115 = bits.Mul64(x113, 0x4000000000000000) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x113, 0x224698fc094cf91b) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x113, 0x992d30ed00000001) - var x121 uint64 - var x122 fiat_pasta_fp_uint1 - x121, x122 = fiat_pasta_fp_addcarryx_u64(x120, x117, 0x0) - x123 := (uint64(x122) + x118) - var x125 fiat_pasta_fp_uint1 - _, x125 = fiat_pasta_fp_addcarryx_u64(x103, x119, 0x0) - var x126 uint64 - var x127 fiat_pasta_fp_uint1 - x126, x127 = fiat_pasta_fp_addcarryx_u64(x105, x121, x125) - var x128 uint64 - var x129 fiat_pasta_fp_uint1 - x128, x129 = fiat_pasta_fp_addcarryx_u64(x107, x123, x127) - var x130 uint64 - var x131 fiat_pasta_fp_uint1 - x130, x131 = fiat_pasta_fp_addcarryx_u64(x109, x115, x129) - var x132 uint64 - var x133 fiat_pasta_fp_uint1 - x132, x133 = fiat_pasta_fp_addcarryx_u64(x111, x116, x131) - x134 := (uint64(x133) + uint64(x112)) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg2[3]) - var x137 uint64 - var x138 uint64 - x138, x137 = bits.Mul64(x3, arg2[2]) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x3, arg2[1]) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, arg2[0]) - var x143 uint64 - var x144 fiat_pasta_fp_uint1 - x143, x144 = fiat_pasta_fp_addcarryx_u64(x142, x139, 0x0) - var x145 uint64 - var x146 fiat_pasta_fp_uint1 - x145, x146 = fiat_pasta_fp_addcarryx_u64(x140, x137, x144) - var x147 uint64 - var x148 fiat_pasta_fp_uint1 - x147, x148 = fiat_pasta_fp_addcarryx_u64(x138, x135, x146) - x149 := (uint64(x148) + x136) - var x150 uint64 - var x151 fiat_pasta_fp_uint1 - x150, x151 = fiat_pasta_fp_addcarryx_u64(x126, x141, 0x0) - var x152 uint64 - var x153 fiat_pasta_fp_uint1 - x152, x153 = fiat_pasta_fp_addcarryx_u64(x128, x143, x151) - var x154 uint64 - var x155 fiat_pasta_fp_uint1 - x154, x155 = fiat_pasta_fp_addcarryx_u64(x130, x145, x153) - var x156 uint64 - var x157 fiat_pasta_fp_uint1 - x156, x157 = fiat_pasta_fp_addcarryx_u64(x132, x147, x155) - var x158 uint64 - var x159 fiat_pasta_fp_uint1 - x158, x159 = fiat_pasta_fp_addcarryx_u64(x134, x149, x157) - var x160 uint64 - _, x160 = bits.Mul64(x150, 0x992d30ecffffffff) - var x162 uint64 - var x163 uint64 - x163, x162 = bits.Mul64(x160, 0x4000000000000000) - var x164 uint64 - var x165 uint64 - x165, x164 = bits.Mul64(x160, 0x224698fc094cf91b) - var x166 uint64 - var x167 uint64 - x167, x166 = bits.Mul64(x160, 0x992d30ed00000001) - var x168 uint64 - var x169 fiat_pasta_fp_uint1 - x168, x169 = fiat_pasta_fp_addcarryx_u64(x167, x164, 0x0) - x170 := (uint64(x169) + x165) - var x172 fiat_pasta_fp_uint1 - _, x172 = fiat_pasta_fp_addcarryx_u64(x150, x166, 0x0) - var x173 uint64 - var x174 fiat_pasta_fp_uint1 - x173, x174 = fiat_pasta_fp_addcarryx_u64(x152, x168, x172) - var x175 uint64 - var x176 fiat_pasta_fp_uint1 - x175, x176 = fiat_pasta_fp_addcarryx_u64(x154, x170, x174) - var x177 uint64 - var x178 fiat_pasta_fp_uint1 - x177, x178 = fiat_pasta_fp_addcarryx_u64(x156, x162, x176) - var x179 uint64 - var x180 fiat_pasta_fp_uint1 - x179, x180 = fiat_pasta_fp_addcarryx_u64(x158, x163, x178) - x181 := (uint64(x180) + uint64(x159)) - var x182 uint64 - var x183 fiat_pasta_fp_uint1 - x182, x183 = fiat_pasta_fp_subborrowx_u64(x173, 0x992d30ed00000001, 0x0) - var x184 uint64 - var x185 fiat_pasta_fp_uint1 - x184, x185 = fiat_pasta_fp_subborrowx_u64(x175, 0x224698fc094cf91b, x183) - var x186 uint64 - var x187 fiat_pasta_fp_uint1 - x186, x187 = fiat_pasta_fp_subborrowx_u64(x177, uint64(0x0), x185) - var x188 uint64 - var x189 fiat_pasta_fp_uint1 - x188, x189 = fiat_pasta_fp_subborrowx_u64(x179, 0x4000000000000000, x187) - var x191 fiat_pasta_fp_uint1 - _, x191 = fiat_pasta_fp_subborrowx_u64(x181, uint64(0x0), x189) - var x192 uint64 - fiat_pasta_fp_cmovznz_u64(&x192, x191, x182, x173) - var x193 uint64 - fiat_pasta_fp_cmovznz_u64(&x193, x191, x184, x175) - var x194 uint64 - fiat_pasta_fp_cmovznz_u64(&x194, x191, x186, x177) - var x195 uint64 - fiat_pasta_fp_cmovznz_u64(&x195, x191, x188, x179) - out1[0] = x192 - out1[1] = x193 - out1[2] = x194 - out1[3] = x195 -} - -// The function fiat_pasta_fp_square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_square( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 fiat_pasta_fp_uint1 - x13, x14 = fiat_pasta_fp_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fp_uint1 - x15, x16 = fiat_pasta_fp_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fp_uint1 - x17, x18 = fiat_pasta_fp_addcarryx_u64(x8, x5, x16) - x19 := (uint64(x18) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x992d30ecffffffff) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0x4000000000000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0x224698fc094cf91b) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0x992d30ed00000001) - var x28 uint64 - var x29 fiat_pasta_fp_uint1 - x28, x29 = fiat_pasta_fp_addcarryx_u64(x27, x24, 0x0) - x30 := (uint64(x29) + x25) - var x32 fiat_pasta_fp_uint1 - _, x32 = fiat_pasta_fp_addcarryx_u64(x11, x26, 0x0) - var x33 uint64 - var x34 fiat_pasta_fp_uint1 - x33, x34 = fiat_pasta_fp_addcarryx_u64(x13, x28, x32) - var x35 uint64 - var x36 fiat_pasta_fp_uint1 - x35, x36 = fiat_pasta_fp_addcarryx_u64(x15, x30, x34) - var x37 uint64 - var x38 fiat_pasta_fp_uint1 - x37, x38 = fiat_pasta_fp_addcarryx_u64(x17, x22, x36) - var x39 uint64 - var x40 fiat_pasta_fp_uint1 - x39, x40 = fiat_pasta_fp_addcarryx_u64(x19, x23, x38) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg1[3]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg1[2]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg1[1]) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg1[0]) - var x49 uint64 - var x50 fiat_pasta_fp_uint1 - x49, x50 = fiat_pasta_fp_addcarryx_u64(x48, x45, 0x0) - var x51 uint64 - var x52 fiat_pasta_fp_uint1 - x51, x52 = fiat_pasta_fp_addcarryx_u64(x46, x43, x50) - var x53 uint64 - var x54 fiat_pasta_fp_uint1 - x53, x54 = fiat_pasta_fp_addcarryx_u64(x44, x41, x52) - x55 := (uint64(x54) + x42) - var x56 uint64 - var x57 fiat_pasta_fp_uint1 - x56, x57 = fiat_pasta_fp_addcarryx_u64(x33, x47, 0x0) - var x58 uint64 - var x59 fiat_pasta_fp_uint1 - x58, x59 = fiat_pasta_fp_addcarryx_u64(x35, x49, x57) - var x60 uint64 - var x61 fiat_pasta_fp_uint1 - x60, x61 = fiat_pasta_fp_addcarryx_u64(x37, x51, x59) - var x62 uint64 - var x63 fiat_pasta_fp_uint1 - x62, x63 = fiat_pasta_fp_addcarryx_u64(x39, x53, x61) - var x64 uint64 - var x65 fiat_pasta_fp_uint1 - x64, x65 = fiat_pasta_fp_addcarryx_u64(uint64(x40), x55, x63) - var x66 uint64 - _, x66 = bits.Mul64(x56, 0x992d30ecffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc094cf91b) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x992d30ed00000001) - var x74 uint64 - var x75 fiat_pasta_fp_uint1 - x74, x75 = fiat_pasta_fp_addcarryx_u64(x73, x70, 0x0) - x76 := (uint64(x75) + x71) - var x78 fiat_pasta_fp_uint1 - _, x78 = fiat_pasta_fp_addcarryx_u64(x56, x72, 0x0) - var x79 uint64 - var x80 fiat_pasta_fp_uint1 - x79, x80 = fiat_pasta_fp_addcarryx_u64(x58, x74, x78) - var x81 uint64 - var x82 fiat_pasta_fp_uint1 - x81, x82 = fiat_pasta_fp_addcarryx_u64(x60, x76, x80) - var x83 uint64 - var x84 fiat_pasta_fp_uint1 - x83, x84 = fiat_pasta_fp_addcarryx_u64(x62, x68, x82) - var x85 uint64 - var x86 fiat_pasta_fp_uint1 - x85, x86 = fiat_pasta_fp_addcarryx_u64(x64, x69, x84) - x87 := (uint64(x86) + uint64(x65)) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg1[3]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg1[2]) - var x92 uint64 - var x93 uint64 - x93, x92 = bits.Mul64(x2, arg1[1]) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x2, arg1[0]) - var x96 uint64 - var x97 fiat_pasta_fp_uint1 - x96, x97 = fiat_pasta_fp_addcarryx_u64(x95, x92, 0x0) - var x98 uint64 - var x99 fiat_pasta_fp_uint1 - x98, x99 = fiat_pasta_fp_addcarryx_u64(x93, x90, x97) - var x100 uint64 - var x101 fiat_pasta_fp_uint1 - x100, x101 = fiat_pasta_fp_addcarryx_u64(x91, x88, x99) - x102 := (uint64(x101) + x89) - var x103 uint64 - var x104 fiat_pasta_fp_uint1 - x103, x104 = fiat_pasta_fp_addcarryx_u64(x79, x94, 0x0) - var x105 uint64 - var x106 fiat_pasta_fp_uint1 - x105, x106 = fiat_pasta_fp_addcarryx_u64(x81, x96, x104) - var x107 uint64 - var x108 fiat_pasta_fp_uint1 - x107, x108 = fiat_pasta_fp_addcarryx_u64(x83, x98, x106) - var x109 uint64 - var x110 fiat_pasta_fp_uint1 - x109, x110 = fiat_pasta_fp_addcarryx_u64(x85, x100, x108) - var x111 uint64 - var x112 fiat_pasta_fp_uint1 - x111, x112 = fiat_pasta_fp_addcarryx_u64(x87, x102, x110) - var x113 uint64 - _, x113 = bits.Mul64(x103, 0x992d30ecffffffff) - var x115 uint64 - var x116 uint64 - x116, x115 = bits.Mul64(x113, 0x4000000000000000) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x113, 0x224698fc094cf91b) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x113, 0x992d30ed00000001) - var x121 uint64 - var x122 fiat_pasta_fp_uint1 - x121, x122 = fiat_pasta_fp_addcarryx_u64(x120, x117, 0x0) - x123 := (uint64(x122) + x118) - var x125 fiat_pasta_fp_uint1 - _, x125 = fiat_pasta_fp_addcarryx_u64(x103, x119, 0x0) - var x126 uint64 - var x127 fiat_pasta_fp_uint1 - x126, x127 = fiat_pasta_fp_addcarryx_u64(x105, x121, x125) - var x128 uint64 - var x129 fiat_pasta_fp_uint1 - x128, x129 = fiat_pasta_fp_addcarryx_u64(x107, x123, x127) - var x130 uint64 - var x131 fiat_pasta_fp_uint1 - x130, x131 = fiat_pasta_fp_addcarryx_u64(x109, x115, x129) - var x132 uint64 - var x133 fiat_pasta_fp_uint1 - x132, x133 = fiat_pasta_fp_addcarryx_u64(x111, x116, x131) - x134 := (uint64(x133) + uint64(x112)) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg1[3]) - var x137 uint64 - var x138 uint64 - x138, x137 = bits.Mul64(x3, arg1[2]) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x3, arg1[1]) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, arg1[0]) - var x143 uint64 - var x144 fiat_pasta_fp_uint1 - x143, x144 = fiat_pasta_fp_addcarryx_u64(x142, x139, 0x0) - var x145 uint64 - var x146 fiat_pasta_fp_uint1 - x145, x146 = fiat_pasta_fp_addcarryx_u64(x140, x137, x144) - var x147 uint64 - var x148 fiat_pasta_fp_uint1 - x147, x148 = fiat_pasta_fp_addcarryx_u64(x138, x135, x146) - x149 := (uint64(x148) + x136) - var x150 uint64 - var x151 fiat_pasta_fp_uint1 - x150, x151 = fiat_pasta_fp_addcarryx_u64(x126, x141, 0x0) - var x152 uint64 - var x153 fiat_pasta_fp_uint1 - x152, x153 = fiat_pasta_fp_addcarryx_u64(x128, x143, x151) - var x154 uint64 - var x155 fiat_pasta_fp_uint1 - x154, x155 = fiat_pasta_fp_addcarryx_u64(x130, x145, x153) - var x156 uint64 - var x157 fiat_pasta_fp_uint1 - x156, x157 = fiat_pasta_fp_addcarryx_u64(x132, x147, x155) - var x158 uint64 - var x159 fiat_pasta_fp_uint1 - x158, x159 = fiat_pasta_fp_addcarryx_u64(x134, x149, x157) - var x160 uint64 - _, x160 = bits.Mul64(x150, 0x992d30ecffffffff) - var x162 uint64 - var x163 uint64 - x163, x162 = bits.Mul64(x160, 0x4000000000000000) - var x164 uint64 - var x165 uint64 - x165, x164 = bits.Mul64(x160, 0x224698fc094cf91b) - var x166 uint64 - var x167 uint64 - x167, x166 = bits.Mul64(x160, 0x992d30ed00000001) - var x168 uint64 - var x169 fiat_pasta_fp_uint1 - x168, x169 = fiat_pasta_fp_addcarryx_u64(x167, x164, 0x0) - x170 := (uint64(x169) + x165) - var x172 fiat_pasta_fp_uint1 - _, x172 = fiat_pasta_fp_addcarryx_u64(x150, x166, 0x0) - var x173 uint64 - var x174 fiat_pasta_fp_uint1 - x173, x174 = fiat_pasta_fp_addcarryx_u64(x152, x168, x172) - var x175 uint64 - var x176 fiat_pasta_fp_uint1 - x175, x176 = fiat_pasta_fp_addcarryx_u64(x154, x170, x174) - var x177 uint64 - var x178 fiat_pasta_fp_uint1 - x177, x178 = fiat_pasta_fp_addcarryx_u64(x156, x162, x176) - var x179 uint64 - var x180 fiat_pasta_fp_uint1 - x179, x180 = fiat_pasta_fp_addcarryx_u64(x158, x163, x178) - x181 := (uint64(x180) + uint64(x159)) - var x182 uint64 - var x183 fiat_pasta_fp_uint1 - x182, x183 = fiat_pasta_fp_subborrowx_u64(x173, 0x992d30ed00000001, 0x0) - var x184 uint64 - var x185 fiat_pasta_fp_uint1 - x184, x185 = fiat_pasta_fp_subborrowx_u64(x175, 0x224698fc094cf91b, x183) - var x186 uint64 - var x187 fiat_pasta_fp_uint1 - x186, x187 = fiat_pasta_fp_subborrowx_u64(x177, uint64(0x0), x185) - var x188 uint64 - var x189 fiat_pasta_fp_uint1 - x188, x189 = fiat_pasta_fp_subborrowx_u64(x179, 0x4000000000000000, x187) - var x191 fiat_pasta_fp_uint1 - _, x191 = fiat_pasta_fp_subborrowx_u64(x181, uint64(0x0), x189) - var x192 uint64 - fiat_pasta_fp_cmovznz_u64(&x192, x191, x182, x173) - var x193 uint64 - fiat_pasta_fp_cmovznz_u64(&x193, x191, x184, x175) - var x194 uint64 - fiat_pasta_fp_cmovznz_u64(&x194, x191, x186, x177) - var x195 uint64 - fiat_pasta_fp_cmovznz_u64(&x195, x191, x188, x179) - out1[0] = x192 - out1[1] = x193 - out1[2] = x194 - out1[3] = x195 -} - -// The function fiat_pasta_fp_add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_add( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, - arg2 *fiat_pasta_fp_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fp_uint1 - x1, x2 = fiat_pasta_fp_addcarryx_u64(arg1[0], arg2[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fp_uint1 - x3, x4 = fiat_pasta_fp_addcarryx_u64(arg1[1], arg2[1], x2) - var x5 uint64 - var x6 fiat_pasta_fp_uint1 - x5, x6 = fiat_pasta_fp_addcarryx_u64(arg1[2], arg2[2], x4) - var x7 uint64 - var x8 fiat_pasta_fp_uint1 - x7, x8 = fiat_pasta_fp_addcarryx_u64(arg1[3], arg2[3], x6) - var x9 uint64 - var x10 fiat_pasta_fp_uint1 - x9, x10 = fiat_pasta_fp_subborrowx_u64(x1, 0x992d30ed00000001, 0x0) - var x11 uint64 - var x12 fiat_pasta_fp_uint1 - x11, x12 = fiat_pasta_fp_subborrowx_u64(x3, 0x224698fc094cf91b, x10) - var x13 uint64 - var x14 fiat_pasta_fp_uint1 - x13, x14 = fiat_pasta_fp_subborrowx_u64(x5, uint64(0x0), x12) - var x15 uint64 - var x16 fiat_pasta_fp_uint1 - x15, x16 = fiat_pasta_fp_subborrowx_u64(x7, 0x4000000000000000, x14) - var x18 fiat_pasta_fp_uint1 - _, x18 = fiat_pasta_fp_subborrowx_u64(uint64(x8), uint64(0x0), x16) - var x19 uint64 - fiat_pasta_fp_cmovznz_u64(&x19, x18, x9, x1) - var x20 uint64 - fiat_pasta_fp_cmovznz_u64(&x20, x18, x11, x3) - var x21 uint64 - fiat_pasta_fp_cmovznz_u64(&x21, x18, x13, x5) - var x22 uint64 - fiat_pasta_fp_cmovznz_u64(&x22, x18, x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// The function fiat_pasta_fp_sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_sub( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, - arg2 *fiat_pasta_fp_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fp_uint1 - x1, x2 = fiat_pasta_fp_subborrowx_u64(arg1[0], arg2[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fp_uint1 - x3, x4 = fiat_pasta_fp_subborrowx_u64(arg1[1], arg2[1], x2) - var x5 uint64 - var x6 fiat_pasta_fp_uint1 - x5, x6 = fiat_pasta_fp_subborrowx_u64(arg1[2], arg2[2], x4) - var x7 uint64 - var x8 fiat_pasta_fp_uint1 - x7, x8 = fiat_pasta_fp_subborrowx_u64(arg1[3], arg2[3], x6) - var x9 uint64 - fiat_pasta_fp_cmovznz_u64(&x9, x8, uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 fiat_pasta_fp_uint1 - x10, x11 = fiat_pasta_fp_addcarryx_u64(x1, (x9 & 0x992d30ed00000001), 0x0) - var x12 uint64 - var x13 fiat_pasta_fp_uint1 - x12, x13 = fiat_pasta_fp_addcarryx_u64(x3, (x9 & 0x224698fc094cf91b), x11) - var x14 uint64 - var x15 fiat_pasta_fp_uint1 - x14, x15 = fiat_pasta_fp_addcarryx_u64(x5, uint64(0x0), x13) - var x16 uint64 - x16, _ = fiat_pasta_fp_addcarryx_u64(x7, (x9 & 0x4000000000000000), x15) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// The function fiat_pasta_fp_opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_opp( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fp_uint1 - x1, x2 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), arg1[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fp_uint1 - x3, x4 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), arg1[1], x2) - var x5 uint64 - var x6 fiat_pasta_fp_uint1 - x5, x6 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), arg1[2], x4) - var x7 uint64 - var x8 fiat_pasta_fp_uint1 - x7, x8 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), arg1[3], x6) - var x9 uint64 - fiat_pasta_fp_cmovznz_u64(&x9, x8, uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 fiat_pasta_fp_uint1 - x10, x11 = fiat_pasta_fp_addcarryx_u64(x1, (x9 & 0x992d30ed00000001), 0x0) - var x12 uint64 - var x13 fiat_pasta_fp_uint1 - x12, x13 = fiat_pasta_fp_addcarryx_u64(x3, (x9 & 0x224698fc094cf91b), x11) - var x14 uint64 - var x15 fiat_pasta_fp_uint1 - x14, x15 = fiat_pasta_fp_addcarryx_u64(x5, uint64(0x0), x13) - var x16 uint64 - x16, _ = fiat_pasta_fp_addcarryx_u64(x7, (x9 & 0x4000000000000000), x15) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// The function fiat_pasta_fp_from_montgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_from_montgomery( - out1 *fiat_pasta_fp_non_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_montgomery_domain_field_element, -) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0x992d30ecffffffff) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0x4000000000000000) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0x224698fc094cf91b) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0x992d30ed00000001) - var x10 uint64 - var x11 fiat_pasta_fp_uint1 - x10, x11 = fiat_pasta_fp_addcarryx_u64(x9, x6, 0x0) - var x13 fiat_pasta_fp_uint1 - _, x13 = fiat_pasta_fp_addcarryx_u64(x1, x8, 0x0) - var x14 uint64 - var x15 fiat_pasta_fp_uint1 - x14, x15 = fiat_pasta_fp_addcarryx_u64(uint64(0x0), x10, x13) - var x16 uint64 - var x17 fiat_pasta_fp_uint1 - x16, x17 = fiat_pasta_fp_addcarryx_u64(x14, arg1[1], 0x0) - var x18 uint64 - _, x18 = bits.Mul64(x16, 0x992d30ecffffffff) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x18, 0x4000000000000000) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x18, 0x224698fc094cf91b) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x18, 0x992d30ed00000001) - var x26 uint64 - var x27 fiat_pasta_fp_uint1 - x26, x27 = fiat_pasta_fp_addcarryx_u64(x25, x22, 0x0) - var x29 fiat_pasta_fp_uint1 - _, x29 = fiat_pasta_fp_addcarryx_u64(x16, x24, 0x0) - var x30 uint64 - var x31 fiat_pasta_fp_uint1 - x30, x31 = fiat_pasta_fp_addcarryx_u64( - (uint64(x17) + (uint64(x15) + (uint64(x11) + x7))), - x26, - x29, - ) - var x32 uint64 - var x33 fiat_pasta_fp_uint1 - x32, x33 = fiat_pasta_fp_addcarryx_u64(x4, (uint64(x27) + x23), x31) - var x34 uint64 - var x35 fiat_pasta_fp_uint1 - x34, x35 = fiat_pasta_fp_addcarryx_u64(x5, x20, x33) - var x36 uint64 - var x37 fiat_pasta_fp_uint1 - x36, x37 = fiat_pasta_fp_addcarryx_u64(x30, arg1[2], 0x0) - var x38 uint64 - var x39 fiat_pasta_fp_uint1 - x38, x39 = fiat_pasta_fp_addcarryx_u64(x32, uint64(0x0), x37) - var x40 uint64 - var x41 fiat_pasta_fp_uint1 - x40, x41 = fiat_pasta_fp_addcarryx_u64(x34, uint64(0x0), x39) - var x42 uint64 - _, x42 = bits.Mul64(x36, 0x992d30ecffffffff) - var x44 uint64 - var x45 uint64 - x45, x44 = bits.Mul64(x42, 0x4000000000000000) - var x46 uint64 - var x47 uint64 - x47, x46 = bits.Mul64(x42, 0x224698fc094cf91b) - var x48 uint64 - var x49 uint64 - x49, x48 = bits.Mul64(x42, 0x992d30ed00000001) - var x50 uint64 - var x51 fiat_pasta_fp_uint1 - x50, x51 = fiat_pasta_fp_addcarryx_u64(x49, x46, 0x0) - var x53 fiat_pasta_fp_uint1 - _, x53 = fiat_pasta_fp_addcarryx_u64(x36, x48, 0x0) - var x54 uint64 - var x55 fiat_pasta_fp_uint1 - x54, x55 = fiat_pasta_fp_addcarryx_u64(x38, x50, x53) - var x56 uint64 - var x57 fiat_pasta_fp_uint1 - x56, x57 = fiat_pasta_fp_addcarryx_u64(x40, (uint64(x51) + x47), x55) - var x58 uint64 - var x59 fiat_pasta_fp_uint1 - x58, x59 = fiat_pasta_fp_addcarryx_u64((uint64(x41) + (uint64(x35) + x21)), x44, x57) - var x60 uint64 - var x61 fiat_pasta_fp_uint1 - x60, x61 = fiat_pasta_fp_addcarryx_u64(x54, arg1[3], 0x0) - var x62 uint64 - var x63 fiat_pasta_fp_uint1 - x62, x63 = fiat_pasta_fp_addcarryx_u64(x56, uint64(0x0), x61) - var x64 uint64 - var x65 fiat_pasta_fp_uint1 - x64, x65 = fiat_pasta_fp_addcarryx_u64(x58, uint64(0x0), x63) - var x66 uint64 - _, x66 = bits.Mul64(x60, 0x992d30ecffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc094cf91b) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x992d30ed00000001) - var x74 uint64 - var x75 fiat_pasta_fp_uint1 - x74, x75 = fiat_pasta_fp_addcarryx_u64(x73, x70, 0x0) - var x77 fiat_pasta_fp_uint1 - _, x77 = fiat_pasta_fp_addcarryx_u64(x60, x72, 0x0) - var x78 uint64 - var x79 fiat_pasta_fp_uint1 - x78, x79 = fiat_pasta_fp_addcarryx_u64(x62, x74, x77) - var x80 uint64 - var x81 fiat_pasta_fp_uint1 - x80, x81 = fiat_pasta_fp_addcarryx_u64(x64, (uint64(x75) + x71), x79) - var x82 uint64 - var x83 fiat_pasta_fp_uint1 - x82, x83 = fiat_pasta_fp_addcarryx_u64((uint64(x65) + (uint64(x59) + x45)), x68, x81) - x84 := (uint64(x83) + x69) - var x85 uint64 - var x86 fiat_pasta_fp_uint1 - x85, x86 = fiat_pasta_fp_subborrowx_u64(x78, 0x992d30ed00000001, 0x0) - var x87 uint64 - var x88 fiat_pasta_fp_uint1 - x87, x88 = fiat_pasta_fp_subborrowx_u64(x80, 0x224698fc094cf91b, x86) - var x89 uint64 - var x90 fiat_pasta_fp_uint1 - x89, x90 = fiat_pasta_fp_subborrowx_u64(x82, uint64(0x0), x88) - var x91 uint64 - var x92 fiat_pasta_fp_uint1 - x91, x92 = fiat_pasta_fp_subborrowx_u64(x84, 0x4000000000000000, x90) - var x94 fiat_pasta_fp_uint1 - _, x94 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), uint64(0x0), x92) - var x95 uint64 - fiat_pasta_fp_cmovznz_u64(&x95, x94, x85, x78) - var x96 uint64 - fiat_pasta_fp_cmovznz_u64(&x96, x94, x87, x80) - var x97 uint64 - fiat_pasta_fp_cmovznz_u64(&x97, x94, x89, x82) - var x98 uint64 - fiat_pasta_fp_cmovznz_u64(&x98, x94, x91, x84) - out1[0] = x95 - out1[1] = x96 - out1[2] = x97 - out1[3] = x98 -} - -// The function fiat_pasta_fp_to_montgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fp_to_montgomery( - out1 *fiat_pasta_fp_montgomery_domain_field_element, - arg1 *fiat_pasta_fp_non_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x96d41af7b9cb714) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0x7797a99bc3c95d18) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0xd7d30dbd8b0de0e7) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0x8c78ecb30000000f) - var x13 uint64 - var x14 fiat_pasta_fp_uint1 - x13, x14 = fiat_pasta_fp_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fp_uint1 - x15, x16 = fiat_pasta_fp_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fp_uint1 - x17, x18 = fiat_pasta_fp_addcarryx_u64(x8, x5, x16) - var x19 uint64 - _, x19 = bits.Mul64(x11, 0x992d30ecffffffff) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x19, 0x4000000000000000) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x19, 0x224698fc094cf91b) - var x25 uint64 - var x26 uint64 - x26, x25 = bits.Mul64(x19, 0x992d30ed00000001) - var x27 uint64 - var x28 fiat_pasta_fp_uint1 - x27, x28 = fiat_pasta_fp_addcarryx_u64(x26, x23, 0x0) - var x30 fiat_pasta_fp_uint1 - _, x30 = fiat_pasta_fp_addcarryx_u64(x11, x25, 0x0) - var x31 uint64 - var x32 fiat_pasta_fp_uint1 - x31, x32 = fiat_pasta_fp_addcarryx_u64(x13, x27, x30) - var x33 uint64 - var x34 fiat_pasta_fp_uint1 - x33, x34 = fiat_pasta_fp_addcarryx_u64(x15, (uint64(x28) + x24), x32) - var x35 uint64 - var x36 fiat_pasta_fp_uint1 - x35, x36 = fiat_pasta_fp_addcarryx_u64(x17, x21, x34) - var x37 uint64 - var x38 uint64 - x38, x37 = bits.Mul64(x1, 0x96d41af7b9cb714) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, 0x7797a99bc3c95d18) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, 0xd7d30dbd8b0de0e7) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, 0x8c78ecb30000000f) - var x45 uint64 - var x46 fiat_pasta_fp_uint1 - x45, x46 = fiat_pasta_fp_addcarryx_u64(x44, x41, 0x0) - var x47 uint64 - var x48 fiat_pasta_fp_uint1 - x47, x48 = fiat_pasta_fp_addcarryx_u64(x42, x39, x46) - var x49 uint64 - var x50 fiat_pasta_fp_uint1 - x49, x50 = fiat_pasta_fp_addcarryx_u64(x40, x37, x48) - var x51 uint64 - var x52 fiat_pasta_fp_uint1 - x51, x52 = fiat_pasta_fp_addcarryx_u64(x31, x43, 0x0) - var x53 uint64 - var x54 fiat_pasta_fp_uint1 - x53, x54 = fiat_pasta_fp_addcarryx_u64(x33, x45, x52) - var x55 uint64 - var x56 fiat_pasta_fp_uint1 - x55, x56 = fiat_pasta_fp_addcarryx_u64(x35, x47, x54) - var x57 uint64 - var x58 fiat_pasta_fp_uint1 - x57, x58 = fiat_pasta_fp_addcarryx_u64(((uint64(x36) + (uint64(x18) + x6)) + x22), x49, x56) - var x59 uint64 - _, x59 = bits.Mul64(x51, 0x992d30ecffffffff) - var x61 uint64 - var x62 uint64 - x62, x61 = bits.Mul64(x59, 0x4000000000000000) - var x63 uint64 - var x64 uint64 - x64, x63 = bits.Mul64(x59, 0x224698fc094cf91b) - var x65 uint64 - var x66 uint64 - x66, x65 = bits.Mul64(x59, 0x992d30ed00000001) - var x67 uint64 - var x68 fiat_pasta_fp_uint1 - x67, x68 = fiat_pasta_fp_addcarryx_u64(x66, x63, 0x0) - var x70 fiat_pasta_fp_uint1 - _, x70 = fiat_pasta_fp_addcarryx_u64(x51, x65, 0x0) - var x71 uint64 - var x72 fiat_pasta_fp_uint1 - x71, x72 = fiat_pasta_fp_addcarryx_u64(x53, x67, x70) - var x73 uint64 - var x74 fiat_pasta_fp_uint1 - x73, x74 = fiat_pasta_fp_addcarryx_u64(x55, (uint64(x68) + x64), x72) - var x75 uint64 - var x76 fiat_pasta_fp_uint1 - x75, x76 = fiat_pasta_fp_addcarryx_u64(x57, x61, x74) - var x77 uint64 - var x78 uint64 - x78, x77 = bits.Mul64(x2, 0x96d41af7b9cb714) - var x79 uint64 - var x80 uint64 - x80, x79 = bits.Mul64(x2, 0x7797a99bc3c95d18) - var x81 uint64 - var x82 uint64 - x82, x81 = bits.Mul64(x2, 0xd7d30dbd8b0de0e7) - var x83 uint64 - var x84 uint64 - x84, x83 = bits.Mul64(x2, 0x8c78ecb30000000f) - var x85 uint64 - var x86 fiat_pasta_fp_uint1 - x85, x86 = fiat_pasta_fp_addcarryx_u64(x84, x81, 0x0) - var x87 uint64 - var x88 fiat_pasta_fp_uint1 - x87, x88 = fiat_pasta_fp_addcarryx_u64(x82, x79, x86) - var x89 uint64 - var x90 fiat_pasta_fp_uint1 - x89, x90 = fiat_pasta_fp_addcarryx_u64(x80, x77, x88) - var x91 uint64 - var x92 fiat_pasta_fp_uint1 - x91, x92 = fiat_pasta_fp_addcarryx_u64(x71, x83, 0x0) - var x93 uint64 - var x94 fiat_pasta_fp_uint1 - x93, x94 = fiat_pasta_fp_addcarryx_u64(x73, x85, x92) - var x95 uint64 - var x96 fiat_pasta_fp_uint1 - x95, x96 = fiat_pasta_fp_addcarryx_u64(x75, x87, x94) - var x97 uint64 - var x98 fiat_pasta_fp_uint1 - x97, x98 = fiat_pasta_fp_addcarryx_u64( - ((uint64(x76) + (uint64(x58) + (uint64(x50) + x38))) + x62), - x89, - x96, - ) - var x99 uint64 - _, x99 = bits.Mul64(x91, 0x992d30ecffffffff) - var x101 uint64 - var x102 uint64 - x102, x101 = bits.Mul64(x99, 0x4000000000000000) - var x103 uint64 - var x104 uint64 - x104, x103 = bits.Mul64(x99, 0x224698fc094cf91b) - var x105 uint64 - var x106 uint64 - x106, x105 = bits.Mul64(x99, 0x992d30ed00000001) - var x107 uint64 - var x108 fiat_pasta_fp_uint1 - x107, x108 = fiat_pasta_fp_addcarryx_u64(x106, x103, 0x0) - var x110 fiat_pasta_fp_uint1 - _, x110 = fiat_pasta_fp_addcarryx_u64(x91, x105, 0x0) - var x111 uint64 - var x112 fiat_pasta_fp_uint1 - x111, x112 = fiat_pasta_fp_addcarryx_u64(x93, x107, x110) - var x113 uint64 - var x114 fiat_pasta_fp_uint1 - x113, x114 = fiat_pasta_fp_addcarryx_u64(x95, (uint64(x108) + x104), x112) - var x115 uint64 - var x116 fiat_pasta_fp_uint1 - x115, x116 = fiat_pasta_fp_addcarryx_u64(x97, x101, x114) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x3, 0x96d41af7b9cb714) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x3, 0x7797a99bc3c95d18) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x3, 0xd7d30dbd8b0de0e7) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x3, 0x8c78ecb30000000f) - var x125 uint64 - var x126 fiat_pasta_fp_uint1 - x125, x126 = fiat_pasta_fp_addcarryx_u64(x124, x121, 0x0) - var x127 uint64 - var x128 fiat_pasta_fp_uint1 - x127, x128 = fiat_pasta_fp_addcarryx_u64(x122, x119, x126) - var x129 uint64 - var x130 fiat_pasta_fp_uint1 - x129, x130 = fiat_pasta_fp_addcarryx_u64(x120, x117, x128) - var x131 uint64 - var x132 fiat_pasta_fp_uint1 - x131, x132 = fiat_pasta_fp_addcarryx_u64(x111, x123, 0x0) - var x133 uint64 - var x134 fiat_pasta_fp_uint1 - x133, x134 = fiat_pasta_fp_addcarryx_u64(x113, x125, x132) - var x135 uint64 - var x136 fiat_pasta_fp_uint1 - x135, x136 = fiat_pasta_fp_addcarryx_u64(x115, x127, x134) - var x137 uint64 - var x138 fiat_pasta_fp_uint1 - x137, x138 = fiat_pasta_fp_addcarryx_u64( - ((uint64(x116) + (uint64(x98) + (uint64(x90) + x78))) + x102), - x129, - x136, - ) - var x139 uint64 - _, x139 = bits.Mul64(x131, 0x992d30ecffffffff) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x139, 0x4000000000000000) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x139, 0x224698fc094cf91b) - var x145 uint64 - var x146 uint64 - x146, x145 = bits.Mul64(x139, 0x992d30ed00000001) - var x147 uint64 - var x148 fiat_pasta_fp_uint1 - x147, x148 = fiat_pasta_fp_addcarryx_u64(x146, x143, 0x0) - var x150 fiat_pasta_fp_uint1 - _, x150 = fiat_pasta_fp_addcarryx_u64(x131, x145, 0x0) - var x151 uint64 - var x152 fiat_pasta_fp_uint1 - x151, x152 = fiat_pasta_fp_addcarryx_u64(x133, x147, x150) - var x153 uint64 - var x154 fiat_pasta_fp_uint1 - x153, x154 = fiat_pasta_fp_addcarryx_u64(x135, (uint64(x148) + x144), x152) - var x155 uint64 - var x156 fiat_pasta_fp_uint1 - x155, x156 = fiat_pasta_fp_addcarryx_u64(x137, x141, x154) - x157 := ((uint64(x156) + (uint64(x138) + (uint64(x130) + x118))) + x142) - var x158 uint64 - var x159 fiat_pasta_fp_uint1 - x158, x159 = fiat_pasta_fp_subborrowx_u64(x151, 0x992d30ed00000001, 0x0) - var x160 uint64 - var x161 fiat_pasta_fp_uint1 - x160, x161 = fiat_pasta_fp_subborrowx_u64(x153, 0x224698fc094cf91b, x159) - var x162 uint64 - var x163 fiat_pasta_fp_uint1 - x162, x163 = fiat_pasta_fp_subborrowx_u64(x155, uint64(0x0), x161) - var x164 uint64 - var x165 fiat_pasta_fp_uint1 - x164, x165 = fiat_pasta_fp_subborrowx_u64(x157, 0x4000000000000000, x163) - var x167 fiat_pasta_fp_uint1 - _, x167 = fiat_pasta_fp_subborrowx_u64(uint64(0x0), uint64(0x0), x165) - var x168 uint64 - fiat_pasta_fp_cmovznz_u64(&x168, x167, x158, x151) - var x169 uint64 - fiat_pasta_fp_cmovznz_u64(&x169, x167, x160, x153) - var x170 uint64 - fiat_pasta_fp_cmovznz_u64(&x170, x167, x162, x155) - var x171 uint64 - fiat_pasta_fp_cmovznz_u64(&x171, x167, x164, x157) - out1[0] = x168 - out1[1] = x169 - out1[2] = x170 - out1[3] = x171 -} - -// The function fiat_pasta_fp_selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func fiat_pasta_fp_selectznz( - out1 *[4]uint64, - arg1 fiat_pasta_fp_uint1, - arg2 *[4]uint64, - arg3 *[4]uint64, -) { - var x1 uint64 - fiat_pasta_fp_cmovznz_u64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - fiat_pasta_fp_cmovznz_u64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - fiat_pasta_fp_cmovznz_u64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - fiat_pasta_fp_cmovznz_u64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// The function fiat_pasta_fp_to_bytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x7fffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] -func fiat_pasta_fp_to_bytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// The function fiat_pasta_fp_from_bytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x7fffffffffffffff]] -func fiat_pasta_fp_from_bytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} diff --git a/crypto/core/curves/native/pasta/fq/fq.go b/crypto/core/curves/native/pasta/fq/fq.go deleted file mode 100644 index 2cbf01fe0..000000000 --- a/crypto/core/curves/native/pasta/fq/fq.go +++ /dev/null @@ -1,369 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - "encoding/binary" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/internal" -) - -type Fq fiat_pasta_fq_montgomery_domain_field_element - -// r = 2^256 mod p -var r = &Fq{0x5b2b3e9cfffffffd, 0x992c350be3420567, 0xffffffffffffffff, 0x3fffffffffffffff} - -// r2 = 2^512 mod p -var r2 = &Fq{0xfc9678ff0000000f, 0x67bb433d891a16e3, 0x7fae231004ccf590, 0x096d41af7ccfdaa9} - -// r3 = 2^768 mod p -var r3 = &Fq{0x008b421c249dae4c, 0xe13bda50dba41326, 0x88fececb8e15cb63, 0x07dd97a06e6792c8} - -// generator = 5 mod p is a generator of the `p - 1` order multiplicative -// subgroup, or in other words a primitive element of the field. -var generator = &Fq{0x96bc8c8cffffffed, 0x74c2a54b49f7778e, 0xfffffffffffffffd, 0x3fffffffffffffff} - -var s = 32 - -// modulus representation -// p = 0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001 -var modulus = &Fq{0x8c46eb2100000001, 0x224698fc0994a8dd, 0x0000000000000000, 0x4000000000000000} - -var BiModulus = new(big.Int).SetBytes([]byte{ - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x46, 0x98, 0xfc, 0x09, 0x94, 0xa8, 0xdd, - 0x8c, 0x46, 0xeb, 0x21, 0x00, 0x00, 0x00, 0x01, -}) - -// Cmp returns -1 if fp < rhs -// 0 if fp == rhs -// 1 if fp > rhs -func (fq *Fq) Cmp(rhs *Fq) int { - gt := 0 - lt := 0 - for i := len(fq) - 1; i >= 0; i-- { - gt |= int((rhs[i]-fq[i])>>63) &^ lt - lt |= int((fq[i]-rhs[i])>>63) &^ gt - } - return gt - lt -} - -// Equal returns true if fp == rhs -func (fq *Fq) Equal(rhs *Fq) bool { - t := fq[0] ^ rhs[0] - t |= fq[1] ^ rhs[1] - t |= fq[2] ^ rhs[2] - t |= fq[3] ^ rhs[3] - return t == 0 -} - -// IsZero returns true if fp == 0 -func (fq *Fq) IsZero() bool { - t := fq[0] - t |= fq[1] - t |= fq[2] - t |= fq[3] - return t == 0 -} - -// IsOne returns true if fp == r -func (fq *Fq) IsOne() bool { - return fq.Equal(r) -} - -// Set fp == rhs -func (fq *Fq) Set(rhs *Fq) *Fq { - fq[0] = rhs[0] - fq[1] = rhs[1] - fq[2] = rhs[2] - fq[3] = rhs[3] - return fq -} - -// SetUint64 sets fp == rhs -func (fq *Fq) SetUint64(rhs uint64) *Fq { - r := &fiat_pasta_fq_non_montgomery_domain_field_element{rhs, 0, 0, 0} - fiat_pasta_fq_to_montgomery((*fiat_pasta_fq_montgomery_domain_field_element)(fq), r) - return fq -} - -func (fq *Fq) SetBool(rhs bool) *Fq { - if rhs { - fq.SetOne() - } else { - fq.SetZero() - } - return fq -} - -// SetOne fp == r -func (fq *Fq) SetOne() *Fq { - return fq.Set(r) -} - -// SetZero fp == 0 -func (fq *Fq) SetZero() *Fq { - fq[0] = 0 - fq[1] = 0 - fq[2] = 0 - fq[3] = 0 - return fq -} - -// SetBytesWide takes 64 bytes as input and treats them as a 512-bit number. -// Attributed to https://github.com/zcash/pasta_curves/blob/main/src/fields/fq.rs#L255 -// We reduce an arbitrary 512-bit number by decomposing it into two 256-bit digits -// with the higher bits multiplied by 2^256. Thus, we perform two reductions -// -// 1. the lower bits are multiplied by r^2, as normal -// 2. the upper bits are multiplied by r^2 * 2^256 = r^3 -// -// and computing their sum in the field. It remains to see that arbitrary 256-bit -// numbers can be placed into Montgomery form safely using the reduction. The -// reduction works so long as the product is less than r=2^256 multiplied by -// the modulus. This holds because for any `c` smaller than the modulus, we have -// that (2^256 - 1)*c is an acceptable product for the reduction. Therefore, the -// reduction always works so long as `c` is in the field; in this case it is either the -// constant `r2` or `r3`. -func (fq *Fq) SetBytesWide(input *[64]byte) *Fq { - d0 := fiat_pasta_fq_montgomery_domain_field_element{ - binary.LittleEndian.Uint64(input[:8]), - binary.LittleEndian.Uint64(input[8:16]), - binary.LittleEndian.Uint64(input[16:24]), - binary.LittleEndian.Uint64(input[24:32]), - } - d1 := fiat_pasta_fq_montgomery_domain_field_element{ - binary.LittleEndian.Uint64(input[32:40]), - binary.LittleEndian.Uint64(input[40:48]), - binary.LittleEndian.Uint64(input[48:56]), - binary.LittleEndian.Uint64(input[56:64]), - } - // Convert to Montgomery form - tv1 := &fiat_pasta_fq_montgomery_domain_field_element{} - tv2 := &fiat_pasta_fq_montgomery_domain_field_element{} - // d0 * r2 + d1 * r3 - fiat_pasta_fq_mul(tv1, &d0, (*fiat_pasta_fq_montgomery_domain_field_element)(r2)) - fiat_pasta_fq_mul(tv2, &d1, (*fiat_pasta_fq_montgomery_domain_field_element)(r3)) - fiat_pasta_fq_add((*fiat_pasta_fq_montgomery_domain_field_element)(fq), tv1, tv2) - return fq -} - -// SetBytes attempts to convert a little endian byte representation -// of a scalar into a `Fq`, failing if input is not canonical -func (fq *Fq) SetBytes(input *[32]byte) (*Fq, error) { - d0 := &Fq{ - binary.LittleEndian.Uint64(input[:8]), - binary.LittleEndian.Uint64(input[8:16]), - binary.LittleEndian.Uint64(input[16:24]), - binary.LittleEndian.Uint64(input[24:32]), - } - if d0.Cmp(modulus) != -1 { - return nil, fmt.Errorf("invalid byte sequence") - } - fiat_pasta_fq_from_bytes((*[4]uint64)(fq), input) - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(fq), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(fq), - ) - return fq, nil -} - -// SetBigInt initializes an element from big.Int -// The value is reduced by the modulus -func (fq *Fq) SetBigInt(bi *big.Int) *Fq { - var buffer [32]byte - r := new(big.Int).Set(bi) - r.Mod(r, BiModulus) - r.FillBytes(buffer[:]) - copy(buffer[:], internal.ReverseScalarBytes(buffer[:])) - _, _ = fq.SetBytes(&buffer) - return fq -} - -// SetRaw converts a raw array into a field element -func (fq *Fq) SetRaw(array *[4]uint64) *Fq { - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(fq), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(array), - ) - return fq -} - -// Bytes converts this element into a byte representation -// in little endian byte order -func (fq *Fq) Bytes() [32]byte { - var output [32]byte - tv := &fiat_pasta_fq_non_montgomery_domain_field_element{} - fiat_pasta_fq_from_montgomery(tv, (*fiat_pasta_fq_montgomery_domain_field_element)(fq)) - fiat_pasta_fq_to_bytes(&output, (*[4]uint64)(tv)) - return output -} - -// BigInt converts this element into the big.Int struct -func (fq *Fq) BigInt() *big.Int { - buffer := fq.Bytes() - return new(big.Int).SetBytes(internal.ReverseScalarBytes(buffer[:])) -} - -// Double this element -func (fq *Fq) Double(elem *Fq) *Fq { - delem := (*fiat_pasta_fq_montgomery_domain_field_element)(elem) - fiat_pasta_fq_add((*fiat_pasta_fq_montgomery_domain_field_element)(fq), delem, delem) - return fq -} - -// Square this element -func (fq *Fq) Square(elem *Fq) *Fq { - delem := (*fiat_pasta_fq_montgomery_domain_field_element)(elem) - fiat_pasta_fq_square((*fiat_pasta_fq_montgomery_domain_field_element)(fq), delem) - return fq -} - -// Sqrt this element, if it exists. If true, then value -// is a square root. If false, value is a QNR -func (fq *Fq) Sqrt(elem *Fq) (*Fq, bool) { - return fq.tonelliShanks(elem) -} - -// See sqrt_ts_ct at -// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.4 -func (fq *Fq) tonelliShanks(elem *Fq) (*Fq, bool) { - // c1 := 32 - // c2 := (q - 1) / (2^c1) - //c2 := [4]uint64{ - // 0x0994a8dd8c46eb21, - // 0x00000000224698fc, - // 0x0000000000000000, - // 0x0000000040000000, - //} - // c3 := (c2 - 1) / 2 - c3 := [4]uint64{ - 0x04ca546ec6237590, - 0x0000000011234c7e, - 0x0000000000000000, - 0x0000000020000000, - } - // c4 := generator - // c5 := new(Fq).pow(&generator, c2) - c5 := &Fq{ - 0x218077428c9942de, - 0xcc49578921b60494, - 0xac2e5d27b2efbee2, - 0xb79fa897f2db056, - } - - z := new(Fq).pow(elem, c3) - t := new(Fq).Square(z) - t.Mul(t, elem) - - z.Mul(z, elem) - - b := new(Fq).Set(t) - c := new(Fq).Set(c5) - flags := map[bool]int{ - true: 1, - false: 0, - } - - for i := s; i >= 2; i-- { - for j := 1; j <= i-2; j++ { - b.Square(b) - } - z.CMove(z, new(Fq).Mul(z, c), flags[!b.IsOne()]) - c.Square(c) - t.CMove(t, new(Fq).Mul(t, c), flags[!b.IsOne()]) - b.Set(t) - } - wasSquare := c.Square(z).Equal(elem) - return fq.Set(z), wasSquare -} - -// Invert this element i.e. compute the multiplicative inverse -// return false, zero if this element is zero -func (fq *Fq) Invert(elem *Fq) (*Fq, bool) { - // computes elem^(p - 2) mod p - exp := [4]uint64{ - 0x8c46eb20ffffffff, - 0x224698fc0994a8dd, - 0x0000000000000000, - 0x4000000000000000, - } - return fq.pow(elem, exp), !elem.IsZero() -} - -// Mul returns the result from multiplying this element by rhs -func (fq *Fq) Mul(lhs, rhs *Fq) *Fq { - dlhs := (*fiat_pasta_fq_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fq_montgomery_domain_field_element)(rhs) - fiat_pasta_fq_mul((*fiat_pasta_fq_montgomery_domain_field_element)(fq), dlhs, drhs) - return fq -} - -// Sub returns the result from subtracting rhs from this element -func (fq *Fq) Sub(lhs, rhs *Fq) *Fq { - dlhs := (*fiat_pasta_fq_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fq_montgomery_domain_field_element)(rhs) - fiat_pasta_fq_sub((*fiat_pasta_fq_montgomery_domain_field_element)(fq), dlhs, drhs) - return fq -} - -// Add returns the result from adding rhs to this element -func (fq *Fq) Add(lhs, rhs *Fq) *Fq { - dlhs := (*fiat_pasta_fq_montgomery_domain_field_element)(lhs) - drhs := (*fiat_pasta_fq_montgomery_domain_field_element)(rhs) - fiat_pasta_fq_add((*fiat_pasta_fq_montgomery_domain_field_element)(fq), dlhs, drhs) - return fq -} - -// Neg returns negation of this element -func (fq *Fq) Neg(elem *Fq) *Fq { - delem := (*fiat_pasta_fq_montgomery_domain_field_element)(elem) - fiat_pasta_fq_opp((*fiat_pasta_fq_montgomery_domain_field_element)(fq), delem) - return fq -} - -// Exp exponentiates this element by exp -func (fq *Fq) Exp(base, exp *Fq) *Fq { - // convert exponent to integer form - tv := &fiat_pasta_fq_non_montgomery_domain_field_element{} - fiat_pasta_fq_from_montgomery(tv, (*fiat_pasta_fq_montgomery_domain_field_element)(exp)) - - e := (*[4]uint64)(tv) - return fq.pow(base, *e) -} - -func (fq *Fq) pow(base *Fq, exp [4]uint64) *Fq { - res := new(Fq).SetOne() - tmp := new(Fq) - - for i := len(exp) - 1; i >= 0; i-- { - for j := 63; j >= 0; j-- { - res.Square(res) - tmp.Mul(res, base) - res.CMove(res, tmp, int(exp[i]>>j)&1) - } - } - return fq.Set(res) -} - -// CMove selects lhs if choice == 0 and rhs if choice == 1 -func (fq *Fq) CMove(lhs, rhs *Fq, choice int) *Fq { - dlhs := (*[4]uint64)(lhs) - drhs := (*[4]uint64)(rhs) - fiat_pasta_fq_selectznz((*[4]uint64)(fq), fiat_pasta_fq_uint1(choice), dlhs, drhs) - return fq -} - -// ToRaw converts this element into the a [4]uint64 -func (fq *Fq) ToRaw() [4]uint64 { - res := &fiat_pasta_fq_non_montgomery_domain_field_element{} - fiat_pasta_fq_from_montgomery(res, (*fiat_pasta_fq_montgomery_domain_field_element)(fq)) - return *(*[4]uint64)(res) -} diff --git a/crypto/core/curves/native/pasta/fq/fq_test.go b/crypto/core/curves/native/pasta/fq/fq_test.go deleted file mode 100755 index c203ddf03..000000000 --- a/crypto/core/curves/native/pasta/fq/fq_test.go +++ /dev/null @@ -1,273 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package fq - -import ( - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFqSetOne(t *testing.T) { - fq := new(Fq).SetOne() - require.NotNil(t, fq) - require.True(t, fq.Equal(r)) -} - -func TestFqSetUint64(t *testing.T) { - act := new(Fq).SetUint64(1 << 60) - require.NotNil(t, act) - // Remember it will be in montgomery form - require.Equal(t, int(act[0]), 0x4c46eb2100000001) -} - -func TestFqAdd(t *testing.T) { - lhs := new(Fq).SetOne() - rhs := new(Fq).SetOne() - exp := new(Fq).SetUint64(2) - res := new(Fq).Add(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - e := l + r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := new(Fq).Add(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqSub(t *testing.T) { - lhs := new(Fq).SetOne() - rhs := new(Fq).SetOne() - exp := new(Fq).SetZero() - res := new(Fq).Sub(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint64() >> 2 - r := rand.Uint64() >> 2 - if l < r { - l, r = r, l - } - e := l - r - lhs.SetUint64(l) - rhs.SetUint64(r) - exp.SetUint64(e) - - a := new(Fq).Sub(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqMul(t *testing.T) { - lhs := new(Fq).SetOne() - rhs := new(Fq).SetOne() - exp := new(Fq).SetOne() - res := new(Fq).Mul(lhs, rhs) - require.NotNil(t, res) - require.True(t, res.Equal(exp)) - - // Fuzz test - for i := 0; i < 25; i++ { - // Divide by 4 to prevent overflow false errors - l := rand.Uint32() - r := rand.Uint32() - e := uint64(l) * uint64(r) - lhs.SetUint64(uint64(l)) - rhs.SetUint64(uint64(r)) - exp.SetUint64(e) - - a := new(Fq).Mul(lhs, rhs) - require.NotNil(t, a) - require.Equal(t, exp, a) - } -} - -func TestFqDouble(t *testing.T) { - a := new(Fq).SetUint64(2) - e := new(Fq).SetUint64(4) - require.Equal(t, e, new(Fq).Double(a)) - - for i := 0; i < 25; i++ { - tv := rand.Uint32() - ttv := uint64(tv) * 2 - a = new(Fq).SetUint64(uint64(tv)) - e = new(Fq).SetUint64(ttv) - require.Equal(t, e, new(Fq).Double(a)) - } -} - -func TestFqSquare(t *testing.T) { - a := new(Fq).SetUint64(4) - e := new(Fq).SetUint64(16) - require.Equal(t, e, a.Square(a)) - - for i := 0; i < 25; i++ { - j := rand.Uint32() - exp := uint64(j) * uint64(j) - e.SetUint64(exp) - a.SetUint64(uint64(j)) - require.Equal(t, e, a.Square(a)) - } -} - -func TestFqNeg(t *testing.T) { - a := new(Fq).SetOne() - a.Neg(a) - e := &Fq{0x311bac8400000004, 0x891a63f02652a376, 0, 0} - require.Equal(t, e, a) - a.Neg(generator) - e = &Fq{0xf58a5e9400000014, 0xad83f3b0bf9d314e, 0x2, 0x0} - require.Equal(t, e, a) -} - -func TestFqExp(t *testing.T) { - e := new(Fq).SetUint64(8) - a := new(Fq).SetUint64(2) - by := new(Fq).SetUint64(3) - require.Equal(t, e, a.Exp(a, by)) -} - -func TestFqSqrt(t *testing.T) { - t1 := new(Fq).SetUint64(2) - t2 := new(Fq).Neg(t1) - t3 := new(Fq).Square(t1) - _, wasSquare := t3.Sqrt(t3) - require.True(t, wasSquare) - require.True(t, t1.Equal(t3) || t2.Equal(t3)) - t1.SetUint64(5) - _, wasSquare = new(Fq).Sqrt(t1) - require.False(t, wasSquare) -} - -func TestFqInvert(t *testing.T) { - twoInv := &Fq{0xc623759080000001, 0x11234c7e04ca546e, 0x0000000000000000, 0x2000000000000000} - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(twoInv), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(twoInv), - ) - two := new(Fq).SetUint64(2) - a, inverted := new(Fq).Invert(two) - require.True(t, inverted) - require.Equal(t, a, twoInv) - - rootOfUnity := &Fq{ - 0xa70e2c1102b6d05f, - 0x9bb97ea3c106f049, - 0x9e5c4dfd492ae26e, - 0x2de6a9b8746d3f58, - } - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(rootOfUnity), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(rootOfUnity), - ) - rootOfUnityInv := &Fq{ - 0x57eecda0a84b6836, - 0x4ad38b9084b8a80c, - 0xf4c8f353124086c1, - 0x2235e1a7415bf936, - } - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(rootOfUnityInv), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(rootOfUnityInv), - ) - a, inverted = new(Fq).Invert(rootOfUnity) - require.True(t, inverted) - require.Equal(t, a, rootOfUnityInv) - - lhs := new(Fq).SetUint64(9) - rhs := new(Fq).SetUint64(3) - rhsInv, inverted := new(Fq).Invert(rhs) - require.True(t, inverted) - require.Equal(t, rhs, new(Fq).Mul(lhs, rhsInv)) - - rhs.SetZero() - _, inverted = new(Fq).Invert(rhs) - require.False(t, inverted) -} - -func TestFqCMove(t *testing.T) { - t1 := new(Fq).SetUint64(5) - t2 := new(Fq).SetUint64(10) - require.Equal(t, t1, new(Fq).CMove(t1, t2, 0)) - require.Equal(t, t2, new(Fq).CMove(t1, t2, 1)) -} - -func TestFqBytes(t *testing.T) { - t1 := new(Fq).SetUint64(99) - seq := t1.Bytes() - t2, err := new(Fq).SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - - for i := 0; i < 25; i++ { - t1.SetUint64(rand.Uint64()) - seq = t1.Bytes() - _, err = t2.SetBytes(&seq) - require.NoError(t, err) - require.Equal(t, t1, t2) - } -} - -func TestFqBigInt(t *testing.T) { - t1 := new(Fq).SetBigInt(big.NewInt(9999)) - t2 := new(Fq).SetBigInt(t1.BigInt()) - require.Equal(t, t1, t2) - - e := &Fq{0x7bb1416dea3d6ae3, 0x62f9108a340aa525, 0x303b3f30fcaa477f, 0x11c9ef5422d80a4d} - b := new( - big.Int, - ).SetBytes([]byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}) - t1.SetBigInt(b) - require.Equal(t, e, t1) - e[0] = 0x1095a9b315c2951e - e[1] = 0xbf4d8871d58a03b8 - e[2] = 0xcfc4c0cf0355b880 - e[3] = 0x2e3610abdd27f5b2 - b.Neg(b) - t1.SetBigInt(b) - require.Equal(t, e, t1) -} - -func TestFqSetBool(t *testing.T) { - require.Equal(t, new(Fq).SetOne(), new(Fq).SetBool(true)) - require.Equal(t, new(Fq).SetZero(), new(Fq).SetBool(false)) -} - -func TestFqSetBytesWide(t *testing.T) { - e := &Fq{0xe22bd0d1b22cc43e, 0x6b84e5b52490a7c8, 0x264262941ac9e229, 0x27dcfdf361ce4254} - fiat_pasta_fq_to_montgomery( - (*fiat_pasta_fq_montgomery_domain_field_element)(e), - (*fiat_pasta_fq_non_montgomery_domain_field_element)(e), - ) - a := new(Fq).SetBytesWide(&[64]byte{ - 0x69, 0x23, 0x5a, 0x0b, 0xce, 0x0c, 0xa8, 0x64, - 0x3c, 0x78, 0xbc, 0x01, 0x05, 0xef, 0xf2, 0x84, - 0xde, 0xbb, 0x6b, 0xc8, 0x63, 0x5e, 0x6e, 0x69, - 0x62, 0xcc, 0xc6, 0x2d, 0xf5, 0x72, 0x40, 0x92, - 0x28, 0x11, 0xd6, 0xc8, 0x07, 0xa5, 0x88, 0x82, - 0xfe, 0xe3, 0x97, 0xf6, 0x1e, 0xfb, 0x2e, 0x3b, - 0x27, 0x5f, 0x85, 0x06, 0x8d, 0x99, 0xa4, 0x75, - 0xc0, 0x2c, 0x71, 0x69, 0x9e, 0x58, 0xea, 0x52, - }) - require.Equal(t, e, a) -} diff --git a/crypto/core/curves/native/pasta/fq/pasta_fq.go b/crypto/core/curves/native/pasta/fq/pasta_fq.go deleted file mode 100755 index ad6b214ee..000000000 --- a/crypto/core/curves/native/pasta/fq/pasta_fq.go +++ /dev/null @@ -1,1518 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Autogenerated: './src/ExtractionOCaml/word_by_word_montgomery' --lang Go pasta_fq 64 '2^254 + 45560315531506369815346746415080538113' -// -// curve description: pasta_fq -// -// machine_wordsize = 64 (from "64") -// -// requested operations: (all) -// -// m = 0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001 (from "2^254 + 45560315531506369815346746415080538113") -// -// -// -// NOTE: In addition to the bounds specified above each function, all -// -// functions synthesized for this Montgomery arithmetic require the -// -// input to be strictly less than the prime modulus (m), and also -// -// require the input to be in the unique saturated representation. -// -// All functions also ensure that these two properties are true of -// -// return values. -// -// -// -// Computed values: -// -// eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) -// -// bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) -// -// twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in -// -// if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 - -package fq - -import "math/bits" - -type ( - fiat_pasta_fq_uint1 uint64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 - fiat_pasta_fq_int1 int64 // We use uint64 instead of a more narrow type for performance reasons; see https://github.com/mit-plv/fiat-crypto/pull/1006#issuecomment-892625927 -) - -// The type fiat_pasta_fq_montgomery_domain_field_element is a field element in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiat_pasta_fq_montgomery_domain_field_element [4]uint64 - -// The type fiat_pasta_fq_non_montgomery_domain_field_element is a field element NOT in the Montgomery domain. -// -// Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -type fiat_pasta_fq_non_montgomery_domain_field_element [4]uint64 - -// The function fiat_pasta_fq_addcarryx_u64 is a thin wrapper around bits.Add64 that uses fiat_pasta_fq_uint1 rather than uint64 -func fiat_pasta_fq_addcarryx_u64( - x uint64, - y uint64, - carry fiat_pasta_fq_uint1, -) (uint64, fiat_pasta_fq_uint1) { - sum, carryOut := bits.Add64(x, y, uint64(carry)) - return sum, fiat_pasta_fq_uint1(carryOut) -} - -// The function fiat_pasta_fq_subborrowx_u64 is a thin wrapper around bits.Sub64 that uses fiat_pasta_fq_uint1 rather than uint64 -func fiat_pasta_fq_subborrowx_u64( - x uint64, - y uint64, - carry fiat_pasta_fq_uint1, -) (uint64, fiat_pasta_fq_uint1) { - sum, carryOut := bits.Sub64(x, y, uint64(carry)) - return sum, fiat_pasta_fq_uint1(carryOut) -} - -// The function fiat_pasta_fq_cmovznz_u64 is a single-word conditional move. -// -// Postconditions: -// -// out1 = (if arg1 = 0 then arg2 else arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [0x0 ~> 0xffffffffffffffff] -// arg3: [0x0 ~> 0xffffffffffffffff] -// -// Output Bounds: -// -// out1: [0x0 ~> 0xffffffffffffffff] -func fiat_pasta_fq_cmovznz_u64(out1 *uint64, arg1 fiat_pasta_fq_uint1, arg2 uint64, arg3 uint64) { - x1 := arg1 - x2 := (uint64((fiat_pasta_fq_int1(0x0) - fiat_pasta_fq_int1(x1))) & 0xffffffffffffffff) - x3 := ((x2 & arg3) | ((^x2) & arg2)) - *out1 = x3 -} - -// The function fiat_pasta_fq_mul multiplies two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_mul( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, - arg2 *fiat_pasta_fq_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg2[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg2[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg2[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg2[0]) - var x13 uint64 - var x14 fiat_pasta_fq_uint1 - x13, x14 = fiat_pasta_fq_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fq_uint1 - x15, x16 = fiat_pasta_fq_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fq_uint1 - x17, x18 = fiat_pasta_fq_addcarryx_u64(x8, x5, x16) - x19 := (uint64(x18) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x8c46eb20ffffffff) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0x4000000000000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0x224698fc0994a8dd) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0x8c46eb2100000001) - var x28 uint64 - var x29 fiat_pasta_fq_uint1 - x28, x29 = fiat_pasta_fq_addcarryx_u64(x27, x24, 0x0) - x30 := (uint64(x29) + x25) - var x32 fiat_pasta_fq_uint1 - _, x32 = fiat_pasta_fq_addcarryx_u64(x11, x26, 0x0) - var x33 uint64 - var x34 fiat_pasta_fq_uint1 - x33, x34 = fiat_pasta_fq_addcarryx_u64(x13, x28, x32) - var x35 uint64 - var x36 fiat_pasta_fq_uint1 - x35, x36 = fiat_pasta_fq_addcarryx_u64(x15, x30, x34) - var x37 uint64 - var x38 fiat_pasta_fq_uint1 - x37, x38 = fiat_pasta_fq_addcarryx_u64(x17, x22, x36) - var x39 uint64 - var x40 fiat_pasta_fq_uint1 - x39, x40 = fiat_pasta_fq_addcarryx_u64(x19, x23, x38) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg2[3]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg2[2]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg2[1]) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg2[0]) - var x49 uint64 - var x50 fiat_pasta_fq_uint1 - x49, x50 = fiat_pasta_fq_addcarryx_u64(x48, x45, 0x0) - var x51 uint64 - var x52 fiat_pasta_fq_uint1 - x51, x52 = fiat_pasta_fq_addcarryx_u64(x46, x43, x50) - var x53 uint64 - var x54 fiat_pasta_fq_uint1 - x53, x54 = fiat_pasta_fq_addcarryx_u64(x44, x41, x52) - x55 := (uint64(x54) + x42) - var x56 uint64 - var x57 fiat_pasta_fq_uint1 - x56, x57 = fiat_pasta_fq_addcarryx_u64(x33, x47, 0x0) - var x58 uint64 - var x59 fiat_pasta_fq_uint1 - x58, x59 = fiat_pasta_fq_addcarryx_u64(x35, x49, x57) - var x60 uint64 - var x61 fiat_pasta_fq_uint1 - x60, x61 = fiat_pasta_fq_addcarryx_u64(x37, x51, x59) - var x62 uint64 - var x63 fiat_pasta_fq_uint1 - x62, x63 = fiat_pasta_fq_addcarryx_u64(x39, x53, x61) - var x64 uint64 - var x65 fiat_pasta_fq_uint1 - x64, x65 = fiat_pasta_fq_addcarryx_u64(uint64(x40), x55, x63) - var x66 uint64 - _, x66 = bits.Mul64(x56, 0x8c46eb20ffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc0994a8dd) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x8c46eb2100000001) - var x74 uint64 - var x75 fiat_pasta_fq_uint1 - x74, x75 = fiat_pasta_fq_addcarryx_u64(x73, x70, 0x0) - x76 := (uint64(x75) + x71) - var x78 fiat_pasta_fq_uint1 - _, x78 = fiat_pasta_fq_addcarryx_u64(x56, x72, 0x0) - var x79 uint64 - var x80 fiat_pasta_fq_uint1 - x79, x80 = fiat_pasta_fq_addcarryx_u64(x58, x74, x78) - var x81 uint64 - var x82 fiat_pasta_fq_uint1 - x81, x82 = fiat_pasta_fq_addcarryx_u64(x60, x76, x80) - var x83 uint64 - var x84 fiat_pasta_fq_uint1 - x83, x84 = fiat_pasta_fq_addcarryx_u64(x62, x68, x82) - var x85 uint64 - var x86 fiat_pasta_fq_uint1 - x85, x86 = fiat_pasta_fq_addcarryx_u64(x64, x69, x84) - x87 := (uint64(x86) + uint64(x65)) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg2[3]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg2[2]) - var x92 uint64 - var x93 uint64 - x93, x92 = bits.Mul64(x2, arg2[1]) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x2, arg2[0]) - var x96 uint64 - var x97 fiat_pasta_fq_uint1 - x96, x97 = fiat_pasta_fq_addcarryx_u64(x95, x92, 0x0) - var x98 uint64 - var x99 fiat_pasta_fq_uint1 - x98, x99 = fiat_pasta_fq_addcarryx_u64(x93, x90, x97) - var x100 uint64 - var x101 fiat_pasta_fq_uint1 - x100, x101 = fiat_pasta_fq_addcarryx_u64(x91, x88, x99) - x102 := (uint64(x101) + x89) - var x103 uint64 - var x104 fiat_pasta_fq_uint1 - x103, x104 = fiat_pasta_fq_addcarryx_u64(x79, x94, 0x0) - var x105 uint64 - var x106 fiat_pasta_fq_uint1 - x105, x106 = fiat_pasta_fq_addcarryx_u64(x81, x96, x104) - var x107 uint64 - var x108 fiat_pasta_fq_uint1 - x107, x108 = fiat_pasta_fq_addcarryx_u64(x83, x98, x106) - var x109 uint64 - var x110 fiat_pasta_fq_uint1 - x109, x110 = fiat_pasta_fq_addcarryx_u64(x85, x100, x108) - var x111 uint64 - var x112 fiat_pasta_fq_uint1 - x111, x112 = fiat_pasta_fq_addcarryx_u64(x87, x102, x110) - var x113 uint64 - _, x113 = bits.Mul64(x103, 0x8c46eb20ffffffff) - var x115 uint64 - var x116 uint64 - x116, x115 = bits.Mul64(x113, 0x4000000000000000) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x113, 0x224698fc0994a8dd) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x113, 0x8c46eb2100000001) - var x121 uint64 - var x122 fiat_pasta_fq_uint1 - x121, x122 = fiat_pasta_fq_addcarryx_u64(x120, x117, 0x0) - x123 := (uint64(x122) + x118) - var x125 fiat_pasta_fq_uint1 - _, x125 = fiat_pasta_fq_addcarryx_u64(x103, x119, 0x0) - var x126 uint64 - var x127 fiat_pasta_fq_uint1 - x126, x127 = fiat_pasta_fq_addcarryx_u64(x105, x121, x125) - var x128 uint64 - var x129 fiat_pasta_fq_uint1 - x128, x129 = fiat_pasta_fq_addcarryx_u64(x107, x123, x127) - var x130 uint64 - var x131 fiat_pasta_fq_uint1 - x130, x131 = fiat_pasta_fq_addcarryx_u64(x109, x115, x129) - var x132 uint64 - var x133 fiat_pasta_fq_uint1 - x132, x133 = fiat_pasta_fq_addcarryx_u64(x111, x116, x131) - x134 := (uint64(x133) + uint64(x112)) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg2[3]) - var x137 uint64 - var x138 uint64 - x138, x137 = bits.Mul64(x3, arg2[2]) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x3, arg2[1]) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, arg2[0]) - var x143 uint64 - var x144 fiat_pasta_fq_uint1 - x143, x144 = fiat_pasta_fq_addcarryx_u64(x142, x139, 0x0) - var x145 uint64 - var x146 fiat_pasta_fq_uint1 - x145, x146 = fiat_pasta_fq_addcarryx_u64(x140, x137, x144) - var x147 uint64 - var x148 fiat_pasta_fq_uint1 - x147, x148 = fiat_pasta_fq_addcarryx_u64(x138, x135, x146) - x149 := (uint64(x148) + x136) - var x150 uint64 - var x151 fiat_pasta_fq_uint1 - x150, x151 = fiat_pasta_fq_addcarryx_u64(x126, x141, 0x0) - var x152 uint64 - var x153 fiat_pasta_fq_uint1 - x152, x153 = fiat_pasta_fq_addcarryx_u64(x128, x143, x151) - var x154 uint64 - var x155 fiat_pasta_fq_uint1 - x154, x155 = fiat_pasta_fq_addcarryx_u64(x130, x145, x153) - var x156 uint64 - var x157 fiat_pasta_fq_uint1 - x156, x157 = fiat_pasta_fq_addcarryx_u64(x132, x147, x155) - var x158 uint64 - var x159 fiat_pasta_fq_uint1 - x158, x159 = fiat_pasta_fq_addcarryx_u64(x134, x149, x157) - var x160 uint64 - _, x160 = bits.Mul64(x150, 0x8c46eb20ffffffff) - var x162 uint64 - var x163 uint64 - x163, x162 = bits.Mul64(x160, 0x4000000000000000) - var x164 uint64 - var x165 uint64 - x165, x164 = bits.Mul64(x160, 0x224698fc0994a8dd) - var x166 uint64 - var x167 uint64 - x167, x166 = bits.Mul64(x160, 0x8c46eb2100000001) - var x168 uint64 - var x169 fiat_pasta_fq_uint1 - x168, x169 = fiat_pasta_fq_addcarryx_u64(x167, x164, 0x0) - x170 := (uint64(x169) + x165) - var x172 fiat_pasta_fq_uint1 - _, x172 = fiat_pasta_fq_addcarryx_u64(x150, x166, 0x0) - var x173 uint64 - var x174 fiat_pasta_fq_uint1 - x173, x174 = fiat_pasta_fq_addcarryx_u64(x152, x168, x172) - var x175 uint64 - var x176 fiat_pasta_fq_uint1 - x175, x176 = fiat_pasta_fq_addcarryx_u64(x154, x170, x174) - var x177 uint64 - var x178 fiat_pasta_fq_uint1 - x177, x178 = fiat_pasta_fq_addcarryx_u64(x156, x162, x176) - var x179 uint64 - var x180 fiat_pasta_fq_uint1 - x179, x180 = fiat_pasta_fq_addcarryx_u64(x158, x163, x178) - x181 := (uint64(x180) + uint64(x159)) - var x182 uint64 - var x183 fiat_pasta_fq_uint1 - x182, x183 = fiat_pasta_fq_subborrowx_u64(x173, 0x8c46eb2100000001, 0x0) - var x184 uint64 - var x185 fiat_pasta_fq_uint1 - x184, x185 = fiat_pasta_fq_subborrowx_u64(x175, 0x224698fc0994a8dd, x183) - var x186 uint64 - var x187 fiat_pasta_fq_uint1 - x186, x187 = fiat_pasta_fq_subborrowx_u64(x177, uint64(0x0), x185) - var x188 uint64 - var x189 fiat_pasta_fq_uint1 - x188, x189 = fiat_pasta_fq_subborrowx_u64(x179, 0x4000000000000000, x187) - var x191 fiat_pasta_fq_uint1 - _, x191 = fiat_pasta_fq_subborrowx_u64(x181, uint64(0x0), x189) - var x192 uint64 - fiat_pasta_fq_cmovznz_u64(&x192, x191, x182, x173) - var x193 uint64 - fiat_pasta_fq_cmovznz_u64(&x193, x191, x184, x175) - var x194 uint64 - fiat_pasta_fq_cmovznz_u64(&x194, x191, x186, x177) - var x195 uint64 - fiat_pasta_fq_cmovznz_u64(&x195, x191, x188, x179) - out1[0] = x192 - out1[1] = x193 - out1[2] = x194 - out1[3] = x195 -} - -// The function fiat_pasta_fq_square squares a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_square( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, arg1[3]) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, arg1[2]) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, arg1[1]) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, arg1[0]) - var x13 uint64 - var x14 fiat_pasta_fq_uint1 - x13, x14 = fiat_pasta_fq_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fq_uint1 - x15, x16 = fiat_pasta_fq_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fq_uint1 - x17, x18 = fiat_pasta_fq_addcarryx_u64(x8, x5, x16) - x19 := (uint64(x18) + x6) - var x20 uint64 - _, x20 = bits.Mul64(x11, 0x8c46eb20ffffffff) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x20, 0x4000000000000000) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x20, 0x224698fc0994a8dd) - var x26 uint64 - var x27 uint64 - x27, x26 = bits.Mul64(x20, 0x8c46eb2100000001) - var x28 uint64 - var x29 fiat_pasta_fq_uint1 - x28, x29 = fiat_pasta_fq_addcarryx_u64(x27, x24, 0x0) - x30 := (uint64(x29) + x25) - var x32 fiat_pasta_fq_uint1 - _, x32 = fiat_pasta_fq_addcarryx_u64(x11, x26, 0x0) - var x33 uint64 - var x34 fiat_pasta_fq_uint1 - x33, x34 = fiat_pasta_fq_addcarryx_u64(x13, x28, x32) - var x35 uint64 - var x36 fiat_pasta_fq_uint1 - x35, x36 = fiat_pasta_fq_addcarryx_u64(x15, x30, x34) - var x37 uint64 - var x38 fiat_pasta_fq_uint1 - x37, x38 = fiat_pasta_fq_addcarryx_u64(x17, x22, x36) - var x39 uint64 - var x40 fiat_pasta_fq_uint1 - x39, x40 = fiat_pasta_fq_addcarryx_u64(x19, x23, x38) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, arg1[3]) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, arg1[2]) - var x45 uint64 - var x46 uint64 - x46, x45 = bits.Mul64(x1, arg1[1]) - var x47 uint64 - var x48 uint64 - x48, x47 = bits.Mul64(x1, arg1[0]) - var x49 uint64 - var x50 fiat_pasta_fq_uint1 - x49, x50 = fiat_pasta_fq_addcarryx_u64(x48, x45, 0x0) - var x51 uint64 - var x52 fiat_pasta_fq_uint1 - x51, x52 = fiat_pasta_fq_addcarryx_u64(x46, x43, x50) - var x53 uint64 - var x54 fiat_pasta_fq_uint1 - x53, x54 = fiat_pasta_fq_addcarryx_u64(x44, x41, x52) - x55 := (uint64(x54) + x42) - var x56 uint64 - var x57 fiat_pasta_fq_uint1 - x56, x57 = fiat_pasta_fq_addcarryx_u64(x33, x47, 0x0) - var x58 uint64 - var x59 fiat_pasta_fq_uint1 - x58, x59 = fiat_pasta_fq_addcarryx_u64(x35, x49, x57) - var x60 uint64 - var x61 fiat_pasta_fq_uint1 - x60, x61 = fiat_pasta_fq_addcarryx_u64(x37, x51, x59) - var x62 uint64 - var x63 fiat_pasta_fq_uint1 - x62, x63 = fiat_pasta_fq_addcarryx_u64(x39, x53, x61) - var x64 uint64 - var x65 fiat_pasta_fq_uint1 - x64, x65 = fiat_pasta_fq_addcarryx_u64(uint64(x40), x55, x63) - var x66 uint64 - _, x66 = bits.Mul64(x56, 0x8c46eb20ffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc0994a8dd) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x8c46eb2100000001) - var x74 uint64 - var x75 fiat_pasta_fq_uint1 - x74, x75 = fiat_pasta_fq_addcarryx_u64(x73, x70, 0x0) - x76 := (uint64(x75) + x71) - var x78 fiat_pasta_fq_uint1 - _, x78 = fiat_pasta_fq_addcarryx_u64(x56, x72, 0x0) - var x79 uint64 - var x80 fiat_pasta_fq_uint1 - x79, x80 = fiat_pasta_fq_addcarryx_u64(x58, x74, x78) - var x81 uint64 - var x82 fiat_pasta_fq_uint1 - x81, x82 = fiat_pasta_fq_addcarryx_u64(x60, x76, x80) - var x83 uint64 - var x84 fiat_pasta_fq_uint1 - x83, x84 = fiat_pasta_fq_addcarryx_u64(x62, x68, x82) - var x85 uint64 - var x86 fiat_pasta_fq_uint1 - x85, x86 = fiat_pasta_fq_addcarryx_u64(x64, x69, x84) - x87 := (uint64(x86) + uint64(x65)) - var x88 uint64 - var x89 uint64 - x89, x88 = bits.Mul64(x2, arg1[3]) - var x90 uint64 - var x91 uint64 - x91, x90 = bits.Mul64(x2, arg1[2]) - var x92 uint64 - var x93 uint64 - x93, x92 = bits.Mul64(x2, arg1[1]) - var x94 uint64 - var x95 uint64 - x95, x94 = bits.Mul64(x2, arg1[0]) - var x96 uint64 - var x97 fiat_pasta_fq_uint1 - x96, x97 = fiat_pasta_fq_addcarryx_u64(x95, x92, 0x0) - var x98 uint64 - var x99 fiat_pasta_fq_uint1 - x98, x99 = fiat_pasta_fq_addcarryx_u64(x93, x90, x97) - var x100 uint64 - var x101 fiat_pasta_fq_uint1 - x100, x101 = fiat_pasta_fq_addcarryx_u64(x91, x88, x99) - x102 := (uint64(x101) + x89) - var x103 uint64 - var x104 fiat_pasta_fq_uint1 - x103, x104 = fiat_pasta_fq_addcarryx_u64(x79, x94, 0x0) - var x105 uint64 - var x106 fiat_pasta_fq_uint1 - x105, x106 = fiat_pasta_fq_addcarryx_u64(x81, x96, x104) - var x107 uint64 - var x108 fiat_pasta_fq_uint1 - x107, x108 = fiat_pasta_fq_addcarryx_u64(x83, x98, x106) - var x109 uint64 - var x110 fiat_pasta_fq_uint1 - x109, x110 = fiat_pasta_fq_addcarryx_u64(x85, x100, x108) - var x111 uint64 - var x112 fiat_pasta_fq_uint1 - x111, x112 = fiat_pasta_fq_addcarryx_u64(x87, x102, x110) - var x113 uint64 - _, x113 = bits.Mul64(x103, 0x8c46eb20ffffffff) - var x115 uint64 - var x116 uint64 - x116, x115 = bits.Mul64(x113, 0x4000000000000000) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x113, 0x224698fc0994a8dd) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x113, 0x8c46eb2100000001) - var x121 uint64 - var x122 fiat_pasta_fq_uint1 - x121, x122 = fiat_pasta_fq_addcarryx_u64(x120, x117, 0x0) - x123 := (uint64(x122) + x118) - var x125 fiat_pasta_fq_uint1 - _, x125 = fiat_pasta_fq_addcarryx_u64(x103, x119, 0x0) - var x126 uint64 - var x127 fiat_pasta_fq_uint1 - x126, x127 = fiat_pasta_fq_addcarryx_u64(x105, x121, x125) - var x128 uint64 - var x129 fiat_pasta_fq_uint1 - x128, x129 = fiat_pasta_fq_addcarryx_u64(x107, x123, x127) - var x130 uint64 - var x131 fiat_pasta_fq_uint1 - x130, x131 = fiat_pasta_fq_addcarryx_u64(x109, x115, x129) - var x132 uint64 - var x133 fiat_pasta_fq_uint1 - x132, x133 = fiat_pasta_fq_addcarryx_u64(x111, x116, x131) - x134 := (uint64(x133) + uint64(x112)) - var x135 uint64 - var x136 uint64 - x136, x135 = bits.Mul64(x3, arg1[3]) - var x137 uint64 - var x138 uint64 - x138, x137 = bits.Mul64(x3, arg1[2]) - var x139 uint64 - var x140 uint64 - x140, x139 = bits.Mul64(x3, arg1[1]) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x3, arg1[0]) - var x143 uint64 - var x144 fiat_pasta_fq_uint1 - x143, x144 = fiat_pasta_fq_addcarryx_u64(x142, x139, 0x0) - var x145 uint64 - var x146 fiat_pasta_fq_uint1 - x145, x146 = fiat_pasta_fq_addcarryx_u64(x140, x137, x144) - var x147 uint64 - var x148 fiat_pasta_fq_uint1 - x147, x148 = fiat_pasta_fq_addcarryx_u64(x138, x135, x146) - x149 := (uint64(x148) + x136) - var x150 uint64 - var x151 fiat_pasta_fq_uint1 - x150, x151 = fiat_pasta_fq_addcarryx_u64(x126, x141, 0x0) - var x152 uint64 - var x153 fiat_pasta_fq_uint1 - x152, x153 = fiat_pasta_fq_addcarryx_u64(x128, x143, x151) - var x154 uint64 - var x155 fiat_pasta_fq_uint1 - x154, x155 = fiat_pasta_fq_addcarryx_u64(x130, x145, x153) - var x156 uint64 - var x157 fiat_pasta_fq_uint1 - x156, x157 = fiat_pasta_fq_addcarryx_u64(x132, x147, x155) - var x158 uint64 - var x159 fiat_pasta_fq_uint1 - x158, x159 = fiat_pasta_fq_addcarryx_u64(x134, x149, x157) - var x160 uint64 - _, x160 = bits.Mul64(x150, 0x8c46eb20ffffffff) - var x162 uint64 - var x163 uint64 - x163, x162 = bits.Mul64(x160, 0x4000000000000000) - var x164 uint64 - var x165 uint64 - x165, x164 = bits.Mul64(x160, 0x224698fc0994a8dd) - var x166 uint64 - var x167 uint64 - x167, x166 = bits.Mul64(x160, 0x8c46eb2100000001) - var x168 uint64 - var x169 fiat_pasta_fq_uint1 - x168, x169 = fiat_pasta_fq_addcarryx_u64(x167, x164, 0x0) - x170 := (uint64(x169) + x165) - var x172 fiat_pasta_fq_uint1 - _, x172 = fiat_pasta_fq_addcarryx_u64(x150, x166, 0x0) - var x173 uint64 - var x174 fiat_pasta_fq_uint1 - x173, x174 = fiat_pasta_fq_addcarryx_u64(x152, x168, x172) - var x175 uint64 - var x176 fiat_pasta_fq_uint1 - x175, x176 = fiat_pasta_fq_addcarryx_u64(x154, x170, x174) - var x177 uint64 - var x178 fiat_pasta_fq_uint1 - x177, x178 = fiat_pasta_fq_addcarryx_u64(x156, x162, x176) - var x179 uint64 - var x180 fiat_pasta_fq_uint1 - x179, x180 = fiat_pasta_fq_addcarryx_u64(x158, x163, x178) - x181 := (uint64(x180) + uint64(x159)) - var x182 uint64 - var x183 fiat_pasta_fq_uint1 - x182, x183 = fiat_pasta_fq_subborrowx_u64(x173, 0x8c46eb2100000001, 0x0) - var x184 uint64 - var x185 fiat_pasta_fq_uint1 - x184, x185 = fiat_pasta_fq_subborrowx_u64(x175, 0x224698fc0994a8dd, x183) - var x186 uint64 - var x187 fiat_pasta_fq_uint1 - x186, x187 = fiat_pasta_fq_subborrowx_u64(x177, uint64(0x0), x185) - var x188 uint64 - var x189 fiat_pasta_fq_uint1 - x188, x189 = fiat_pasta_fq_subborrowx_u64(x179, 0x4000000000000000, x187) - var x191 fiat_pasta_fq_uint1 - _, x191 = fiat_pasta_fq_subborrowx_u64(x181, uint64(0x0), x189) - var x192 uint64 - fiat_pasta_fq_cmovznz_u64(&x192, x191, x182, x173) - var x193 uint64 - fiat_pasta_fq_cmovznz_u64(&x193, x191, x184, x175) - var x194 uint64 - fiat_pasta_fq_cmovznz_u64(&x194, x191, x186, x177) - var x195 uint64 - fiat_pasta_fq_cmovznz_u64(&x195, x191, x188, x179) - out1[0] = x192 - out1[1] = x193 - out1[2] = x194 - out1[3] = x195 -} - -// The function fiat_pasta_fq_add adds two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_add( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, - arg2 *fiat_pasta_fq_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fq_uint1 - x1, x2 = fiat_pasta_fq_addcarryx_u64(arg1[0], arg2[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fq_uint1 - x3, x4 = fiat_pasta_fq_addcarryx_u64(arg1[1], arg2[1], x2) - var x5 uint64 - var x6 fiat_pasta_fq_uint1 - x5, x6 = fiat_pasta_fq_addcarryx_u64(arg1[2], arg2[2], x4) - var x7 uint64 - var x8 fiat_pasta_fq_uint1 - x7, x8 = fiat_pasta_fq_addcarryx_u64(arg1[3], arg2[3], x6) - var x9 uint64 - var x10 fiat_pasta_fq_uint1 - x9, x10 = fiat_pasta_fq_subborrowx_u64(x1, 0x8c46eb2100000001, 0x0) - var x11 uint64 - var x12 fiat_pasta_fq_uint1 - x11, x12 = fiat_pasta_fq_subborrowx_u64(x3, 0x224698fc0994a8dd, x10) - var x13 uint64 - var x14 fiat_pasta_fq_uint1 - x13, x14 = fiat_pasta_fq_subborrowx_u64(x5, uint64(0x0), x12) - var x15 uint64 - var x16 fiat_pasta_fq_uint1 - x15, x16 = fiat_pasta_fq_subborrowx_u64(x7, 0x4000000000000000, x14) - var x18 fiat_pasta_fq_uint1 - _, x18 = fiat_pasta_fq_subborrowx_u64(uint64(x8), uint64(0x0), x16) - var x19 uint64 - fiat_pasta_fq_cmovznz_u64(&x19, x18, x9, x1) - var x20 uint64 - fiat_pasta_fq_cmovznz_u64(&x20, x18, x11, x3) - var x21 uint64 - fiat_pasta_fq_cmovznz_u64(&x21, x18, x13, x5) - var x22 uint64 - fiat_pasta_fq_cmovznz_u64(&x22, x18, x15, x7) - out1[0] = x19 - out1[1] = x20 - out1[2] = x21 - out1[3] = x22 -} - -// The function fiat_pasta_fq_sub subtracts two field elements in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// 0 ≤ eval arg2 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_sub( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, - arg2 *fiat_pasta_fq_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fq_uint1 - x1, x2 = fiat_pasta_fq_subborrowx_u64(arg1[0], arg2[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fq_uint1 - x3, x4 = fiat_pasta_fq_subborrowx_u64(arg1[1], arg2[1], x2) - var x5 uint64 - var x6 fiat_pasta_fq_uint1 - x5, x6 = fiat_pasta_fq_subborrowx_u64(arg1[2], arg2[2], x4) - var x7 uint64 - var x8 fiat_pasta_fq_uint1 - x7, x8 = fiat_pasta_fq_subborrowx_u64(arg1[3], arg2[3], x6) - var x9 uint64 - fiat_pasta_fq_cmovznz_u64(&x9, x8, uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 fiat_pasta_fq_uint1 - x10, x11 = fiat_pasta_fq_addcarryx_u64(x1, (x9 & 0x8c46eb2100000001), 0x0) - var x12 uint64 - var x13 fiat_pasta_fq_uint1 - x12, x13 = fiat_pasta_fq_addcarryx_u64(x3, (x9 & 0x224698fc0994a8dd), x11) - var x14 uint64 - var x15 fiat_pasta_fq_uint1 - x14, x15 = fiat_pasta_fq_addcarryx_u64(x5, uint64(0x0), x13) - var x16 uint64 - x16, _ = fiat_pasta_fq_addcarryx_u64(x7, (x9 & 0x4000000000000000), x15) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// The function fiat_pasta_fq_opp negates a field element in the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_opp( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, -) { - var x1 uint64 - var x2 fiat_pasta_fq_uint1 - x1, x2 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), arg1[0], 0x0) - var x3 uint64 - var x4 fiat_pasta_fq_uint1 - x3, x4 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), arg1[1], x2) - var x5 uint64 - var x6 fiat_pasta_fq_uint1 - x5, x6 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), arg1[2], x4) - var x7 uint64 - var x8 fiat_pasta_fq_uint1 - x7, x8 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), arg1[3], x6) - var x9 uint64 - fiat_pasta_fq_cmovznz_u64(&x9, x8, uint64(0x0), 0xffffffffffffffff) - var x10 uint64 - var x11 fiat_pasta_fq_uint1 - x10, x11 = fiat_pasta_fq_addcarryx_u64(x1, (x9 & 0x8c46eb2100000001), 0x0) - var x12 uint64 - var x13 fiat_pasta_fq_uint1 - x12, x13 = fiat_pasta_fq_addcarryx_u64(x3, (x9 & 0x224698fc0994a8dd), x11) - var x14 uint64 - var x15 fiat_pasta_fq_uint1 - x14, x15 = fiat_pasta_fq_addcarryx_u64(x5, uint64(0x0), x13) - var x16 uint64 - x16, _ = fiat_pasta_fq_addcarryx_u64(x7, (x9 & 0x4000000000000000), x15) - out1[0] = x10 - out1[1] = x12 - out1[2] = x14 - out1[3] = x16 -} - -// The function fiat_pasta_fq_from_montgomery translates a field element out of the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_from_montgomery( - out1 *fiat_pasta_fq_non_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_montgomery_domain_field_element, -) { - x1 := arg1[0] - var x2 uint64 - _, x2 = bits.Mul64(x1, 0x8c46eb20ffffffff) - var x4 uint64 - var x5 uint64 - x5, x4 = bits.Mul64(x2, 0x4000000000000000) - var x6 uint64 - var x7 uint64 - x7, x6 = bits.Mul64(x2, 0x224698fc0994a8dd) - var x8 uint64 - var x9 uint64 - x9, x8 = bits.Mul64(x2, 0x8c46eb2100000001) - var x10 uint64 - var x11 fiat_pasta_fq_uint1 - x10, x11 = fiat_pasta_fq_addcarryx_u64(x9, x6, 0x0) - var x13 fiat_pasta_fq_uint1 - _, x13 = fiat_pasta_fq_addcarryx_u64(x1, x8, 0x0) - var x14 uint64 - var x15 fiat_pasta_fq_uint1 - x14, x15 = fiat_pasta_fq_addcarryx_u64(uint64(0x0), x10, x13) - var x16 uint64 - var x17 fiat_pasta_fq_uint1 - x16, x17 = fiat_pasta_fq_addcarryx_u64(x14, arg1[1], 0x0) - var x18 uint64 - _, x18 = bits.Mul64(x16, 0x8c46eb20ffffffff) - var x20 uint64 - var x21 uint64 - x21, x20 = bits.Mul64(x18, 0x4000000000000000) - var x22 uint64 - var x23 uint64 - x23, x22 = bits.Mul64(x18, 0x224698fc0994a8dd) - var x24 uint64 - var x25 uint64 - x25, x24 = bits.Mul64(x18, 0x8c46eb2100000001) - var x26 uint64 - var x27 fiat_pasta_fq_uint1 - x26, x27 = fiat_pasta_fq_addcarryx_u64(x25, x22, 0x0) - var x29 fiat_pasta_fq_uint1 - _, x29 = fiat_pasta_fq_addcarryx_u64(x16, x24, 0x0) - var x30 uint64 - var x31 fiat_pasta_fq_uint1 - x30, x31 = fiat_pasta_fq_addcarryx_u64( - (uint64(x17) + (uint64(x15) + (uint64(x11) + x7))), - x26, - x29, - ) - var x32 uint64 - var x33 fiat_pasta_fq_uint1 - x32, x33 = fiat_pasta_fq_addcarryx_u64(x4, (uint64(x27) + x23), x31) - var x34 uint64 - var x35 fiat_pasta_fq_uint1 - x34, x35 = fiat_pasta_fq_addcarryx_u64(x5, x20, x33) - var x36 uint64 - var x37 fiat_pasta_fq_uint1 - x36, x37 = fiat_pasta_fq_addcarryx_u64(x30, arg1[2], 0x0) - var x38 uint64 - var x39 fiat_pasta_fq_uint1 - x38, x39 = fiat_pasta_fq_addcarryx_u64(x32, uint64(0x0), x37) - var x40 uint64 - var x41 fiat_pasta_fq_uint1 - x40, x41 = fiat_pasta_fq_addcarryx_u64(x34, uint64(0x0), x39) - var x42 uint64 - _, x42 = bits.Mul64(x36, 0x8c46eb20ffffffff) - var x44 uint64 - var x45 uint64 - x45, x44 = bits.Mul64(x42, 0x4000000000000000) - var x46 uint64 - var x47 uint64 - x47, x46 = bits.Mul64(x42, 0x224698fc0994a8dd) - var x48 uint64 - var x49 uint64 - x49, x48 = bits.Mul64(x42, 0x8c46eb2100000001) - var x50 uint64 - var x51 fiat_pasta_fq_uint1 - x50, x51 = fiat_pasta_fq_addcarryx_u64(x49, x46, 0x0) - var x53 fiat_pasta_fq_uint1 - _, x53 = fiat_pasta_fq_addcarryx_u64(x36, x48, 0x0) - var x54 uint64 - var x55 fiat_pasta_fq_uint1 - x54, x55 = fiat_pasta_fq_addcarryx_u64(x38, x50, x53) - var x56 uint64 - var x57 fiat_pasta_fq_uint1 - x56, x57 = fiat_pasta_fq_addcarryx_u64(x40, (uint64(x51) + x47), x55) - var x58 uint64 - var x59 fiat_pasta_fq_uint1 - x58, x59 = fiat_pasta_fq_addcarryx_u64((uint64(x41) + (uint64(x35) + x21)), x44, x57) - var x60 uint64 - var x61 fiat_pasta_fq_uint1 - x60, x61 = fiat_pasta_fq_addcarryx_u64(x54, arg1[3], 0x0) - var x62 uint64 - var x63 fiat_pasta_fq_uint1 - x62, x63 = fiat_pasta_fq_addcarryx_u64(x56, uint64(0x0), x61) - var x64 uint64 - var x65 fiat_pasta_fq_uint1 - x64, x65 = fiat_pasta_fq_addcarryx_u64(x58, uint64(0x0), x63) - var x66 uint64 - _, x66 = bits.Mul64(x60, 0x8c46eb20ffffffff) - var x68 uint64 - var x69 uint64 - x69, x68 = bits.Mul64(x66, 0x4000000000000000) - var x70 uint64 - var x71 uint64 - x71, x70 = bits.Mul64(x66, 0x224698fc0994a8dd) - var x72 uint64 - var x73 uint64 - x73, x72 = bits.Mul64(x66, 0x8c46eb2100000001) - var x74 uint64 - var x75 fiat_pasta_fq_uint1 - x74, x75 = fiat_pasta_fq_addcarryx_u64(x73, x70, 0x0) - var x77 fiat_pasta_fq_uint1 - _, x77 = fiat_pasta_fq_addcarryx_u64(x60, x72, 0x0) - var x78 uint64 - var x79 fiat_pasta_fq_uint1 - x78, x79 = fiat_pasta_fq_addcarryx_u64(x62, x74, x77) - var x80 uint64 - var x81 fiat_pasta_fq_uint1 - x80, x81 = fiat_pasta_fq_addcarryx_u64(x64, (uint64(x75) + x71), x79) - var x82 uint64 - var x83 fiat_pasta_fq_uint1 - x82, x83 = fiat_pasta_fq_addcarryx_u64((uint64(x65) + (uint64(x59) + x45)), x68, x81) - x84 := (uint64(x83) + x69) - var x85 uint64 - var x86 fiat_pasta_fq_uint1 - x85, x86 = fiat_pasta_fq_subborrowx_u64(x78, 0x8c46eb2100000001, 0x0) - var x87 uint64 - var x88 fiat_pasta_fq_uint1 - x87, x88 = fiat_pasta_fq_subborrowx_u64(x80, 0x224698fc0994a8dd, x86) - var x89 uint64 - var x90 fiat_pasta_fq_uint1 - x89, x90 = fiat_pasta_fq_subborrowx_u64(x82, uint64(0x0), x88) - var x91 uint64 - var x92 fiat_pasta_fq_uint1 - x91, x92 = fiat_pasta_fq_subborrowx_u64(x84, 0x4000000000000000, x90) - var x94 fiat_pasta_fq_uint1 - _, x94 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), uint64(0x0), x92) - var x95 uint64 - fiat_pasta_fq_cmovznz_u64(&x95, x94, x85, x78) - var x96 uint64 - fiat_pasta_fq_cmovznz_u64(&x96, x94, x87, x80) - var x97 uint64 - fiat_pasta_fq_cmovznz_u64(&x97, x94, x89, x82) - var x98 uint64 - fiat_pasta_fq_cmovznz_u64(&x98, x94, x91, x84) - out1[0] = x95 - out1[1] = x96 - out1[2] = x97 - out1[3] = x98 -} - -// The function fiat_pasta_fq_to_montgomery translates a field element into the Montgomery domain. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// eval (from_montgomery out1) mod m = eval arg1 mod m -// 0 ≤ eval out1 < m -func fiat_pasta_fq_to_montgomery( - out1 *fiat_pasta_fq_montgomery_domain_field_element, - arg1 *fiat_pasta_fq_non_montgomery_domain_field_element, -) { - x1 := arg1[1] - x2 := arg1[2] - x3 := arg1[3] - x4 := arg1[0] - var x5 uint64 - var x6 uint64 - x6, x5 = bits.Mul64(x4, 0x96d41af7ccfdaa9) - var x7 uint64 - var x8 uint64 - x8, x7 = bits.Mul64(x4, 0x7fae231004ccf590) - var x9 uint64 - var x10 uint64 - x10, x9 = bits.Mul64(x4, 0x67bb433d891a16e3) - var x11 uint64 - var x12 uint64 - x12, x11 = bits.Mul64(x4, 0xfc9678ff0000000f) - var x13 uint64 - var x14 fiat_pasta_fq_uint1 - x13, x14 = fiat_pasta_fq_addcarryx_u64(x12, x9, 0x0) - var x15 uint64 - var x16 fiat_pasta_fq_uint1 - x15, x16 = fiat_pasta_fq_addcarryx_u64(x10, x7, x14) - var x17 uint64 - var x18 fiat_pasta_fq_uint1 - x17, x18 = fiat_pasta_fq_addcarryx_u64(x8, x5, x16) - var x19 uint64 - _, x19 = bits.Mul64(x11, 0x8c46eb20ffffffff) - var x21 uint64 - var x22 uint64 - x22, x21 = bits.Mul64(x19, 0x4000000000000000) - var x23 uint64 - var x24 uint64 - x24, x23 = bits.Mul64(x19, 0x224698fc0994a8dd) - var x25 uint64 - var x26 uint64 - x26, x25 = bits.Mul64(x19, 0x8c46eb2100000001) - var x27 uint64 - var x28 fiat_pasta_fq_uint1 - x27, x28 = fiat_pasta_fq_addcarryx_u64(x26, x23, 0x0) - var x30 fiat_pasta_fq_uint1 - _, x30 = fiat_pasta_fq_addcarryx_u64(x11, x25, 0x0) - var x31 uint64 - var x32 fiat_pasta_fq_uint1 - x31, x32 = fiat_pasta_fq_addcarryx_u64(x13, x27, x30) - var x33 uint64 - var x34 fiat_pasta_fq_uint1 - x33, x34 = fiat_pasta_fq_addcarryx_u64(x15, (uint64(x28) + x24), x32) - var x35 uint64 - var x36 fiat_pasta_fq_uint1 - x35, x36 = fiat_pasta_fq_addcarryx_u64(x17, x21, x34) - var x37 uint64 - var x38 uint64 - x38, x37 = bits.Mul64(x1, 0x96d41af7ccfdaa9) - var x39 uint64 - var x40 uint64 - x40, x39 = bits.Mul64(x1, 0x7fae231004ccf590) - var x41 uint64 - var x42 uint64 - x42, x41 = bits.Mul64(x1, 0x67bb433d891a16e3) - var x43 uint64 - var x44 uint64 - x44, x43 = bits.Mul64(x1, 0xfc9678ff0000000f) - var x45 uint64 - var x46 fiat_pasta_fq_uint1 - x45, x46 = fiat_pasta_fq_addcarryx_u64(x44, x41, 0x0) - var x47 uint64 - var x48 fiat_pasta_fq_uint1 - x47, x48 = fiat_pasta_fq_addcarryx_u64(x42, x39, x46) - var x49 uint64 - var x50 fiat_pasta_fq_uint1 - x49, x50 = fiat_pasta_fq_addcarryx_u64(x40, x37, x48) - var x51 uint64 - var x52 fiat_pasta_fq_uint1 - x51, x52 = fiat_pasta_fq_addcarryx_u64(x31, x43, 0x0) - var x53 uint64 - var x54 fiat_pasta_fq_uint1 - x53, x54 = fiat_pasta_fq_addcarryx_u64(x33, x45, x52) - var x55 uint64 - var x56 fiat_pasta_fq_uint1 - x55, x56 = fiat_pasta_fq_addcarryx_u64(x35, x47, x54) - var x57 uint64 - var x58 fiat_pasta_fq_uint1 - x57, x58 = fiat_pasta_fq_addcarryx_u64(((uint64(x36) + (uint64(x18) + x6)) + x22), x49, x56) - var x59 uint64 - _, x59 = bits.Mul64(x51, 0x8c46eb20ffffffff) - var x61 uint64 - var x62 uint64 - x62, x61 = bits.Mul64(x59, 0x4000000000000000) - var x63 uint64 - var x64 uint64 - x64, x63 = bits.Mul64(x59, 0x224698fc0994a8dd) - var x65 uint64 - var x66 uint64 - x66, x65 = bits.Mul64(x59, 0x8c46eb2100000001) - var x67 uint64 - var x68 fiat_pasta_fq_uint1 - x67, x68 = fiat_pasta_fq_addcarryx_u64(x66, x63, 0x0) - var x70 fiat_pasta_fq_uint1 - _, x70 = fiat_pasta_fq_addcarryx_u64(x51, x65, 0x0) - var x71 uint64 - var x72 fiat_pasta_fq_uint1 - x71, x72 = fiat_pasta_fq_addcarryx_u64(x53, x67, x70) - var x73 uint64 - var x74 fiat_pasta_fq_uint1 - x73, x74 = fiat_pasta_fq_addcarryx_u64(x55, (uint64(x68) + x64), x72) - var x75 uint64 - var x76 fiat_pasta_fq_uint1 - x75, x76 = fiat_pasta_fq_addcarryx_u64(x57, x61, x74) - var x77 uint64 - var x78 uint64 - x78, x77 = bits.Mul64(x2, 0x96d41af7ccfdaa9) - var x79 uint64 - var x80 uint64 - x80, x79 = bits.Mul64(x2, 0x7fae231004ccf590) - var x81 uint64 - var x82 uint64 - x82, x81 = bits.Mul64(x2, 0x67bb433d891a16e3) - var x83 uint64 - var x84 uint64 - x84, x83 = bits.Mul64(x2, 0xfc9678ff0000000f) - var x85 uint64 - var x86 fiat_pasta_fq_uint1 - x85, x86 = fiat_pasta_fq_addcarryx_u64(x84, x81, 0x0) - var x87 uint64 - var x88 fiat_pasta_fq_uint1 - x87, x88 = fiat_pasta_fq_addcarryx_u64(x82, x79, x86) - var x89 uint64 - var x90 fiat_pasta_fq_uint1 - x89, x90 = fiat_pasta_fq_addcarryx_u64(x80, x77, x88) - var x91 uint64 - var x92 fiat_pasta_fq_uint1 - x91, x92 = fiat_pasta_fq_addcarryx_u64(x71, x83, 0x0) - var x93 uint64 - var x94 fiat_pasta_fq_uint1 - x93, x94 = fiat_pasta_fq_addcarryx_u64(x73, x85, x92) - var x95 uint64 - var x96 fiat_pasta_fq_uint1 - x95, x96 = fiat_pasta_fq_addcarryx_u64(x75, x87, x94) - var x97 uint64 - var x98 fiat_pasta_fq_uint1 - x97, x98 = fiat_pasta_fq_addcarryx_u64( - ((uint64(x76) + (uint64(x58) + (uint64(x50) + x38))) + x62), - x89, - x96, - ) - var x99 uint64 - _, x99 = bits.Mul64(x91, 0x8c46eb20ffffffff) - var x101 uint64 - var x102 uint64 - x102, x101 = bits.Mul64(x99, 0x4000000000000000) - var x103 uint64 - var x104 uint64 - x104, x103 = bits.Mul64(x99, 0x224698fc0994a8dd) - var x105 uint64 - var x106 uint64 - x106, x105 = bits.Mul64(x99, 0x8c46eb2100000001) - var x107 uint64 - var x108 fiat_pasta_fq_uint1 - x107, x108 = fiat_pasta_fq_addcarryx_u64(x106, x103, 0x0) - var x110 fiat_pasta_fq_uint1 - _, x110 = fiat_pasta_fq_addcarryx_u64(x91, x105, 0x0) - var x111 uint64 - var x112 fiat_pasta_fq_uint1 - x111, x112 = fiat_pasta_fq_addcarryx_u64(x93, x107, x110) - var x113 uint64 - var x114 fiat_pasta_fq_uint1 - x113, x114 = fiat_pasta_fq_addcarryx_u64(x95, (uint64(x108) + x104), x112) - var x115 uint64 - var x116 fiat_pasta_fq_uint1 - x115, x116 = fiat_pasta_fq_addcarryx_u64(x97, x101, x114) - var x117 uint64 - var x118 uint64 - x118, x117 = bits.Mul64(x3, 0x96d41af7ccfdaa9) - var x119 uint64 - var x120 uint64 - x120, x119 = bits.Mul64(x3, 0x7fae231004ccf590) - var x121 uint64 - var x122 uint64 - x122, x121 = bits.Mul64(x3, 0x67bb433d891a16e3) - var x123 uint64 - var x124 uint64 - x124, x123 = bits.Mul64(x3, 0xfc9678ff0000000f) - var x125 uint64 - var x126 fiat_pasta_fq_uint1 - x125, x126 = fiat_pasta_fq_addcarryx_u64(x124, x121, 0x0) - var x127 uint64 - var x128 fiat_pasta_fq_uint1 - x127, x128 = fiat_pasta_fq_addcarryx_u64(x122, x119, x126) - var x129 uint64 - var x130 fiat_pasta_fq_uint1 - x129, x130 = fiat_pasta_fq_addcarryx_u64(x120, x117, x128) - var x131 uint64 - var x132 fiat_pasta_fq_uint1 - x131, x132 = fiat_pasta_fq_addcarryx_u64(x111, x123, 0x0) - var x133 uint64 - var x134 fiat_pasta_fq_uint1 - x133, x134 = fiat_pasta_fq_addcarryx_u64(x113, x125, x132) - var x135 uint64 - var x136 fiat_pasta_fq_uint1 - x135, x136 = fiat_pasta_fq_addcarryx_u64(x115, x127, x134) - var x137 uint64 - var x138 fiat_pasta_fq_uint1 - x137, x138 = fiat_pasta_fq_addcarryx_u64( - ((uint64(x116) + (uint64(x98) + (uint64(x90) + x78))) + x102), - x129, - x136, - ) - var x139 uint64 - _, x139 = bits.Mul64(x131, 0x8c46eb20ffffffff) - var x141 uint64 - var x142 uint64 - x142, x141 = bits.Mul64(x139, 0x4000000000000000) - var x143 uint64 - var x144 uint64 - x144, x143 = bits.Mul64(x139, 0x224698fc0994a8dd) - var x145 uint64 - var x146 uint64 - x146, x145 = bits.Mul64(x139, 0x8c46eb2100000001) - var x147 uint64 - var x148 fiat_pasta_fq_uint1 - x147, x148 = fiat_pasta_fq_addcarryx_u64(x146, x143, 0x0) - var x150 fiat_pasta_fq_uint1 - _, x150 = fiat_pasta_fq_addcarryx_u64(x131, x145, 0x0) - var x151 uint64 - var x152 fiat_pasta_fq_uint1 - x151, x152 = fiat_pasta_fq_addcarryx_u64(x133, x147, x150) - var x153 uint64 - var x154 fiat_pasta_fq_uint1 - x153, x154 = fiat_pasta_fq_addcarryx_u64(x135, (uint64(x148) + x144), x152) - var x155 uint64 - var x156 fiat_pasta_fq_uint1 - x155, x156 = fiat_pasta_fq_addcarryx_u64(x137, x141, x154) - x157 := ((uint64(x156) + (uint64(x138) + (uint64(x130) + x118))) + x142) - var x158 uint64 - var x159 fiat_pasta_fq_uint1 - x158, x159 = fiat_pasta_fq_subborrowx_u64(x151, 0x8c46eb2100000001, 0x0) - var x160 uint64 - var x161 fiat_pasta_fq_uint1 - x160, x161 = fiat_pasta_fq_subborrowx_u64(x153, 0x224698fc0994a8dd, x159) - var x162 uint64 - var x163 fiat_pasta_fq_uint1 - x162, x163 = fiat_pasta_fq_subborrowx_u64(x155, uint64(0x0), x161) - var x164 uint64 - var x165 fiat_pasta_fq_uint1 - x164, x165 = fiat_pasta_fq_subborrowx_u64(x157, 0x4000000000000000, x163) - var x167 fiat_pasta_fq_uint1 - _, x167 = fiat_pasta_fq_subborrowx_u64(uint64(0x0), uint64(0x0), x165) - var x168 uint64 - fiat_pasta_fq_cmovznz_u64(&x168, x167, x158, x151) - var x169 uint64 - fiat_pasta_fq_cmovznz_u64(&x169, x167, x160, x153) - var x170 uint64 - fiat_pasta_fq_cmovznz_u64(&x170, x167, x162, x155) - var x171 uint64 - fiat_pasta_fq_cmovznz_u64(&x171, x167, x164, x157) - out1[0] = x168 - out1[1] = x169 - out1[2] = x170 - out1[3] = x171 -} - -// The function fiat_pasta_fq_selectznz is a multi-limb conditional select. -// -// Postconditions: -// -// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) -// -// Input Bounds: -// -// arg1: [0x0 ~> 0x1] -// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] -func fiat_pasta_fq_selectznz( - out1 *[4]uint64, - arg1 fiat_pasta_fq_uint1, - arg2 *[4]uint64, - arg3 *[4]uint64, -) { - var x1 uint64 - fiat_pasta_fq_cmovznz_u64(&x1, arg1, arg2[0], arg3[0]) - var x2 uint64 - fiat_pasta_fq_cmovznz_u64(&x2, arg1, arg2[1], arg3[1]) - var x3 uint64 - fiat_pasta_fq_cmovznz_u64(&x3, arg1, arg2[2], arg3[2]) - var x4 uint64 - fiat_pasta_fq_cmovznz_u64(&x4, arg1, arg2[3], arg3[3]) - out1[0] = x1 - out1[1] = x2 - out1[2] = x3 - out1[3] = x4 -} - -// The function fiat_pasta_fq_to_bytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ eval arg1 < m -// -// Postconditions: -// -// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x7fffffffffffffff]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] -func fiat_pasta_fq_to_bytes(out1 *[32]uint8, arg1 *[4]uint64) { - x1 := arg1[3] - x2 := arg1[2] - x3 := arg1[1] - x4 := arg1[0] - x5 := (uint8(x4) & 0xff) - x6 := (x4 >> 8) - x7 := (uint8(x6) & 0xff) - x8 := (x6 >> 8) - x9 := (uint8(x8) & 0xff) - x10 := (x8 >> 8) - x11 := (uint8(x10) & 0xff) - x12 := (x10 >> 8) - x13 := (uint8(x12) & 0xff) - x14 := (x12 >> 8) - x15 := (uint8(x14) & 0xff) - x16 := (x14 >> 8) - x17 := (uint8(x16) & 0xff) - x18 := uint8((x16 >> 8)) - x19 := (uint8(x3) & 0xff) - x20 := (x3 >> 8) - x21 := (uint8(x20) & 0xff) - x22 := (x20 >> 8) - x23 := (uint8(x22) & 0xff) - x24 := (x22 >> 8) - x25 := (uint8(x24) & 0xff) - x26 := (x24 >> 8) - x27 := (uint8(x26) & 0xff) - x28 := (x26 >> 8) - x29 := (uint8(x28) & 0xff) - x30 := (x28 >> 8) - x31 := (uint8(x30) & 0xff) - x32 := uint8((x30 >> 8)) - x33 := (uint8(x2) & 0xff) - x34 := (x2 >> 8) - x35 := (uint8(x34) & 0xff) - x36 := (x34 >> 8) - x37 := (uint8(x36) & 0xff) - x38 := (x36 >> 8) - x39 := (uint8(x38) & 0xff) - x40 := (x38 >> 8) - x41 := (uint8(x40) & 0xff) - x42 := (x40 >> 8) - x43 := (uint8(x42) & 0xff) - x44 := (x42 >> 8) - x45 := (uint8(x44) & 0xff) - x46 := uint8((x44 >> 8)) - x47 := (uint8(x1) & 0xff) - x48 := (x1 >> 8) - x49 := (uint8(x48) & 0xff) - x50 := (x48 >> 8) - x51 := (uint8(x50) & 0xff) - x52 := (x50 >> 8) - x53 := (uint8(x52) & 0xff) - x54 := (x52 >> 8) - x55 := (uint8(x54) & 0xff) - x56 := (x54 >> 8) - x57 := (uint8(x56) & 0xff) - x58 := (x56 >> 8) - x59 := (uint8(x58) & 0xff) - x60 := uint8((x58 >> 8)) - out1[0] = x5 - out1[1] = x7 - out1[2] = x9 - out1[3] = x11 - out1[4] = x13 - out1[5] = x15 - out1[6] = x17 - out1[7] = x18 - out1[8] = x19 - out1[9] = x21 - out1[10] = x23 - out1[11] = x25 - out1[12] = x27 - out1[13] = x29 - out1[14] = x31 - out1[15] = x32 - out1[16] = x33 - out1[17] = x35 - out1[18] = x37 - out1[19] = x39 - out1[20] = x41 - out1[21] = x43 - out1[22] = x45 - out1[23] = x46 - out1[24] = x47 - out1[25] = x49 - out1[26] = x51 - out1[27] = x53 - out1[28] = x55 - out1[29] = x57 - out1[30] = x59 - out1[31] = x60 -} - -// The function fiat_pasta_fq_from_bytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. -// -// Preconditions: -// -// 0 ≤ bytes_eval arg1 < m -// -// Postconditions: -// -// eval out1 mod m = bytes_eval arg1 mod m -// 0 ≤ eval out1 < m -// -// Input Bounds: -// -// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] -// -// Output Bounds: -// -// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x7fffffffffffffff]] -func fiat_pasta_fq_from_bytes(out1 *[4]uint64, arg1 *[32]uint8) { - x1 := (uint64(arg1[31]) << 56) - x2 := (uint64(arg1[30]) << 48) - x3 := (uint64(arg1[29]) << 40) - x4 := (uint64(arg1[28]) << 32) - x5 := (uint64(arg1[27]) << 24) - x6 := (uint64(arg1[26]) << 16) - x7 := (uint64(arg1[25]) << 8) - x8 := arg1[24] - x9 := (uint64(arg1[23]) << 56) - x10 := (uint64(arg1[22]) << 48) - x11 := (uint64(arg1[21]) << 40) - x12 := (uint64(arg1[20]) << 32) - x13 := (uint64(arg1[19]) << 24) - x14 := (uint64(arg1[18]) << 16) - x15 := (uint64(arg1[17]) << 8) - x16 := arg1[16] - x17 := (uint64(arg1[15]) << 56) - x18 := (uint64(arg1[14]) << 48) - x19 := (uint64(arg1[13]) << 40) - x20 := (uint64(arg1[12]) << 32) - x21 := (uint64(arg1[11]) << 24) - x22 := (uint64(arg1[10]) << 16) - x23 := (uint64(arg1[9]) << 8) - x24 := arg1[8] - x25 := (uint64(arg1[7]) << 56) - x26 := (uint64(arg1[6]) << 48) - x27 := (uint64(arg1[5]) << 40) - x28 := (uint64(arg1[4]) << 32) - x29 := (uint64(arg1[3]) << 24) - x30 := (uint64(arg1[2]) << 16) - x31 := (uint64(arg1[1]) << 8) - x32 := arg1[0] - x33 := (x31 + uint64(x32)) - x34 := (x30 + x33) - x35 := (x29 + x34) - x36 := (x28 + x35) - x37 := (x27 + x36) - x38 := (x26 + x37) - x39 := (x25 + x38) - x40 := (x23 + uint64(x24)) - x41 := (x22 + x40) - x42 := (x21 + x41) - x43 := (x20 + x42) - x44 := (x19 + x43) - x45 := (x18 + x44) - x46 := (x17 + x45) - x47 := (x15 + uint64(x16)) - x48 := (x14 + x47) - x49 := (x13 + x48) - x50 := (x12 + x49) - x51 := (x11 + x50) - x52 := (x10 + x51) - x53 := (x9 + x52) - x54 := (x7 + uint64(x8)) - x55 := (x6 + x54) - x56 := (x5 + x55) - x57 := (x4 + x56) - x58 := (x3 + x57) - x59 := (x2 + x58) - x60 := (x1 + x59) - out1[0] = x39 - out1[1] = x46 - out1[2] = x53 - out1[3] = x60 -} diff --git a/crypto/core/curves/native/pasta/pallas.go b/crypto/core/curves/native/pasta/pallas.go deleted file mode 100755 index d90bc3d9d..000000000 --- a/crypto/core/curves/native/pasta/pallas.go +++ /dev/null @@ -1,7 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package pasta diff --git a/crypto/core/curves/native/point.go b/crypto/core/curves/native/point.go deleted file mode 100755 index 1718df60f..000000000 --- a/crypto/core/curves/native/point.go +++ /dev/null @@ -1,471 +0,0 @@ -package native - -import ( - "crypto/sha256" - "crypto/sha512" - "fmt" - "hash" - "io" - "math/big" - - "github.com/pkg/errors" - "golang.org/x/crypto/blake2b" - "golang.org/x/crypto/sha3" -) - -// EllipticPointHashType is to indicate which expand operation is used -// for hash to curve operations -type EllipticPointHashType uint - -// EllipticPointHashName is to indicate the hash function is used -// for hash to curve operations -type EllipticPointHashName uint - -const ( - // XMD - use ExpandMsgXmd - XMD EllipticPointHashType = iota - // XOF - use ExpandMsgXof - XOF -) - -const ( - SHA256 EllipticPointHashName = iota - SHA512 - SHA3_256 - SHA3_384 - SHA3_512 - BLAKE2B - SHAKE128 - SHAKE256 -) - -// EllipticPoint represents a Weierstrauss elliptic curve point -type EllipticPoint struct { - X *Field - Y *Field - Z *Field - Params *EllipticPointParams - Arithmetic EllipticPointArithmetic -} - -// EllipticPointParams are the Weierstrauss curve parameters -// such as the name, the coefficients the generator point, -// and the prime bit size -type EllipticPointParams struct { - Name string - A *Field - B *Field - Gx *Field - Gy *Field - BitSize int -} - -// EllipticPointHasher is the type of hashing methods for -// hashing byte sequences to curve point. -type EllipticPointHasher struct { - name EllipticPointHashName - hashType EllipticPointHashType - xmd hash.Hash - xof sha3.ShakeHash -} - -// Name returns the hash name for this hasher -func (e *EllipticPointHasher) Name() string { - return e.name.String() -} - -// Type returns the hash type for this hasher -func (e *EllipticPointHasher) Type() EllipticPointHashType { - return e.hashType -} - -// Xmd returns the hash method for ExpandMsgXmd -func (e *EllipticPointHasher) Xmd() hash.Hash { - return e.xmd -} - -// Xof returns the hash method for ExpandMsgXof -func (e *EllipticPointHasher) Xof() sha3.ShakeHash { - return e.xof -} - -// EllipticPointHasherSha256 creates a point hasher that uses Sha256 -func EllipticPointHasherSha256() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHA256, - hashType: XMD, - xmd: sha256.New(), - } -} - -// EllipticPointHasherSha512 creates a point hasher that uses Sha512 -func EllipticPointHasherSha512() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHA512, - hashType: XMD, - xmd: sha512.New(), - } -} - -// EllipticPointHasherSha3256 creates a point hasher that uses Sha3256 -func EllipticPointHasherSha3256() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHA3_256, - hashType: XMD, - xmd: sha3.New256(), - } -} - -// EllipticPointHasherSha3384 creates a point hasher that uses Sha3384 -func EllipticPointHasherSha3384() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHA3_384, - hashType: XMD, - xmd: sha3.New384(), - } -} - -// EllipticPointHasherSha3512 creates a point hasher that uses Sha3512 -func EllipticPointHasherSha3512() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHA3_512, - hashType: XMD, - xmd: sha3.New512(), - } -} - -// EllipticPointHasherBlake2b creates a point hasher that uses Blake2b -func EllipticPointHasherBlake2b() *EllipticPointHasher { - h, _ := blake2b.New(64, []byte{}) - return &EllipticPointHasher{ - name: BLAKE2B, - hashType: XMD, - xmd: h, - } -} - -// EllipticPointHasherShake128 creates a point hasher that uses Shake128 -func EllipticPointHasherShake128() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHAKE128, - hashType: XOF, - xof: sha3.NewShake128(), - } -} - -// EllipticPointHasherShake256 creates a point hasher that uses Shake256 -func EllipticPointHasherShake256() *EllipticPointHasher { - return &EllipticPointHasher{ - name: SHAKE128, - hashType: XOF, - xof: sha3.NewShake256(), - } -} - -// EllipticPointArithmetic are the methods that specific curves -// need to implement for higher abstractions to wrap the point -type EllipticPointArithmetic interface { - // Hash a byte sequence to the curve using the specified hasher - // and dst and store the result in out - Hash(out *EllipticPoint, hasher *EllipticPointHasher, bytes, dst []byte) error - // Double arg and store the result in out - Double(out, arg *EllipticPoint) - // Add arg1 with arg2 and store the result in out - Add(out, arg1, arg2 *EllipticPoint) - // IsOnCurve tests arg if it represents a valid point on the curve - IsOnCurve(arg *EllipticPoint) bool - // ToAffine converts arg to affine coordinates storing the result in out - ToAffine(out, arg *EllipticPoint) - // RhsEq computes the right-hand side of the ecc equation - RhsEq(out, x *Field) -} - -func (t EllipticPointHashType) String() string { - switch t { - case XMD: - return "XMD" - case XOF: - return "XOF" - } - return "unknown" -} - -func (n EllipticPointHashName) String() string { - switch n { - case SHA256: - return "SHA-256" - case SHA512: - return "SHA-512" - case SHA3_256: - return "SHA3-256" - case SHA3_384: - return "SHA3-384" - case SHA3_512: - return "SHA3-512" - case BLAKE2B: - return "BLAKE2b" - case SHAKE128: - return "SHAKE-128" - case SHAKE256: - return "SHAKE-256" - } - return "unknown" -} - -// Random creates a random point on the curve -// from the specified reader -func (p *EllipticPoint) Random(reader io.Reader) (*EllipticPoint, error) { - var seed [WideFieldBytes]byte - n, err := reader.Read(seed[:]) - if err != nil { - return nil, errors.Wrap(err, "random could not read from stream") - } - if n != WideFieldBytes { - return nil, fmt.Errorf("insufficient bytes read %d when %d are needed", n, WideFieldBytes) - } - dst := []byte(fmt.Sprintf("%s_XMD:SHA-256_SSWU_RO_", p.Params.Name)) - err = p.Arithmetic.Hash(p, EllipticPointHasherSha256(), seed[:], dst) - if err != nil { - return nil, errors.Wrap(err, "ecc hash failed") - } - return p, nil -} - -// Hash uses the hasher to map bytes to a valid point -func (p *EllipticPoint) Hash(bytes []byte, hasher *EllipticPointHasher) (*EllipticPoint, error) { - dst := []byte(fmt.Sprintf("%s_%s:%s_SSWU_RO_", p.Params.Name, hasher.hashType, hasher.name)) - err := p.Arithmetic.Hash(p, hasher, bytes, dst) - if err != nil { - return nil, errors.Wrap(err, "hash failed") - } - return p, nil -} - -// Identity returns the identity point -func (p *EllipticPoint) Identity() *EllipticPoint { - p.X.SetZero() - p.Y.SetZero() - p.Z.SetZero() - return p -} - -// Generator returns the base point for the curve -func (p *EllipticPoint) Generator() *EllipticPoint { - p.X.Set(p.Params.Gx) - p.Y.Set(p.Params.Gy) - p.Z.SetOne() - return p -} - -// IsIdentity returns true if this point is at infinity -func (p *EllipticPoint) IsIdentity() bool { - return p.Z.IsZero() == 1 -} - -// Double this point -func (p *EllipticPoint) Double(point *EllipticPoint) *EllipticPoint { - p.Set(point) - p.Arithmetic.Double(p, point) - return p -} - -// Neg negates this point -func (p *EllipticPoint) Neg(point *EllipticPoint) *EllipticPoint { - p.Set(point) - p.Y.Neg(p.Y) - return p -} - -// Add adds the two points -func (p *EllipticPoint) Add(lhs, rhs *EllipticPoint) *EllipticPoint { - p.Set(lhs) - p.Arithmetic.Add(p, lhs, rhs) - return p -} - -// Sub subtracts the two points -func (p *EllipticPoint) Sub(lhs, rhs *EllipticPoint) *EllipticPoint { - p.Set(lhs) - p.Arithmetic.Add(p, lhs, new(EllipticPoint).Neg(rhs)) - return p -} - -// Mul multiplies this point by the input scalar -func (p *EllipticPoint) Mul(point *EllipticPoint, scalar *Field) *EllipticPoint { - bytes := scalar.Bytes() - precomputed := [16]*EllipticPoint{} - precomputed[0] = new(EllipticPoint).Set(point).Identity() - precomputed[1] = new(EllipticPoint).Set(point) - for i := 2; i < 16; i += 2 { - precomputed[i] = new(EllipticPoint).Set(point).Double(precomputed[i>>1]) - precomputed[i+1] = new(EllipticPoint).Set(point).Add(precomputed[i], point) - } - p.Identity() - for i := 0; i < 256; i += 4 { - // Brouwer / windowing method. window size of 4. - for j := 0; j < 4; j++ { - p.Double(p) - } - window := bytes[32-1-i>>3] >> (4 - i&0x04) & 0x0F - p.Add(p, precomputed[window]) - } - return p -} - -// Equal returns 1 if the two points are equal 0 otherwise. -func (p *EllipticPoint) Equal(rhs *EllipticPoint) int { - var x1, x2, y1, y2 Field - - x1.Arithmetic = p.X.Arithmetic - x2.Arithmetic = p.X.Arithmetic - y1.Arithmetic = p.Y.Arithmetic - y2.Arithmetic = p.Y.Arithmetic - - x1.Mul(p.X, rhs.Z) - x2.Mul(rhs.X, p.Z) - - y1.Mul(p.Y, rhs.Z) - y2.Mul(rhs.Y, p.Z) - - e1 := p.Z.IsZero() - e2 := rhs.Z.IsZero() - - // Both at infinity or coordinates are the same - return (e1 & e2) | (^e1 & ^e2)&x1.Equal(&x2)&y1.Equal(&y2) -} - -// Set copies clone into p -func (p *EllipticPoint) Set(clone *EllipticPoint) *EllipticPoint { - p.X = new(Field).Set(clone.X) - p.Y = new(Field).Set(clone.Y) - p.Z = new(Field).Set(clone.Z) - p.Params = clone.Params - p.Arithmetic = clone.Arithmetic - return p -} - -// BigInt returns the x and y as big.Ints in affine -func (p *EllipticPoint) BigInt() (x, y *big.Int) { - t := new(EllipticPoint).Set(p) - p.Arithmetic.ToAffine(t, p) - x = t.X.BigInt() - y = t.Y.BigInt() - return x, y -} - -// SetBigInt creates a point from affine x, y -// and returns the point if it is on the curve -func (p *EllipticPoint) SetBigInt(x, y *big.Int) (*EllipticPoint, error) { - xx := &Field{ - Params: p.Params.Gx.Params, - Arithmetic: p.Params.Gx.Arithmetic, - } - xx.SetBigInt(x) - yy := &Field{ - Params: p.Params.Gx.Params, - Arithmetic: p.Params.Gx.Arithmetic, - } - yy.SetBigInt(y) - pp := new(EllipticPoint).Set(p) - - zero := new(Field).Set(xx).SetZero() - one := new(Field).Set(xx).SetOne() - isIdentity := xx.IsZero() & yy.IsZero() - pp.X = xx.CMove(xx, zero, isIdentity) - pp.Y = yy.CMove(yy, zero, isIdentity) - pp.Z = one.CMove(one, zero, isIdentity) - if !p.Arithmetic.IsOnCurve(pp) && isIdentity == 0 { - return nil, fmt.Errorf("invalid coordinates") - } - return p.Set(pp), nil -} - -// GetX returns the affine X coordinate -func (p *EllipticPoint) GetX() *Field { - t := new(EllipticPoint).Set(p) - p.Arithmetic.ToAffine(t, p) - return t.X -} - -// GetY returns the affine Y coordinate -func (p *EllipticPoint) GetY() *Field { - t := new(EllipticPoint).Set(p) - p.Arithmetic.ToAffine(t, p) - return t.Y -} - -// IsOnCurve determines if this point represents a valid curve point -func (p *EllipticPoint) IsOnCurve() bool { - return p.Arithmetic.IsOnCurve(p) -} - -// ToAffine converts the point into affine coordinates -func (p *EllipticPoint) ToAffine(clone *EllipticPoint) *EllipticPoint { - p.Arithmetic.ToAffine(p, clone) - return p -} - -// SumOfProducts computes the multi-exponentiation for the specified -// points and scalars and stores the result in `p`. -// Returns an error if the lengths of the arguments is not equal. -func (p *EllipticPoint) SumOfProducts( - points []*EllipticPoint, - scalars []*Field, -) (*EllipticPoint, error) { - const Upper = 256 - const W = 4 - const Windows = Upper / W // careful--use ceiling division in case this doesn't divide evenly - if len(points) != len(scalars) { - return nil, fmt.Errorf("length mismatch") - } - - bucketSize := 1 << W - windows := make([]*EllipticPoint, Windows) - bytes := make([][32]byte, len(scalars)) - buckets := make([]*EllipticPoint, bucketSize) - - for i, scalar := range scalars { - bytes[i] = scalar.Bytes() - } - for i := range windows { - windows[i] = new(EllipticPoint).Set(p).Identity() - } - - for i := 0; i < bucketSize; i++ { - buckets[i] = new(EllipticPoint).Set(p).Identity() - } - - sum := new(EllipticPoint).Set(p) - - for j := 0; j < len(windows); j++ { - for i := 0; i < bucketSize; i++ { - buckets[i].Identity() - } - - for i := 0; i < len(scalars); i++ { - // j*W to get the nibble - // >> 3 to convert to byte, / 8 - // (W * j & W) gets the nibble, mod W - // 1 << W - 1 to get the offset - index := bytes[i][j*W>>3] >> (W * j & W) & (1< 0; i-- { - sum.Add(sum, buckets[i]) - windows[j].Add(windows[j], sum) - } - } - - p.Identity() - for i := len(windows) - 1; i >= 0; i-- { - for j := 0; j < W; j++ { - p.Double(p) - } - - p.Add(p, windows[i]) - } - return p, nil -} diff --git a/crypto/core/curves/p256_bench_test.go b/crypto/core/curves/p256_bench_test.go deleted file mode 100644 index 2202653dd..000000000 --- a/crypto/core/curves/p256_bench_test.go +++ /dev/null @@ -1,756 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - crand "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "fmt" - "io" - "math/big" - "testing" - - "github.com/sonr-io/sonr/crypto/core" -) - -func BenchmarkP256(b *testing.B) { - // 1000 points - - b.Run("1000 point hash - p256", func(b *testing.B) { - b.StopTimer() - points := make([][]byte, 1000) - for i := range points { - t := make([]byte, 32) - _, _ = crand.Read(t) - points[i] = t - } - acc := new(BenchPointP256).Identity() - b.StartTimer() - for _, pt := range points { - acc = acc.Hash(pt) - } - }) - - b.Run("1000 point hash - ct p256", func(b *testing.B) { - b.StopTimer() - points := make([][]byte, 1000) - for i := range points { - t := make([]byte, 32) - _, _ = crand.Read(t) - points[i] = t - } - acc := new(PointP256).Identity() - b.StartTimer() - for _, pt := range points { - acc = acc.Hash(pt) - } - }) - - b.Run("1000 point add - p256", func(b *testing.B) { - b.StopTimer() - points := make([]*BenchPointP256, 1000) - for i := range points { - points[i] = points[i].Random(crand.Reader).(*BenchPointP256) - } - acc := new(BenchPointP256).Identity() - b.StartTimer() - for _, pt := range points { - acc = acc.Add(pt) - } - }) - b.Run("1000 point add - ct p256", func(b *testing.B) { - b.StopTimer() - curve := P256() - points := make([]*PointP256, 1000) - for i := range points { - points[i] = curve.NewIdentityPoint().Random(crand.Reader).(*PointP256) - } - acc := curve.NewIdentityPoint() - b.StartTimer() - for _, pt := range points { - acc = acc.Add(pt) - } - }) - b.Run("1000 point double - p256", func(b *testing.B) { - b.StopTimer() - acc := new(BenchPointP256).Generator() - b.StartTimer() - for i := 0; i < 1000; i++ { - acc = acc.Double() - } - }) - b.Run("1000 point double - ct p256", func(b *testing.B) { - b.StopTimer() - acc := new(PointP256).Generator() - b.StartTimer() - for i := 0; i < 1000; i++ { - acc = acc.Double() - } - }) - b.Run("1000 point multiply - p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalarP256, 1000) - for i := range scalars { - s := new(BenchScalarP256).Random(crand.Reader) - scalars[i] = s.(*BenchScalarP256) - } - acc := new(BenchPointP256).Generator().Mul(new(BenchScalarP256).New(2)) - b.StartTimer() - for _, sc := range scalars { - acc = acc.Mul(sc) - } - }) - b.Run("1000 point multiply - ct p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarP256, 1000) - for i := range scalars { - s := new(ScalarP256).Random(crand.Reader) - scalars[i] = s.(*ScalarP256) - } - acc := new(PointP256).Generator() - b.StartTimer() - for _, sc := range scalars { - acc = acc.Mul(sc) - } - }) - b.Run("1000 scalar invert - p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalarP256, 1000) - for i := range scalars { - s := new(BenchScalarP256).Random(crand.Reader) - scalars[i] = s.(*BenchScalarP256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Invert() - } - }) - b.Run("1000 scalar invert - ct p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarP256, 1000) - for i := range scalars { - s := new(ScalarP256).Random(crand.Reader) - scalars[i] = s.(*ScalarP256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Invert() - } - }) - b.Run("1000 scalar sqrt - p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*BenchScalarP256, 1000) - for i := range scalars { - s := new(BenchScalarP256).Random(crand.Reader) - scalars[i] = s.(*BenchScalarP256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Sqrt() - } - }) - b.Run("1000 scalar sqrt - ct p256", func(b *testing.B) { - b.StopTimer() - scalars := make([]*ScalarP256, 1000) - for i := range scalars { - s := new(ScalarP256).Random(crand.Reader) - scalars[i] = s.(*ScalarP256) - } - b.StartTimer() - for _, sc := range scalars { - _, _ = sc.Sqrt() - } - }) -} - -type BenchScalarP256 struct { - value *big.Int -} - -type BenchPointP256 struct { - x, y *big.Int -} - -func (s *BenchScalarP256) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *BenchScalarP256) Hash(bytes []byte) Scalar { - xmd, err := expandMsgXmd(sha256.New(), bytes, []byte("P256_XMD:SHA-256_SSWU_RO_"), 48) - if err != nil { - return nil - } - v := new(big.Int).SetBytes(xmd) - return &BenchScalarP256{ - value: v.Mod(v, elliptic.P256().Params().N), - } -} - -func (s *BenchScalarP256) Zero() Scalar { - return &BenchScalarP256{ - value: big.NewInt(0), - } -} - -func (s *BenchScalarP256) One() Scalar { - return &BenchScalarP256{ - value: big.NewInt(1), - } -} - -func (s *BenchScalarP256) IsZero() bool { - return subtle.ConstantTimeCompare(s.value.Bytes(), []byte{}) == 1 -} - -func (s *BenchScalarP256) IsOne() bool { - return subtle.ConstantTimeCompare(s.value.Bytes(), []byte{1}) == 1 -} - -func (s *BenchScalarP256) IsOdd() bool { - return s.value.Bit(0) == 1 -} - -func (s *BenchScalarP256) IsEven() bool { - return s.value.Bit(0) == 0 -} - -func (s *BenchScalarP256) New(value int) Scalar { - v := big.NewInt(int64(value)) - if value < 0 { - v.Mod(v, elliptic.P256().Params().N) - } - return &BenchScalarP256{ - value: v, - } -} - -func (s *BenchScalarP256) Cmp(rhs Scalar) int { - r, ok := rhs.(*BenchScalarP256) - if ok { - return s.value.Cmp(r.value) - } else { - return -2 - } -} - -func (s *BenchScalarP256) Square() Scalar { - return &BenchScalarP256{ - value: new(big.Int).Exp(s.value, big.NewInt(2), elliptic.P256().Params().N), - } -} - -func (s *BenchScalarP256) Double() Scalar { - v := new(big.Int).Add(s.value, s.value) - return &BenchScalarP256{ - value: v.Mod(v, elliptic.P256().Params().N), - } -} - -func (s *BenchScalarP256) Invert() (Scalar, error) { - return &BenchScalarP256{ - value: new(big.Int).ModInverse(s.value, elliptic.P256().Params().N), - }, nil -} - -func (s *BenchScalarP256) Sqrt() (Scalar, error) { - return &BenchScalarP256{ - value: new(big.Int).ModSqrt(s.value, elliptic.P256().Params().N), - }, nil -} - -func (s *BenchScalarP256) Cube() Scalar { - return &BenchScalarP256{ - value: new(big.Int).Exp(s.value, big.NewInt(3), elliptic.P256().Params().N), - } -} - -func (s *BenchScalarP256) Add(rhs Scalar) Scalar { - r, ok := rhs.(*BenchScalarP256) - if ok { - v := new(big.Int).Add(s.value, r.value) - return &BenchScalarP256{ - value: v.Mod(v, elliptic.P256().Params().N), - } - } else { - return nil - } -} - -func (s *BenchScalarP256) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*BenchScalarP256) - if ok { - v := new(big.Int).Sub(s.value, r.value) - return &BenchScalarP256{ - value: v.Mod(v, elliptic.P256().Params().N), - } - } else { - return nil - } -} - -func (s *BenchScalarP256) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*BenchScalarP256) - if ok { - v := new(big.Int).Mul(s.value, r.value) - return &BenchScalarP256{ - value: v.Mod(v, elliptic.P256().Params().N), - } - } else { - return nil - } -} - -func (s *BenchScalarP256) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *BenchScalarP256) Div(rhs Scalar) Scalar { - n := elliptic.P256().Params().N - r, ok := rhs.(*BenchScalarP256) - if ok { - v := new(big.Int).ModInverse(r.value, n) - v.Mul(v, s.value) - return &BenchScalarP256{ - value: v.Mod(v, n), - } - } else { - return nil - } -} - -func (s *BenchScalarP256) Neg() Scalar { - z := new(big.Int).Neg(s.value) - return &BenchScalarP256{ - value: z.Mod(z, elliptic.P256().Params().N), - } -} - -func (s *BenchScalarP256) SetBigInt(v *big.Int) (Scalar, error) { - if v == nil { - return nil, fmt.Errorf("invalid value") - } - t := new(big.Int).Mod(v, elliptic.P256().Params().N) - if t.Cmp(v) != 0 { - return nil, fmt.Errorf("invalid value") - } - return &BenchScalarP256{ - value: t, - }, nil -} - -func (s *BenchScalarP256) BigInt() *big.Int { - return new(big.Int).Set(s.value) -} - -func (s *BenchScalarP256) Bytes() []byte { - var out [32]byte - return s.value.FillBytes(out[:]) -} - -func (s *BenchScalarP256) SetBytes(bytes []byte) (Scalar, error) { - value := new(big.Int).SetBytes(bytes) - t := new(big.Int).Mod(value, elliptic.P256().Params().N) - if t.Cmp(value) != 0 { - return nil, fmt.Errorf("invalid byte sequence") - } - return &BenchScalarP256{ - value: t, - }, nil -} - -func (s *BenchScalarP256) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) < 32 || len(bytes) > 128 { - return nil, fmt.Errorf("invalid byte sequence") - } - value := new(big.Int).SetBytes(bytes) - value.Mod(value, elliptic.P256().Params().N) - return &BenchScalarP256{ - value, - }, nil -} - -func (s *BenchScalarP256) Point() Point { - return new(BenchPointP256).Identity() -} - -func (s *BenchScalarP256) Clone() Scalar { - return &BenchScalarP256{ - value: new(big.Int).Set(s.value), - } -} - -func (s *BenchScalarP256) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *BenchScalarP256) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*BenchScalarP256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *BenchScalarP256) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *BenchScalarP256) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*BenchScalarP256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *BenchScalarP256) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *BenchScalarP256) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*BenchScalarP256) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (p *BenchPointP256) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *BenchPointP256) Hash(bytes []byte) Point { - curve := elliptic.P256() - - domain := []byte("P256_XMD:SHA-256_SSWU_RO_") - uniformBytes, _ := expandMsgXmd(sha256.New(), bytes, domain, 96) - - u0 := new(big.Int).SetBytes(uniformBytes[:48]) - u1 := new(big.Int).SetBytes(uniformBytes[48:]) - - u0.Mod(u0, curve.Params().P) - u1.Mod(u1, curve.Params().P) - - ssParams := p256SswuParams() - q0x, q0y := osswu3mod4(u0, ssParams) - q1x, q1y := osswu3mod4(u1, ssParams) - - x, y := curve.Add(q0x, q0y, q1x, q1y) - - return &BenchPointP256{ - x, y, - } -} - -func (p *BenchPointP256) Identity() Point { - return &BenchPointP256{ - x: big.NewInt(0), y: big.NewInt(0), - } -} - -func (p *BenchPointP256) Generator() Point { - curve := elliptic.P256().Params() - return &BenchPointP256{ - x: new(big.Int).Set(curve.Gx), - y: new(big.Int).Set(curve.Gy), - } -} - -func (p *BenchPointP256) IsIdentity() bool { - x := core.ConstantTimeEqByte(p.x, core.Zero) - y := core.ConstantTimeEqByte(p.y, core.Zero) - return (x & y) == 1 -} - -func (p *BenchPointP256) IsNegative() bool { - return p.y.Bit(0) == 1 -} - -func (p *BenchPointP256) IsOnCurve() bool { - return elliptic.P256().IsOnCurve(p.x, p.y) -} - -func (p *BenchPointP256) Double() Point { - curve := elliptic.P256() - x, y := curve.Double(p.x, p.y) - return &BenchPointP256{x, y} -} - -func (p *BenchPointP256) Scalar() Scalar { - return new(BenchScalarP256).Zero() -} - -func (p *BenchPointP256) Neg() Point { - y := new(big.Int).Sub(elliptic.P256().Params().P, p.y) - y.Mod(y, elliptic.P256().Params().P) - return &BenchPointP256{x: p.x, y: y} -} - -func (p *BenchPointP256) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*BenchPointP256) - if ok { - x, y := elliptic.P256().Add(p.x, p.y, r.x, r.y) - return &BenchPointP256{x, y} - } else { - return nil - } -} - -func (p *BenchPointP256) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.Neg().(*BenchPointP256) - if ok { - x, y := elliptic.P256().Add(p.x, p.y, r.x, r.y) - return &BenchPointP256{x, y} - } else { - return nil - } -} - -func (p *BenchPointP256) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*BenchScalarP256) - if ok { - x, y := elliptic.P256().ScalarMult(p.x, p.y, r.value.Bytes()) - return &BenchPointP256{x, y} - } else { - return nil - } -} - -func (p *BenchPointP256) Equal(rhs Point) bool { - r, ok := rhs.(*BenchPointP256) - if ok { - x := core.ConstantTimeEqByte(p.x, r.x) - y := core.ConstantTimeEqByte(p.y, r.y) - return (x & y) == 1 - } else { - return false - } -} - -func (p *BenchPointP256) Set(x, y *big.Int) (Point, error) { - // check is identity or on curve - xx := subtle.ConstantTimeCompare(x.Bytes(), []byte{}) - yy := subtle.ConstantTimeCompare(y.Bytes(), []byte{}) - // Checks are constant time - onCurve := elliptic.P256().IsOnCurve(x, y) - if !onCurve && (xx&yy) != 1 { - return nil, fmt.Errorf("invalid coordinates") - } - x = new(big.Int).Set(x) - y = new(big.Int).Set(y) - return &BenchPointP256{x, y}, nil -} - -func (p *BenchPointP256) ToAffineCompressed() []byte { - var x [33]byte - x[0] = byte(2) - x[0] |= byte(p.y.Bit(0)) - p.x.FillBytes(x[1:]) - return x[:] -} - -func (p *BenchPointP256) ToAffineUncompressed() []byte { - var out [65]byte - out[0] = byte(4) - p.x.FillBytes(out[1:33]) - p.y.FillBytes(out[33:]) - return out[:] -} - -func (p *BenchPointP256) FromAffineCompressed(bytes []byte) (Point, error) { - if len(bytes) != 33 { - return nil, fmt.Errorf("invalid byte sequence") - } - sign := int(bytes[0]) - if sign != 2 && sign != 3 { - return nil, fmt.Errorf("invalid sign byte") - } - sign &= 0x1 - - x := new(big.Int).SetBytes(bytes[1:]) - rhs := rhsP256(x, elliptic.P256().Params()) - // test that rhs is quadratic residue - // if not, then this Point is at infinity - y := new(big.Int).ModSqrt(rhs, elliptic.P256().Params().P) - if y != nil { - // fix the sign - if int(y.Bit(0)) != sign { - y.Neg(y) - y.Mod(y, elliptic.P256().Params().P) - } - } else { - x = new(big.Int) - y = new(big.Int) - } - return &BenchPointP256{ - x, y, - }, nil -} - -func (p *BenchPointP256) FromAffineUncompressed(bytes []byte) (Point, error) { - if len(bytes) != 65 { - return nil, fmt.Errorf("invalid byte sequence") - } - if bytes[0] != 4 { - return nil, fmt.Errorf("invalid sign byte") - } - x := new(big.Int).SetBytes(bytes[1:33]) - y := new(big.Int).SetBytes(bytes[33:]) - return &BenchPointP256{x, y}, nil -} - -func (p *BenchPointP256) CurveName() string { - return elliptic.P256().Params().Name -} - -func (p *BenchPointP256) SumOfProducts(points []Point, scalars []Scalar) Point { - nScalars := make([]*big.Int, len(scalars)) - for i, sc := range scalars { - s, ok := sc.(*BenchScalarP256) - if !ok { - return nil - } - nScalars[i] = s.value - } - return sumOfProductsPippenger(points, nScalars) -} - -func (p *BenchPointP256) X() *big.Int { - return new(big.Int).Set(p.x) -} - -func (p *BenchPointP256) Y() *big.Int { - return new(big.Int).Set(p.y) -} - -func (p *BenchPointP256) Params() *elliptic.CurveParams { - return elliptic.P256().Params() -} - -func (p *BenchPointP256) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *BenchPointP256) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*BenchPointP256) - if !ok { - return fmt.Errorf("invalid point") - } - p.x = ppt.x - p.y = ppt.y - return nil -} - -func (p *BenchPointP256) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *BenchPointP256) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*BenchPointP256) - if !ok { - return fmt.Errorf("invalid point") - } - p.x = ppt.x - p.y = ppt.y - return nil -} - -func (p *BenchPointP256) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *BenchPointP256) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*BenchPointP256) - if !ok { - return fmt.Errorf("invalid type") - } - p.x = P.x - p.y = P.y - return nil -} - -// From https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2 -func p256SswuParams() *sswuParams { - params := elliptic.P256().Params() - - // c1 = (q - 3) / 4 - c1 := new(big.Int).Set(params.P) - c1.Sub(c1, big.NewInt(3)) - c1.Rsh(c1, 2) - - a := big.NewInt(-3) - a.Mod(a, params.P) - b := new(big.Int).Set(params.B) - z := big.NewInt(-10) - z.Mod(z, params.P) - // sqrt(-Z^3) - zTmp := new(big.Int).Exp(z, big.NewInt(3), nil) - zTmp = zTmp.Neg(zTmp) - zTmp.Mod(zTmp, params.P) - c2 := new(big.Int).ModSqrt(zTmp, params.P) - - return &sswuParams{ - params, c1, c2, a, b, z, - } -} - -// rhs of the curve equation -func rhsP256(x *big.Int, params *elliptic.CurveParams) *big.Int { - f := NewField(params.P) - r := f.NewElement(x) - r2 := r.Mul(r) - - // x^3-3x+B - a := r.Mul(f.NewElement(big.NewInt(3))) - r = r2.Mul(r) - return r.Add(a.Neg()).Add(f.NewElement(params.B)).Value -} diff --git a/crypto/core/curves/p256_curve.go b/crypto/core/curves/p256_curve.go deleted file mode 100644 index 17d2c0a89..000000000 --- a/crypto/core/curves/p256_curve.go +++ /dev/null @@ -1,670 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - "fmt" - "io" - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - p256n "github.com/sonr-io/sonr/crypto/core/curves/native/p256" - "github.com/sonr-io/sonr/crypto/core/curves/native/p256/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/p256/fq" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - oldP256InitOnce sync.Once - oldP256 NistP256 -) - -type NistP256 struct { - *elliptic.CurveParams -} - -func oldP256InitAll() { - curve := elliptic.P256() - oldP256.CurveParams = curve.Params() - oldP256.P = curve.Params().P - oldP256.N = curve.Params().N - oldP256.Gx = curve.Params().Gx - oldP256.Gy = curve.Params().Gy - oldP256.B = curve.Params().B - oldP256.BitSize = curve.Params().BitSize - oldP256.Name = curve.Params().Name -} - -func NistP256Curve() *NistP256 { - oldP256InitOnce.Do(oldP256InitAll) - return &oldP256 -} - -func (curve *NistP256) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *NistP256) IsOnCurve(x, y *big.Int) bool { - _, err := p256n.P256PointNew().SetBigInt(x, y) - return err == nil -} - -func (curve *NistP256) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - p1, err := p256n.P256PointNew().SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - p2, err := p256n.P256PointNew().SetBigInt(x2, y2) - if err != nil { - return nil, nil - } - return p1.Add(p1, p2).BigInt() -} - -func (curve *NistP256) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p1, err := p256n.P256PointNew().SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - return p1.Double(p1).BigInt() -} - -func (curve *NistP256) ScalarMul(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p1, err := p256n.P256PointNew().SetBigInt(Bx, By) - if err != nil { - return nil, nil - } - var bytes [32]byte - copy(bytes[:], internal.ReverseScalarBytes(k)) - s, err := fq.P256FqNew().SetBytes(&bytes) - if err != nil { - return nil, nil - } - return p1.Mul(p1, s).BigInt() -} - -func (curve *NistP256) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - var bytes [32]byte - copy(bytes[:], internal.ReverseScalarBytes(k)) - s, err := fq.P256FqNew().SetBytes(&bytes) - if err != nil { - return nil, nil - } - p1 := p256n.P256PointNew().Generator() - return p1.Mul(p1, s).BigInt() -} - -type ScalarP256 struct { - value *native.Field -} - -type PointP256 struct { - value *native.EllipticPoint -} - -func (s *ScalarP256) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarP256) Hash(bytes []byte) Scalar { - dst := []byte("P256_XMD:SHA-256_SSWU_RO_") - xmd := native.ExpandMsgXmd(native.EllipticPointHasherSha256(), bytes, dst, 48) - var t [64]byte - copy(t[:48], internal.ReverseScalarBytes(xmd)) - - return &ScalarP256{ - value: fq.P256FqNew().SetBytesWide(&t), - } -} - -func (s *ScalarP256) Zero() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().SetZero(), - } -} - -func (s *ScalarP256) One() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().SetOne(), - } -} - -func (s *ScalarP256) IsZero() bool { - return s.value.IsZero() == 1 -} - -func (s *ScalarP256) IsOne() bool { - return s.value.IsOne() == 1 -} - -func (s *ScalarP256) IsOdd() bool { - return s.value.Bytes()[0]&1 == 1 -} - -func (s *ScalarP256) IsEven() bool { - return s.value.Bytes()[0]&1 == 0 -} - -func (s *ScalarP256) New(value int) Scalar { - t := fq.P256FqNew() - v := big.NewInt(int64(value)) - if value < 0 { - v.Mod(v, t.Params.BiModulus) - } - return &ScalarP256{ - value: t.SetBigInt(v), - } -} - -func (s *ScalarP256) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarP256) - if ok { - return s.value.Cmp(r.value) - } else { - return -2 - } -} - -func (s *ScalarP256) Square() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().Square(s.value), - } -} - -func (s *ScalarP256) Double() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().Double(s.value), - } -} - -func (s *ScalarP256) Invert() (Scalar, error) { - value, wasInverted := fq.P256FqNew().Invert(s.value) - if !wasInverted { - return nil, fmt.Errorf("inverse doesn't exist") - } - return &ScalarP256{ - value, - }, nil -} - -func (s *ScalarP256) Sqrt() (Scalar, error) { - value, wasSquare := fq.P256FqNew().Sqrt(s.value) - if !wasSquare { - return nil, fmt.Errorf("not a square") - } - return &ScalarP256{ - value, - }, nil -} - -func (s *ScalarP256) Cube() Scalar { - value := fq.P256FqNew().Mul(s.value, s.value) - value.Mul(value, s.value) - return &ScalarP256{ - value, - } -} - -func (s *ScalarP256) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarP256) - if ok { - return &ScalarP256{ - value: fq.P256FqNew().Add(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarP256) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarP256) - if ok { - return &ScalarP256{ - value: fq.P256FqNew().Sub(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarP256) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarP256) - if ok { - return &ScalarP256{ - value: fq.P256FqNew().Mul(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarP256) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarP256) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarP256) - if ok { - v, wasInverted := fq.P256FqNew().Invert(r.value) - if !wasInverted { - return nil - } - v.Mul(v, s.value) - return &ScalarP256{value: v} - } else { - return nil - } -} - -func (s *ScalarP256) Neg() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().Neg(s.value), - } -} - -func (s *ScalarP256) SetBigInt(v *big.Int) (Scalar, error) { - if v == nil { - return nil, fmt.Errorf("'v' cannot be nil") - } - value := fq.P256FqNew().SetBigInt(v) - return &ScalarP256{ - value, - }, nil -} - -func (s *ScalarP256) BigInt() *big.Int { - return s.value.BigInt() -} - -func (s *ScalarP256) Bytes() []byte { - t := s.value.Bytes() - return internal.ReverseScalarBytes(t[:]) -} - -func (s *ScalarP256) SetBytes(bytes []byte) (Scalar, error) { - if len(bytes) != 32 { - return nil, fmt.Errorf("invalid length") - } - var seq [32]byte - copy(seq[:], internal.ReverseScalarBytes(bytes)) - value, err := fq.P256FqNew().SetBytes(&seq) - if err != nil { - return nil, err - } - return &ScalarP256{ - value, - }, nil -} - -func (s *ScalarP256) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) != 64 { - return nil, fmt.Errorf("invalid length") - } - var seq [64]byte - copy(seq[:], bytes) - return &ScalarP256{ - value: fq.P256FqNew().SetBytesWide(&seq), - }, nil -} - -func (s *ScalarP256) Point() Point { - return new(PointP256).Identity() -} - -func (s *ScalarP256) Clone() Scalar { - return &ScalarP256{ - value: fq.P256FqNew().Set(s.value), - } -} - -func (s *ScalarP256) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarP256) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarP256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarP256) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarP256) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarP256) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarP256) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarP256) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarP256) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -func (p *PointP256) Random(reader io.Reader) Point { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *PointP256) Hash(bytes []byte) Point { - value, err := p256n.P256PointNew().Hash(bytes, native.EllipticPointHasherSha256()) - // Note: Interface constraint prevents returning error directly - // Returning nil on error for now, caller should check for nil - if err != nil { - // Log error for debugging if logger is available - return nil - } - - return &PointP256{value} -} - -func (p *PointP256) Identity() Point { - return &PointP256{ - value: p256n.P256PointNew().Identity(), - } -} - -func (p *PointP256) Generator() Point { - return &PointP256{ - value: p256n.P256PointNew().Generator(), - } -} - -func (p *PointP256) IsIdentity() bool { - return p.value.IsIdentity() -} - -func (p *PointP256) IsNegative() bool { - return p.value.GetY().Value[0]&1 == 1 -} - -func (p *PointP256) IsOnCurve() bool { - return p.value.IsOnCurve() -} - -func (p *PointP256) Double() Point { - value := p256n.P256PointNew().Double(p.value) - return &PointP256{value} -} - -func (p *PointP256) Scalar() Scalar { - return new(ScalarP256).Zero() -} - -func (p *PointP256) Neg() Point { - value := p256n.P256PointNew().Neg(p.value) - return &PointP256{value} -} - -func (p *PointP256) Add(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointP256) - if ok { - value := p256n.P256PointNew().Add(p.value, r.value) - return &PointP256{value} - } else { - return nil - } -} - -func (p *PointP256) Sub(rhs Point) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*PointP256) - if ok { - value := p256n.P256PointNew().Sub(p.value, r.value) - return &PointP256{value} - } else { - return nil - } -} - -func (p *PointP256) Mul(rhs Scalar) Point { - if rhs == nil { - return nil - } - r, ok := rhs.(*ScalarP256) - if ok { - value := p256n.P256PointNew().Mul(p.value, r.value) - return &PointP256{value} - } else { - return nil - } -} - -func (p *PointP256) Equal(rhs Point) bool { - r, ok := rhs.(*PointP256) - if ok { - return p.value.Equal(r.value) == 1 - } else { - return false - } -} - -func (p *PointP256) Set(x, y *big.Int) (Point, error) { - value, err := p256n.P256PointNew().SetBigInt(x, y) - if err != nil { - return nil, err - } - return &PointP256{value}, nil -} - -func (p *PointP256) ToAffineCompressed() []byte { - var x [33]byte - x[0] = byte(2) - - t := p256n.P256PointNew().ToAffine(p.value) - - x[0] |= t.Y.Bytes()[0] & 1 - - xBytes := t.X.Bytes() - copy(x[1:], internal.ReverseScalarBytes(xBytes[:])) - return x[:] -} - -func (p *PointP256) ToAffineUncompressed() []byte { - var out [65]byte - out[0] = byte(4) - t := p256n.P256PointNew().ToAffine(p.value) - arr := t.X.Bytes() - copy(out[1:33], internal.ReverseScalarBytes(arr[:])) - arr = t.Y.Bytes() - copy(out[33:], internal.ReverseScalarBytes(arr[:])) - return out[:] -} - -func (p *PointP256) FromAffineCompressed(bytes []byte) (Point, error) { - var raw [native.FieldBytes]byte - if len(bytes) != 33 { - return nil, fmt.Errorf("invalid byte sequence") - } - sign := int(bytes[0]) - if sign != 2 && sign != 3 { - return nil, fmt.Errorf("invalid sign byte") - } - sign &= 0x1 - - copy(raw[:], internal.ReverseScalarBytes(bytes[1:])) - x, err := fp.P256FpNew().SetBytes(&raw) - if err != nil { - return nil, err - } - - value := p256n.P256PointNew().Identity() - rhs := fp.P256FpNew() - p.value.Arithmetic.RhsEq(rhs, x) - // test that rhs is quadratic residue - // if not, then this Point is at infinity - y, wasQr := fp.P256FpNew().Sqrt(rhs) - if wasQr { - // fix the sign - sigY := int(y.Bytes()[0] & 1) - if sigY != sign { - y.Neg(y) - } - value.X = x - value.Y = y - value.Z.SetOne() - } - return &PointP256{value}, nil -} - -func (p *PointP256) FromAffineUncompressed(bytes []byte) (Point, error) { - var arr [native.FieldBytes]byte - if len(bytes) != 65 { - return nil, fmt.Errorf("invalid byte sequence") - } - if bytes[0] != 4 { - return nil, fmt.Errorf("invalid sign byte") - } - - copy(arr[:], internal.ReverseScalarBytes(bytes[1:33])) - x, err := fp.P256FpNew().SetBytes(&arr) - if err != nil { - return nil, err - } - copy(arr[:], internal.ReverseScalarBytes(bytes[33:])) - y, err := fp.P256FpNew().SetBytes(&arr) - if err != nil { - return nil, err - } - value := p256n.P256PointNew() - value.X = x - value.Y = y - value.Z.SetOne() - return &PointP256{value}, nil -} - -func (p *PointP256) CurveName() string { - return elliptic.P256().Params().Name -} - -func (p *PointP256) SumOfProducts(points []Point, scalars []Scalar) Point { - nPoints := make([]*native.EllipticPoint, len(points)) - nScalars := make([]*native.Field, len(scalars)) - for i, pt := range points { - ptv, ok := pt.(*PointP256) - if !ok { - return nil - } - nPoints[i] = ptv.value - } - for i, sc := range scalars { - s, ok := sc.(*ScalarP256) - if !ok { - return nil - } - nScalars[i] = s.value - } - value := p256n.P256PointNew() - _, err := value.SumOfProducts(nPoints, nScalars) - if err != nil { - return nil - } - return &PointP256{value} -} - -func (p *PointP256) X() *native.Field { - return p.value.GetX() -} - -func (p *PointP256) Y() *native.Field { - return p.value.GetY() -} - -func (p *PointP256) Params() *elliptic.CurveParams { - return elliptic.P256().Params() -} - -func (p *PointP256) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointP256) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointP256) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointP256) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointP256) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointP256) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointP256) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointP256) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointP256) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} diff --git a/crypto/core/curves/p256_curve_test.go b/crypto/core/curves/p256_curve_test.go deleted file mode 100755 index 962ec2058..000000000 --- a/crypto/core/curves/p256_curve_test.go +++ /dev/null @@ -1,556 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - crand "crypto/rand" - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestScalarP256Random(t *testing.T) { - p256 := P256() - sc := p256.Scalar.Random(testRng()) - s, ok := sc.(*ScalarP256) - require.True(t, ok) - expected := bhex("02ca487e56f8cb1ad9666027b2282d1159792d39a5e05f0bc696f85de5acc6d4") - require.Equal(t, s.value.BigInt(), expected) - // Try 10 random values - for i := 0; i < 10; i++ { - sc := p256.Scalar.Random(crand.Reader) - _, ok := sc.(*ScalarP256) - require.True(t, ok) - require.True(t, !sc.IsZero()) - } -} - -func TestScalarP256Hash(t *testing.T) { - var b [32]byte - p256 := P256() - sc := p256.Scalar.Hash(b[:]) - s, ok := sc.(*ScalarP256) - require.True(t, ok) - expected := bhex("43ca74a23022b221e60c8499781afff2a2776ec23362712df90a3080b5557f90") - require.Equal(t, s.value.BigInt(), expected) -} - -func TestScalarP256Zero(t *testing.T) { - p256 := P256() - sc := p256.Scalar.Zero() - require.True(t, sc.IsZero()) - require.True(t, sc.IsEven()) -} - -func TestScalarP256One(t *testing.T) { - p256 := P256() - sc := p256.Scalar.One() - require.True(t, sc.IsOne()) - require.True(t, sc.IsOdd()) -} - -func TestScalarP256New(t *testing.T) { - p256 := P256() - three := p256.Scalar.New(3) - require.True(t, three.IsOdd()) - four := p256.Scalar.New(4) - require.True(t, four.IsEven()) - neg1 := p256.Scalar.New(-1) - require.True(t, neg1.IsEven()) - neg2 := p256.Scalar.New(-2) - require.True(t, neg2.IsOdd()) -} - -func TestScalarP256Square(t *testing.T) { - p256 := P256() - three := p256.Scalar.New(3) - nine := p256.Scalar.New(9) - require.Equal(t, three.Square().Cmp(nine), 0) -} - -func TestScalarP256Cube(t *testing.T) { - p256 := P256() - three := p256.Scalar.New(3) - twentySeven := p256.Scalar.New(27) - require.Equal(t, three.Cube().Cmp(twentySeven), 0) -} - -func TestScalarP256Double(t *testing.T) { - p256 := P256() - three := p256.Scalar.New(3) - six := p256.Scalar.New(6) - require.Equal(t, three.Double().Cmp(six), 0) -} - -func TestScalarP256Neg(t *testing.T) { - p256 := P256() - one := p256.Scalar.One() - neg1 := p256.Scalar.New(-1) - require.Equal(t, one.Neg().Cmp(neg1), 0) - lotsOfThrees := p256.Scalar.New(333333) - expected := p256.Scalar.New(-333333) - require.Equal(t, lotsOfThrees.Neg().Cmp(expected), 0) -} - -func TestScalarP256Invert(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - actual, _ := nine.Invert() - sa, _ := actual.(*ScalarP256) - bn := bhex("8e38e38daaaaaaab38e38e38e38e38e368f2197ceb0d1f2d6af570a536e1bf66") - expected, err := p256.Scalar.SetBigInt(bn) - require.NoError(t, err) - require.Equal(t, sa.Cmp(expected), 0) -} - -func TestScalarP256Sqrt(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - actual, err := nine.Sqrt() - sa, _ := actual.(*ScalarP256) - expected := p256.Scalar.New(3) - require.NoError(t, err) - require.Equal(t, sa.Cmp(expected), 0) -} - -func TestScalarP256Add(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - six := p256.Scalar.New(6) - fifteen := nine.Add(six) - require.NotNil(t, fifteen) - expected := p256.Scalar.New(15) - require.Equal(t, expected.Cmp(fifteen), 0) - n := new(big.Int).Set(elliptic.P256().Params().N) - n.Sub(n, big.NewInt(3)) - - upper, err := p256.Scalar.SetBigInt(n) - require.NoError(t, err) - actual := upper.Add(nine) - require.NotNil(t, actual) - require.Equal(t, actual.Cmp(six), 0) -} - -func TestScalarP256Sub(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - six := p256.Scalar.New(6) - n := new(big.Int).Set(elliptic.P256().Params().N) - n.Sub(n, big.NewInt(3)) - - expected, err := p256.Scalar.SetBigInt(n) - require.NoError(t, err) - actual := six.Sub(nine) - require.Equal(t, expected.Cmp(actual), 0) - - actual = nine.Sub(six) - require.Equal(t, actual.Cmp(p256.Scalar.New(3)), 0) -} - -func TestScalarP256Mul(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - six := p256.Scalar.New(6) - actual := nine.Mul(six) - require.Equal(t, actual.Cmp(p256.Scalar.New(54)), 0) - n := new(big.Int).Set(elliptic.P256().Params().N) - n.Sub(n, big.NewInt(1)) - upper, err := p256.Scalar.SetBigInt(n) - require.NoError(t, err) - require.Equal(t, upper.Mul(upper).Cmp(p256.Scalar.New(1)), 0) -} - -func TestScalarP256Div(t *testing.T) { - p256 := P256() - nine := p256.Scalar.New(9) - actual := nine.Div(nine) - require.Equal(t, actual.Cmp(p256.Scalar.New(1)), 0) - require.Equal(t, p256.Scalar.New(54).Div(nine).Cmp(p256.Scalar.New(6)), 0) -} - -func TestScalarP256Serialize(t *testing.T) { - p256 := P256() - sc := p256.Scalar.New(255) - sequence := sc.Bytes() - require.Equal(t, len(sequence), 32) - require.Equal( - t, - sequence, - []byte{ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0xff, - }, - ) - ret, err := p256.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - - // Try 10 random values - for i := 0; i < 10; i++ { - sc = p256.Scalar.Random(crand.Reader) - sequence = sc.Bytes() - require.Equal(t, len(sequence), 32) - ret, err = p256.Scalar.SetBytes(sequence) - require.NoError(t, err) - require.Equal(t, ret.Cmp(sc), 0) - } -} - -func TestScalarP256Nil(t *testing.T) { - p256 := P256() - one := p256.Scalar.New(1) - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, one.Div(nil)) - require.Nil(t, p256.Scalar.Random(nil)) - require.Equal(t, one.Cmp(nil), -2) - _, err := p256.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointP256Random(t *testing.T) { - p256 := P256() - sc := p256.Point.Random(testRng()) - s, ok := sc.(*PointP256) - require.True(t, ok) - expectedX, _ := new( - big.Int, - ).SetString("7d31a079d75687cd0dd1118996f726c3e4d52806a5124d23c1faeee9fadb2201", 16) - expectedY, _ := new( - big.Int, - ).SetString("da62629181a0e2ec6943c263bbe81f53d87cb94d0039a707309f415f04d47bab", 16) - require.Equal(t, s.X().BigInt(), expectedX) - require.Equal(t, s.Y().BigInt(), expectedY) - // Try 10 random values - for i := 0; i < 10; i++ { - sc := p256.Point.Random(crand.Reader) - _, ok := sc.(*PointP256) - require.True(t, ok) - require.True(t, !sc.IsIdentity()) - } -} - -func TestPointP256Hash(t *testing.T) { - var b [32]byte - p256 := P256() - sc := p256.Point.Hash(b[:]) - s, ok := sc.(*PointP256) - require.True(t, ok) - expectedX, _ := new( - big.Int, - ).SetString("10f1699c24cf20f5322b92bfab4fdf14814ee1472ffc6b1ef2ec36be3051925d", 16) - expectedY, _ := new( - big.Int, - ).SetString("99efe055f13c3e5e3fc65be12043a89d0482b806c7a9945c276b7aee887c1de0", 16) - require.Equal(t, s.X().BigInt(), expectedX) - require.Equal(t, s.Y().BigInt(), expectedY) -} - -func TestPointP256Identity(t *testing.T) { - p256 := P256() - sc := p256.Point.Identity() - require.True(t, sc.IsIdentity()) - require.Equal( - t, - sc.ToAffineCompressed(), - []byte{ - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - }, - ) -} - -func TestPointP256Generator(t *testing.T) { - p256 := P256() - sc := p256.Point.Generator() - s, ok := sc.(*PointP256) - require.True(t, ok) - require.Equal(t, s.X().BigInt(), elliptic.P256().Params().Gx) - require.Equal(t, s.Y().BigInt(), elliptic.P256().Params().Gy) -} - -func TestPointP256Set(t *testing.T) { - p256 := P256() - iden, err := p256.Point.Set(big.NewInt(0), big.NewInt(0)) - require.NoError(t, err) - require.True(t, iden.IsIdentity()) - _, err = p256.Point.Set(elliptic.P256().Params().Gx, elliptic.P256().Params().Gy) - require.NoError(t, err) -} - -func TestPointP256Double(t *testing.T) { - p256 := P256() - g := p256.Point.Generator() - g2 := g.Double() - require.True(t, g2.Equal(g.Mul(p256.Scalar.New(2)))) - i := p256.Point.Identity() - require.True(t, i.Double().Equal(i)) -} - -func TestPointP256Neg(t *testing.T) { - p256 := P256() - g := p256.Point.Generator().Neg() - require.True(t, g.Neg().Equal(p256.Point.Generator())) - require.True(t, p256.Point.Identity().Neg().Equal(p256.Point.Identity())) -} - -func TestPointP256Add(t *testing.T) { - p256 := P256() - pt := p256.Point.Generator() - require.True(t, pt.Add(pt).Equal(pt.Double())) - require.True(t, pt.Mul(p256.Scalar.New(3)).Equal(pt.Add(pt).Add(pt))) -} - -func TestPointP256Sub(t *testing.T) { - p256 := P256() - g := p256.Point.Generator() - pt := p256.Point.Generator().Mul(p256.Scalar.New(4)) - require.True(t, pt.Sub(g).Sub(g).Sub(g).Equal(g)) - require.True(t, pt.Sub(g).Sub(g).Sub(g).Sub(g).IsIdentity()) -} - -func TestPointP256Mul(t *testing.T) { - p256 := P256() - g := p256.Point.Generator() - pt := p256.Point.Generator().Mul(p256.Scalar.New(4)) - require.True(t, g.Double().Double().Equal(pt)) -} - -func TestPointP256Serialize(t *testing.T) { - p256 := P256() - ss := p256.Scalar.Random(testRng()) - g := p256.Point.Generator() - - ppt := g.Mul(ss) - require.Equal( - t, - ppt.ToAffineCompressed(), - []byte{ - 0x3, - 0x1b, - 0xfa, - 0x44, - 0xfb, - 0x6, - 0xa4, - 0x6d, - 0xe1, - 0x38, - 0x72, - 0x39, - 0x9a, - 0x69, - 0xd4, - 0x71, - 0x38, - 0x3f, - 0x8b, - 0x13, - 0x39, - 0x60, - 0xdc, - 0x61, - 0x91, - 0x22, - 0x70, - 0x58, - 0x7c, - 0xdf, - 0x82, - 0x33, - 0xba, - }, - ) - require.Equal( - t, - ppt.ToAffineUncompressed(), - []byte{ - 0x4, - 0x1b, - 0xfa, - 0x44, - 0xfb, - 0x6, - 0xa4, - 0x6d, - 0xe1, - 0x38, - 0x72, - 0x39, - 0x9a, - 0x69, - 0xd4, - 0x71, - 0x38, - 0x3f, - 0x8b, - 0x13, - 0x39, - 0x60, - 0xdc, - 0x61, - 0x91, - 0x22, - 0x70, - 0x58, - 0x7c, - 0xdf, - 0x82, - 0x33, - 0xba, - 0x48, - 0xdf, - 0x58, - 0xac, - 0x70, - 0xf3, - 0x9b, - 0x9d, - 0x5d, - 0x84, - 0x6e, - 0x2d, - 0x75, - 0xc9, - 0x6, - 0x1e, - 0xd9, - 0x62, - 0x8b, - 0x15, - 0x0, - 0x65, - 0x69, - 0x79, - 0xfb, - 0x42, - 0xc, - 0x35, - 0xce, - 0x2e, - 0x8b, - 0xfd, - }, - ) - retP, err := ppt.FromAffineCompressed(ppt.ToAffineCompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - retP, err = ppt.FromAffineUncompressed(ppt.ToAffineUncompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - - // smoke test - for i := 0; i < 25; i++ { - s := p256.Scalar.Random(crand.Reader) - pt := g.Mul(s) - cmprs := pt.ToAffineCompressed() - require.Equal(t, len(cmprs), 33) - retC, err := pt.FromAffineCompressed(cmprs) - require.NoError(t, err) - require.True(t, pt.Equal(retC)) - - un := pt.ToAffineUncompressed() - require.Equal(t, len(un), 65) - retU, err := pt.FromAffineUncompressed(un) - require.NoError(t, err) - require.True(t, pt.Equal(retU)) - } -} - -func TestPointP256Nil(t *testing.T) { - p256 := P256() - one := p256.Point.Generator() - require.Nil(t, one.Add(nil)) - require.Nil(t, one.Sub(nil)) - require.Nil(t, one.Mul(nil)) - require.Nil(t, p256.Scalar.Random(nil)) - require.False(t, one.Equal(nil)) - _, err := p256.Scalar.SetBigInt(nil) - require.Error(t, err) -} - -func TestPointP256SumOfProducts(t *testing.T) { - lhs := new(PointP256).Generator().Mul(new(ScalarP256).New(50)) - points := make([]Point, 5) - for i := range points { - points[i] = new(PointP256).Generator() - } - scalars := []Scalar{ - new(ScalarP256).New(8), - new(ScalarP256).New(9), - new(ScalarP256).New(10), - new(ScalarP256).New(11), - new(ScalarP256).New(12), - } - rhs := lhs.SumOfProducts(points, scalars) - require.NotNil(t, rhs) - require.True(t, lhs.Equal(rhs)) -} diff --git a/crypto/core/curves/pallas_curve.go b/crypto/core/curves/pallas_curve.go deleted file mode 100644 index d30004378..000000000 --- a/crypto/core/curves/pallas_curve.go +++ /dev/null @@ -1,1216 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - "crypto/elliptic" - crand "crypto/rand" - "crypto/subtle" - "errors" - "fmt" - "io" - "math/big" - "sync" - - "golang.org/x/crypto/blake2b" - - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -var ( - b = new(fp.Fp).SetUint64(5) - three = &fp.Fp{ - 0x6b0ee5d0fffffff5, - 0x86f76d2b99b14bd0, - 0xfffffffffffffffe, - 0x3fffffffffffffff, - } - eight = &fp.Fp{ - 0x7387134cffffffe1, - 0xd973797adfadd5a8, - 0xfffffffffffffffb, - 0x3fffffffffffffff, - } - bool2int = map[bool]int{ - true: 1, - false: 0, - } -) - -var isomapper = [13]*fp.Fp{ - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x775f6034aaaaaaab, 0x4081775473d8375b, 0xe38e38e38e38e38e, 0x0e38e38e38e38e38}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x8cf863b02814fb76, 0x0f93b82ee4b99495, 0x267c7ffa51cf412a, 0x3509afd51872d88e}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x0eb64faef37ea4f7, 0x380af066cfeb6d69, 0x98c7d7ac3d98fd13, 0x17329b9ec5253753}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0xeebec06955555580, 0x8102eea8e7b06eb6, 0xc71c71c71c71c71c, 0x1c71c71c71c71c71}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0xc47f2ab668bcd71f, 0x9c434ac1c96b6980, 0x5a607fcce0494a79, 0x1d572e7ddc099cff}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x2aa3af1eae5b6604, 0xb4abf9fb9a1fc81c, 0x1d13bf2a7f22b105, 0x325669becaecd5d1}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x5ad985b5e38e38e4, 0x7642b01ad461bad2, 0x4bda12f684bda12f, 0x1a12f684bda12f68}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0xc67c31d8140a7dbb, 0x07c9dc17725cca4a, 0x133e3ffd28e7a095, 0x1a84d7ea8c396c47}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x02e2be87d225b234, 0x1765e924f7459378, 0x303216cce1db9ff1, 0x3fb98ff0d2ddcadd}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x93e53ab371c71c4f, 0x0ac03e8e134eb3e4, 0x7b425ed097b425ed, 0x025ed097b425ed09}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x5a28279b1d1b42ae, 0x5941a3a4a97aa1b3, 0x0790bfb3506defb6, 0x0c02c5bcca0e6b7f}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x4d90ab820b12320a, 0xd976bbfabbc5661d, 0x573b3d7f7d681310, 0x17033d3c60c68173}), - new( - fp.Fp, - ).SetRaw(&[4]uint64{0x992d30ecfffffde5, 0x224698fc094cf91b, 0x0000000000000000, 0x4000000000000000}), -} - -var ( - isoa = new( - fp.Fp, - ).SetRaw(&[4]uint64{0x92bb4b0b657a014b, 0xb74134581a27a59f, 0x49be2d7258370742, 0x18354a2eb0ea8c9c}) - isob = new(fp.Fp).SetRaw(&[4]uint64{1265, 0, 0, 0}) - z = new( - fp.Fp, - ).SetRaw(&[4]uint64{0x992d30ecfffffff4, 0x224698fc094cf91b, 0x0000000000000000, 0x4000000000000000}) -) - -var ( - oldPallasInitonce sync.Once - oldPallas PallasCurve -) - -type PallasCurve struct { - *elliptic.CurveParams -} - -func oldPallasInitAll() { - oldPallas.CurveParams = new(elliptic.CurveParams) - oldPallas.P = new(big.Int).SetBytes([]byte{ - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x46, 0x98, 0xfc, 0x09, 0x4c, 0xf9, 0x1b, - 0x99, 0x2d, 0x30, 0xed, 0x00, 0x00, 0x00, 0x01, - }) - oldPallas.N = new(big.Int).SetBytes([]byte{ - 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x22, 0x46, 0x98, 0xfc, 0x09, 0x94, 0xa8, 0xdd, - 0x8c, 0x46, 0xeb, 0x21, 0x00, 0x00, 0x00, 0x01, - }) - g := new(Ep).Generator() - oldPallas.Gx = g.x.BigInt() - oldPallas.Gy = g.y.BigInt() - oldPallas.B = big.NewInt(5) - oldPallas.BitSize = 255 - pallas.Name = PallasName -} - -func Pallas() *PallasCurve { - oldPallasInitonce.Do(oldPallasInitAll) - return &oldPallas -} - -func (curve *PallasCurve) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *PallasCurve) IsOnCurve(x, y *big.Int) bool { - p := new(Ep) - p.x = new(fp.Fp).SetBigInt(x) - p.y = new(fp.Fp).SetBigInt(y) - p.z = new(fp.Fp).SetOne() - - return p.IsOnCurve() -} - -func (curve *PallasCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - p := new(Ep) - p.x = new(fp.Fp).SetBigInt(x1) - p.y = new(fp.Fp).SetBigInt(y1) - p.z = new(fp.Fp).SetOne() - if p.x.IsZero() && p.y.IsZero() { - p.z.SetZero() - } - - q := new(Ep) - q.x = new(fp.Fp).SetBigInt(x2) - q.y = new(fp.Fp).SetBigInt(y2) - q.z = new(fp.Fp).SetOne() - if q.x.IsZero() && q.y.IsZero() { - q.z.SetZero() - } - p.Add(p, q) - p.toAffine() - return p.x.BigInt(), p.y.BigInt() -} - -func (curve *PallasCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p := new(Ep) - p.x = new(fp.Fp).SetBigInt(x1) - p.y = new(fp.Fp).SetBigInt(y1) - p.z = new(fp.Fp).SetOne() - if p.x.IsZero() && p.y.IsZero() { - p.z.SetZero() - } - p.Double(p) - p.toAffine() - return p.x.BigInt(), p.y.BigInt() -} - -func (curve *PallasCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p := new(Ep) - p.x = new(fp.Fp).SetBigInt(Bx) - p.y = new(fp.Fp).SetBigInt(By) - p.z = new(fp.Fp).SetOne() - if p.x.IsZero() && p.y.IsZero() { - p.z.SetZero() - } - var t [32]byte - copy(t[:], k) - ss := new(big.Int).SetBytes(k) - sc := new(fq.Fq).SetBigInt(ss) - p.Mul(p, sc) - p.toAffine() - return p.x.BigInt(), p.y.BigInt() -} - -func (curve *PallasCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - p := new(Ep).Generator() - var t [32]byte - copy(t[:], k) - ss := new(big.Int).SetBytes(k) - sc := new(fq.Fq).SetBigInt(ss) - p.Mul(p, sc) - p.toAffine() - return p.x.BigInt(), p.y.BigInt() -} - -// PallasScalar - Old interface -type PallasScalar struct{} - -func NewPallasScalar() *PallasScalar { - return &PallasScalar{} -} - -func (k PallasScalar) Add(x, y *big.Int) *big.Int { - r := new(big.Int).Add(x, y) - return r.Mod(r, fq.BiModulus) -} - -func (k PallasScalar) Sub(x, y *big.Int) *big.Int { - r := new(big.Int).Sub(x, y) - return r.Mod(r, fq.BiModulus) -} - -func (k PallasScalar) Neg(x *big.Int) *big.Int { - r := new(big.Int).Neg(x) - return r.Mod(r, fq.BiModulus) -} - -func (k PallasScalar) Mul(x, y *big.Int) *big.Int { - r := new(big.Int).Mul(x, y) - return r.Mod(r, fq.BiModulus) -} - -func (k PallasScalar) Div(x, y *big.Int) *big.Int { - r := new(big.Int).ModInverse(y, fq.BiModulus) - r.Mul(r, x) - return r.Mod(r, fq.BiModulus) -} - -func (k PallasScalar) Hash(input []byte) *big.Int { - return new(ScalarPallas).Hash(input).(*ScalarPallas).value.BigInt() -} - -func (k PallasScalar) Bytes(x *big.Int) []byte { - return x.Bytes() -} - -func (k PallasScalar) Random() (*big.Int, error) { - s, ok := new(ScalarPallas).Random(crand.Reader).(*ScalarPallas) - if !ok { - return nil, errors.New("incorrect type conversion") - } - return s.value.BigInt(), nil -} - -func (k PallasScalar) IsValid(x *big.Int) bool { - return x.Cmp(fq.BiModulus) == -1 -} - -// ScalarPallas - New interface -type ScalarPallas struct { - value *fq.Fq -} - -func (s *ScalarPallas) Random(reader io.Reader) Scalar { - if reader == nil { - return nil - } - var seed [64]byte - _, _ = reader.Read(seed[:]) - return s.Hash(seed[:]) -} - -func (s *ScalarPallas) Hash(bytes []byte) Scalar { - h, _ := blake2b.New(64, []byte{}) - xmd, err := expandMsgXmd(h, bytes, []byte("pallas_XMD:BLAKE2b_SSWU_RO_"), 64) - if err != nil { - return nil - } - var t [64]byte - copy(t[:], xmd) - return &ScalarPallas{ - value: new(fq.Fq).SetBytesWide(&t), - } -} - -func (s *ScalarPallas) Zero() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).SetZero(), - } -} - -func (s *ScalarPallas) One() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).SetOne(), - } -} - -func (s *ScalarPallas) IsZero() bool { - return s.value.IsZero() -} - -func (s *ScalarPallas) IsOne() bool { - return s.value.IsOne() -} - -func (s *ScalarPallas) IsOdd() bool { - return (s.value[0] & 1) == 1 -} - -func (s *ScalarPallas) IsEven() bool { - return (s.value[0] & 1) == 0 -} - -func (s *ScalarPallas) New(value int) Scalar { - v := big.NewInt(int64(value)) - return &ScalarPallas{ - value: new(fq.Fq).SetBigInt(v), - } -} - -func (s *ScalarPallas) Cmp(rhs Scalar) int { - r, ok := rhs.(*ScalarPallas) - if ok { - return s.value.Cmp(r.value) - } else { - return -2 - } -} - -func (s *ScalarPallas) Square() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).Square(s.value), - } -} - -func (s *ScalarPallas) Double() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).Double(s.value), - } -} - -func (s *ScalarPallas) Invert() (Scalar, error) { - value, wasInverted := new(fq.Fq).Invert(s.value) - if !wasInverted { - return nil, fmt.Errorf("inverse doesn't exist") - } - return &ScalarPallas{ - value, - }, nil -} - -func (s *ScalarPallas) Sqrt() (Scalar, error) { - value, wasSquare := new(fq.Fq).Sqrt(s.value) - if !wasSquare { - return nil, fmt.Errorf("not a square") - } - return &ScalarPallas{ - value, - }, nil -} - -func (s *ScalarPallas) Cube() Scalar { - value := new(fq.Fq).Mul(s.value, s.value) - value.Mul(value, s.value) - return &ScalarPallas{ - value, - } -} - -func (s *ScalarPallas) Add(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarPallas) - if ok { - return &ScalarPallas{ - value: new(fq.Fq).Add(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarPallas) Sub(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarPallas) - if ok { - return &ScalarPallas{ - value: new(fq.Fq).Sub(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarPallas) Mul(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarPallas) - if ok { - return &ScalarPallas{ - value: new(fq.Fq).Mul(s.value, r.value), - } - } else { - return nil - } -} - -func (s *ScalarPallas) MulAdd(y, z Scalar) Scalar { - return s.Mul(y).Add(z) -} - -func (s *ScalarPallas) Div(rhs Scalar) Scalar { - r, ok := rhs.(*ScalarPallas) - if ok { - v, wasInverted := new(fq.Fq).Invert(r.value) - if !wasInverted { - return nil - } - v.Mul(v, s.value) - return &ScalarPallas{value: v} - } else { - return nil - } -} - -func (s *ScalarPallas) Neg() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).Neg(s.value), - } -} - -func (s *ScalarPallas) SetBigInt(v *big.Int) (Scalar, error) { - return &ScalarPallas{ - value: new(fq.Fq).SetBigInt(v), - }, nil -} - -func (s *ScalarPallas) BigInt() *big.Int { - return s.value.BigInt() -} - -func (s *ScalarPallas) Bytes() []byte { - t := s.value.Bytes() - return t[:] -} - -func (s *ScalarPallas) SetBytes(bytes []byte) (Scalar, error) { - if len(bytes) != 32 { - return nil, fmt.Errorf("invalid length") - } - var seq [32]byte - copy(seq[:], bytes) - value, err := new(fq.Fq).SetBytes(&seq) - if err != nil { - return nil, err - } - return &ScalarPallas{ - value, - }, nil -} - -func (s *ScalarPallas) SetBytesWide(bytes []byte) (Scalar, error) { - if len(bytes) != 64 { - return nil, fmt.Errorf("invalid length") - } - var seq [64]byte - copy(seq[:], bytes) - return &ScalarPallas{ - value: new(fq.Fq).SetBytesWide(&seq), - }, nil -} - -func (s *ScalarPallas) Point() Point { - return new(PointPallas).Identity() -} - -func (s *ScalarPallas) Clone() Scalar { - return &ScalarPallas{ - value: new(fq.Fq).Set(s.value), - } -} - -func (s *ScalarPallas) GetFq() *fq.Fq { - return new(fq.Fq).Set(s.value) -} - -func (s *ScalarPallas) SetFq(fq *fq.Fq) *ScalarPallas { - s.value = fq - return s -} - -func (s *ScalarPallas) MarshalBinary() ([]byte, error) { - return scalarMarshalBinary(s) -} - -func (s *ScalarPallas) UnmarshalBinary(input []byte) error { - sc, err := scalarUnmarshalBinary(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarPallas) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarPallas) MarshalText() ([]byte, error) { - return scalarMarshalText(s) -} - -func (s *ScalarPallas) UnmarshalText(input []byte) error { - sc, err := scalarUnmarshalText(input) - if err != nil { - return err - } - ss, ok := sc.(*ScalarPallas) - if !ok { - return fmt.Errorf("invalid scalar") - } - s.value = ss.value - return nil -} - -func (s *ScalarPallas) MarshalJSON() ([]byte, error) { - return scalarMarshalJson(s) -} - -func (s *ScalarPallas) UnmarshalJSON(input []byte) error { - sc, err := scalarUnmarshalJson(input) - if err != nil { - return err - } - S, ok := sc.(*ScalarPallas) - if !ok { - return fmt.Errorf("invalid type") - } - s.value = S.value - return nil -} - -type PointPallas struct { - value *Ep -} - -func (p *PointPallas) Random(reader io.Reader) Point { - return &PointPallas{new(Ep).Random(reader)} -} - -func (p *PointPallas) Hash(bytes []byte) Point { - return &PointPallas{new(Ep).Hash(bytes)} -} - -func (p *PointPallas) Identity() Point { - return &PointPallas{new(Ep).Identity()} -} - -func (p *PointPallas) Generator() Point { - return &PointPallas{new(Ep).Generator()} -} - -func (p *PointPallas) IsIdentity() bool { - return p.value.IsIdentity() -} - -func (p *PointPallas) IsNegative() bool { - return p.value.Y().IsOdd() -} - -func (p *PointPallas) IsOnCurve() bool { - return p.value.IsOnCurve() -} - -func (p *PointPallas) Double() Point { - return &PointPallas{new(Ep).Double(p.value)} -} - -func (p *PointPallas) Scalar() Scalar { - return &ScalarPallas{new(fq.Fq).SetZero()} -} - -func (p *PointPallas) Neg() Point { - return &PointPallas{new(Ep).Neg(p.value)} -} - -func (p *PointPallas) Add(rhs Point) Point { - r, ok := rhs.(*PointPallas) - if !ok { - return nil - } - return &PointPallas{new(Ep).Add(p.value, r.value)} -} - -func (p *PointPallas) Sub(rhs Point) Point { - r, ok := rhs.(*PointPallas) - if !ok { - return nil - } - return &PointPallas{new(Ep).Sub(p.value, r.value)} -} - -func (p *PointPallas) Mul(rhs Scalar) Point { - s, ok := rhs.(*ScalarPallas) - if !ok { - return nil - } - return &PointPallas{new(Ep).Mul(p.value, s.value)} -} - -func (p *PointPallas) Equal(rhs Point) bool { - r, ok := rhs.(*PointPallas) - if !ok { - return false - } - return p.value.Equal(r.value) -} - -func (p *PointPallas) Set(x, y *big.Int) (Point, error) { - xx := subtle.ConstantTimeCompare(x.Bytes(), []byte{}) - yy := subtle.ConstantTimeCompare(y.Bytes(), []byte{}) - xElem := new(fp.Fp).SetBigInt(x) - var data [32]byte - if yy == 1 { - if xx == 1 { - return &PointPallas{new(Ep).Identity()}, nil - } - data = xElem.Bytes() - return p.FromAffineCompressed(data[:]) - } - yElem := new(fp.Fp).SetBigInt(y) - value := &Ep{xElem, yElem, new(fp.Fp).SetOne()} - if !value.IsOnCurve() { - return nil, fmt.Errorf("point is not on the curve") - } - return &PointPallas{value}, nil -} - -func (p *PointPallas) ToAffineCompressed() []byte { - return p.value.ToAffineCompressed() -} - -func (p *PointPallas) ToAffineUncompressed() []byte { - return p.value.ToAffineUncompressed() -} - -func (p *PointPallas) FromAffineCompressed(bytes []byte) (Point, error) { - value, err := new(Ep).FromAffineCompressed(bytes) - if err != nil { - return nil, err - } - return &PointPallas{value}, nil -} - -func (p *PointPallas) FromAffineUncompressed(bytes []byte) (Point, error) { - value, err := new(Ep).FromAffineUncompressed(bytes) - if err != nil { - return nil, err - } - return &PointPallas{value}, nil -} - -func (p *PointPallas) CurveName() string { - return PallasName -} - -func (p *PointPallas) SumOfProducts(points []Point, scalars []Scalar) Point { - eps := make([]*Ep, len(points)) - for i, pt := range points { - ps, ok := pt.(*PointPallas) - if !ok { - return nil - } - eps[i] = ps.value - } - value := p.value.SumOfProducts(eps, scalars) - return &PointPallas{value} -} - -func (p *PointPallas) MarshalBinary() ([]byte, error) { - return pointMarshalBinary(p) -} - -func (p *PointPallas) UnmarshalBinary(input []byte) error { - pt, err := pointUnmarshalBinary(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointPallas) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointPallas) MarshalText() ([]byte, error) { - return pointMarshalText(p) -} - -func (p *PointPallas) UnmarshalText(input []byte) error { - pt, err := pointUnmarshalText(input) - if err != nil { - return err - } - ppt, ok := pt.(*PointPallas) - if !ok { - return fmt.Errorf("invalid point") - } - p.value = ppt.value - return nil -} - -func (p *PointPallas) MarshalJSON() ([]byte, error) { - return pointMarshalJSON(p) -} - -func (p *PointPallas) UnmarshalJSON(input []byte) error { - pt, err := pointUnmarshalJSON(input) - if err != nil { - return err - } - P, ok := pt.(*PointPallas) - if !ok { - return fmt.Errorf("invalid type") - } - p.value = P.value - return nil -} - -func (p *PointPallas) X() *fp.Fp { - return p.value.X() -} - -func (p *PointPallas) Y() *fp.Fp { - return p.value.Y() -} - -func (p *PointPallas) GetEp() *Ep { - return new(Ep).Set(p.value) -} - -type Ep struct { - x *fp.Fp - y *fp.Fp - z *fp.Fp -} - -func (p *Ep) Random(reader io.Reader) *Ep { - var seed [64]byte - _, _ = reader.Read(seed[:]) - return p.Hash(seed[:]) -} - -func (p *Ep) Hash(bytes []byte) *Ep { - if bytes == nil { - bytes = []byte{} - } - h, _ := blake2b.New(64, []byte{}) - u, _ := expandMsgXmd(h, bytes, []byte("pallas_XMD:BLAKE2b_SSWU_RO_"), 128) - var buf [64]byte - copy(buf[:], u[:64]) - u0 := new(fp.Fp).SetBytesWide(&buf) - copy(buf[:], u[64:]) - u1 := new(fp.Fp).SetBytesWide(&buf) - - q0 := mapSswu(u0) - q1 := mapSswu(u1) - r1 := isoMap(q0) - r2 := isoMap(q1) - return p.Identity().Add(r1, r2) -} - -func (p *Ep) Identity() *Ep { - p.x = new(fp.Fp).SetZero() - p.y = new(fp.Fp).SetZero() - p.z = new(fp.Fp).SetZero() - return p -} - -func (p *Ep) Generator() *Ep { - p.x = new(fp.Fp).SetOne() - p.y = &fp.Fp{0x2f474795455d409d, 0xb443b9b74b8255d9, 0x270c412f2c9a5d66, 0x8e00f71ba43dd6b} - p.z = new(fp.Fp).SetOne() - return p -} - -func (p *Ep) IsIdentity() bool { - return p.z.IsZero() -} - -func (p *Ep) Double(other *Ep) *Ep { - if other.IsIdentity() { - p.Set(other) - return p - } - r := new(Ep) - // essentially paraphrased https://github.com/MinaProtocol/c-reference-signer/blob/master/crypto.c#L306-L337 - a := new(fp.Fp).Square(other.x) - b := new(fp.Fp).Square(other.y) - c := new(fp.Fp).Square(b) - r.x = new(fp.Fp).Add(other.x, b) - r.y = new(fp.Fp).Square(r.x) - r.z = new(fp.Fp).Sub(r.y, a) - r.x.Sub(r.z, c) - d := new(fp.Fp).Double(r.x) - e := new(fp.Fp).Mul(three, a) - f := new(fp.Fp).Square(e) - r.y.Double(d) - r.x.Sub(f, r.y) - r.y.Sub(d, r.x) - f.Mul(eight, c) - r.z.Mul(e, r.y) - r.y.Sub(r.z, f) - f.Mul(other.y, other.z) - r.z.Double(f) - p.Set(r) - return p -} - -func (p *Ep) Neg(other *Ep) *Ep { - p.x = new(fp.Fp).Set(other.x) - p.y = new(fp.Fp).Neg(other.y) - p.z = new(fp.Fp).Set(other.z) - return p -} - -func (p *Ep) Add(lhs *Ep, rhs *Ep) *Ep { - if lhs.IsIdentity() { - return p.Set(rhs) - } - if rhs.IsIdentity() { - return p.Set(lhs) - } - z1z1 := new(fp.Fp).Square(lhs.z) - z2z2 := new(fp.Fp).Square(rhs.z) - u1 := new(fp.Fp).Mul(lhs.x, z2z2) - u2 := new(fp.Fp).Mul(rhs.x, z1z1) - s1 := new(fp.Fp).Mul(lhs.y, z2z2) - s1.Mul(s1, rhs.z) - s2 := new(fp.Fp).Mul(rhs.y, z1z1) - s2.Mul(s2, lhs.z) - - if u1.Equal(u2) { - if s1.Equal(s2) { - return p.Double(lhs) - } else { - return p.Identity() - } - } else { - h := new(fp.Fp).Sub(u2, u1) - i := new(fp.Fp).Double(h) - i.Square(i) - j := new(fp.Fp).Mul(i, h) - r := new(fp.Fp).Sub(s2, s1) - r.Double(r) - v := new(fp.Fp).Mul(u1, i) - x3 := new(fp.Fp).Square(r) - x3.Sub(x3, j) - x3.Sub(x3, new(fp.Fp).Double(v)) - s1.Mul(s1, j) - s1.Double(s1) - y3 := new(fp.Fp).Mul(r, new(fp.Fp).Sub(v, x3)) - y3.Sub(y3, s1) - z3 := new(fp.Fp).Add(lhs.z, rhs.z) - z3.Square(z3) - z3.Sub(z3, z1z1) - z3.Sub(z3, z2z2) - z3.Mul(z3, h) - p.x = new(fp.Fp).Set(x3) - p.y = new(fp.Fp).Set(y3) - p.z = new(fp.Fp).Set(z3) - - return p - } -} - -func (p *Ep) Sub(lhs, rhs *Ep) *Ep { - return p.Add(lhs, new(Ep).Neg(rhs)) -} - -func (p *Ep) Mul(point *Ep, scalar *fq.Fq) *Ep { - bytes := scalar.Bytes() - precomputed := [16]*Ep{} - precomputed[0] = new(Ep).Identity() - precomputed[1] = new(Ep).Set(point) - for i := 2; i < 16; i += 2 { - precomputed[i] = new(Ep).Double(precomputed[i>>1]) - precomputed[i+1] = new(Ep).Add(precomputed[i], point) - } - p.Identity() - for i := 0; i < 256; i += 4 { - // Brouwer / windowing method. window size of 4. - for j := 0; j < 4; j++ { - p.Double(p) - } - window := bytes[32-1-i>>3] >> (4 - i&0x04) & 0x0F - p.Add(p, precomputed[window]) - } - return p -} - -func (p *Ep) Equal(other *Ep) bool { - // warning: requires converting both to affine - // could save slightly by modifying one so that its z-value equals the other - // this would save one inversion and a handful of multiplications - // but this is more subtle and error-prone, so going to just convert both to affine. - lhs := new(Ep).Set(p) - rhs := new(Ep).Set(other) - lhs.toAffine() - rhs.toAffine() - return lhs.x.Equal(rhs.x) && lhs.y.Equal(rhs.y) -} - -func (p *Ep) Set(other *Ep) *Ep { - // check is identity or on curve - p.x = new(fp.Fp).Set(other.x) - p.y = new(fp.Fp).Set(other.y) - p.z = new(fp.Fp).Set(other.z) - return p -} - -func (p *Ep) toAffine() *Ep { - // mutates `p` in-place to convert it to "affine" form. - if p.IsIdentity() { - // warning: control flow / not constant-time - p.x.SetZero() - p.y.SetZero() - p.z.SetOne() - return p - } - zInv3, _ := new(fp.Fp).Invert(p.z) // z is necessarily nonzero - zInv2 := new(fp.Fp).Square(zInv3) - zInv3.Mul(zInv3, zInv2) - p.x.Mul(p.x, zInv2) - p.y.Mul(p.y, zInv3) - p.z.SetOne() - return p -} - -func (p *Ep) ToAffineCompressed() []byte { - // Use ZCash encoding where infinity is all zeros - // and the top bit represents the sign of y and the - // remainder represent the x-coordinate - var inf [32]byte - p1 := new(Ep).Set(p) - p1.toAffine() - x := p1.x.Bytes() - x[31] |= (p1.y.Bytes()[0] & 1) << 7 - subtle.ConstantTimeCopy(bool2int[p1.IsIdentity()], x[:], inf[:]) - return x[:] -} - -func (p *Ep) ToAffineUncompressed() []byte { - p1 := new(Ep).Set(p) - p1.toAffine() - x := p1.x.Bytes() - y := p1.y.Bytes() - return append(x[:], y[:]...) -} - -func (p *Ep) FromAffineCompressed(bytes []byte) (*Ep, error) { - if len(bytes) != 32 { - return nil, fmt.Errorf("invalid byte sequence") - } - - var input [32]byte - copy(input[:], bytes) - sign := (input[31] >> 7) & 1 - input[31] &= 0x7F - - x := new(fp.Fp) - if _, err := x.SetBytes(&input); err != nil { - return nil, err - } - rhs := rhsPallas(x) - if _, square := rhs.Sqrt(rhs); !square { - return nil, fmt.Errorf("rhs of given x-coordinate is not a square") - } - if rhs.Bytes()[0]&1 != sign { - rhs.Neg(rhs) - } - p.x = x - p.y = rhs - p.z = new(fp.Fp).SetOne() - if !p.IsOnCurve() { - return nil, fmt.Errorf("invalid point") - } - return p, nil -} - -func (p *Ep) FromAffineUncompressed(bytes []byte) (*Ep, error) { - if len(bytes) != 64 { - return nil, fmt.Errorf("invalid length") - } - p.z = new(fp.Fp).SetOne() - p.x = new(fp.Fp) - p.y = new(fp.Fp) - var x, y [32]byte - copy(x[:], bytes[:32]) - copy(y[:], bytes[32:]) - if _, err := p.x.SetBytes(&x); err != nil { - return nil, err - } - if _, err := p.y.SetBytes(&y); err != nil { - return nil, err - } - if !p.IsOnCurve() { - return nil, fmt.Errorf("invalid point") - } - return p, nil -} - -// rhs of the curve equation -func rhsPallas(x *fp.Fp) *fp.Fp { - x2 := new(fp.Fp).Square(x) - x3 := new(fp.Fp).Mul(x, x2) - return new(fp.Fp).Add(x3, b) -} - -func (p Ep) CurveName() string { - return "pallas" -} - -func (p Ep) SumOfProducts(points []*Ep, scalars []Scalar) *Ep { - nScalars := make([]*big.Int, len(scalars)) - for i, s := range scalars { - sc, ok := s.(*ScalarPallas) - if !ok { - return nil - } - nScalars[i] = sc.value.BigInt() - } - return sumOfProductsPippengerPallas(points, nScalars) -} - -func (p *Ep) X() *fp.Fp { - t := new(Ep).Set(p) - t.toAffine() - return new(fp.Fp).Set(t.x) -} - -func (p *Ep) Y() *fp.Fp { - t := new(Ep).Set(p) - t.toAffine() - return new(fp.Fp).Set(t.y) -} - -func (p *Ep) IsOnCurve() bool { - // y^2 = x^3 + axz^4 + bz^6 - // a = 0 - // b = 5 - z2 := new(fp.Fp).Square(p.z) - z4 := new(fp.Fp).Square(z2) - z6 := new(fp.Fp).Mul(z2, z4) - x2 := new(fp.Fp).Square(p.x) - x3 := new(fp.Fp).Mul(x2, p.x) - - lhs := new(fp.Fp).Square(p.y) - rhs := new(fp.Fp).SetUint64(5) - rhs.Mul(rhs, z6) - rhs.Add(rhs, x3) - return p.z.IsZero() || lhs.Equal(rhs) -} - -func (p *Ep) CMove(lhs, rhs *Ep, condition int) *Ep { - p.x = new(fp.Fp).CMove(lhs.x, rhs.x, condition) - p.y = new(fp.Fp).CMove(lhs.y, rhs.y, condition) - p.z = new(fp.Fp).CMove(lhs.z, rhs.z, condition) - return p -} - -func sumOfProductsPippengerPallas(points []*Ep, scalars []*big.Int) *Ep { - if len(points) != len(scalars) { - return nil - } - - const w = 6 - - bucketSize := (1 << w) - 1 - windows := make([]*Ep, 255/w+1) - for i := range windows { - windows[i] = new(Ep).Identity() - } - bucket := make([]*Ep, bucketSize) - - for j := 0; j < len(windows); j++ { - for i := 0; i < bucketSize; i++ { - bucket[i] = new(Ep).Identity() - } - - for i := 0; i < len(scalars); i++ { - index := bucketSize & int(new(big.Int).Rsh(scalars[i], uint(w*j)).Int64()) - if index != 0 { - bucket[index-1].Add(bucket[index-1], points[i]) - } - } - - acc, sum := new(Ep).Identity(), new(Ep).Identity() - - for i := bucketSize - 1; i >= 0; i-- { - sum.Add(sum, bucket[i]) - acc.Add(acc, sum) - } - windows[j] = acc - } - - acc := new(Ep).Identity() - for i := len(windows) - 1; i >= 0; i-- { - for j := 0; j < w; j++ { - acc.Double(acc) - } - acc.Add(acc, windows[i]) - } - return acc -} - -// Implements a degree 3 isogeny map. -// The input and output are in Jacobian coordinates, using the method -// in "Avoiding inversions" [WB2019, section 4.3]. -func isoMap(p *Ep) *Ep { - var z [4]*fp.Fp - z[0] = new(fp.Fp).Square(p.z) // z^2 - z[1] = new(fp.Fp).Mul(z[0], p.z) // z^3 - z[2] = new(fp.Fp).Square(z[0]) // z^4 - z[3] = new(fp.Fp).Square(z[1]) // z^6 - - // ((iso[0] * x + iso[1] * z^2) * x + iso[2] * z^4) * x + iso[3] * z^6 - numX := new(fp.Fp).Set(isomapper[0]) - numX.Mul(numX, p.x) - numX.Add(numX, new(fp.Fp).Mul(isomapper[1], z[0])) - numX.Mul(numX, p.x) - numX.Add(numX, new(fp.Fp).Mul(isomapper[2], z[2])) - numX.Mul(numX, p.x) - numX.Add(numX, new(fp.Fp).Mul(isomapper[3], z[3])) - - // (z^2 * x + iso[4] * z^4) * x + iso[5] * z^6 - divX := new(fp.Fp).Set(z[0]) - divX.Mul(divX, p.x) - divX.Add(divX, new(fp.Fp).Mul(isomapper[4], z[2])) - divX.Mul(divX, p.x) - divX.Add(divX, new(fp.Fp).Mul(isomapper[5], z[3])) - - // (((iso[6] * x + iso[7] * z2) * x + iso[8] * z4) * x + iso[9] * z6) * y - numY := new(fp.Fp).Set(isomapper[6]) - numY.Mul(numY, p.x) - numY.Add(numY, new(fp.Fp).Mul(isomapper[7], z[0])) - numY.Mul(numY, p.x) - numY.Add(numY, new(fp.Fp).Mul(isomapper[8], z[2])) - numY.Mul(numY, p.x) - numY.Add(numY, new(fp.Fp).Mul(isomapper[9], z[3])) - numY.Mul(numY, p.y) - - // (((x + iso[10] * z2) * x + iso[11] * z4) * x + iso[12] * z6) * z3 - divY := new(fp.Fp).Set(p.x) - divY.Add(divY, new(fp.Fp).Mul(isomapper[10], z[0])) - divY.Mul(divY, p.x) - divY.Add(divY, new(fp.Fp).Mul(isomapper[11], z[2])) - divY.Mul(divY, p.x) - divY.Add(divY, new(fp.Fp).Mul(isomapper[12], z[3])) - divY.Mul(divY, z[1]) - - z0 := new(fp.Fp).Mul(divX, divY) - x := new(fp.Fp).Mul(numX, divY) - x.Mul(x, z0) - y := new(fp.Fp).Mul(numY, divX) - y.Mul(y, new(fp.Fp).Square(z0)) - - return &Ep{ - x, y, z0, - } -} - -func mapSswu(u *fp.Fp) *Ep { - // c1 := new(fp.Fp).Neg(isoa) - // c1.Invert(c1) - // c1.Mul(isob, c1) - c1 := &fp.Fp{ - 0x1ee770ce078456ec, - 0x48cfd64c2ce76be0, - 0x43d5774c0ab79e2f, - 0x23368d2bdce28cf3, - } - // c2 := new(fp.Fp).Neg(z) - // c2.Invert(c2) - c2 := &fp.Fp{ - 0x03df915f89d89d8a, - 0x8f1e8db09ef82653, - 0xd89d89d89d89d89d, - 0x1d89d89d89d89d89, - } - - u2 := new(fp.Fp).Square(u) - tv1 := new(fp.Fp).Mul(z, u2) - tv2 := new(fp.Fp).Square(tv1) - x1 := new(fp.Fp).Add(tv1, tv2) - x1.Invert(x1) - e1 := bool2int[x1.IsZero()] - x1.Add(x1, new(fp.Fp).SetOne()) - x1.CMove(x1, c2, e1) - x1.Mul(x1, c1) - gx1 := new(fp.Fp).Square(x1) - gx1.Add(gx1, isoa) - gx1.Mul(gx1, x1) - gx1.Add(gx1, isob) - x2 := new(fp.Fp).Mul(tv1, x1) - tv2.Mul(tv1, tv2) - gx2 := new(fp.Fp).Mul(gx1, tv2) - gx1Sqrt, e2 := new(fp.Fp).Sqrt(gx1) - x := new(fp.Fp).CMove(x2, x1, bool2int[e2]) - gx2Sqrt, _ := new(fp.Fp).Sqrt(gx2) - y := new(fp.Fp).CMove(gx2Sqrt, gx1Sqrt, bool2int[e2]) - e3 := u.IsOdd() == y.IsOdd() - y.CMove(new(fp.Fp).Neg(y), y, bool2int[e3]) - - return &Ep{ - x: x, y: y, z: new(fp.Fp).SetOne(), - } -} diff --git a/crypto/core/curves/pallas_curve_test.go b/crypto/core/curves/pallas_curve_test.go deleted file mode 100644 index 76545fe17..000000000 --- a/crypto/core/curves/pallas_curve_test.go +++ /dev/null @@ -1,244 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package curves - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -func TestPointPallasAddDoubleMul(t *testing.T) { - g := new(Ep).Generator() - id := new(Ep).Identity() - require.Equal(t, g.Add(g, id), g) - - g2 := new(Ep).Add(g, g) - require.True(t, new(Ep).Double(g).Equal(g2)) - require.Equal(t, new(Ep).Double(g), new(Ep).Add(g, g)) - g3 := new(Ep).Add(g, g2) - require.True(t, g3.Equal(new(Ep).Mul(g, new(fq.Fq).SetUint64(3)))) - - g4 := new(Ep).Add(g3, g) - require.True(t, g4.Equal(new(Ep).Double(g2))) - require.True(t, g4.Equal(new(Ep).Mul(g, new(fq.Fq).SetUint64(4)))) -} - -func TestPointPallasHash(t *testing.T) { - h0 := new(Ep).Hash(nil) - require.True(t, h0.IsOnCurve()) - h1 := new(Ep).Hash([]byte{}) - require.True(t, h1.IsOnCurve()) - require.True(t, h0.Equal(h1)) - h2 := new(Ep).Hash([]byte{1}) - require.True(t, h2.IsOnCurve()) -} - -func TestPointPallasNeg(t *testing.T) { - g := new(Ep).Generator() - g.Neg(g) - require.True(t, g.Neg(g).Equal(new(Ep).Generator())) - id := new(Ep).Identity() - require.True(t, new(Ep).Neg(id).Equal(id)) -} - -func TestPointPallasRandom(t *testing.T) { - a := new(Ep).Random(testRng()) - require.NotNil(t, a.x) - require.NotNil(t, a.y) - require.NotNil(t, a.z) - require.True(t, a.IsOnCurve()) - e := &Ep{ - x: &fp.Fp{ - 0x7263083d01d4859c, - 0x65a03323b5a3d204, - 0xe71d73222b136668, - 0x1d1b1bcf1256b539, - }, - y: &fp.Fp{ - 0x8cc2516ffe23e1bb, - 0x5418f941eeaca812, - 0x16c9af658a846f29, - 0x11c572091c418668, - }, - z: &fp.Fp{ - 0xa879589adb77a88e, - 0x5444a531a19f2406, - 0x637ff77c51dda524, - 0x0369e90d219ce821, - }, - } - require.True(t, a.Equal(e)) -} - -func TestPointPallasSerialize(t *testing.T) { - ss := new(ScalarPallas).Random(testRng()).(*ScalarPallas) - g := new(Ep).Generator() - - ppt := new(Ep).Mul(g, ss.value) - require.Equal( - t, - ppt.ToAffineCompressed(), - []byte{ - 0x1c, - 0x6d, - 0x47, - 0x1f, - 0x4a, - 0x81, - 0xcd, - 0x8, - 0x4e, - 0xb3, - 0x17, - 0x9a, - 0xcd, - 0x17, - 0xe2, - 0x9a, - 0x24, - 0x69, - 0xb, - 0x4e, - 0x69, - 0x5f, - 0x35, - 0x1a, - 0x92, - 0x12, - 0x95, - 0xc9, - 0xe6, - 0xd3, - 0x7a, - 0x0, - }, - ) - require.Equal( - t, - ppt.ToAffineUncompressed(), - []byte{ - 0x1c, - 0x6d, - 0x47, - 0x1f, - 0x4a, - 0x81, - 0xcd, - 0x8, - 0x4e, - 0xb3, - 0x17, - 0x9a, - 0xcd, - 0x17, - 0xe2, - 0x9a, - 0x24, - 0x69, - 0xb, - 0x4e, - 0x69, - 0x5f, - 0x35, - 0x1a, - 0x92, - 0x12, - 0x95, - 0xc9, - 0xe6, - 0xd3, - 0x7a, - 0x0, - 0x80, - 0x5c, - 0xa1, - 0x56, - 0x6d, - 0x1b, - 0x87, - 0x5f, - 0xb0, - 0x2e, - 0xae, - 0x85, - 0x4e, - 0x86, - 0xa9, - 0xcd, - 0xde, - 0x37, - 0x6a, - 0xc8, - 0x4a, - 0x80, - 0xf6, - 0x43, - 0xaa, - 0xe6, - 0x2c, - 0x2d, - 0x15, - 0xdb, - 0xda, - 0x29, - }, - ) - retP, err := new(Ep).FromAffineCompressed(ppt.ToAffineCompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - retP, err = new(Ep).FromAffineUncompressed(ppt.ToAffineUncompressed()) - require.NoError(t, err) - require.True(t, ppt.Equal(retP)) - - // smoke test - for i := 0; i < 25; i++ { - s := new(ScalarPallas).Random(crand.Reader).(*ScalarPallas) - pt := new(Ep).Mul(g, s.value) - cmprs := pt.ToAffineCompressed() - require.Equal(t, len(cmprs), 32) - retC, err := new(Ep).FromAffineCompressed(cmprs) - require.NoError(t, err) - require.True(t, pt.Equal(retC)) - - un := pt.ToAffineUncompressed() - require.Equal(t, len(un), 64) - retU, err := new(Ep).FromAffineUncompressed(un) - require.NoError(t, err) - require.True(t, pt.Equal(retU)) - } -} - -func TestPointPallasCMove(t *testing.T) { - a := new(Ep).Random(crand.Reader) - b := new(Ep).Random(crand.Reader) - require.True(t, new(Ep).CMove(a, b, 1).Equal(b)) - require.True(t, new(Ep).CMove(a, b, 0).Equal(a)) -} - -func TestPointPallasSumOfProducts(t *testing.T) { - lhs := new(Ep).Generator() - lhs.Mul(lhs, new(fq.Fq).SetUint64(50)) - points := make([]*Ep, 5) - for i := range points { - points[i] = new(Ep).Generator() - } - scalars := []Scalar{ - new(ScalarPallas).New(8), - new(ScalarPallas).New(9), - new(ScalarPallas).New(10), - new(ScalarPallas).New(11), - new(ScalarPallas).New(12), - } - rhs := lhs.SumOfProducts(points, scalars) - require.NotNil(t, rhs) - require.True(t, lhs.Equal(rhs)) -} diff --git a/crypto/core/curves/secp256k1/secp256k1.go b/crypto/core/curves/secp256k1/secp256k1.go deleted file mode 100644 index add8f6dfa..000000000 --- a/crypto/core/curves/secp256k1/secp256k1.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Copyright 2011 ThePiachu. All rights reserved. -// Copyright 2015 Jeffrey Wilcke, Felix Lange, Gustav Simonsson. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// * The name of ThePiachu may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package secp256k1 - -import ( - "crypto/elliptic" - "math/big" -) - -const ( - // number of bits in a big.Word - wordBits = 32 << (uint64(^big.Word(0)) >> 63) - // number of bytes in a big.Word - wordBytes = wordBits / 8 -) - -// ScalarMult returns k*(Bx,By) where k is a number in big-endian form. -func (bitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - Bz := new(big.Int).SetInt64(1) - x, y, z := new(big.Int), new(big.Int), new(big.Int) - - for _, byte := range k { - for bitNum := 0; bitNum < 8; bitNum++ { - x, y, z = bitCurve.doubleJacobian(x, y, z) - if byte&0x80 == 0x80 { - x, y, z = bitCurve.addJacobian(Bx, By, Bz, x, y, z) - } - byte <<= 1 - } - } - - return bitCurve.affineFromJacobian(x, y, z) -} - -// readBits encodes the absolute value of bigint as big-endian bytes. Callers -// must ensure that buf has enough space. If buf is too short the result will -// be incomplete. -func readBits(bigint *big.Int, buf []byte) { - i := len(buf) - for _, d := range bigint.Bits() { - for j := 0; j < wordBytes && i > 0; j++ { - i-- - buf[i] = byte(d) - d >>= 8 - } - } -} - -// This code is from https://github.com/ThePiachu/GoBit and implements -// several Koblitz elliptic curves over prime fields. -// -// The curve methods, internally, on Jacobian coordinates. For a given -// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, -// z1) where x = x1/z1² and y = y1/z1³. The greatest speedups come -// when the whole calculation can be performed within the transform -// (as in ScalarMult and ScalarBaseMult). But even for Add and Double, -// it's faster to apply and reverse the transform than to operate in -// affine coordinates. - -// A BitCurve represents a Koblitz Curve with a=0. -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html -type BitCurve struct { - P *big.Int // the order of the underlying field - N *big.Int // the order of the base point - B *big.Int // the constant of the BitCurve equation - Gx, Gy *big.Int // (x,y) of the base point - BitSize int // the size of the underlying field -} - -func (bitCurve *BitCurve) Params() *elliptic.CurveParams { - return &elliptic.CurveParams{ - P: bitCurve.P, - N: bitCurve.N, - B: bitCurve.B, - Gx: bitCurve.Gx, - Gy: bitCurve.Gy, - BitSize: bitCurve.BitSize, - } -} - -// IsOnCurve returns true if the given (x,y) lies on the BitCurve. -func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { - // y² = x³ + b - y2 := new(big.Int).Mul(y, y) // y² - y2.Mod(y2, bitCurve.P) // y²%P - - x3 := new(big.Int).Mul(x, x) // x² - x3.Mul(x3, x) // x³ - - x3.Add(x3, bitCurve.B) // x³+B - x3.Mod(x3, bitCurve.P) //(x³+B)%P - - return x3.Cmp(y2) == 0 -} - -// affineFromJacobian reverses the Jacobian transform. See the comment at the -// top of the file. -func (bitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { - if z.Sign() == 0 { - return new(big.Int), new(big.Int) - } - - zinv := new(big.Int).ModInverse(z, bitCurve.P) - zinvsq := new(big.Int).Mul(zinv, zinv) - - xOut = new(big.Int).Mul(x, zinvsq) - xOut.Mod(xOut, bitCurve.P) - zinvsq.Mul(zinvsq, zinv) - yOut = new(big.Int).Mul(y, zinvsq) - yOut.Mod(yOut, bitCurve.P) - return xOut, yOut -} - -// Add returns the sum of (x1,y1) and (x2,y2) -func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - // If one point is at infinity, return the other point. - // Adding the point at infinity to any point will preserve the other point. - if x1.Sign() == 0 && y1.Sign() == 0 { - return x2, y2 - } - if x2.Sign() == 0 && y2.Sign() == 0 { - return x1, y1 - } - z := new(big.Int).SetInt64(1) - if x1.Cmp(x2) == 0 && y1.Cmp(y2) == 0 { - return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z)) - } - return bitCurve.affineFromJacobian(bitCurve.addJacobian(x1, y1, z, x2, y2, z)) -} - -// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and -// (x2, y2, z2) and returns their sum, also in Jacobian form. -func (bitCurve *BitCurve) addJacobian( - x1, y1, z1, x2, y2, z2 *big.Int, -) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl - z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, bitCurve.P) - z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, bitCurve.P) - - u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, bitCurve.P) - u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, bitCurve.P) - h := new(big.Int).Sub(u2, u1) - if h.Sign() == -1 { - h.Add(h, bitCurve.P) - } - i := new(big.Int).Lsh(h, 1) - i.Mul(i, i) - j := new(big.Int).Mul(h, i) - - s1 := new(big.Int).Mul(y1, z2) - s1.Mul(s1, z2z2) - s1.Mod(s1, bitCurve.P) - s2 := new(big.Int).Mul(y2, z1) - s2.Mul(s2, z1z1) - s2.Mod(s2, bitCurve.P) - r := new(big.Int).Sub(s2, s1) - if r.Sign() == -1 { - r.Add(r, bitCurve.P) - } - r.Lsh(r, 1) - v := new(big.Int).Mul(u1, i) - - x3 := new(big.Int).Set(r) - x3.Mul(x3, x3) - x3.Sub(x3, j) - x3.Sub(x3, v) - x3.Sub(x3, v) - x3.Mod(x3, bitCurve.P) - - y3 := new(big.Int).Set(r) - v.Sub(v, x3) - y3.Mul(y3, v) - s1.Mul(s1, j) - s1.Lsh(s1, 1) - y3.Sub(y3, s1) - y3.Mod(y3, bitCurve.P) - - z3 := new(big.Int).Add(z1, z2) - z3.Mul(z3, z3) - z3.Sub(z3, z1z1) - if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) - } - z3.Sub(z3, z2z2) - if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) - } - z3.Mul(z3, h) - z3.Mod(z3, bitCurve.P) - - return x3, y3, z3 -} - -// Double returns 2*(x,y) -func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - z1 := new(big.Int).SetInt64(1) - return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) -} - -// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and -// returns its double, also in Jacobian form. -func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - - a := new(big.Int).Mul(x, x) // X1² - b := new(big.Int).Mul(y, y) // Y1² - c := new(big.Int).Mul(b, b) // B² - - d := new(big.Int).Add(x, b) // X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C - d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) - - e := new(big.Int).Mul(big.NewInt(3), a) // 3*A - f := new(big.Int).Mul(e, e) // E² - - x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D - x3.Sub(f, x3) // F-2*D - x3.Mod(x3, bitCurve.P) - - y3 := new(big.Int).Sub(d, x3) // D-X3 - y3.Mul(e, y3) // E*(D-X3) - y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C - y3.Mod(y3, bitCurve.P) - - z3 := new(big.Int).Mul(y, z) // Y1*Z1 - z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1 - z3.Mod(z3, bitCurve.P) - - return x3, y3, z3 -} - -// ScalarBaseMult returns k*G, where G is the base point of the group and k is -// an integer in big-endian form. -func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) -} - -// Marshal converts a point into the form specified in section 4.3.6 of ANSI -// X9.62. -func (bitCurve *BitCurve) Marshal(x, y *big.Int) []byte { - byteLen := (bitCurve.BitSize + 7) >> 3 - ret := make([]byte, 1+2*byteLen) - ret[0] = 4 // uncompressed point flag - readBits(x, ret[1:1+byteLen]) - readBits(y, ret[1+byteLen:]) - return ret -} - -// Unmarshal converts a point, serialised by Marshal, into an x, y pair. On -// error, x = nil. -func (bitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { - byteLen := (bitCurve.BitSize + 7) >> 3 - if len(data) != 1+2*byteLen { - return x, y - } - if data[0] != 4 { // uncompressed form - return x, y - } - x = new(big.Int).SetBytes(data[1 : 1+byteLen]) - y = new(big.Int).SetBytes(data[1+byteLen:]) - return x, y -} - -var theCurve = new(BitCurve) - -func init() { - // See SEC 2 section 2.7.1 - // curve parameters taken from: - // http://www.secg.org/sec2-v2.pdf - theCurve.P, _ = new( - big.Int, - ).SetString("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 0) - theCurve.N, _ = new( - big.Int, - ).SetString("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 0) - theCurve.B, _ = new( - big.Int, - ).SetString("0x0000000000000000000000000000000000000000000000000000000000000007", 0) - theCurve.Gx, _ = new( - big.Int, - ).SetString("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 0) - theCurve.Gy, _ = new( - big.Int, - ).SetString("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 0) - theCurve.BitSize = 256 -} - -// S256 returns a BitCurve which implements secp256k1. -func S256() *BitCurve { - return theCurve -} diff --git a/crypto/core/curves/sp256_curve.go b/crypto/core/curves/sp256_curve.go deleted file mode 100644 index e7831f091..000000000 --- a/crypto/core/curves/sp256_curve.go +++ /dev/null @@ -1,11 +0,0 @@ -package curves - -import ( - "crypto/elliptic" - - "github.com/dustinxie/ecc" -) - -func SP256() elliptic.Curve { - return ecc.P256k1() -} diff --git a/crypto/core/hash.go b/crypto/core/hash.go deleted file mode 100644 index 5a975dfaf..000000000 --- a/crypto/core/hash.go +++ /dev/null @@ -1,339 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "bytes" - "crypto/elliptic" - "crypto/sha256" - "crypto/sha512" - "fmt" - "hash" - "math" - "math/big" - - "github.com/btcsuite/btcd/btcec/v2" - "golang.org/x/crypto/hkdf" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/internal" -) - -type HashField struct { - // F_p^k - Order *big.Int // p^k - Characteristic *big.Int // p - ExtensionDegree *big.Int // k -} - -type Params struct { - F *HashField - SecurityParameter int - Hash func() hash.Hash - L int -} - -// Helper functions reserved for future use - -// getCurveFromName returns the appropriate elliptic curve for a given name -// nolint:unused,deadcode -func getCurveFromName(name string) elliptic.Curve { - switch name { - case "P-256", "secp256r1": - return elliptic.P256() - case "P-384", "secp384r1": - return elliptic.P384() - case "P-521", "secp521r1": - return elliptic.P521() - default: - return nil - } -} - -// validateCurveParams validates curve parameters for security -// nolint:unused,deadcode -func validateCurveParams(curve elliptic.Curve) error { - if curve == nil { - return fmt.Errorf("curve is nil") - } - params := curve.Params() - if params == nil { - return fmt.Errorf("curve parameters are nil") - } - if params.P == nil || params.N == nil { - return fmt.Errorf("invalid curve parameters: P or N is nil") - } - // Ensure the curve order is large enough for security - if params.N.BitLen() < 224 { - return fmt.Errorf("curve order too small for security: %d bits", params.N.BitLen()) - } - return nil -} - -func getParams(curve elliptic.Curve) (*Params, error) { - switch curve.Params().Name { - case btcec.S256().Name, elliptic.P256().Params().Name: - return &Params{ - F: &HashField{ - Order: curve.Params().P, - Characteristic: curve.Params().P, - ExtensionDegree: new(big.Int).SetInt64(1), - }, - SecurityParameter: 128, - Hash: sha256.New, - L: 48, - }, nil - case elliptic.P384().Params().Name, "P-384", "secp384r1": - // P-384 curve with 192-bit security level - return &Params{ - F: &HashField{ - Order: curve.Params().P, - Characteristic: curve.Params().P, - ExtensionDegree: new(big.Int).SetInt64(1), - }, - SecurityParameter: 192, - Hash: sha3.New384, // Using SHA3-384 for P-384 - L: 72, // 192-bit security requires 72 bytes - }, nil - case elliptic.P521().Params().Name, "P-521", "secp521r1": - // P-521 curve with 256-bit security level - return &Params{ - F: &HashField{ - Order: curve.Params().P, - Characteristic: curve.Params().P, - ExtensionDegree: new(big.Int).SetInt64(1), - }, - SecurityParameter: 256, - Hash: sha512.New, // Using SHA-512 for P-521 - L: 98, // 256-bit security with P-521's 521-bit field - }, nil - case "Bls12381G1": - return &Params{ - F: &HashField{ - Order: curve.Params().P, - Characteristic: curve.Params().P, - ExtensionDegree: new(big.Int).SetInt64(1), - }, - SecurityParameter: 128, - Hash: sha256.New, - L: 48, - }, nil - case "ed25519": - return &Params{ - F: &HashField{ - Order: curve.Params().P, - Characteristic: curve.Params().P, - ExtensionDegree: new(big.Int).SetInt64(1), - }, - SecurityParameter: 128, - Hash: sha256.New, - L: 48, - }, nil - default: - return nil, fmt.Errorf("unsupported curve: %s", curve.Params().Name) - } -} - -func I2OSP(b, n int) []byte { - os := new(big.Int).SetInt64(int64(b)).Bytes() - if n > len(os) { - var buf bytes.Buffer - buf.Write(make([]byte, n-len(os))) - buf.Write(os) - return buf.Bytes() - } - return os[:n] -} - -func OS2IP(os []byte) *big.Int { - return new(big.Int).SetBytes(os) -} - -func hashThis(f func() hash.Hash, this []byte) ([]byte, error) { - h := f() - w, err := h.Write(this) - if w != len(this) { - return nil, fmt.Errorf("bytes written to hash doesn't match expected") - } else if err != nil { - return nil, err - } - v := h.Sum(nil) - return v, nil -} - -func concat(xs ...[]byte) []byte { - var result []byte - for _, x := range xs { - result = append(result, x...) - } - return result -} - -func xor(b1, b2 []byte) []byte { - // b1 and b2 must be same length - result := make([]byte, len(b1)) - for i := range b1 { - result[i] = b1[i] ^ b2[i] - } - - return result -} - -func ExpandMessageXmd(f func() hash.Hash, msg, DST []byte, lenInBytes int) ([]byte, error) { - // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.4.1 - - // step 1 - ell := int(math.Ceil(float64(lenInBytes) / float64(f().Size()))) - - // step 2 - if ell > 255 { - return nil, fmt.Errorf("ell > 255") - } - - // step 3 - dstPrime := append(DST, I2OSP(len(DST), 1)...) - - // step 4 - zPad := I2OSP(0, f().BlockSize()) - - // step 5 & 6 - msgPrime := concat(zPad, msg, I2OSP(lenInBytes, 2), I2OSP(0, 1), dstPrime) - - var err error - - b := make([][]byte, ell+1) - - // step 7 - b[0], err = hashThis(f, msgPrime) - if err != nil { - return nil, err - } - - // step 8 - b[1], err = hashThis(f, concat(b[0], I2OSP(1, 1), dstPrime)) - if err != nil { - return nil, err - } - - // step 9 - for i := 2; i <= ell; i++ { - // step 10 - b[i], err = hashThis(f, concat(xor(b[0], b[i-1]), I2OSP(i, 1), dstPrime)) - if err != nil { - return nil, err - } - } - // step 11 - uniformBytes := concat(b[1:]...) - - // step 12 - return uniformBytes[:lenInBytes], nil -} - -func hashToField(msg []byte, count int, curve elliptic.Curve) ([][]*big.Int, error) { - // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.3 - - parameters, err := getParams(curve) - if err != nil { - return nil, err - } - - f := parameters.Hash - - DST := []byte("Coinbase_tECDSA") - - m := int(parameters.F.ExtensionDegree.Int64()) - L := parameters.L - - // step 1 - lenInBytes := count * m * L - - // step 2 - uniformBytes, err := ExpandMessageXmd(f, msg, DST, lenInBytes) - if err != nil { - return nil, err - } - - u := make([][]*big.Int, count) - - // step 3 - for i := 0; i < count; i++ { - e := make([]*big.Int, m) - // step 4 - for j := 0; j < m; j++ { - // step 5 - elmOffset := L * (j + i*m) - // step 6 - tv := uniformBytes[elmOffset : elmOffset+L] - // step 7 - e[j] = new(big.Int).Mod(OS2IP(tv), parameters.F.Characteristic) - - } - // step 8 - u[i] = e - } - // step 9 - return u, nil -} - -func Hash(msg []byte, curve elliptic.Curve) (*big.Int, error) { - u, err := hashToField(msg, 1, curve) - if err != nil { - return nil, err - } - return u[0][0], nil -} - -// fiatShamir computes the HKDF over many values -// iteratively such that each value is hashed separately -// and based on preceding values -// -// The first value is computed as okm_0 = KDF(f || value) where -// f is a byte slice of 32 0xFF -// salt is zero-filled byte slice with length equal to the hash output length -// info is the protocol name -// okm is the 32 byte output -// -// The each subsequent iteration is computed by as okm_i = KDF(f_i || value || okm_{i-1}) -// where f_i = 2^b - 1 - i such that there are 0xFF bytes prior to the value. -// f_1 changes the first byte to 0xFE, f_2 to 0xFD. The previous okm is appended to the value -// to provide cryptographic domain separation. -// See https://signal.org/docs/specifications/x3dh/#cryptographic-notation -// and https://signal.org/docs/specifications/xeddsa/#hash-functions -// for more details. -// This uses the KDF function similar to X3DH for each `value` -// But changes the key just like XEdDSA where the prefix bytes change by a single bit -func FiatShamir(values ...*big.Int) ([]byte, error) { - // Don't accept any nil arguments - if AnyNil(values...) { - return nil, internal.ErrNilArguments - } - - info := []byte("Coinbase tECDSA 1.0") - salt := make([]byte, 32) - okm := make([]byte, 32) - f := bytes.Repeat([]byte{0xFF}, 32) - - for _, b := range values { - ikm := append(f, b.Bytes()...) - ikm = append(ikm, okm...) - kdf := hkdf.New(sha256.New, ikm, salt, info) - n, err := kdf.Read(okm) - if err != nil { - return nil, err - } - if n != len(okm) { - return nil, fmt.Errorf( - "unable to read expected number of bytes want=%v got=%v", - len(okm), - n, - ) - } - internal.ByteSub(f) - } - return okm, nil -} diff --git a/crypto/core/hash_test.go b/crypto/core/hash_test.go deleted file mode 100755 index 77b8963e5..000000000 --- a/crypto/core/hash_test.go +++ /dev/null @@ -1,323 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "fmt" - "hash" - "math/big" - "strconv" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestExpandMessageXmd(t *testing.T) { - // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#appendix-K.1 - tests := []struct { - f func() hash.Hash - msg []byte - lenInBytesHex string - expectedHex string - }{ - { - sha256.New, - []byte(""), - "20", - "f659819a6473c1835b25ea59e3d38914c98b374f0970b7e4c92181df928fca88", - }, - { - sha256.New, - []byte("abc"), - "20", - "1c38f7c211ef233367b2420d04798fa4698080a8901021a795a1151775fe4da7", - }, - { - sha256.New, - []byte("abcdef0123456789"), - "20", - "8f7e7b66791f0da0dbb5ec7c22ec637f79758c0a48170bfb7c4611bd304ece89", - }, - { - sha256.New, - []byte( - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - ), - "20", - "72d5aa5ec810370d1f0013c0df2f1d65699494ee2a39f72e1716b1b964e1c642", - }, - { - sha256.New, - []byte( - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ), - "20", - "3b8e704fc48336aca4c2a12195b720882f2162a4b7b13a9c350db46f429b771b", - }, - { - sha256.New, - []byte(""), - "80", - "8bcffd1a3cae24cf9cd7ab85628fd111bb17e3739d3b53f89580d217aa79526f1708354a76a402d3569d6a9d19ef3de4d0b991e4f54b9f20dcde9b95a66824cbdf6c1a963a1913d43fd7ac443a02fc5d9d8d77e2071b86ab114a9f34150954a7531da568a1ea8c760861c0cde2005afc2c114042ee7b5848f5303f0611cf297f", - }, - { - sha256.New, - []byte("abc"), - "80", - "fe994ec51bdaa821598047b3121c149b364b178606d5e72bfbb713933acc29c186f316baecf7ea22212f2496ef3f785a27e84a40d8b299cec56032763eceeff4c61bd1fe65ed81decafff4a31d0198619c0aa0c6c51fca15520789925e813dcfd318b542f8799441271f4db9ee3b8092a7a2e8d5b75b73e28fb1ab6b4573c192", - }, - { - sha256.New, - []byte("abcdef0123456789"), - "80", - "c9ec7941811b1e19ce98e21db28d22259354d4d0643e301175e2f474e030d32694e9dd5520dde93f3600d8edad94e5c364903088a7228cc9eff685d7eaac50d5a5a8229d083b51de4ccc3733917f4b9535a819b445814890b7029b5de805bf62b33a4dc7e24acdf2c924e9fe50d55a6b832c8c84c7f82474b34e48c6d43867be", - }, - { - sha256.New, - []byte( - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - ), - "80", - "48e256ddba722053ba462b2b93351fc966026e6d6db493189798181c5f3feea377b5a6f1d8368d7453faef715f9aecb078cd402cbd548c0e179c4ed1e4c7e5b048e0a39d31817b5b24f50db58bb3720fe96ba53db947842120a068816ac05c159bb5266c63658b4f000cbf87b1209a225def8ef1dca917bcda79a1e42acd8069", - }, - { - sha256.New, - []byte( - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ), - "80", - "396962db47f749ec3b5042ce2452b619607f27fd3939ece2746a7614fb83a1d097f554df3927b084e55de92c7871430d6b95c2a13896d8a33bc48587b1f66d21b128a1a8240d5b0c26dfe795a1a842a0807bb148b77c2ef82ed4b6c9f7fcb732e7f94466c8b51e52bf378fba044a31f5cb44583a892f5969dcd73b3fa128816e", - }, - - { - sha512.New, - []byte(""), - "20", - "2eaa1f7b5715f4736e6a5dbe288257abf1faa028680c1d938cd62ac699ead642", - }, - { - sha512.New, - []byte("abc"), - "20", - "0eeda81f69376c80c0f8986496f22f21124cb3c562cf1dc608d2c13005553b0f", - }, - { - sha512.New, - []byte("abcdef0123456789"), - "20", - "2e375fc05e05e80dbf3083796fde2911789d9e8847e1fcebf4ca4b36e239b338", - }, - { - sha512.New, - []byte( - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - ), - "20", - "c37f9095fe7fe4f01c03c3540c1229e6ac8583b07510085920f62ec66acc0197", - }, - { - sha512.New, - []byte( - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ), - "20", - "af57a7f56e9ed2aa88c6eab45c8c6e7638ae02da7c92cc04f6648c874ebd560e", - }, - { - sha512.New, - []byte(""), - "80", - "0687ce02eba5eb3faf1c3c539d1f04babd3c0f420edae244eeb2253b6c6d6865145c31458e824b4e87ca61c3442dc7c8c9872b0b7250aa33e0668ccebbd2b386de658ca11a1dcceb51368721ae6dcd2d4bc86eaebc4e0d11fa02ad053289c9b28a03da6c942b2e12c14e88dbde3b0ba619d6214f47212b628f3e1b537b66efcf", - }, - { - sha512.New, - []byte("abc"), - "80", - "779ae4fd8a92f365e4df96b9fde97b40486bb005c1a2096c86f55f3d92875d89045fbdbc4a0e9f2d3e1e6bcd870b2d7131d868225b6fe72881a81cc5166b5285393f71d2e68bb0ac603479959370d06bdbe5f0d8bfd9af9494d1e4029bd68ab35a561341dd3f866b3ef0c95c1fdfaab384ce24a23427803dda1db0c7d8d5344a", - }, - { - sha512.New, - []byte("abcdef0123456789"), - "80", - "f0953d28846a50e9f88b7ae35b643fc43733c9618751b569a73960c655c068db7b9f044ad5a40d49d91c62302eaa26163c12abfa982e2b5d753049e000adf7630ae117aeb1fb9b61fc724431ac68b369e12a9481b4294384c3c890d576a79264787bc8076e7cdabe50c044130e480501046920ff090c1a091c88391502f0fbac", - }, - { - sha512.New, - []byte( - "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", - ), - "80", - "64d3e59f0bc3c5e653011c914b419ba8310390a9585311fddb26791d26663bd71971c347e1b5e88ba9274d2445ed9dcf48eea9528d807b7952924159b7c27caa4f25a2ea94df9508e70a7012dfce0e8021b37e59ea21b80aa9af7f1a1f2efa4fbe523c4266ce7d342acaacd438e452c501c131156b4945515e9008d2b155c258", - }, - { - sha512.New, - []byte( - "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ), - "80", - "01524feea5b22f6509f6b1e805c97df94faf4d821b01aadeebc89e9daaed0733b4544e50852fd3e019d58eaad6d267a134c8bc2c08bc46c10bfeff3ee03110bcd8a0d695d75a34092bd8b677bdd369a13325549abab54f4ac907b712bdd3567f38c4554c51902b735b81f43a7ef6f938c7690d107c052c7e7b795ac635b3200a", - }, - } - - for _, test := range tests { - t.Run(fmt.Sprintf("msg: %s", test.msg), func(t *testing.T) { - DST := []byte("QUUX-V01-CS02-with-expander") - lenInBytes, err := strconv.ParseInt(test.lenInBytesHex, 16, 64) - require.NoError(t, err) - expected, err := hex.DecodeString(test.expectedHex) - require.NoError(t, err) - actual, err := ExpandMessageXmd(test.f, test.msg, DST, int(lenInBytes)) - require.NoError(t, err) - require.Equal(t, actual, expected) - }) - } -} - -func TestFiatShamirDeterministic(t *testing.T) { - a := big.NewInt(1) - hash, err := FiatShamir(a) - require.Nil(t, err) - require.Equal( - t, - hash, - []byte{ - 0x3d, - 0x95, - 0xc0, - 0x9f, - 0x41, - 0x33, - 0x25, - 0xbb, - 0x10, - 0x77, - 0x2d, - 0x83, - 0x1d, - 0x3e, - 0x67, - 0x98, - 0xce, - 0x7b, - 0xde, - 0xd5, - 0x7f, - 0x9, - 0x7e, - 0xfc, - 0x77, - 0x23, - 0xfc, - 0x49, - 0x36, - 0x82, - 0xdd, - 0x6a, - }, - ) - - a = big.NewInt(0xaaa) - hash, err = FiatShamir(a) - require.Nil(t, err) - require.Equal( - t, - hash, - []byte{ - 0x61, - 0xa9, - 0x7f, - 0x6, - 0x74, - 0xec, - 0x47, - 0xf5, - 0xac, - 0x30, - 0xa0, - 0x4c, - 0x34, - 0xdb, - 0x51, - 0x97, - 0x60, - 0x7e, - 0xb2, - 0x4a, - 0x97, - 0x9, - 0xa5, - 0xb9, - 0x1c, - 0x89, - 0x30, - 0x39, - 0xb7, - 0x29, - 0xe6, - 0x30, - }, - ) -} - -func TestFiatShamirEqual(t *testing.T) { - pi, err := FiatShamir(One) - require.Nil(t, err) - pi_, err := FiatShamir(One) - require.Nil(t, err) - require.Equal(t, pi, pi_) -} - -func TestFiatShamirNotEqual(t *testing.T) { - pi, err := FiatShamir(One) - require.Nil(t, err) - pi_, err := FiatShamir(Two) - require.Nil(t, err) - require.NotEqual(t, pi, pi_) -} - -func TestFiatShamirOrderDependent(t *testing.T) { - a := big.NewInt(1) - b := big.NewInt(100) - - pi, err := FiatShamir(a, b) - require.Nil(t, err) - pi_, err := FiatShamir(a, b) - require.Nil(t, err) - require.Equal(t, pi, pi_) - - q, _ := FiatShamir(b, a) - require.NotEqual(t, pi, q) -} - -func TestFiatShamirExtensionAttackResistance(t *testing.T) { - a := big.NewInt(0x00FF) - b := big.NewInt(0xFF00) - - c := big.NewInt(0x00) - d := big.NewInt(0xFFFF00) - - pi, err := FiatShamir(a, b) - require.Nil(t, err) - pi_, err := FiatShamir(c, d) - require.Nil(t, err) - require.NotEqual(t, pi, pi_) - - a = big.NewInt(0x0000) - b = big.NewInt(0xFFFF) - - c = big.NewInt(0x0000F) - d = big.NewInt(0xFFF) - - q, err := FiatShamir(a, b) - require.Nil(t, err) - q_, err := FiatShamir(c, d) - require.Nil(t, err) - require.NotEqual(t, q, q_) -} diff --git a/crypto/core/mod.go b/crypto/core/mod.go deleted file mode 100644 index 0b4f4cbca..000000000 --- a/crypto/core/mod.go +++ /dev/null @@ -1,178 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// -// Package core contains convenience functions for modular arithmetic. - -// Package core contains a set of primitives, including but not limited to various -// elliptic curves, hashes, and commitment schemes. These primitives are used internally -// and can also be used independently on their own externally. -package core - -import ( - crand "crypto/rand" - "crypto/subtle" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - // Zero is additive identity in the set of integers - Zero = big.NewInt(0) - - // One is the multiplicative identity in the set of integers - One = big.NewInt(1) - - // Two is the odd prime - Two = big.NewInt(2) -) - -// ConstantTimeEqByte determines if a, b have identical byte serialization -// and signs. It uses the crypto/subtle package to get a constant time comparison -// over byte representations. Return value is a byte which may be -// useful in bitwise operations. Returns 0x1 if the two values have the -// identical sign and byte representation; 0x0 otherwise. -func ConstantTimeEqByte(a, b *big.Int) byte { - if a == nil && a == b { - return 1 - } - if a == nil || b == nil { - return 0 - } - // Determine if the byte representations are the same - var sameBytes byte - if subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1 { - sameBytes = 1 - } else { - sameBytes = 0 - } - - // Determine if the signs are the same - var sameSign byte - if a.Sign() == b.Sign() { - sameSign = 1 - } else { - sameSign = 0 - } - - // Report the conjunction - return sameBytes & sameSign -} - -// ConstantTimeEq determines if a, b have identical byte serialization -// and uses the crypto/subtle package to get a constant time comparison -// over byte representations. -func ConstantTimeEq(a, b *big.Int) bool { - return ConstantTimeEqByte(a, b) == 1 -} - -// In determines ring membership before modular reduction: x ∈ Z_m -// returns nil if 0 ≤ x < m -func In(x, m *big.Int) error { - if AnyNil(x, m) { - return internal.ErrNilArguments - } - // subtle doesn't support constant time big.Int compare - // just use big.Cmp for now - // x ∈ Z_m ⇔ 0 ≤ x < m - if x.Cmp(Zero) != -1 && x.Cmp(m) == -1 { - return nil - } - return internal.ErrZmMembership -} - -// Add (modular addition): z = x+y (modulo m) -func Add(x, y, m *big.Int) (*big.Int, error) { - if AnyNil(x, y) { - return nil, internal.ErrNilArguments - } - z := new(big.Int).Add(x, y) - // Compute the residue if one is specified, otherwise - // we leave the value as an unbound integer - if m != nil { - z.Mod(z, m) - } - return z, nil -} - -// Mul (modular multiplication): z = x*y (modulo m) -func Mul(x, y, m *big.Int) (*big.Int, error) { - if AnyNil(x, y) { - return nil, internal.ErrNilArguments - } - z := new(big.Int).Mul(x, y) - - // Compute the residue if one is specified, otherwise - // we leave the value as an unbound integer - if m != nil { - z.Mod(z, m) - } - return z, nil -} - -// Exp (modular exponentiation): z = x^y (modulo m) -func Exp(x, y, m *big.Int) (*big.Int, error) { - if AnyNil(x, y) { - return nil, internal.ErrNilArguments - } - // This wrapper looks silly, but it makes the calling code read more consistently. - return new(big.Int).Exp(x, y, m), nil -} - -// Neg (modular negation): z = -x (modulo m) -func Neg(x, m *big.Int) (*big.Int, error) { - if AnyNil(x, m) { - return nil, internal.ErrNilArguments - } - z := new(big.Int).Neg(x) - z.Mod(z, m) - return z, nil -} - -// Inv (modular inverse): returns y such that xy = 1 (modulo m). -func Inv(x, m *big.Int) (*big.Int, error) { - if AnyNil(x, m) { - return nil, internal.ErrNilArguments - } - z := new(big.Int).ModInverse(x, m) - if z == nil { - return nil, fmt.Errorf("cannot compute the multiplicative inverse") - } - return z, nil -} - -// Rand generates a cryptographically secure random integer in the range: 1 < r < m. -func Rand(m *big.Int) (*big.Int, error) { - if m == nil { - return nil, internal.ErrNilArguments - } - - // Select a random element, but not zero or one - // The reason is the random element may be used as a Scalar or an exponent. - // An exponent of 1 is generally acceptable because the generator can't be - // 1. If a Scalar is combined with another Scalar like in fiat-shamir, it - // offers no hiding properties when multiplied. - for { - result, err := crand.Int(crand.Reader, m) - if err != nil { - return nil, err - } - - if result.Cmp(One) == 1 { // result > 1 - return result, nil - } - } -} - -// AnyNil determines if any of values are nil -func AnyNil(values ...*big.Int) bool { - for _, x := range values { - if x == nil { - return true - } - } - return false -} diff --git a/crypto/core/mod_test.go b/crypto/core/mod_test.go deleted file mode 100644 index e9e3e6708..000000000 --- a/crypto/core/mod_test.go +++ /dev/null @@ -1,589 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - four = big.NewInt(4) - - // Large numbers for testing -- computing with independent tooling - // x,y 100-digit numbers - x, _ = new( - big.Int, - ).SetString("7146643783615963513942641287213372249533955323510461217840179896547799100626220786140425637990097431", 10) - y, _ = new( - big.Int, - ).SetString("1747698065194620177681258504464368264357359841192790848951902311522815739310792522712583635858354245", 10) - sumxy, _ = new( - big.Int, - ).SetString("8894341848810583691623899791677740513891315164703252066792082208070614839937013308853009273848451676", 10) - xy, _ = new( - big.Int, - ).SetString("12490175513260779219420155073726764321605372267033815716483640700978475653623775696463227582174703069158832890348206546318843052423532258178885792744599932977235221784868792263260215861775082862444595", 10) - - // 101-digit modulus - m, _ = new( - big.Int, - ).SetString("85832751158419329546684678412285185885848111422509523329716452068504806021136687603399722116388773253", 10) - - // 99-digit modulus - n, _ = new( - big.Int, - ).SetString("604464499356780653111583485887412477603580949137220100557796699530113283915988830359783807274682723", 10) -) - -func TestConstantTimeEqByteSound(t *testing.T) { - hundoDigit := internal.B10( - "3593421565679030456559622742114065111786271367498220644136232358421457354322411370928949366452183472", - ) - tests := []struct { - name string - a, b *big.Int - expected byte - }{ - {"positive: 5", internal.B10("5"), internal.B10("5"), 1}, - {"positive: 100", internal.B10("100"), internal.B10("100"), 1}, - {"positive: -1204", internal.B10("-1204"), internal.B10("-1204"), 1}, - {"positive: 100 digits", hundoDigit, hundoDigit, 1}, - {"positive: 0", internal.B10("0"), internal.B10("0"), 1}, - {"positive: 0/-0", internal.B10("0"), internal.B10("-0"), 1}, - {"positive: -0/-0", internal.B10("-0"), internal.B10("-0"), 1}, - - {"negative: 5/-5", internal.B10("5"), internal.B10("-5"), 0}, - {"negative: 5/500", internal.B10("5"), internal.B10("500"), 0}, - {"negative: 100/100 digit", internal.B10("100"), hundoDigit, 0}, - {"negative: -1204/-5", internal.B10("-1204"), internal.B10("-15"), 0}, - {"negative: 0/-5 digits", internal.B10("0"), internal.B10("-5"), 0}, - } - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := ConstantTimeEqByte(test.a, test.b) - require.Equal(t, test.expected, actual) - }) - } -} - -func TestConstantTimeEqSound(t *testing.T) { - hundoDigit := internal.B10( - "3593421565679030456559622742114065111786271367498220644136232358421457354322411370928949366452183472", - ) - tests := []struct { - name string - a, b *big.Int - expected bool - }{ - {"positive: 5", internal.B10("5"), internal.B10("5"), true}, - {"positive: 100", internal.B10("100"), internal.B10("100"), true}, - {"positive: -1204", internal.B10("-1204"), internal.B10("-1204"), true}, - {"positive: 100 digits", hundoDigit, hundoDigit, true}, - {"positive: 0", internal.B10("0"), internal.B10("0"), true}, - {"positive: 0/-0", internal.B10("0"), internal.B10("-0"), true}, - {"positive: -0/-0", internal.B10("-0"), internal.B10("-0"), true}, - - {"negative: 5/-5", internal.B10("5"), internal.B10("-5"), false}, - {"negative: 5/500", internal.B10("5"), internal.B10("500"), false}, - {"negative: 100/100 digit", internal.B10("100"), hundoDigit, false}, - {"negative: -1204/-5", internal.B10("-1204"), internal.B10("-15"), false}, - {"negative: 0/-5 digits", internal.B10("0"), internal.B10("-5"), false}, - } - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := ConstantTimeEq(test.a, test.b) - require.Equal(t, test.expected, actual) - }) - } -} - -// Ring membership tests -func TestIn(t *testing.T) { - // Some large numbers for testing - x, _ := new( - big.Int, - ).SetString("21888242871839275222246405745257275088696311157297823662689037894645226208583", 10) - y, _ := new( - big.Int, - ).SetString("32168432167132168106409840321684604654063138460840123871234181628904319728058", 10) - N := new(big.Int).Mul(x, y) // N = xy - NN := new(big.Int).Mul(N, N) // N^2 = N*N = x^2y^2 - errMember := internal.ErrZmMembership - - tests := []struct { - x *big.Int - m *big.Int - expected error - }{ - // - // Completist test for: Z_4 - // - // Too small: -x ∉ Z_4, \forall \x \in \N - {big.NewInt(-4), four, errMember}, - {big.NewInt(-3), four, errMember}, - {big.NewInt(-2), four, errMember}, - {big.NewInt(-1), four, errMember}, - - // Just right: {0,1,2,3} = Z_4 - {big.NewInt(0), four, nil}, - {big.NewInt(1), four, nil}, - {big.NewInt(2), four, nil}, - {big.NewInt(3), four, nil}, - - // Too big: {4,5,6,7} ∉ Z_4 - {big.NewInt(4), four, errMember}, - {big.NewInt(5), four, errMember}, - {big.NewInt(6), four, errMember}, - {big.NewInt(7), four, errMember}, - - // - // Large numbers - // - // x,y,N < N^2 - {x, NN, nil}, - {y, NN, nil}, - {N, NN, nil}, - - // N+x,N+y,2N < N^2 ⇒ x ∈ Z_N^2 - {big.NewInt(0).Add(N, x), NN, nil}, - {big.NewInt(0).Add(N, y), NN, nil}, - {big.NewInt(0).Add(N, N), NN, nil}, - - // Nx,Ny < N^2 ⇒ x ∈ Z_N^2 - {big.NewInt(0).Mul(N, x), NN, nil}, - {big.NewInt(0).Mul(N, y), NN, nil}, - - // -x,-y,-N ∉ Z_N^2 - {big.NewInt(0).Neg(x), NN, errMember}, - {big.NewInt(0).Neg(y), NN, errMember}, - {big.NewInt(0).Neg(N), NN, errMember}, - - // N^2 ∉ Z_N^2 - {NN, NN, errMember}, - } - - // All the tests! - for _, test := range tests { - actual := In(test.x, test.m) - require.Equal(t, test.expected, actual) - } -} - -// Tests for modular addition with known answers -func TestAdd(t *testing.T) { - // Pre-compute some values - sumXyModn, err := Add(x, y, n) - require.Nil(t, err) - - tests := []struct { - x, y, m, expected *big.Int // inputs: x,y,m - }{ - // Small number tests - {big.NewInt(-1), big.NewInt(1), four, big.NewInt(0)}, - {big.NewInt(2), big.NewInt(1), four, big.NewInt(3)}, - {big.NewInt(0), big.NewInt(2), four, big.NewInt(2)}, - {big.NewInt(2), big.NewInt(4), four, big.NewInt(2)}, - {big.NewInt(15), big.NewInt(15), four, big.NewInt(2)}, - - // Large number tests - {x, y, m, sumxy}, - {y, x, m, sumxy}, - - // Large number Zero tests - {Zero, x, m, x}, - {x, Zero, m, x}, - {Zero, y, m, y}, - {y, Zero, m, y}, - - // Commutative - {x, y, m, sumxy}, - {y, x, m, sumxy}, - {x, y, n, sumXyModn}, - {y, x, n, sumXyModn}, - {sumXyModn, Zero, n, sumXyModn}, - {Zero, sumXyModn, n, sumXyModn}, - } - // All the tests! - for _, test := range tests { - actual, err := Add(test.x, test.y, test.m) - require.NoError(t, err) - require.Zero(t, actual.Cmp(test.expected)) - } -} - -// Tests for modular addition according to known invariants -func TestAddInvariants(t *testing.T) { - inputs := []*big.Int{x, y, Zero, One, new(big.Int).Neg(x), new(big.Int).Neg(y)} - moduli := []*big.Int{m, n, big.NewInt(10001)} - - // Run all combinations of the inputs/moduli - for _, x := range inputs { - for _, y := range inputs { - for _, m := range moduli { - - // Addition is commutative - z0, err := Add(x, y, m) - require.NoError(t, err) - z1, err := Add(y, x, m) - require.NoError(t, err) - require.Equal(t, z0, z1) - - // Addition is transitive: x+x+y == y+x+x == x+y+x - a0, _ := Add(x, x, m) - a0, _ = Add(a0, y, m) - - a1, _ := Add(y, x, m) - a1, _ = Add(a1, x, m) - - a2, _ := Add(x, y, m) - a2, _ = Add(a2, x, m) - - require.Equal(t, a0, a1) - require.Equal(t, a1, a2) - } - } - } -} - -// Tests modular multiplication with known answers -func TestMul(t *testing.T) { - // Pre-compute some values - xyModm := new(big.Int).Mod(xy, m) - - tests := []struct { - x, y, m, expected *big.Int // inputs: x,y,m - }{ - // Small number tests - {big.NewInt(-1), big.NewInt(1), four, big.NewInt(3)}, - {big.NewInt(2), big.NewInt(1), four, big.NewInt(2)}, - {big.NewInt(0), big.NewInt(2), four, big.NewInt(0)}, - {big.NewInt(2), big.NewInt(4), four, big.NewInt(0)}, - {big.NewInt(15), big.NewInt(15), four, big.NewInt(1)}, - - // Large number tests - {x, y, m, xyModm}, - {y, x, m, xyModm}, - - // Large number Zero tests - {Zero, x, m, Zero}, - {x, Zero, m, Zero}, - {Zero, y, n, Zero}, - } - // All the tests! - for _, test := range tests { - z, err := Mul(test.x, test.y, test.m) - require.NoError(t, err) - require.Zero(t, z.Cmp(test.expected)) - } -} - -// Tests for modular multiplication according to known invariants -func TestMulInvariants(t *testing.T) { - inputs := []*big.Int{x, y, Zero, One, new(big.Int).Neg(x), new(big.Int).Neg(y)} - moduli := []*big.Int{m, n, big.NewInt(10001)} - - // Run all combinations of the inputs/moduli - for _, x := range inputs { - for _, y := range inputs { - for _, m := range moduli { - - // Mul is commutative - a, err := Mul(x, y, m) - require.NoError(t, err) - aʹ, err := Mul(y, x, m) - require.NoError(t, err) - require.Equal(t, a, aʹ) - - // Mul is transitive: (xx)y == (xy)x - z, _ := Mul(x, x, m) - z, _ = Mul(z, y, m) - - zʹ, _ := Mul(x, y, m) - zʹ, _ = Mul(zʹ, x, m) - require.Equal(t, z, zʹ) - } - } - } -} - -// Tests modular negation with known answers -func TestNeg(t *testing.T) { - tests := []struct { - x, m, e *big.Int - }{ - {big.NewInt(1), big.NewInt(7), big.NewInt(6)}, - {big.NewInt(2), big.NewInt(7), big.NewInt(5)}, - {big.NewInt(3), big.NewInt(7), big.NewInt(4)}, - {big.NewInt(4), big.NewInt(7), big.NewInt(3)}, - {big.NewInt(5), big.NewInt(7), big.NewInt(2)}, - {big.NewInt(6), big.NewInt(7), big.NewInt(1)}, - - {big.NewInt(-1), big.NewInt(7), big.NewInt(1)}, - {big.NewInt(-2), big.NewInt(7), big.NewInt(2)}, - {big.NewInt(-3), big.NewInt(7), big.NewInt(3)}, - {big.NewInt(-4), big.NewInt(7), big.NewInt(4)}, - {big.NewInt(-5), big.NewInt(7), big.NewInt(5)}, - {big.NewInt(-6), big.NewInt(7), big.NewInt(6)}, - - {big.NewInt(8), big.NewInt(7), big.NewInt(6)}, - {big.NewInt(9), big.NewInt(7), big.NewInt(5)}, - {big.NewInt(10), big.NewInt(7), big.NewInt(4)}, - {big.NewInt(11), big.NewInt(7), big.NewInt(3)}, - {big.NewInt(12), big.NewInt(7), big.NewInt(2)}, - {big.NewInt(13), big.NewInt(7), big.NewInt(1)}, - } - - for _, test := range tests { - r, err := Neg(test.x, test.m) - require.NoError(t, err) - if r.Cmp(test.e) != 0 { - t.Errorf("TestNeg failed. Expected %v, got: %v ", test.e, r) - } - } -} - -func TestNegInvariants(t *testing.T) { - tests := []struct { - x, m, e *big.Int - }{ - {big.NewInt(0), big.NewInt(7), big.NewInt(0)}, - {big.NewInt(7), big.NewInt(7), big.NewInt(0)}, - {big.NewInt(-7), big.NewInt(7), big.NewInt(0)}, - } - - for _, test := range tests { - r, err := Neg(test.x, test.m) - require.NoError(t, err) - if r.Cmp(test.e) != 0 { - t.Errorf("TestNeg failed. Expected %v, got: %v ", test.e, r) - } - } -} - -// Simple test for distinct Rand output -func TestRandDistinct(t *testing.T) { - // Each value should be distinct - a, _ := Rand(n) - b, _ := Rand(n) - c, _ := Rand(n) - - // ❄️❄️❄️ - require.NotEqual(t, a, b) - require.NotEqual(t, a, c) - require.NotEqual(t, b, c) -} - -// Rand values should be O(log2(m)) bits -func TestRandIsExpectedLength(t *testing.T) { - trials := 1000 - max := big.NewInt(-1) - - // Generate many nonces, keep the max - for i := 0; i < trials; i++ { - r, err := Rand(m) - require.NoError(t, err) - - // Nonces should be < m - if r.Cmp(m) != -1 { - t.Errorf("nonce too large, require %v < %v", r, m) - } - - if r.Cmp(max) == 1 { - max = r - } - } - - // With high probability, the max nonce should be very close N - lowerBound := new(big.Int).Rsh(m, 1) - if max.Cmp(lowerBound) == -1 { - t.Errorf("Expected max nonce: %v > %v", max, lowerBound) - } -} - -// Randomly selected nonces with a large modulus will be unique with overwhelming probability -func TestRandDistinctWithLargeModulus(t *testing.T) { - const iterations = 1000 - testUnique(t, iterations, func() *big.Int { - r, _ := Rand(m) - return r - }) -} - -// Calls sampleFunc() n times and asserts that the lower 64B of each output are unique. -func testUnique(t *testing.T, iterations int, sampleFunc func() *big.Int) { - // For simplicity, we test only the lower 64B of each nonce. This is sufficient - // to prove uniqueness and go-lang doesn't hash slices (no slices in maps) - const size = 256 / 8 - seen := make(map[[size]byte]bool) - var x [size]byte - - // Check the pre-computed commitments for uniquness - for i := 0; i < iterations; i++ { - // Retrieve a sample - sample := sampleFunc() - require.NotNil(t, sample) - - // Copy the bytes from slice>array - copy(x[:], sample.Bytes()) - - // Ensure each sample is unique - if seen[x] { - t.Errorf("duplicate sample found: %v", x) - } - seen[x] = true - } -} - -// Ensure Rand never returns 0 or 1. -func TestRandNotZeroNotOne(t *testing.T) { - // Test for non-zero only useful when iterations >> |Z_m| - const iterations = 1000 - m := big.NewInt(5) - - for i := 0; i < iterations; i++ { - r, err := Rand(m) - require.NoError(t, err) - // Not 0 or 1 - require.NotEqual(t, r, Zero) - require.NotEqual(t, r, One) - } -} - -func TestRand_NilModulusErrors(t *testing.T) { - r, err := Rand(nil) - require.Nil(t, r) - require.Contains(t, err.Error(), internal.ErrNilArguments.Error()) -} - -// Double-inverse is the identity function in fields -func TestInvRoundTrip(t *testing.T) { - m := internal.B10("1031") // Prime-order modulus - - for _, a := range []*big.Int{ - internal.B10("500"), - internal.B10("-500"), - internal.B10("1"), - internal.B10("1030"), - } { - // Our expected value is the modular reduction of the test value - expected := a.Mod(a, m) - - // Invert and check - aInv, err := Inv(a, m) - require.NoError(t, err, "a=%v", a) - require.NotNil(t, aInv) - - // Invert again and check - a_, err := Inv(aInv, m) - if err != nil { - require.Equal(t, expected, a_) - } - } -} - -// Tests values for which there is no inverse in the given field -func TestInvNotFound(t *testing.T) { - m := internal.B10("1024") // m = 2^10 - // 0 and even numbers will not have inverse in this ring - - for _, a := range []*big.Int{ - internal.B10("500"), - internal.B10("-500"), - internal.B10("0"), - internal.B10("1024"), - internal.B10("512"), - internal.B10("300000000"), - } { - // Invert and check - aInv, err := Inv(a, m) - require.Error(t, err, "a=%v", a) - require.Nil(t, aInv) - } -} - -func TestExpKnownAnswer(t *testing.T) { - p := internal.B10("1031") // prime-order field - pMinus1 := internal.B10("1030") - tests := []struct { - name string - x, e, m *big.Int - expected *big.Int - }{ - {"fermat's little thm: 500", internal.B10("500"), p, p, internal.B10("500")}, - {"fermat's little thm (p-1): 500", internal.B10("500"), pMinus1, p, One}, - {"fermat's little thm (p-1): 5000", internal.B10("5000"), pMinus1, p, One}, - {"399^0 = 1", internal.B10("399"), Zero, p, One}, - {"673^1 = 673", internal.B10("673"), One, p, internal.B10("673")}, - } - - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual, err := Exp(test.x, test.e, test.m) - if err != nil { - require.Equal(t, test.expected, actual) - } - }) - } -} - -// A product of two 1024b safe primes -var N1024 = internal.B10( - "22657252520748253292205422817162431301953923432914829530688424232913850279325496327198502914522231560238552529734156383924448818535517634061008476071362010781638360092704508943571866960229942049437914690556866055765377519627454975682400206932320319743805083072214857842762721537739950074695623974079312071498296625705376593890814889314744719469735809152488403143751157723139035869185892099006348653635981206799193781030834368833947197930944812082594326193527332208252230115672713914945889734620959932802893197325106135662762752470236627025599443912886530954179753873735786171937758916890000958846322096261981191349917", -) - -// A product of two 256b safe primes -var N256 = internal.B10( - "10815068324662993508164204692909269429257853772524581783499643160896147777579932560873002543907262462663453338979819981987639157192530671167315407970757417", -) - -func Benchmark_rand1024(b *testing.B) { - if testing.Short() { - b.Skip("skipping test in short mode.") - } - - for i := 0; i < b.N; i++ { - Rand(N1024) // nolint - } -} - -func BenchmarkRand1024(b *testing.B) { - if testing.Short() { - b.Skip("skipping test in short mode.") - } - - for i := 0; i < b.N; i++ { - Rand(N1024) // nolint - } -} - -func Benchmark_rand256(b *testing.B) { - if testing.Short() { - b.Skip("skipping test in short mode.") - } - - for i := 0; i < b.N; i++ { - Rand(N256) // nolint - } -} - -func BenchmarkRandStar256(b *testing.B) { - if testing.Short() { - b.Skip("skipping test in short mode.") - } - - for i := 0; i < b.N; i++ { - Rand(N256) // nolint - } -} diff --git a/crypto/core/primes.go b/crypto/core/primes.go deleted file mode 100755 index 24ae766ed..000000000 --- a/crypto/core/primes.go +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package core - -import ( - "crypto/rand" - "fmt" - "math" - "math/big" -) - -// GenerateSafePrime creates a prime number `p` -// where (`p`-1)/2 is also prime with at least `bits` -func GenerateSafePrime(bits uint) (*big.Int, error) { - if bits < 3 { - return nil, fmt.Errorf("safe prime size must be at least 3-bits") - } - - var p *big.Int - var err error - checks := int(math.Max(float64(bits)/16, 8)) - for { - // rand.Prime throws an error if bits < 2 - // -1 so the Sophie-Germain prime is 1023 bits - // and the Safe prime is 1024 - p, err = rand.Prime(rand.Reader, int(bits)-1) - if err != nil { - return nil, err - } - p.Add(p.Lsh(p, 1), One) - - if p.ProbablyPrime(checks) { - break - } - } - - return p, nil -} diff --git a/crypto/core/protocol/protocol.go b/crypto/core/protocol/protocol.go deleted file mode 100644 index ba454767e..000000000 --- a/crypto/core/protocol/protocol.go +++ /dev/null @@ -1,114 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package protocol - -import ( - "encoding/base64" - "encoding/json" - "fmt" -) - -var ( - ErrNotInitialized = fmt.Errorf("object has not been initialized") - ErrProtocolFinished = fmt.Errorf("the protocol has finished") -) - -const ( - // Dkls18Dkg specifies the DKG protocol of the DKLs18 potocol. - Dkls18Dkg = "DKLs18-DKG" - - // Dkls18Sign specifies the DKG protocol of the DKLs18 potocol. - Dkls18Sign = "DKLs18-Sign" - - // Dkls18Refresh specifies the DKG protocol of the DKLs18 potocol. - Dkls18Refresh = "DKLs18-Refresh" - - // versions will increment in 100 intervals, to leave room for adding other versions in between them if it is - // ever needed in the future. - - // Version0 is version 0! - Version0 = 100 - - // Version1 is version 2! - Version1 = 200 -) - -// Message provides serializers and deserializer for the inputs and outputs of each step of the protocol. -// Moreover, it adds some metadata and versioning around the serialized data. -type Message struct { - Payloads map[string][]byte `json:"payloads"` - Metadata map[string]string `json:"metadata"` - Protocol string `json:"protocol"` - Version uint `json:"version"` -} - -// EncodeMessage encodes the message to a string. -func EncodeMessage(m *Message) (string, error) { - bz, err := json.Marshal(m) - if err != nil { - return "", err - } - return base64.StdEncoding.EncodeToString(bz), nil -} - -// DecodeMessage decodes the message from a string. -func DecodeMessage(s string) (*Message, error) { - bz, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return nil, err - } - var m Message - if err := json.Unmarshal(bz, &m); err != nil { - return nil, err - } - return &m, nil -} - -// MarshalJSON marshals the message to JSON. -func (m *Message) MarshalJSON() ([]byte, error) { - type Alias Message // Use type alias to avoid infinite recursion - return json.Marshal(&struct { - *Alias - }{ - Alias: (*Alias)(m), - }) -} - -// UnmarshalJSON unmarshals the message from JSON. -func (m *Message) UnmarshalJSON(data []byte) error { - var obj map[string]any - if err := json.Unmarshal(data, &obj); err != nil { - return err - } - m.Payloads = make(map[string][]byte) - m.Metadata = make(map[string]string) - for k, v := range obj { - switch k { - case "payloads": - m.Payloads = v.(map[string][]byte) - case "metadata": - m.Metadata = v.(map[string]string) - case "protocol": - m.Protocol = v.(string) - case "version": - m.Version = uint(v.(float64)) - } - } - return nil -} - -// Iterator an interface for the DKLs18 protocols that follows the iterator pattern. -type Iterator interface { - // Next runs the next round of the protocol. - // Returns `ErrProtocolFinished` when protocol has completed. - Next(input *Message) (*Message, error) - - // Result returns the final result, if any, of the completed protocol. - // Returns nil if the protocol has not yet terminated. - // Returns an error if an error was encountered during protocol execution. - Result(version uint) (*Message, error) -} diff --git a/crypto/daed/aes_siv.go b/crypto/daed/aes_siv.go deleted file mode 100644 index fa8a06381..000000000 --- a/crypto/daed/aes_siv.go +++ /dev/null @@ -1,246 +0,0 @@ -package daed - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/subtle" - "errors" - "fmt" - "math" - // Placeholder for internal crypto/cipher allowlist, please ignore. - // Placeholder for internal crypto/subtle allowlist, please ignore. -) - -// AESSIV is an implementation of AES-SIV-CMAC as defined in -// https://tools.ietf.org/html/rfc5297. -// -// AESSIV implements a deterministic encryption with associated data (i.e. the -// DeterministicAEAD interface). Hence the implementation below is restricted -// to one AD component. -// -// Security Note: -// -// Chatterjee, Menezes and Sarkar analyze AES-SIV in Section 5.1 of -// https://www.math.uwaterloo.ca/~ajmeneze/publications/tightness.pdf -// -// Their analysis shows that AES-SIV is susceptible to an attack in -// a multi-user setting. Concretely, if an attacker knows the encryption -// of a message m encrypted and authenticated with k different keys, -// then it is possible to find one of the MAC keys in time 2^b / k -// where b is the size of the MAC key. A consequence of this attack -// is that 128-bit MAC keys give unsufficient security. -// Since 192-bit AES keys are not supported by tink for voodoo reasons -// and RFC 5297 only supports same size encryption and MAC keys this -// implies that keys must be 64 bytes (2*256 bits) long. -type AESSIV struct { - Cipher cipher.Block - K1 []byte - K2 []byte - CmacK1 []byte - CmacK2 []byte -} - -const ( - // AESSIVKeySize is the key size in bytes. - AESSIVKeySize = 64 - - intSize = 32 << (^uint(0) >> 63) // 32 or 64 - maxInt = 1<<(intSize-1) - 1 -) - -// NewAESSIV returns an AESSIV instance. -func NewAESSIV(key []byte) (*AESSIV, error) { - if len(key) != AESSIVKeySize { - return nil, fmt.Errorf("aes_siv: invalid key size %d", len(key)) - } - - k1 := key[:32] - k2 := key[32:] - c, err := aes.NewCipher(k1) - if err != nil { - return nil, fmt.Errorf("aes_siv: aes.NewCipher(%s) failed, %v", k1, err) - } - - block := make([]byte, aes.BlockSize) - c.Encrypt(block, block) - multiplyByX(block) - cmacK1 := make([]byte, aes.BlockSize) - copy(cmacK1, block) - multiplyByX(block) - cmacK2 := make([]byte, aes.BlockSize) - copy(cmacK2, block) - - return &AESSIV{ - K1: k1, - K2: k2, - CmacK1: cmacK1, - CmacK2: cmacK2, - Cipher: c, - }, nil -} - -// multiplyByX multiplies an element in GF(2^128) by its generator. -// -// This function is incorrectly named "doubling" in section 2.3 of RFC 5297. -func multiplyByX(block []byte) { - carry := int(block[0] >> 7) - for i := 0; i < aes.BlockSize-1; i++ { - block[i] = (block[i] << 1) | (block[i+1] >> 7) - } - - block[aes.BlockSize-1] = (block[aes.BlockSize-1] << 1) ^ byte( - subtle.ConstantTimeSelect(carry, 0x87, 0x00), - ) -} - -// EncryptDeterministically deterministically encrypts plaintext with associatedData. -func (asc *AESSIV) EncryptDeterministically(plaintext, associatedData []byte) ([]byte, error) { - if len(plaintext) > maxInt-aes.BlockSize { - return nil, fmt.Errorf("aes_siv: plaintext too long") - } - siv := make([]byte, aes.BlockSize) - asc.s2v(plaintext, associatedData, siv) - - ct := make([]byte, len(plaintext)+aes.BlockSize) - copy(ct[:aes.BlockSize], siv) - if err := asc.ctrCrypt(siv, plaintext, ct[aes.BlockSize:]); err != nil { - return nil, err - } - - return ct, nil -} - -// DecryptDeterministically deterministically decrypts ciphertext with associatedData. -func (asc *AESSIV) DecryptDeterministically(ciphertext, associatedData []byte) ([]byte, error) { - if len(ciphertext) < aes.BlockSize { - return nil, errors.New("aes_siv: ciphertext is too short") - } - - pt := make([]byte, len(ciphertext)-aes.BlockSize) - siv := ciphertext[:aes.BlockSize] - asc.ctrCrypt(siv, ciphertext[aes.BlockSize:], pt) - s2v := make([]byte, aes.BlockSize) - asc.s2v(pt, associatedData, s2v) - - diff := byte(0) - for i := 0; i < aes.BlockSize; i++ { - diff |= siv[i] ^ s2v[i] - } - if diff != 0 { - return nil, errors.New("aes_siv: invalid ciphertext") - } - - return pt, nil -} - -// ctrCrypt encrypts (or decrypts) the bytes in in using an SIV and writes the -// result to out. -func (asc *AESSIV) ctrCrypt(siv, in, out []byte) error { - // siv might be used outside of ctrCrypt(), so making a copy of it. - iv := make([]byte, aes.BlockSize) - copy(iv, siv) - iv[8] &= 0x7f - iv[12] &= 0x7f - - c, err := aes.NewCipher(asc.K2) - if err != nil { - return fmt.Errorf("aes_siv: aes.NewCipher(%s) failed, %v", asc.K2, err) - } - - steam := cipher.NewCTR(c, iv) - steam.XORKeyStream(out, in) - return nil -} - -// s2v is a Pseudo-Random Function (PRF) construction: -// https://tools.ietf.org/html/rfc5297. -func (asc *AESSIV) s2v(msg, ad, siv []byte) { - block := make([]byte, aes.BlockSize) - asc.cmac(block, block) - multiplyByX(block) - - adMac := make([]byte, aes.BlockSize) - asc.cmac(ad, adMac) - xorBlock(adMac, block) - - if len(msg) >= aes.BlockSize { - asc.cmacLong(msg, block, siv) - } else { - multiplyByX(block) - for i := 0; i < len(msg); i++ { - block[i] ^= msg[i] - } - block[len(msg)] ^= 0x80 - asc.cmac(block, siv) - } -} - -// cmacLong computes CMAC(XorEnd(data, last)), where XorEnd xors the bytes in -// last to the last bytes in data. -// -// The size of the data must be at least 16 bytes. -func (asc *AESSIV) cmacLong(data, last, mac []byte) { - block := make([]byte, aes.BlockSize) - copy(block, data[:aes.BlockSize]) - - idx := aes.BlockSize - for aes.BlockSize <= len(data)-idx { - asc.Cipher.Encrypt(block, block) - xorBlock(data[idx:idx+aes.BlockSize], block) - idx += aes.BlockSize - } - - remaining := len(data) - idx - for i := 0; i < aes.BlockSize-remaining; i++ { - block[remaining+i] ^= last[i] - } - if remaining == 0 { - xorBlock(asc.CmacK1, block) - } else { - asc.Cipher.Encrypt(block, block) - for i := 0; i < remaining; i++ { - block[i] ^= last[aes.BlockSize-remaining+i] - block[i] ^= data[idx+i] - } - block[remaining] ^= 0x80 - xorBlock(asc.CmacK2, block) - } - - asc.Cipher.Encrypt(mac, block) -} - -// cmac computes a CMAC of some data. -func (asc *AESSIV) cmac(data, mac []byte) { - numBs := int(math.Ceil(float64(len(data)) / aes.BlockSize)) - if numBs == 0 { - numBs = 1 - } - lastBSize := len(data) - (numBs-1)*aes.BlockSize - - block := make([]byte, aes.BlockSize) - idx := 0 - for i := 0; i < numBs-1; i++ { - xorBlock(data[idx:idx+aes.BlockSize], block) - asc.Cipher.Encrypt(block, block) - idx += aes.BlockSize - } - for j := 0; j < lastBSize; j++ { - block[j] ^= data[idx+j] - } - - if lastBSize == aes.BlockSize { - xorBlock(asc.CmacK1, block) - } else { - block[lastBSize] ^= 0x80 - xorBlock(asc.CmacK2, block) - } - - asc.Cipher.Encrypt(mac, block) -} - -// xorBlock sets block[i] = x[i] ^ block[i]. -func xorBlock(x, block []byte) { - for i := 0; i < aes.BlockSize; i++ { - block[i] ^= x[i] - } -} diff --git a/crypto/daed/aes_siv_test.go b/crypto/daed/aes_siv_test.go deleted file mode 100644 index 19e615d9c..000000000 --- a/crypto/daed/aes_siv_test.go +++ /dev/null @@ -1,303 +0,0 @@ -package daed_test - -import ( - "bytes" - "encoding/hex" - "encoding/json" - "os" - "path/filepath" - "testing" - - subtle "github.com/sonr-io/sonr/crypto/daed" - "github.com/sonr-io/sonr/crypto/subtle/random" -) - -type testData struct { - Algorithm string - GeneratorVersion string - TestGroups []*testGroup - NumberOfTests uint32 -} - -type testGroup struct { - Type string - Tests []*testCase - KeySize uint32 -} - -type testCase struct { - Key string - Aad string - Msg string - Ct string - Result string - TcID uint32 -} - -func TestAESSIV_EncryptDecrypt(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - msg := []byte("Some data to encrypt.") - aad := []byte("Additional data") - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - ct, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, msg) { - t.Errorf("Mismatched plaintexts: got %v, want %v", pt, msg) - } -} - -func TestAESSIV_EmptyPlaintext(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - aad := []byte("Additional data") - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - ct, err := a.EncryptDeterministically(nil, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, []byte{}) { - t.Errorf("Mismatched plaintexts: got %v, want []", pt) - } - - ct, err = a.EncryptDeterministically([]byte{}, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, []byte{}) { - t.Errorf("Mismatched plaintexts: got %v, want []", pt) - } -} - -func TestAESSIV_EmptyAdditionalData(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - ct, err := a.EncryptDeterministically(nil, nil) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - - if pt, err := a.DecryptDeterministically(ct, nil); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, []byte{}) { - t.Errorf("Mismatched plaintexts: got %v, want []", pt) - } - - if pt, err := a.DecryptDeterministically(ct, []byte{}); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, []byte{}) { - t.Errorf("Mismatched plaintexts: got %v, want []", pt) - } -} - -func TestAESSIV_KeySizes(t *testing.T) { - keyStr := "198371900187498172316311acf81d238ff7619873a61983d619c87b63a1987f" + - "987131819803719b847126381cd763871638aa71638176328761287361231321" + - "812731321de508761437195ff231765aa4913219873ac6918639816312130011" + - "abc900bba11400187984719827431246bbab1231eb4145215ff7141436616beb" + - "9817298148712fed3aab61000ff123313e" - key, _ := hex.DecodeString(keyStr) - - for i := 0; i < len(key); i++ { - _, err := subtle.NewAESSIV(key[:i]) - if i == subtle.AESSIVKeySize && err != nil { - t.Errorf("Rejected valid key size: %v, %v", i, err) - } - if i != subtle.AESSIVKeySize && err == nil { - t.Errorf("Allowed invalid key size: %v", i) - } - } -} - -func TestAESSIV_MessageSizes(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - aad := []byte("Additional data") - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - for i := uint32(0); i < 1024; i++ { - msg := random.GetRandomBytes(i) - ct, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, msg) { - t.Errorf("Mismatched plaintexts: got %v, want %v", pt, msg) - } - } - - for i := uint32(1024); i < 100000; i += 5000 { - msg := random.GetRandomBytes(i) - ct, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, msg) { - t.Errorf("Mismatched plaintexts: got %v, want %v", pt, msg) - } - } -} - -func TestAESSIV_AdditionalDataSizes(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - msg := []byte("Some data to encrypt.") - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - for i := uint32(0); i < 1024; i++ { - aad := random.GetRandomBytes(i) - ct, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - if pt, err := a.DecryptDeterministically(ct, aad); err != nil { - t.Errorf("Unexpected decryption error: %v", err) - } else if !bytes.Equal(pt, msg) { - t.Errorf("Mismatched plaintexts: got %v, want %v", pt, msg) - } - } -} - -func TestAESSIV_CiphertextModifications(t *testing.T) { - keyStr := "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + - "00112233445566778899aabbccddeefff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" - key, _ := hex.DecodeString(keyStr) - aad := []byte("Additional data") - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - } - - for i := uint32(0); i < 50; i++ { - msg := random.GetRandomBytes(i) - ct, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("Unexpected encryption error: %v", err) - } - for j := 0; j < len(ct); j++ { - for b := uint32(0); b < 8; b++ { - ct[j] ^= 1 << b - if _, err := a.DecryptDeterministically(ct, aad); err == nil { - t.Errorf("Modified ciphertext decrypted: byte %d, bit %d", j, b) - } - ct[j] ^= 1 << b - } - } - } -} - -func TestAESSIV_WycheproofVectors(t *testing.T) { - srcDir, ok := os.LookupEnv("TEST_SRCDIR") - if !ok { - t.Skip("TEST_SRCDIR not set") - } - f, err := os.Open(filepath.Join(srcDir, "wycheproof/testvectors/aes_siv_cmac_test.json")) - if err != nil { - t.Fatalf("Cannot open file: %s", err) - } - parser := json.NewDecoder(f) - data := new(testData) - if err := parser.Decode(data); err != nil { - t.Fatalf("Cannot decode test data: %s", err) - } - - for _, g := range data.TestGroups { - if g.KeySize/8 != subtle.AESSIVKeySize { - continue - } - - for _, tc := range g.Tests { - key, err := hex.DecodeString(tc.Key) - if err != nil { - t.Errorf("#%d, cannot decode key: %s", tc.TcID, err) - } - aad, err := hex.DecodeString(tc.Aad) - if err != nil { - t.Errorf("#%d, cannot decode aad: %s", tc.TcID, err) - } - msg, err := hex.DecodeString(tc.Msg) - if err != nil { - t.Errorf("#%d, cannot decode msg: %s", tc.TcID, err) - } - ct, err := hex.DecodeString(tc.Ct) - if err != nil { - t.Errorf("#%d, cannot decode ct: %s", tc.TcID, err) - } - - a, err := subtle.NewAESSIV(key) - if err != nil { - t.Errorf("NewAESSIV(key) = _, %v, want _, nil", err) - continue - } - - // EncryptDeterministically should always succeed since msg and aad are valid inputs. - gotCt, err := a.EncryptDeterministically(msg, aad) - if err != nil { - t.Errorf("#%d, unexpected encryption error: %v", tc.TcID, err) - } else { - if tc.Result == "valid" && !bytes.Equal(gotCt, ct) { - t.Errorf("#%d, incorrect encryption: got %v, want %v", tc.TcID, gotCt, ct) - } - if tc.Result == "invalid" && bytes.Equal(gotCt, ct) { - t.Errorf("#%d, invalid encryption: got %v, want %v", tc.TcID, gotCt, ct) - } - } - - pt, err := a.DecryptDeterministically(ct, aad) - if tc.Result == "valid" { - if err != nil { - t.Errorf("#%d, unexpected decryption error: %v", tc.TcID, err) - } else if !bytes.Equal(pt, msg) { - t.Errorf("#%d, incorrect decryption: got %v, want %v", tc.TcID, pt, msg) - } - } else { - if err == nil { - t.Errorf("#%d, decryption error expected: got nil", tc.TcID) - } - } - } - } -} diff --git a/crypto/dkg/frost/README.md b/crypto/dkg/frost/README.md deleted file mode 100755 index a85c425a7..000000000 --- a/crypto/dkg/frost/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## FROST: Flexible Round-Optimized Schnorr Threshold Signatures - -This package is an implementation of the DKG part of -[FROST: Flexible Round-Optimized Schnorr Threshold Signatures](https://eprint.iacr.org/2020/852.pdf) diff --git a/crypto/dkg/frost/dkg_round1.go b/crypto/dkg/frost/dkg_round1.go deleted file mode 100644 index 91819fcb1..000000000 --- a/crypto/dkg/frost/dkg_round1.go +++ /dev/null @@ -1,153 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "bytes" - crand "crypto/rand" - "encoding/gob" - "fmt" - "reflect" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/sharing" -) - -// Round1Bcast are values that are broadcast to all other participants -// after round1 completes -type Round1Bcast struct { - Verifiers *sharing.FeldmanVerifier - Wi, Ci curves.Scalar -} - -type Round1Result struct { - Broadcast *Round1Bcast - P2P *sharing.ShamirShare -} - -func (result *Round1Result) Encode() ([]byte, error) { - gob.Register(result.Broadcast.Verifiers.Commitments[0]) // just the point for now - gob.Register(result.Broadcast.Ci) - buf := &bytes.Buffer{} - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return buf.Bytes(), nil -} - -func (result *Round1Result) Decode(input []byte) error { - buf := bytes.NewBuffer(input) - dec := gob.NewDecoder(buf) - if err := dec.Decode(result); err != nil { - return errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return nil -} - -// Round1P2PSend are values that are P2PSend to all other participants -// after round1 completes -type Round1P2PSend = map[uint32]*sharing.ShamirShare - -// Round1 implements dkg round 1 of FROST -func (dp *DkgParticipant) Round1(secret []byte) (*Round1Bcast, Round1P2PSend, error) { - // Make sure dkg participant is not empty - if dp == nil || dp.Curve == nil { - return nil, nil, internal.ErrNilArguments - } - - // Make sure round number is correct - if dp.round != 1 { - return nil, nil, internal.ErrInvalidRound - } - - // Check number of participants - if uint32(len(dp.otherParticipantShares)+1) > dp.feldman.Limit || - uint32(len(dp.otherParticipantShares)+1) < dp.feldman.Threshold { - return nil, nil, fmt.Errorf( - "length of dp.otherParticipantShares + 1 should be equal to feldman limit", - ) - } - - // If secret is nil, sample a new one - // If not, check secret is valid - var s curves.Scalar - var err error - if secret == nil { - s = dp.Curve.Scalar.Random(crand.Reader) - } else { - s, err = dp.Curve.Scalar.SetBytes(secret) - if err != nil { - return nil, nil, err - } - if s.IsZero() { - return nil, nil, internal.ErrZeroValue - } - } - - // Step 1 - (Aj0,...Ajt), (xi1,...,xin) <- FeldmanShare(s) - // We should validate types of Feldman curve scalar and participant's curve scalar. - if reflect.TypeOf(dp.feldman.Curve.Scalar) != reflect.TypeOf(dp.Curve.Scalar) { - return nil, nil, fmt.Errorf( - "feldman scalar should have the same type as the dkg participant scalar", - ) - } - verifiers, shares, err := dp.feldman.Split(s, crand.Reader) - if err != nil { - return nil, nil, err - } - - // Store Verifiers and shares - dp.verifiers = verifiers - dp.secretShares = shares - - // Step 2 - Sample ki <- Z_q - ki := dp.Curve.Scalar.Random(crand.Reader) - - // Step 3 - Compute Ri = ki*G - Ri := dp.Curve.ScalarBaseMult(ki) - - // Step 4 - Compute Ci = H(i, CTX, g^{a_(i,0)}, R_i), where CTX is fixed context string - var msg []byte - // Append participant id - msg = append(msg, byte(dp.Id)) - // Append CTX - msg = append(msg, dp.ctx) - // Append a_{i,0}*G - msg = append(msg, verifiers.Commitments[0].ToAffineCompressed()...) - // Append Ri - msg = append(msg, Ri.ToAffineCompressed()...) - // Hash the message and get Ci - ci := dp.Curve.Scalar.Hash(msg) - - // Step 5 - Compute Wi = ki+a_{i,0}*c_i mod q. Note that a_{i,0} is the secret. - // Note: We have to compute scalar in the following way when using ed25519 curve, rather than scalar := dp.Scalar.Mul(s, Ci) - // there is an invalid encoding error when we compute scalar as above. - wi := s.MulAdd(ci, ki) - - // Step 6 - Broadcast (Ci, Wi, Ci) to other participants - round1Bcast := &Round1Bcast{ - verifiers, - wi, - ci, - } - - // Step 7 - P2PSend f_i(j) to each participant Pj and keep (i, f_j(i)) for himself - p2pSend := make(Round1P2PSend, len(dp.otherParticipantShares)) - for id := range dp.otherParticipantShares { - p2pSend[id] = shares[id-1] - } - - // Update internal state - dp.round = 2 - - // return - return round1Bcast, p2pSend, nil -} diff --git a/crypto/dkg/frost/dkg_round2.go b/crypto/dkg/frost/dkg_round2.go deleted file mode 100644 index 381c3d2c5..000000000 --- a/crypto/dkg/frost/dkg_round2.go +++ /dev/null @@ -1,162 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/sharing" -) - -// Round2Bcast are values that are broadcast to all other participants -// after round2 completes -type Round2Bcast struct { - VerificationKey curves.Point - VkShare curves.Point -} - -// Round2 implements dkg round 2 of FROST -func (dp *DkgParticipant) Round2( - bcast map[uint32]*Round1Bcast, - p2psend map[uint32]*sharing.ShamirShare, -) (*Round2Bcast, error) { - // Make sure dkg participant is not empty - if dp == nil || dp.Curve == nil { - return nil, internal.ErrNilArguments - } - - // Check dkg participant has the correct dkg round number - if dp.round != 2 { - return nil, internal.ErrInvalidRound - } - - // Check the input is valid - if bcast == nil || p2psend == nil || len(p2psend) == 0 { - return nil, internal.ErrNilArguments - } - - // Check length of bcast and p2psend - if uint32(len(bcast)) > dp.feldman.Limit || uint32(len(bcast)) < dp.feldman.Threshold-1 { - return nil, fmt.Errorf("invalid broadcast length") - } - - if uint32(len(p2psend)) > dp.feldman.Limit-1 || uint32(len(p2psend)) < dp.feldman.Threshold-1 { - return nil, fmt.Errorf("invalid p2pSend length") - } - - // We should validate Wi and Ci values in Round1Bcast - for id := range bcast { - // ci should be within the range 1 to q-1, q is the group order. - if bcast[id].Ci.IsZero() { - return nil, fmt.Errorf("ci should not be zero from participant %d", id) - } - } - // Validate each received commitment is on curve - for id := range bcast { - for _, com := range bcast[id].Verifiers.Commitments { - if !com.IsOnCurve() || com.IsIdentity() { - return nil, fmt.Errorf("some commitment is not on curve from participant %d", id) - } - } - } - - var err error - - // Step 2 - for j in 1,...,n - for id := range bcast { - - // Step 3 - if j == i, continue - if id == dp.Id { - continue - } - - // Step 4 - Check equation c_j = H(j, CTX, A_{j,0}, g^{w_j}*A_{j,0}^{-c_j} - // Get Aj0 - Aj0 := bcast[id].Verifiers.Commitments[0] - // Compute g^{w_j} - prod1 := dp.Curve.ScalarBaseMult(bcast[id].Wi) - // Compute A_{j,0}^{-c_j} - prod2 := Aj0.Mul(bcast[id].Ci.Neg()) - - // We need to check Aj0 and prod2 are points on the same curve. - if !Aj0.IsOnCurve() || Aj0.IsIdentity() || !prod2.IsOnCurve() || prod2.IsIdentity() || - Aj0.CurveName() != prod2.CurveName() { - return nil, fmt.Errorf("invalid Aj0 or prod2 which is not on the same curve") - } - if prod2 == nil { - return nil, fmt.Errorf("invalid should not be nil") - } - - prod := prod1.Add(prod2) - var msg []byte - // Append participant id - msg = append(msg, byte(id)) - // Append CTX - msg = append(msg, dp.ctx) - // Append Aj0 - msg = append(msg, Aj0.ToAffineCompressed()...) - // Append prod - msg = append(msg, prod.ToAffineCompressed()...) - // Hash the message and get cj - cj := dp.Curve.Scalar.Hash(msg) - // Check equation - if cj.Cmp(bcast[id].Ci) != 0 { - return nil, fmt.Errorf("hash check fails for participant with id %d", id) - } - - // Step 5 - FeldmanVerify - fji := p2psend[id] - if err = bcast[id].Verifiers.Verify(fji); err != nil { - return nil, fmt.Errorf("feldman verify fails for participant with id %d", id) - } - } - - sk, err := dp.Curve.Scalar.SetBytes(dp.secretShares[dp.Id-1].Value) - if err != nil { - return nil, err - } - vk := dp.verifiers.Commitments[0] - // Step 6 - Compute signing key share ski = \sum_{j=1}^n xji - for id := range bcast { - if id == dp.Id { - continue - } - t2, err := dp.Curve.Scalar.SetBytes(p2psend[id].Value) - if err != nil { - return nil, err - } - sk = sk.Add(t2) - } - - // Step 8 - Compute verification key vk = sum(A_{j,0}), j = 1,...,n - for id := range bcast { - if id == dp.Id { - continue - } - vk = vk.Add(bcast[id].Verifiers.Commitments[0]) - } - - // Store signing key share - dp.SkShare = sk - - // Step 7 - Compute verification key share vki = ski*G and store - dp.VkShare = dp.Curve.ScalarBaseMult(sk) - - // Store verification key - dp.VerificationKey = vk - - // Update round number - dp.round = 3 - - // Broadcast - return &Round2Bcast{ - vk, - dp.VkShare, - }, nil -} diff --git a/crypto/dkg/frost/dkg_rounds_test.go b/crypto/dkg/frost/dkg_rounds_test.go deleted file mode 100644 index 6f6861ef1..000000000 --- a/crypto/dkg/frost/dkg_rounds_test.go +++ /dev/null @@ -1,206 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/sharing" -) - -var ( - testCurve = curves.ED25519() - Ctx = "string to prevent replay attack" -) - -// Test dkg round1 works for 2 participants -func TestDkgRound1Works(t *testing.T) { - p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2) - require.NoError(t, err) - bcast, p2psend, err := p1.Round1(nil) - require.NoError(t, err) - require.NotNil(t, bcast) - require.NotNil(t, p2psend) - require.NotNil(t, p1.ctx) - require.Equal(t, len(p2psend), 1) - require.Equal(t, p1.round, 2) - _, ok := p2psend[2] - require.True(t, ok) -} - -func TestDkgRound1RepeatCall(t *testing.T) { - p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2) - require.NoError(t, err) - _, _, err = p1.Round1(nil) - require.NoError(t, err) - _, _, err = p1.Round1(nil) - require.Error(t, err) -} - -func TestDkgRound1BadSecret(t *testing.T) { - p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2) - require.NoError(t, err) - // secret == 0 - secret := []byte{0} - _, _, err = p1.Round1(secret) - require.Error(t, err) - // secret too big - secret = []byte{ - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - } - _, _, err = p1.Round1(secret) - require.Error(t, err) -} - -func PrepareRound2Input( - t *testing.T, -) (*DkgParticipant, *DkgParticipant, *Round1Bcast, *Round1Bcast, Round1P2PSend, Round1P2PSend) { - // Prepare round 1 output of 2 participants - p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2) - require.NoError(t, err) - require.Equal(t, p1.otherParticipantShares[2].Id, uint32(2)) - p2, err := NewDkgParticipant(2, 2, Ctx, testCurve, 1) - require.NoError(t, err) - require.Equal(t, p2.otherParticipantShares[1].Id, uint32(1)) - bcast1, p2psend1, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - return p1, p2, bcast1, bcast2, p2psend1, p2psend2 -} - -// Test FROST DKG round 2 works -func TestDkgRound2Works(t *testing.T) { - // Prepare Dkg Round1 output - p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t) - // Actual Test - require.NotNil(t, bcast1) - require.NotNil(t, bcast2) - require.NotNil(t, p2psend2[1]) - bcast := make(map[uint32]*Round1Bcast) - p2p := make(map[uint32]*sharing.ShamirShare) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - round2Out, err := p1.Round2(bcast, p2p) - require.NoError(t, err) - require.NotNil(t, round2Out) - require.NotNil(t, p1.SkShare) - require.NotNil(t, p1.VkShare) - require.NotNil(t, p1.VerificationKey) - require.NotNil(t, p1.otherParticipantShares) -} - -// Test FROST DKG round 2 repeat call -func TestDkgRound2RepeatCall(t *testing.T) { - // Prepare round 1 output - p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t) - // Actual Test - require.NotNil(t, bcast1) - require.NotNil(t, bcast2) - require.NotNil(t, p2psend2[1]) - bcast := make(map[uint32]*Round1Bcast) - p2p := make(map[uint32]*sharing.ShamirShare) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - _, err := p1.Round2(bcast, p2p) - require.NoError(t, err) - _, err = p1.Round2(bcast, p2p) - require.Error(t, err) -} - -// Test FROST Dkg Round 2 Bad Input -func TestDkgRound2BadInput(t *testing.T) { - // Prepare Dkg Round 1 output - p1, _, _, _, _, _ := PrepareRound2Input(t) - bcast := make(map[uint32]*Round1Bcast) - p2p := make(map[uint32]*sharing.ShamirShare) - - // Test empty bcast and p2p - _, err := p1.Round2(bcast, p2p) - require.Error(t, err) - - // Test nil bcast and p2p - p1, _, _, _, _, _ = PrepareRound2Input(t) - _, err = p1.Round2(nil, nil) - require.Error(t, err) - - // Test tampered input bcast and p2p - p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t) - bcast = make(map[uint32]*Round1Bcast) - p2p = make(map[uint32]*sharing.ShamirShare) - - // Tamper p2psend2 by doubling the value - tmp, _ := testCurve.Scalar.SetBytes(p2psend2[1].Value) - p2psend2[1].Value = tmp.Double().Bytes() - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - _, err = p1.Round2(bcast, p2p) - require.Error(t, err) -} - -// Test full round works -func TestFullDkgRoundsWorks(t *testing.T) { - // Initiate two participants and running round 1 - p1, p2, bcast1, bcast2, p2psend1, p2psend2 := PrepareRound2Input(t) - bcast := make(map[uint32]*Round1Bcast) - p2p1 := make(map[uint32]*sharing.ShamirShare) - p2p2 := make(map[uint32]*sharing.ShamirShare) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p1[2] = p2psend2[1] - p2p2[1] = p2psend1[2] - - // Running round 2 - round2Out1, _ := p1.Round2(bcast, p2p1) - round2Out2, _ := p2.Round2(bcast, p2p2) - require.Equal(t, round2Out1.VerificationKey, round2Out2.VerificationKey) - s, _ := sharing.NewShamir(2, 2, testCurve) - sk, err := s.Combine(&sharing.ShamirShare{Id: p1.Id, Value: p1.SkShare.Bytes()}, - &sharing.ShamirShare{Id: p2.Id, Value: p2.SkShare.Bytes()}) - require.NoError(t, err) - - vk := testCurve.ScalarBaseMult(sk) - require.True(t, vk.Equal(p1.VerificationKey)) -} diff --git a/crypto/dkg/frost/participant.go b/crypto/dkg/frost/participant.go deleted file mode 100644 index 8cc09ffce..000000000 --- a/crypto/dkg/frost/participant.go +++ /dev/null @@ -1,70 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package frost is an implementation of the DKG part of https://eprint.iacr.org/2020/852.pdf -package frost - -import ( - "strconv" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/sharing" -) - -type DkgParticipant struct { - round int - Curve *curves.Curve - otherParticipantShares map[uint32]*dkgParticipantData - Id uint32 - SkShare curves.Scalar - VerificationKey curves.Point - VkShare curves.Point - feldman *sharing.Feldman - verifiers *sharing.FeldmanVerifier - secretShares []*sharing.ShamirShare - ctx byte -} - -type dkgParticipantData struct { - Id uint32 - Share *sharing.ShamirShare - Verifiers *sharing.FeldmanVerifier -} - -func NewDkgParticipant( - id, threshold uint32, - ctx string, - curve *curves.Curve, - otherParticipants ...uint32, -) (*DkgParticipant, error) { - if curve == nil || len(otherParticipants) == 0 { - return nil, internal.ErrNilArguments - } - limit := uint32(len(otherParticipants)) + 1 - feldman, err := sharing.NewFeldman(threshold, limit, curve) - if err != nil { - return nil, err - } - otherParticipantShares := make(map[uint32]*dkgParticipantData, len(otherParticipants)) - for _, id := range otherParticipants { - otherParticipantShares[id] = &dkgParticipantData{ - Id: id, - } - } - - // SetBigInt the common fixed string - ctxV, _ := strconv.Atoi(ctx) - - return &DkgParticipant{ - Id: id, - round: 1, - Curve: curve, - feldman: feldman, - otherParticipantShares: otherParticipantShares, - ctx: byte(ctxV), - }, nil -} diff --git a/crypto/dkg/gennaro/README.md b/crypto/dkg/gennaro/README.md deleted file mode 100755 index 0bc82ea79..000000000 --- a/crypto/dkg/gennaro/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## One Round Threshold ECDSA with Identifiable Abort (GG20) - -This package is an implementation of the DKG part of -[One Round Threshold ECDSA with Identifiable Abort](https://eprint.iacr.org/2020/540.pdf). diff --git a/crypto/dkg/gennaro/participant.go b/crypto/dkg/gennaro/participant.go deleted file mode 100644 index dd4420d1c..000000000 --- a/crypto/dkg/gennaro/participant.go +++ /dev/null @@ -1,102 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package gennaro is an implementation of the DKG part of https://eprint.iacr.org/2020/540.pdf -package gennaro - -import ( - "crypto/elliptic" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -// Participant is a DKG player that contains information needed to perform DKG rounds -// and yield a secret key share and public key when finished -type Participant struct { - round int - curve elliptic.Curve - scalar curves.EcScalar - otherParticipantShares map[uint32]*dkgParticipantData - id uint32 - skShare *curves.Element - verificationKey *v1.ShareVerifier - feldman *v1.Feldman - pedersen *v1.Pedersen - pedersenResult *v1.PedersenResult -} - -// NewParticipant creates a participant ready to perform a DKG -// `id` is the integer value identifier for this participant -// `threshold` is the minimum bound for the secret sharing scheme -// `generator` is the blinding factor generator used by pedersen's verifiable secret sharing -// `otherParticipants` is the integer value identifiers for the other participants -// `id` and `otherParticipants` must be the set of integers 1,2,....,n -func NewParticipant( - id, threshold uint32, - generator *curves.EcPoint, - scalar curves.EcScalar, - otherParticipants ...uint32, -) (*Participant, error) { - if generator == nil || len(otherParticipants) == 0 { - return nil, internal.ErrNilArguments - } - err := validIds(append(otherParticipants, id)) - if err != nil { - return nil, err - } - - limit := uint32(len(otherParticipants)) + 1 - feldman, err := v1.NewFeldman(threshold, limit, generator.Curve) - if err != nil { - return nil, err - } - pedersen, err := v1.NewPedersen(threshold, limit, generator) - if err != nil { - return nil, err - } - - otherParticipantShares := make(map[uint32]*dkgParticipantData, len(otherParticipants)) - for _, id := range otherParticipants { - otherParticipantShares[id] = &dkgParticipantData{ - Id: id, - } - } - - return &Participant{ - id: id, - round: 1, - curve: generator.Curve, - scalar: scalar, - feldman: feldman, - pedersen: pedersen, - otherParticipantShares: otherParticipantShares, - }, nil -} - -// Determines if the SSIDs are exactly the values 1..n. -func validIds(ids []uint32) error { - // Index - idMap := make(map[uint32]bool, len(ids)) - for _, id := range ids { - idMap[id] = true - } - // Check - for i := 1; i <= len(ids); i++ { - if ok := idMap[uint32(i)]; !ok { - return fmt.Errorf("the ID list %v is invalid; values must be 1,2,..,n", ids) - } - } - return nil -} - -type dkgParticipantData struct { - Id uint32 - Share *v1.ShamirShare - Verifiers []*v1.ShareVerifier -} diff --git a/crypto/dkg/gennaro/participant_test.go b/crypto/dkg/gennaro/participant_test.go deleted file mode 100644 index f1b3070d9..000000000 --- a/crypto/dkg/gennaro/participant_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -var testGenerator, _ = curves.NewScalarBaseMult(btcec.S256(), big.NewInt(3333)) - -func TestNewParticipantWorks(t *testing.T) { - p, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - require.NoError(t, err) - require.NotNil(t, p) - require.Equal(t, p.id, uint32(1)) - require.Equal(t, p.round, 1) - require.Equal(t, p.curve, btcec.S256()) - require.NotNil(t, p.pedersen) - require.NotNil(t, p.feldman) - require.Nil(t, p.pedersenResult) - require.NotNil(t, p.otherParticipantShares) - require.NotNil(t, p.scalar) - _, ok := p.otherParticipantShares[2] - require.True(t, ok) -} - -func TestNewParticipantBadInputs(t *testing.T) { - _, err := NewParticipant(0, 0, nil, nil) - require.Error(t, err) - require.Equal(t, err, internal.ErrNilArguments) - _, err = NewParticipant(1, 2, nil, nil) - require.Error(t, err) - require.Equal(t, err, internal.ErrNilArguments) - _, err = NewParticipant(1, 2, testGenerator, nil) - require.Error(t, err) - require.Equal(t, err, internal.ErrNilArguments) -} diff --git a/crypto/dkg/gennaro/round1.go b/crypto/dkg/gennaro/round1.go deleted file mode 100644 index 2ec405def..000000000 --- a/crypto/dkg/gennaro/round1.go +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/internal" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -// Round1Bcast are the values that are broadcast to all other participants -// after round1 completes -type Round1Bcast = []*v1.ShareVerifier - -// Round1P2PSend are the values that are sent to individual participants based -// on the id -type Round1P2PSend = map[uint32]*Round1P2PSendPacket - -// Round1P2PSendPacket are the shares generated from the secret for a specific participant -type Round1P2PSendPacket struct { - SecretShare *v1.ShamirShare - BlindingShare *v1.ShamirShare -} - -// Round1 computes the first round for the DKG -// `secret` can be nil -// NOTE: if `secret` is nil, a new secret is generated which creates a new key -// if `secret` is set, then this performs key resharing aka proactive secret sharing update -func (dp *Participant) Round1(secret []byte) (Round1Bcast, Round1P2PSend, error) { - if dp.round != 1 { - return nil, nil, internal.ErrInvalidRound - } - - if secret == nil { - // 1. x $← Zq∗ - s, err := dp.scalar.Random() - if err != nil { - return nil, nil, err - } - secret = s.Bytes() - } else { - s := new(big.Int).SetBytes(secret) - if !dp.scalar.IsValid(s) { - return nil, nil, fmt.Errorf("invalid secret value") - } - if s.Cmp(core.Zero) == 0 { - return nil, nil, internal.ErrZeroValue - } - } - - var err error - // 2. {X1,...,Xt},{R1,...,Rt},{x1,...,xn},{r1,...,rn}= PedersenFeldmanShare(E,Q,x,t,{p1,...,pn}) - dp.pedersenResult, err = dp.pedersen.Split(secret) - if err != nil { - return nil, nil, err - } - - // 4. P2PSend x_j,r_j to participant p_j in {p_1,...,p_n}_{i != j} - p2pSend := make(Round1P2PSend, len(dp.otherParticipantShares)) - for id := range dp.otherParticipantShares { - p2pSend[id] = &Round1P2PSendPacket{ - SecretShare: dp.pedersenResult.SecretShares[id-1], - BlindingShare: dp.pedersenResult.BlindingShares[id-1], - } - } - - // Update internal state - dp.round = 2 - - // 3. EchoBroadcast {X_1,...,X_t} to all other participants. - return dp.pedersenResult.BlindedVerifiers, p2pSend, nil -} diff --git a/crypto/dkg/gennaro/round2.go b/crypto/dkg/gennaro/round2.go deleted file mode 100644 index 7be1d9473..000000000 --- a/crypto/dkg/gennaro/round2.go +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/internal" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -type Round2Bcast = []*v1.ShareVerifier - -// Round2 computes the second round for Gennaro DKG -// Algorithm 3 - Gennaro DKG Round 2 -// bcast contains all Round1 broadcast from other participants to this participant -// p2p contains all Round1 P2P send message from other participants to this participant -func (dp *Participant) Round2( - bcast map[uint32]Round1Bcast, - p2p map[uint32]*Round1P2PSendPacket, -) (Round2Bcast, error) { - // Check participant is not empty - if dp == nil || dp.curve == nil { - return nil, internal.ErrNilArguments - } - - // Check participant has the correct dkg round number - if dp.round != 2 { - return nil, internal.ErrInvalidRound - } - - // Check the input is valid - if bcast == nil || p2p == nil || len(bcast) == 0 || len(p2p) == 0 { - return nil, internal.ErrNilArguments - } - - // 1. set sk = x_{ii} - sk := dp.pedersenResult.SecretShares[dp.id-1].Value - - // 2. for j in 1,...,n - for id := range bcast { - - // 3. if i = j continue - if id == dp.id { - continue - } - - // Ensure a valid p2p entry exists - if p2p[id] == nil { - return nil, fmt.Errorf("missing p2p packet for id=%v", id) - } - - // 4. If PedersenVerify(E, Q, x_ji, r_ji, {X_ji,...,X_jt}) = false, abort - xji := p2p[id].SecretShare - rji := p2p[id].BlindingShare - bvs := bcast[id] - if ok, err := dp.pedersen.Verify(xji, rji, bvs); !ok { - if err != nil { - return nil, err - } else { - return nil, fmt.Errorf("invalid share for participant id=%v", id) - } - } - - // Store other participants' shares xji for usage in round 3 - dp.otherParticipantShares[id].Share = p2p[id].SecretShare - - // 5. sk = (sk+xji) mod q - // NOTE: we use the EcScalar class to add instead of - // just using big.Int Add and Mod - // because Ed25519 will fail with the big.Int Add and Mod - // and Ed25519 uses different little endian vs big endian - // in big.Int - t1 := sk.BigInt() - t2 := xji.Value.BigInt() - r := dp.scalar.Add(t1, t2) - - sk = sk.Field().NewElement(r) - } - - // Update internal state - dp.round = 3 - - // 7. Store ski as participant i's secret key share - dp.skShare = sk - - // 6. EchoBroadcast {R_1,...,R_t} to all other participants. - return dp.pedersenResult.Verifiers, nil -} diff --git a/crypto/dkg/gennaro/round3.go b/crypto/dkg/gennaro/round3.go deleted file mode 100644 index 458ce6f18..000000000 --- a/crypto/dkg/gennaro/round3.go +++ /dev/null @@ -1,89 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/internal" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -// Round3Bcast contains values that will be broadcast to other participants. -type Round3Bcast = v1.ShareVerifier - -// Round3 computes the third round for Gennaro DKG -// Algorithm 4 - Gennaro DKG Round 3 -// bcast contains all Round2 broadcast from other participants to this participant. -func (dp *Participant) Round3(bcast map[uint32]Round2Bcast) (*Round3Bcast, *v1.ShamirShare, error) { - // Check participant is not empty - if dp == nil || dp.curve == nil { - return nil, nil, internal.ErrNilArguments - } - - // Check participant has the correct dkg round number - if dp.round != 3 { - return nil, nil, internal.ErrInvalidRound - } - - // Check the input is valid - if len(bcast) == 0 { - return nil, nil, internal.ErrNilArguments - } - - // 1. SetBigInt Pk = R_i1 - Pk := dp.pedersenResult.Verifiers[0] - - // 2. for j in 1,...,n - for id := range bcast { - // 3. if i = j continue - if id == dp.id { - continue - } - - // 4. If FeldmanVerify(E, xji, {R_j1,...,R_jt}) = false; abort - xji := dp.otherParticipantShares[id].Share - vs := bcast[id] - if ok, err := dp.feldman.Verify(xji, vs); !ok { - if err != nil { - return nil, nil, err - } else { - return nil, nil, fmt.Errorf("invalid share for participant #{id}") - } - } - - // Store the feldman verifiers for round 4 - dp.otherParticipantShares[id].Verifiers = vs - - // 5. Pk = Pk+R_j1 - temp, err := Pk.Add(bcast[id][0]) - if err != nil { - return nil, nil, fmt.Errorf("error in computing Pk+R_j1") - } - Pk = temp - } - - // This is a sanity check to make sure nothing went wrong - // when computing the public key - if !Pk.IsOnCurve() || Pk.IsIdentity() { - return nil, nil, fmt.Errorf("invalid public key") - } - - // 6. Store Pk as the public verification key - dp.verificationKey = Pk - - // Update internal state - dp.round = 4 - - skShare := v1.ShamirShare{ - Identifier: dp.id, - Value: dp.skShare, - } - - // Output Pk as the public verification key - return Pk, &skShare, nil -} diff --git a/crypto/dkg/gennaro/round4.go b/crypto/dkg/gennaro/round4.go deleted file mode 100644 index bfb11fd99..000000000 --- a/crypto/dkg/gennaro/round4.go +++ /dev/null @@ -1,76 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "math/big" - - "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -// Round4 computes the public shares used by tECDSA during signing -// that are converted to additive shares once the signing participants -// are known. This function is idempotent -func (dp *Participant) Round4() (map[uint32]*curves.EcPoint, error) { - // Check participant is not empty - if dp == nil || dp.curve == nil { - return nil, internal.ErrNilArguments - } - - // Check participant has the correct dkg round number - if dp.round != 4 { - return nil, internal.ErrInvalidRound - } - - n := len(dp.otherParticipantShares) + 1 //+1 to include self - // Wj's - publicShares := make(map[uint32]*curves.EcPoint, n) - - // 1. R = {{R1,...,Rt},{Rij,...,Rit}i!=j} - r := make(map[uint32][]*v1.ShareVerifier, n) - r[dp.id] = dp.pedersenResult.Verifiers - for j := range dp.otherParticipantShares { - r[j] = dp.otherParticipantShares[j].Verifiers - } - - // 2. for j in 1,...,n - for j, v := range r { - // 3. Wj = Pk - publicShares[j] = &curves.EcPoint{ - Curve: dp.verificationKey.Curve, - X: new(big.Int).Set(dp.verificationKey.X), - Y: new(big.Int).Set(dp.verificationKey.Y), - } - - // 4. for k in 1,...,t - for k := 0; k < len(dp.pedersenResult.Verifiers); k++ { - // 5. ck = pj * k mod q - pj := big.NewInt(int64(j)) - ck, err := core.Mul(pj, big.NewInt(int64(k+1)), dp.curve.Params().N) - if err != nil { - return nil, err - } - - // 6a. t = ck * Rj - t, err := v[k].ScalarMult(ck) - if err != nil { - return nil, err - } - - // 6b. Wj = Wj + t - publicShares[j], err = publicShares[j].Add(t) - if err != nil { - return nil, err - } - } - } - - return publicShares, nil -} diff --git a/crypto/dkg/gennaro/rounds_test.go b/crypto/dkg/gennaro/rounds_test.go deleted file mode 100644 index 04ce3e89e..000000000 --- a/crypto/dkg/gennaro/rounds_test.go +++ /dev/null @@ -1,419 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro - -import ( - "fmt" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -func TestParticipantRound1Works(t *testing.T) { - p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - require.NoError(t, err) - bcast, p2psend, err := p1.Round1(nil) - require.NoError(t, err) - require.NotNil(t, bcast) - require.NotNil(t, p2psend) - require.Equal(t, len(p2psend), 1) - require.Equal(t, len(bcast), 2) - require.NotNil(t, p1.pedersenResult) - require.Equal(t, p1.round, 2) - _, ok := p2psend[2] - require.True(t, ok) -} - -func TestParticipantRound1RepeatCall(t *testing.T) { - p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - require.NoError(t, err) - _, _, err = p1.Round1(nil) - require.NoError(t, err) - _, _, err = p1.Round1(nil) - require.Error(t, err) -} - -func TestParticipantRound1BadSecret(t *testing.T) { - p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - require.NoError(t, err) - // secret == 0 - secret := []byte{0} - _, _, err = p1.Round1(secret) - require.Error(t, err) - // secret too big - secret = []byte{ - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - } - _, _, err = p1.Round1(secret) - require.Error(t, err) -} - -func PrepareRound2Input( - t *testing.T, -) (*Participant, *Participant, Round1Bcast, Round1Bcast, Round1P2PSend) { - // Prepare round 1 output of 2 participants - p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - require.NoError(t, err) - require.Equal(t, p1.otherParticipantShares[2].Id, uint32(2)) - p2, err := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1) - require.NoError(t, err) - require.Equal(t, p2.otherParticipantShares[1].Id, uint32(1)) - bcast1, _, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - return p1, p2, bcast1, bcast2, p2psend2 -} - -// Test Gennaro DKG round2 works -func TestParticipantRound2Works(t *testing.T) { - // Prepare Dkg Round 1 output - p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t) - // Actual Test - require.NotNil(t, bcast1) - require.NotNil(t, bcast2) - require.NotNil(t, p2psend2[1]) - bcast := make(map[uint32]Round1Bcast) - p2p := make(map[uint32]*Round1P2PSendPacket) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - round2Out, err := p1.Round2(bcast, p2p) - require.NoError(t, err) - require.NotNil(t, round2Out) - require.Equal(t, len(round2Out), 2) - require.NotNil(t, p1.skShare) - require.Equal(t, p1.round, 3) - require.NotNil(t, p1.otherParticipantShares) -} - -// Test Gennaro DKG round 2 repeat call -func TestParticipantRound2RepeatCall(t *testing.T) { - // Prepare Dkg Round 1 output - p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t) - // Actual Test - require.NotNil(t, bcast1) - require.NotNil(t, bcast2) - require.NotNil(t, p2psend2[1]) - bcast := make(map[uint32]Round1Bcast) - p2p := make(map[uint32]*Round1P2PSendPacket) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - _, err := p1.Round2(bcast, p2p) - require.NoError(t, err) - _, err = p1.Round2(bcast, p2p) - require.Error(t, err) -} - -// Test Gennaro Dkg Round 2 Bad Input -func TestParticipantRound2BadInput(t *testing.T) { - // Prepare Dkg Round 1 output - p1, _, _, _, _ := PrepareRound2Input(t) - bcast := make(map[uint32]Round1Bcast) - p2p := make(map[uint32]*Round1P2PSendPacket) - - // Test empty bcast and p2p - _, err := p1.Round2(bcast, p2p) - require.Error(t, err) - - // Test nil bcast and p2p - p1, _, _, _, _ = PrepareRound2Input(t) - _, err = p1.Round2(nil, nil) - require.Error(t, err) - - // Test tampered input bcast and p2p - p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t) - bcast = make(map[uint32]Round1Bcast) - p2p = make(map[uint32]*Round1P2PSendPacket) - - // Tamper bcast1 and p2psend2 by doubling their value - bcast1[1].Y = bcast1[1].Y.Add(bcast1[1].Y, bcast1[1].Y) - p2psend2[1].SecretShare.Value = p2psend2[1].SecretShare.Value.Add(p2psend2[1].SecretShare.Value) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p[2] = p2psend2[1] - _, err = p1.Round2(bcast, p2p) - require.Error(t, err) -} - -func PrepareRound3Input(t *testing.T) (*Participant, *Participant, map[uint32]Round2Bcast) { - p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1) - bcast1, p2psend1, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - bcast := make(map[uint32]Round1Bcast) - p2p1 := make(map[uint32]*Round1P2PSendPacket) - p2p2 := make(map[uint32]*Round1P2PSendPacket) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p1[2] = p2psend2[1] - p2p2[1] = p2psend1[2] - round2Out1, _ := p1.Round2(bcast, p2p1) - round2Out2, _ := p2.Round2(bcast, p2p2) - round3Input := make(map[uint32]Round2Bcast) - round3Input[1] = round2Out1 - round3Input[2] = round2Out2 - return p1, p2, round3Input -} - -// Test Gennaro Dkg Round 3 Works -func TestParticipantRound3Works(t *testing.T) { - // Prepare Gennaro Dkg Round 3 Input - p1, p2, round3Input := PrepareRound3Input(t) - - // Actual Test - round3Out1, _, err := p1.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out1) - round3Out2, _, err := p2.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out2) - require.Equal(t, p1.round, 4) - require.Equal(t, p2.round, 4) - require.Equal(t, p1.verificationKey, p2.verificationKey) - - // Test if shares recombine properly - s, _ := v1.NewShamir(2, 2, curves.NewField(btcec.S256().N)) - sk, err := s.Combine(&v1.ShamirShare{Identifier: p1.id, Value: p1.skShare}, - &v1.ShamirShare{Identifier: p2.id, Value: p2.skShare}) - require.NoError(t, err) - - // Test verification keys are G * sk - x, y := btcec.S256().ScalarBaseMult(sk) - tmp := &curves.EcPoint{ - Curve: btcec.S256(), - X: x, - Y: y, - } - require.True(t, tmp.Equals(p1.verificationKey)) - require.True(t, tmp.Equals(p2.verificationKey)) -} - -// Test Gennaro Dkg Round3 Repeat Call -func TestParticipantRound3RepeatCall(t *testing.T) { - // Prepare Round 3 Input - p1, _, round3Input := PrepareRound3Input(t) - - // Actual Test - _, _, err := p1.Round3(round3Input) - require.NoError(t, err) - _, _, err = p1.Round3(round3Input) - require.Error(t, err) -} - -// Test Gennaro DKG Round 3 Bad Input -func TestParticipantRound3BadInput(t *testing.T) { - // Test empty round 3 input - p1, _, _ := PrepareRound3Input(t) - emptyInput := make(map[uint32]Round2Bcast) - _, _, err := p1.Round3(emptyInput) - require.Error(t, err) - - // Test nil round 3 input - p1, _, _ = PrepareRound3Input(t) - _, _, err = p1.Round3(nil) - require.Error(t, err) - - // Test tampered round 3 input - p1, _, round3Input := PrepareRound3Input(t) - // Tamper participant2's broadcast - round3Input[2][0], _ = round3Input[2][0].Add(round3Input[2][1]) - _, _, err = p1.Round3(round3Input) - require.Error(t, err) -} - -// Test Gennaro Dkg Round 4 Works -func TestParticipantRound4Works(t *testing.T) { - // Prepare Gennaro Dkg Round 3 Input - p1, p2, round3Input := PrepareRound3Input(t) - round3Out1, _, err := p1.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out1) - round3Out2, _, err := p2.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out2) - - // Actual test - publicShares1, err := p1.Round4() - require.NoError(t, err) - require.NotNil(t, publicShares1) - publicShares2, err := p2.Round4() - require.NoError(t, err) - require.NotNil(t, publicShares2) - - require.Equal(t, publicShares1, publicShares2) -} - -// Test Gennaro Dkg Round 4 Works -func TestParticipantRound4RepeatCall(t *testing.T) { - // Prepare Gennaro Dkg Round 3 Input - p1, p2, round3Input := PrepareRound3Input(t) - round3Out1, _, err := p1.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out1) - round3Out2, _, err := p2.Round3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out2) - - // Actual test - publicShares1, err := p1.Round4() - require.NoError(t, err) - require.NotNil(t, publicShares1) - publicShares2, err := p1.Round4() - require.NoError(t, err) - require.NotNil(t, publicShares2) - - require.Equal(t, publicShares1, publicShares2) -} - -// Test all Gennaro DKG rounds -func TestAllGennaroDkgRounds(t *testing.T) { - // Initiate two participants - p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1) - - // Running round 1 - bcast1, p2psend1, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - bcast := make(map[uint32]Round1Bcast) - p2p1 := make(map[uint32]*Round1P2PSendPacket) - p2p2 := make(map[uint32]*Round1P2PSendPacket) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p1[2] = p2psend2[1] - p2p2[1] = p2psend1[2] - - // Running round 2 - round2Out1, _ := p1.Round2(bcast, p2p1) - round2Out2, _ := p2.Round2(bcast, p2p2) - round3Input := make(map[uint32]Round2Bcast) - round3Input[1] = round2Out1 - round3Input[2] = round2Out2 - - // Running round 3 - round3Out1, _, _ := p1.Round3(round3Input) - round3Out2, _, _ := p2.Round3(round3Input) - require.NotNil(t, round3Out1) - require.NotNil(t, round3Out2) - - // Running round 4 - publicShares1, _ := p1.Round4() - publicShares2, _ := p2.Round4() - - // Test output of all rounds - require.Equal(t, publicShares1, publicShares2) - s, _ := v1.NewShamir(2, 2, curves.NewField(btcec.S256().N)) - sk, err := s.Combine(&v1.ShamirShare{Identifier: p1.id, Value: p1.skShare}, - &v1.ShamirShare{Identifier: p2.id, Value: p2.skShare}) - require.NoError(t, err) - - x, y := btcec.S256().ScalarBaseMult(sk) - tmp := &curves.EcPoint{ - Curve: btcec.S256(), - X: x, - Y: y, - } - require.True(t, tmp.Equals(p1.verificationKey)) - require.True(t, tmp.Equals(p2.verificationKey)) -} - -// Ensure correct functioning when input is missing -func TestParticipant2BadInput(t *testing.T) { - // - // Setup - // - p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2) - p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1) - bcast1, _, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - bcast := make(map[uint32]Round1Bcast) - p2p1 := make(map[uint32]*Round1P2PSendPacket) - bcast[1] = bcast1 - bcast[2] = bcast2 - // Exclude p2p 2>1 - p2p1[4] = p2psend2[1] - - // Run round 2 - _, err := p1.Round2(bcast, p2p1) - require.Error(t, err) -} - -func TestValidIDs(t *testing.T) { - err := fmt.Errorf("") - tests := []struct { - name string - in []uint32 - expected error - }{ - {"positive-1,2", []uint32{1, 2}, nil}, - {"positive-2,1", []uint32{2, 1}, nil}, - {"positive-1-10", []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil}, - {"positive-1-10-random", []uint32{10, 9, 6, 5, 3, 2, 8, 7, 1, 4}, nil}, - {"negative-1,3", []uint32{1, 3}, err}, - {"negative-1-10-missing-5", []uint32{10, 9, 6, 3, 2, 8, 7, 1, 4}, err}, - } - // Run all the tests! - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := validIds(test.in) - if test.expected == nil { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -// Test newParticipant with arbitrary IDs -func TestParticipantArbitraryIds(t *testing.T) { - _, err := NewParticipant(3, 2, testGenerator, curves.NewK256Scalar(), 4) - require.Error(t, err) - _, err = NewParticipant(0, 2, testGenerator, curves.NewK256Scalar(), 1) - require.Error(t, err) - _, err = NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 2, 3, 5) - require.Error(t, err) - _, err = NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 4) - require.Error(t, err) -} diff --git a/crypto/dkg/gennaro2p/README.md b/crypto/dkg/gennaro2p/README.md deleted file mode 100755 index 365265760..000000000 --- a/crypto/dkg/gennaro2p/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Two-party GG20 - -This package wraps dkg/genarro and specializes it for the 2-party case. diff --git a/crypto/dkg/gennaro2p/genarro2p.go b/crypto/dkg/gennaro2p/genarro2p.go deleted file mode 100644 index dec8bca75..000000000 --- a/crypto/dkg/gennaro2p/genarro2p.go +++ /dev/null @@ -1,151 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package gennaro2p wraps dkg/genarro and specializes it for the 2-party case. Simpler API, no -// distinction between broadcast and peer messages, and only counterparty messages are -// used as round inputs since self-inputs are always ignored. -package gennaro2p - -import ( - "crypto/elliptic" - "fmt" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/dkg/gennaro" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -const threshold = 2 - -// Participant is a DKG player that contains information needed to perform DKG rounds -// and yield a secret key share and public key when finished -type Participant struct { - id uint32 - counterPartyId uint32 - embedded *gennaro.Participant - blind *curves.EcPoint -} - -type Round1Message struct { - Verifiers []*v1.ShareVerifier - SecretShare *v1.ShamirShare - BlindingShare *v1.ShamirShare - Blind *curves.EcPoint -} - -type Round2Message struct { - Verifiers []*v1.ShareVerifier -} - -type DkgResult struct { - PublicKey *curves.EcPoint - SecretShare *v1.ShamirShare - PublicShares map[uint32]*curves.EcPoint -} - -// NewParticipant creates a participant ready to perform a DKG -// blind must be a generator and must be synchronized between counterparties. -// The first participant can set it to `nil` and a secure blinding factor will be -// generated. -func NewParticipant(id, counterPartyId uint32, blind *curves.EcPoint, - scalar curves.EcScalar, curve elliptic.Curve, -) (*Participant, error) { - // Generate blinding value, if required - var err error - if blind == nil { - blind, err = newBlind(scalar, curve) - if err != nil { - return nil, errors.Wrap(err, "generating fresh blinding generator") - } - } - p, err := gennaro.NewParticipant(id, threshold, blind, scalar, counterPartyId) - if err != nil { - return nil, errors.Wrap(err, "created genarro.Participant") - } - return &Participant{id, counterPartyId, p, blind}, nil -} - -// Creates a random blinding factor (as a generator) required for pedersen's VSS -func newBlind(curveScalar curves.EcScalar, curve elliptic.Curve) (*curves.EcPoint, error) { - rScalar, err := curveScalar.Random() - if err != nil { - return nil, errors.Wrap(err, "generating blinding scalar") - } - return curves.NewScalarBaseMult(curve, rScalar) -} - -// Runs DKG round 1. If `secret` is nil, shares of a new, random signing key are generated. -// Otherwise, the existing secret shares will be refreshed but the privkey and pubkey -// will remain unchanged. -func (p *Participant) Round1(secret []byte) (*Round1Message, error) { - // Run round 1 - bcast, p2p, err := p.embedded.Round1(secret) - if err != nil { - return nil, errors.Wrap(err, "calling embedded.Round1()") - } - - // Ensure the map has the expected entry so there's no SIGSEGV when we - // repackage it - if p2p[p.counterPartyId] == nil { - return nil, fmt.Errorf("round1 response for p2p[%v] is nil", p.counterPartyId) - } - - // Package response - return &Round1Message{ - bcast, - p2p[p.counterPartyId].SecretShare, - p2p[p.counterPartyId].BlindingShare, - p.blind, - }, nil -} - -// Runs DKG round 2 using the counterparty's output from round 1. -func (p *Participant) Round2(msg *Round1Message) (*Round2Message, error) { - // Run round 2 - bcast, err := p.embedded.Round2( - map[uint32]gennaro.Round1Bcast{ - p.counterPartyId: msg.Verifiers, - }, - map[uint32]*gennaro.Round1P2PSendPacket{ - p.counterPartyId: { - SecretShare: msg.SecretShare, - BlindingShare: msg.BlindingShare, - }, - }) - if err != nil { - return nil, errors.Wrap(err, "calling embedded.Round2()") - } - - // Package response - return &Round2Message{bcast}, nil -} - -// Completes the DKG using the counterparty's output from round 2. -func (p *Participant) Finalize(msg *Round2Message) (*DkgResult, error) { - // Run round 3 - pk, share, err := p.embedded.Round3( - map[uint32]gennaro.Round2Bcast{ - p.counterPartyId: msg.Verifiers, - }) - if err != nil { - return nil, errors.Wrap(err, "calling embedded.Round3()") - } - - // Compute public shares - pubShares, err := p.embedded.Round4() - if err != nil { - return nil, errors.Wrap(err, "calling embedded.Roun4()") - } - - // Package response - return &DkgResult{ - PublicKey: pk, - SecretShare: share, - PublicShares: pubShares, - }, nil -} diff --git a/crypto/dkg/gennaro2p/genarro2p_test.go b/crypto/dkg/gennaro2p/genarro2p_test.go deleted file mode 100644 index ee68a490c..000000000 --- a/crypto/dkg/gennaro2p/genarro2p_test.go +++ /dev/null @@ -1,181 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package gennaro2p - -import ( - "crypto/elliptic" - "fmt" - "reflect" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -var ( - curveScalar = curves.NewK256Scalar() - curve = btcec.S256() -) - -const ( - clientId = 1 - serverId = 2 -) - -// Benchmark full DKG including blind selection and setup -func BenchmarkDkg(b *testing.B) { - if testing.Short() { - b.Skip("skipping test in short mode.") - } - - for i := 0; i < b.N; i++ { - _, _, err := dkg() - require.NoError(b, err) - } -} - -// Run a DKG and reports the client/server results -func dkg() (*DkgResult, *DkgResult, error) { - // Create client/server - blind, _ := newBlind(curveScalar, curve) - - client, err := NewParticipant(clientId, serverId, blind, curveScalar, curve) - if err != nil { - return nil, nil, err - } - - server, err := NewParticipant(serverId, clientId, blind, curveScalar, curve) - if err != nil { - return nil, nil, err - } - - // R1 - clientR1, err := client.Round1(nil) - if err != nil { - return nil, nil, err - } - - serverR1, err := server.Round1(nil) - if err != nil { - return nil, nil, err - } - - // R2 - clientR2, err := client.Round2(serverR1) - if err != nil { - return nil, nil, err - } - - serverR2, err := server.Round2(clientR1) - if err != nil { - return nil, nil, err - } - - // Finalize - clientResult, err := client.Finalize(serverR2) - if err != nil { - return nil, nil, err - } - - serverResult, err := server.Finalize(clientR2) - if err != nil { - return nil, nil, err - } - - return clientResult, serverResult, nil -} - -// Run a full DKG and verify the absence of errors and valid results -func TestDkg(t *testing.T) { - // Setup and ensure no errors - clientResult, serverResult, err := dkg() - require.NoError(t, err) - require.NotNil(t, clientResult) - require.NotNil(t, serverResult) - - // Now run tests - t.Run("produce the same public key", func(t *testing.T) { - require.Equal(t, clientResult.PublicKey, serverResult.PublicKey) - }) - t.Run("produce identical public shares", func(t *testing.T) { - require.True(t, reflect.DeepEqual(clientResult.PublicShares, serverResult.PublicShares)) - }) - t.Run("produce distinct secret shares", func(t *testing.T) { - require.NotEqual(t, clientResult.SecretShare, serverResult.SecretShare) - }) - t.Run("produce distinct secret shares", func(t *testing.T) { - require.NotEqual(t, clientResult.SecretShare, serverResult.SecretShare) - }) - t.Run("shares sum to expected public key", func(t *testing.T) { - pubkey, err := reconstructPubkey( - clientResult.SecretShare, - serverResult.SecretShare, - curve) - require.NoError(t, err) - require.Equal(t, serverResult.PublicKey, pubkey) - }) -} - -// Reconstruct the pubkey from 2 shares -func reconstructPubkey(s1, s2 *v1.ShamirShare, curve elliptic.Curve) (*curves.EcPoint, error) { - s, err := v1.NewShamir(2, 2, s1.Value.Field()) - if err != nil { - return nil, err - } - - sk, err := s.Combine(s1, s2) - if err != nil { - return nil, err - } - - x, y := curve.ScalarBaseMult(sk) - return &curves.EcPoint{ - Curve: curve, - X: x, - Y: y, - }, nil -} - -// Test blind generator helper function produces a value on the expected curve -func TestNewBlindOnCurve(t *testing.T) { - const n = 1024 - for i := 0; i < n; i++ { - b, err := newBlind(curveScalar, curve) - require.NoError(t, err) - require.NotNil(t, b) - - // Valid point? - require.True(t, b.IsOnCurve() && b.IsValid()) - require.True(t, b.IsValid()) - require.False(t, b.IsIdentity()) - require.False(t, b.IsBasePoint()) - } -} - -func TestNewBlindProvidesDistinctPoints(t *testing.T) { - const n = 1024 - seen := make(map[string]bool, n) - // seen := make(map[core.EcPoint]bool, n) - - for i := 0; i < n; i++ { - b, err := newBlind(curveScalar, curve) - require.NoError(t, err) - - // serialize so the point is hashable - txt := fmt.Sprintf("%#v", b) - - // We shouldn't see the same point twice - ok := seen[txt] - require.False(t, ok) - - // store - seen[txt] = true - } -} diff --git a/crypto/ecdsa/canonical.go b/crypto/ecdsa/canonical.go deleted file mode 100644 index e4bd94da7..000000000 --- a/crypto/ecdsa/canonical.go +++ /dev/null @@ -1,193 +0,0 @@ -// Package ecdsa provides ECDSA signature canonicalization -package ecdsa - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "fmt" - "math/big" -) - -// CanonicalizeSignature ensures ECDSA signature is in canonical form -// This prevents signature malleability attacks where (r, s) and (r, -s mod N) are both valid -func CanonicalizeSignature(r, s *big.Int, curve elliptic.Curve) (*big.Int, *big.Int, error) { - if r == nil || s == nil { - return nil, nil, fmt.Errorf("r and s cannot be nil") - } - - if curve == nil { - return nil, nil, fmt.Errorf("curve cannot be nil") - } - - N := curve.Params().N - if N == nil { - return nil, nil, fmt.Errorf("invalid curve parameters") - } - - // Create copies to avoid modifying originals - rCopy := new(big.Int).Set(r) - sCopy := new(big.Int).Set(s) - - // Check if r is in valid range [1, N-1] - if rCopy.Sign() <= 0 || rCopy.Cmp(N) >= 0 { - return nil, nil, fmt.Errorf("r is not in valid range [1, N-1]") - } - - // Check if s is in valid range [1, N-1] - if sCopy.Sign() <= 0 || sCopy.Cmp(N) >= 0 { - return nil, nil, fmt.Errorf("s is not in valid range [1, N-1]") - } - - // Ensure s is canonical (s <= N/2) - halfN := new(big.Int).Div(N, big.NewInt(2)) - if sCopy.Cmp(halfN) > 0 { - // Use N - s to get canonical form - sCopy.Sub(N, sCopy) - } - - return rCopy, sCopy, nil -} - -// IsSignatureCanonical checks if an ECDSA signature is in canonical form -func IsSignatureCanonical(r, s *big.Int, curve elliptic.Curve) bool { - if r == nil || s == nil || curve == nil { - return false - } - - N := curve.Params().N - if N == nil { - return false - } - - // Check r is in valid range [1, N-1] - if r.Sign() <= 0 || r.Cmp(N) >= 0 { - return false - } - - // Check s is in valid range [1, N/2] - halfN := new(big.Int).Div(N, big.NewInt(2)) - if s.Sign() <= 0 || s.Cmp(halfN) > 0 { - return false - } - - return true -} - -// ValidateAndCanonicalizeSignature validates and canonicalizes an ECDSA signature -func ValidateAndCanonicalizeSignature(pub *ecdsa.PublicKey, hash []byte, r, s *big.Int) (*big.Int, *big.Int, error) { - if pub == nil { - return nil, nil, fmt.Errorf("public key cannot be nil") - } - - if len(hash) == 0 { - return nil, nil, fmt.Errorf("hash cannot be empty") - } - - // Canonicalize the signature - rCanon, sCanon, err := CanonicalizeSignature(r, s, pub.Curve) - if err != nil { - return nil, nil, fmt.Errorf("failed to canonicalize signature: %w", err) - } - - // Verify the canonical signature - if !ecdsa.Verify(pub, hash, rCanon, sCanon) { - // If canonical signature doesn't verify, try the original - // This handles the case where the signature was already canonical but negated - if !ecdsa.Verify(pub, hash, r, s) { - return nil, nil, fmt.Errorf("signature verification failed") - } - // Original verified, return it canonicalized - return CanonicalizeSignature(r, s, pub.Curve) - } - - return rCanon, sCanon, nil -} - -// RejectNonCanonical rejects non-canonical signatures outright -// This is stricter than canonicalization and prevents accepting malleable signatures -func RejectNonCanonical(r, s *big.Int, curve elliptic.Curve) error { - if r == nil || s == nil { - return fmt.Errorf("r and s cannot be nil") - } - - if curve == nil { - return fmt.Errorf("curve cannot be nil") - } - - if !IsSignatureCanonical(r, s, curve) { - return fmt.Errorf("signature is not in canonical form") - } - - return nil -} - -// NormalizeSignature normalizes an ECDSA signature to ensure consistent representation -// This is useful for signature aggregation and comparison -func NormalizeSignature(r, s *big.Int, curve elliptic.Curve) (*big.Int, *big.Int, error) { - // First canonicalize - rNorm, sNorm, err := CanonicalizeSignature(r, s, curve) - if err != nil { - return nil, nil, err - } - - // Additional normalization can be added here if needed - // For example, ensuring consistent byte representation - - return rNorm, sNorm, nil -} - -// CompareSignatures compares two ECDSA signatures for equality after canonicalization -func CompareSignatures(r1, s1, r2, s2 *big.Int, curve elliptic.Curve) (bool, error) { - // Canonicalize both signatures - r1Canon, s1Canon, err := CanonicalizeSignature(r1, s1, curve) - if err != nil { - return false, fmt.Errorf("failed to canonicalize first signature: %w", err) - } - - r2Canon, s2Canon, err := CanonicalizeSignature(r2, s2, curve) - if err != nil { - return false, fmt.Errorf("failed to canonicalize second signature: %w", err) - } - - // Compare canonical forms - return r1Canon.Cmp(r2Canon) == 0 && s1Canon.Cmp(s2Canon) == 0, nil -} - -// SignatureBytes converts signature to bytes in canonical form -// Returns 64 bytes for P-256 (32 bytes for r, 32 bytes for s) -func SignatureBytes(r, s *big.Int, curve elliptic.Curve) ([]byte, error) { - // Canonicalize first - rCanon, sCanon, err := CanonicalizeSignature(r, s, curve) - if err != nil { - return nil, err - } - - // Get the byte size for the curve - byteSize := (curve.Params().BitSize + 7) / 8 - - // Convert to bytes with proper padding - rBytes := rCanon.Bytes() - sBytes := sCanon.Bytes() - - // Pad if necessary - signature := make([]byte, 2*byteSize) - copy(signature[byteSize-len(rBytes):byteSize], rBytes) - copy(signature[2*byteSize-len(sBytes):], sBytes) - - return signature, nil -} - -// SignatureFromBytes reconstructs signature from bytes and ensures it's canonical -func SignatureFromBytes(sig []byte, curve elliptic.Curve) (*big.Int, *big.Int, error) { - byteSize := (curve.Params().BitSize + 7) / 8 - - if len(sig) != 2*byteSize { - return nil, nil, fmt.Errorf("invalid signature length: expected %d, got %d", 2*byteSize, len(sig)) - } - - r := new(big.Int).SetBytes(sig[:byteSize]) - s := new(big.Int).SetBytes(sig[byteSize:]) - - // Ensure canonical form - return CanonicalizeSignature(r, s, curve) -} diff --git a/crypto/ecdsa/canonical_test.go b/crypto/ecdsa/canonical_test.go deleted file mode 100644 index 5931e03d6..000000000 --- a/crypto/ecdsa/canonical_test.go +++ /dev/null @@ -1,276 +0,0 @@ -package ecdsa - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "math/big" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCanonicalizeSignature(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - // Test canonical signature (s <= N/2) - r := big.NewInt(12345) - s := new(big.Int).Sub(halfN, big.NewInt(1)) // s = N/2 - 1 - - rCanon, sCanon, err := CanonicalizeSignature(r, s, curve) - require.NoError(t, err) - assert.Equal(t, r, rCanon) - assert.Equal(t, s, sCanon) - - // Test non-canonical signature (s > N/2) - sNonCanon := new(big.Int).Add(halfN, big.NewInt(1)) // s = N/2 + 1 - - rCanon, sCanon, err = CanonicalizeSignature(r, sNonCanon, curve) - require.NoError(t, err) - assert.Equal(t, r, rCanon) - - // sCanon should be N - sNonCanon - expected := new(big.Int).Sub(N, sNonCanon) - assert.Equal(t, expected, sCanon) -} - -func TestIsSignatureCanonical(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - // Test canonical signature - r := big.NewInt(12345) - s := halfN // s = N/2 (boundary case, still canonical) - - assert.True(t, IsSignatureCanonical(r, s, curve)) - - // Test non-canonical signature - sNonCanon := new(big.Int).Add(halfN, big.NewInt(1)) - assert.False(t, IsSignatureCanonical(r, sNonCanon, curve)) - - // Test invalid r (r = 0) - assert.False(t, IsSignatureCanonical(big.NewInt(0), s, curve)) - - // Test invalid r (r >= N) - assert.False(t, IsSignatureCanonical(N, s, curve)) - - // Test invalid s (s = 0) - assert.False(t, IsSignatureCanonical(r, big.NewInt(0), curve)) - - // Test nil inputs - assert.False(t, IsSignatureCanonical(nil, s, curve)) - assert.False(t, IsSignatureCanonical(r, nil, curve)) - assert.False(t, IsSignatureCanonical(r, s, nil)) -} - -func TestValidateAndCanonicalizeSignature(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("test message") - hash := sha256.Sum256(message) - - // Sign with standard ECDSA - r, s, err := ecdsa.Sign(rand.Reader, priv, hash[:]) - require.NoError(t, err) - - // Validate and canonicalize - rCanon, sCanon, err := ValidateAndCanonicalizeSignature(&priv.PublicKey, hash[:], r, s) - require.NoError(t, err) - - // Verify canonical signature - valid := ecdsa.Verify(&priv.PublicKey, hash[:], rCanon, sCanon) - assert.True(t, valid) - - // Ensure signature is canonical - assert.True(t, IsSignatureCanonical(rCanon, sCanon, priv.Curve)) - - // Test with invalid signature - wrongR := new(big.Int).Add(r, big.NewInt(1)) - _, _, err = ValidateAndCanonicalizeSignature(&priv.PublicKey, hash[:], wrongR, s) - assert.Error(t, err) -} - -func TestRejectNonCanonical(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - - // Test canonical signature - sCanon := new(big.Int).Sub(halfN, big.NewInt(1)) - err := RejectNonCanonical(r, sCanon, curve) - assert.NoError(t, err) - - // Test non-canonical signature - sNonCanon := new(big.Int).Add(halfN, big.NewInt(1)) - err = RejectNonCanonical(r, sNonCanon, curve) - assert.Error(t, err) - assert.Contains(t, err.Error(), "not in canonical form") - - // Test nil inputs - err = RejectNonCanonical(nil, sCanon, curve) - assert.Error(t, err) - - err = RejectNonCanonical(r, nil, curve) - assert.Error(t, err) - - err = RejectNonCanonical(r, sCanon, nil) - assert.Error(t, err) -} - -func TestCompareSignatures(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - s1 := new(big.Int).Sub(halfN, big.NewInt(1)) - - // Same signature should be equal - equal, err := CompareSignatures(r, s1, r, s1, curve) - require.NoError(t, err) - assert.True(t, equal) - - // Canonical and non-canonical versions of same signature should be equal - s1NonCanon := new(big.Int).Sub(N, s1) - equal, err = CompareSignatures(r, s1, r, s1NonCanon, curve) - require.NoError(t, err) - assert.True(t, equal) - - // Different signatures should not be equal - s2 := new(big.Int).Sub(halfN, big.NewInt(10)) - equal, err = CompareSignatures(r, s1, r, s2, curve) - require.NoError(t, err) - assert.False(t, equal) -} - -func TestSignatureBytes(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - s := new(big.Int).Sub(halfN, big.NewInt(1)) - - // Convert to bytes - sigBytes, err := SignatureBytes(r, s, curve) - require.NoError(t, err) - assert.Len(t, sigBytes, 64) // 32 bytes for r, 32 bytes for s on P-256 - - // Test with non-canonical s - should be canonicalized - sNonCanon := new(big.Int).Sub(N, s) - sigBytesNonCanon, err := SignatureBytes(r, sNonCanon, curve) - require.NoError(t, err) - - // Both should produce the same bytes (after canonicalization) - assert.Equal(t, sigBytes, sigBytesNonCanon) -} - -func TestSignatureFromBytes(t *testing.T) { - curve := elliptic.P256() - - // Create a signature - r := big.NewInt(12345) - s := big.NewInt(67890) - - // Convert to bytes - sigBytes, err := SignatureBytes(r, s, curve) - require.NoError(t, err) - - // Convert back from bytes - rRecovered, sRecovered, err := SignatureFromBytes(sigBytes, curve) - require.NoError(t, err) - - // Should be canonical - assert.True(t, IsSignatureCanonical(rRecovered, sRecovered, curve)) - - // Values should match (after canonicalization) - rCanon, sCanon, err := CanonicalizeSignature(r, s, curve) - require.NoError(t, err) - assert.Equal(t, rCanon, rRecovered) - assert.Equal(t, sCanon, sRecovered) - - // Test with invalid length - _, _, err = SignatureFromBytes([]byte("too short"), curve) - assert.Error(t, err) -} - -func TestNormalizeSignature(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - s := new(big.Int).Add(halfN, big.NewInt(1)) // Non-canonical - - // Normalize should canonicalize - rNorm, sNorm, err := NormalizeSignature(r, s, curve) - require.NoError(t, err) - - assert.True(t, IsSignatureCanonical(rNorm, sNorm, curve)) - assert.Equal(t, r, rNorm) - - // sNorm should be N - s - expected := new(big.Int).Sub(N, s) - assert.Equal(t, expected, sNorm) -} - -func TestCanonicalWithRealSignatures(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("test canonical signatures") - hash := sha256.Sum256(message) - - // Generate multiple signatures and ensure all can be canonicalized - for i := 0; i < 10; i++ { - r, s, err := ecdsa.Sign(rand.Reader, priv, hash[:]) - require.NoError(t, err) - - // Canonicalize - rCanon, sCanon, err := CanonicalizeSignature(r, s, priv.Curve) - require.NoError(t, err) - - // Should be canonical - assert.True(t, IsSignatureCanonical(rCanon, sCanon, priv.Curve)) - - // Should still verify - valid := ecdsa.Verify(&priv.PublicKey, hash[:], rCanon, sCanon) - assert.True(t, valid) - } -} - -func BenchmarkCanonicalizeSignature(b *testing.B) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - s := new(big.Int).Add(halfN, big.NewInt(1)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _, _ = CanonicalizeSignature(r, s, curve) - } -} - -func BenchmarkIsSignatureCanonical(b *testing.B) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - r := big.NewInt(12345) - s := new(big.Int).Sub(halfN, big.NewInt(1)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = IsSignatureCanonical(r, s, curve) - } -} diff --git a/crypto/ecdsa/deterministic.go b/crypto/ecdsa/deterministic.go deleted file mode 100644 index 3ef5cd585..000000000 --- a/crypto/ecdsa/deterministic.go +++ /dev/null @@ -1,224 +0,0 @@ -// Package ecdsa provides RFC 6979 deterministic ECDSA implementation -package ecdsa - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/hmac" - "crypto/sha256" - "fmt" - "hash" - "math/big" -) - -// DeterministicSign implements RFC 6979 deterministic ECDSA signing -// This prevents nonce reuse and bias attacks by generating k deterministically -func DeterministicSign(priv *ecdsa.PrivateKey, hash []byte) (*big.Int, *big.Int, error) { - if priv == nil || priv.D == nil { - return nil, nil, fmt.Errorf("invalid private key") - } - - if len(hash) == 0 { - return nil, nil, fmt.Errorf("hash cannot be empty") - } - - // Generate deterministic k using RFC 6979 - k := generateK(priv, hash, sha256.New) - - // Sign with deterministic k - return signWithK(priv, hash, k) -} - -// generateK implements RFC 6979 deterministic nonce generation -func generateK(priv *ecdsa.PrivateKey, hash []byte, hashFunc func() hash.Hash) *big.Int { - curve := priv.Curve - N := curve.Params().N - bitSize := N.BitLen() - byteSize := (bitSize + 7) / 8 - - // Step a: Process hash - h1 := hashToInt(hash, curve) - - // Step b: Convert private key to bytes - x := priv.D.Bytes() - if len(x) < byteSize { - // Pad with zeros on the left - padding := make([]byte, byteSize-len(x)) - x = append(padding, x...) - } - - // Step c: Create HMAC-DRBG instance - hm := hmac.New(hashFunc, nil) - hlen := hm.Size() - - // Step d: Set V = 0x01 0x01 0x01 ... 0x01 - v := bytes(hlen, 0x01) - - // Step e: Set K = 0x00 0x00 0x00 ... 0x00 - k := bytes(hlen, 0x00) - - // Step f: K = HMAC_K(V || 0x00 || x || h1) - k = hmacCompute(hashFunc, k, v, []byte{0x00}, x, h1.Bytes()) - - // Step g: V = HMAC_K(V) - v = hmacCompute(hashFunc, k, v) - - // Step h: K = HMAC_K(V || 0x01 || x || h1) - k = hmacCompute(hashFunc, k, v, []byte{0x01}, x, h1.Bytes()) - - // Step i: V = HMAC_K(V) - v = hmacCompute(hashFunc, k, v) - - // Step j: Generate k - for { - // Step j.1: Set T = empty sequence - var t []byte - - // Step j.2: While tlen < qlen - for len(t)*8 < bitSize { - // V = HMAC_K(V) - v = hmacCompute(hashFunc, k, v) - // T = T || V - t = append(t, v...) - } - - // Step j.3: k = bits2int(T) - kInt := hashToInt(t, curve) - - // Check if k is valid (0 < k < N) - if kInt.Sign() > 0 && kInt.Cmp(N) < 0 { - return kInt - } - - // Step j.4: K = HMAC_K(V || 0x00) - k = hmacCompute(hashFunc, k, v, []byte{0x00}) - // V = HMAC_K(V) - v = hmacCompute(hashFunc, k, v) - } -} - -// signWithK performs ECDSA signing with a given k value -func signWithK(priv *ecdsa.PrivateKey, hash []byte, k *big.Int) (*big.Int, *big.Int, error) { - curve := priv.Curve - N := curve.Params().N - - // Calculate r = x-coordinate of k*G mod N - x, _ := curve.ScalarBaseMult(k.Bytes()) - r := new(big.Int).Set(x) - r.Mod(r, N) - - if r.Sign() == 0 { - return nil, nil, fmt.Errorf("invalid r value") - } - - // Calculate s = k^(-1) * (h + r*d) mod N - e := hashToInt(hash, curve) - - kInv := new(big.Int).ModInverse(k, N) - if kInv == nil { - return nil, nil, fmt.Errorf("k has no inverse") - } - - s := new(big.Int).Mul(r, priv.D) - s.Add(s, e) - s.Mul(s, kInv) - s.Mod(s, N) - - if s.Sign() == 0 { - return nil, nil, fmt.Errorf("invalid s value") - } - - // Canonicalize signature (ensure s <= N/2) - rFinal, sFinal := canonicalize(r, s, N) - return rFinal, sFinal, nil -} - -// canonicalize ensures the signature is in canonical form (s <= N/2) -// This prevents signature malleability -func canonicalize(r, s, N *big.Int) (*big.Int, *big.Int) { - halfN := new(big.Int).Div(N, big.NewInt(2)) - - // If s > N/2, use N - s instead - if s.Cmp(halfN) > 0 { - s = new(big.Int).Sub(N, s) - } - - return r, s -} - -// hashToInt converts a hash value to an integer for ECDSA operations -func hashToInt(hash []byte, curve elliptic.Curve) *big.Int { - N := curve.Params().N - orderBits := N.BitLen() - orderBytes := (orderBits + 7) / 8 - - if len(hash) > orderBytes { - hash = hash[:orderBytes] - } - - ret := new(big.Int).SetBytes(hash) - excess := len(hash)*8 - orderBits - if excess > 0 { - ret.Rsh(ret, uint(excess)) - } - - return ret -} - -// hmacCompute computes HMAC with concatenated data -func hmacCompute(hashFunc func() hash.Hash, key []byte, data ...[]byte) []byte { - mac := hmac.New(hashFunc, key) - for _, d := range data { - mac.Write(d) - } - return mac.Sum(nil) -} - -// bytes creates a byte slice filled with value -func bytes(size int, value byte) []byte { - b := make([]byte, size) - for i := range b { - b[i] = value - } - return b -} - -// VerifyDeterministic verifies a deterministic ECDSA signature -func VerifyDeterministic(pub *ecdsa.PublicKey, hash []byte, r, s *big.Int) bool { - if pub == nil || r == nil || s == nil { - return false - } - - // Ensure signature is canonical - N := pub.Curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - // Check r and s are in valid range - if r.Sign() <= 0 || r.Cmp(N) >= 0 { - return false - } - if s.Sign() <= 0 || s.Cmp(halfN) > 0 { - return false // s must be <= N/2 for canonical form - } - - return ecdsa.Verify(pub, hash, r, s) -} - -// IsCanonical checks if a signature is in canonical form -func IsCanonical(s, N *big.Int) bool { - if s == nil || N == nil { - return false - } - - halfN := new(big.Int).Div(N, big.NewInt(2)) - return s.Cmp(halfN) <= 0 -} - -// MakeCanonical converts a signature to canonical form -func MakeCanonical(r, s, N *big.Int) (*big.Int, *big.Int) { - if r == nil || s == nil || N == nil { - return r, s - } - - return canonicalize(r, s, N) -} diff --git a/crypto/ecdsa/deterministic_test.go b/crypto/ecdsa/deterministic_test.go deleted file mode 100644 index d9ea00a5e..000000000 --- a/crypto/ecdsa/deterministic_test.go +++ /dev/null @@ -1,286 +0,0 @@ -package ecdsa - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "math/big" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestDeterministicSign(t *testing.T) { - // Generate test key - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - // Test message - message := []byte("test message for deterministic signing") - hash := sha256.Sum256(message) - - // Sign with deterministic algorithm - r1, s1, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - assert.NotNil(t, r1) - assert.NotNil(t, s1) - - // Sign again - should produce identical signature - r2, s2, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - assert.Equal(t, r1, r2, "deterministic signatures should be identical") - assert.Equal(t, s1, s2, "deterministic signatures should be identical") - - // Verify signature - valid := ecdsa.Verify(&priv.PublicKey, hash[:], r1, s1) - assert.True(t, valid, "signature should be valid") - - // Different message should produce different signature - message2 := []byte("different message") - hash2 := sha256.Sum256(message2) - r3, s3, err := DeterministicSign(priv, hash2[:]) - require.NoError(t, err) - assert.NotEqual(t, r1, r3, "different messages should produce different signatures") - // Also verify the s component is different - assert.NotEqual(t, s1, s3, "different messages should produce different s values") -} - -func TestCanonicalSignature(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("test canonical signature") - hash := sha256.Sum256(message) - - // Sign multiple times and check all signatures are canonical - for i := 0; i < 10; i++ { - r, s, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - - // Check signature is canonical (s <= N/2) - N := priv.Curve.Params().N - assert.True(t, IsCanonical(s, N), "signature should be canonical") - - // Verify signature - valid := ecdsa.Verify(&priv.PublicKey, hash[:], r, s) - assert.True(t, valid, "canonical signature should be valid") - } -} - -func TestMakeCanonical(t *testing.T) { - curve := elliptic.P256() - N := curve.Params().N - halfN := new(big.Int).Div(N, big.NewInt(2)) - - // Test with non-canonical s (s > N/2) - r := big.NewInt(12345) - s := new(big.Int).Add(halfN, big.NewInt(1)) // s = N/2 + 1 - - assert.False(t, IsCanonical(s, N), "s > N/2 should not be canonical") - - // Make canonical - rCanon, sCanon := MakeCanonical(r, s, N) - - assert.Equal(t, r, rCanon, "r should not change") - assert.True(t, IsCanonical(sCanon, N), "canonicalized s should be <= N/2") - - // sCanon should equal N - s - expected := new(big.Int).Sub(N, s) - assert.Equal(t, expected, sCanon, "canonical s should be N - s") -} - -func TestVerifyDeterministic(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("test verification") - hash := sha256.Sum256(message) - - // Create deterministic signature - r, s, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - - // Verify with our function - valid := VerifyDeterministic(&priv.PublicKey, hash[:], r, s) - assert.True(t, valid, "signature should verify") - - // Test with non-canonical signature (should fail) - N := priv.Curve.Params().N - sNonCanon := new(big.Int).Sub(N, s) // Create non-canonical s - - valid = VerifyDeterministic(&priv.PublicKey, hash[:], r, sNonCanon) - assert.False(t, valid, "non-canonical signature should not verify") - - // Test with wrong hash - wrongHash := sha256.Sum256([]byte("wrong message")) - valid = VerifyDeterministic(&priv.PublicKey, wrongHash[:], r, s) - assert.False(t, valid, "signature with wrong hash should not verify") -} - -func TestInvalidInputs(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - hash := sha256.Sum256([]byte("test")) - - // Test with nil private key - r, s, err := DeterministicSign(nil, hash[:]) - assert.Error(t, err) - assert.Nil(t, r) - assert.Nil(t, s) - - // Test with empty hash - r, s, err = DeterministicSign(priv, []byte{}) - assert.Error(t, err) - assert.Nil(t, r) - assert.Nil(t, s) - - // Test verify with nil inputs - assert.False(t, VerifyDeterministic(nil, hash[:], big.NewInt(1), big.NewInt(1))) - assert.False(t, VerifyDeterministic(&priv.PublicKey, hash[:], nil, big.NewInt(1))) - assert.False(t, VerifyDeterministic(&priv.PublicKey, hash[:], big.NewInt(1), nil)) -} - -func TestDifferentCurves(t *testing.T) { - curves := []elliptic.Curve{ - elliptic.P224(), - elliptic.P256(), - elliptic.P384(), - elliptic.P521(), - } - - message := []byte("test message for different curves") - hash := sha256.Sum256(message) - - for _, curve := range curves { - t.Run(curve.Params().Name, func(t *testing.T) { - priv, err := ecdsa.GenerateKey(curve, rand.Reader) - require.NoError(t, err) - - // Sign deterministically - r, s, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - - // Verify signature is canonical - N := curve.Params().N - assert.True(t, IsCanonical(s, N)) - - // Verify signature - valid := ecdsa.Verify(&priv.PublicKey, hash[:], r, s) - assert.True(t, valid) - - // Verify deterministic property - r2, s2, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - assert.Equal(t, r, r2) - assert.Equal(t, s, s2) - }) - } -} - -// TestRFC6979Vectors tests against known test vectors -// These are simplified vectors - in production, use the full RFC 6979 test vectors -func TestRFC6979Vectors(t *testing.T) { - // Test vector for P-256 with SHA-256 - // This is a simplified example - real implementation should use official test vectors - privKeyHex := "c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721" - messageHex := "73616d706c65" // "sample" - - privKeyBytes, err := hex.DecodeString(privKeyHex) - require.NoError(t, err) - - message, err := hex.DecodeString(messageHex) - require.NoError(t, err) - - // Create private key - priv := new(ecdsa.PrivateKey) - priv.Curve = elliptic.P256() - priv.D = new(big.Int).SetBytes(privKeyBytes) - priv.PublicKey.Curve = priv.Curve - priv.PublicKey.X, priv.PublicKey.Y = priv.Curve.ScalarBaseMult(privKeyBytes) - - // Hash message - hash := sha256.Sum256(message) - - // Sign deterministically - r, s, err := DeterministicSign(priv, hash[:]) - require.NoError(t, err) - assert.NotNil(t, r) - assert.NotNil(t, s) - - // Verify signature - valid := ecdsa.Verify(&priv.PublicKey, hash[:], r, s) - assert.True(t, valid, "RFC 6979 test vector signature should verify") -} - -func BenchmarkDeterministicSign(b *testing.B) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(b, err) - - message := []byte("benchmark message") - hash := sha256.Sum256(message) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _, _ = DeterministicSign(priv, hash[:]) - } -} - -func BenchmarkVerifyDeterministic(b *testing.B) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(b, err) - - message := []byte("benchmark message") - hash := sha256.Sum256(message) - - r, s, err := DeterministicSign(priv, hash[:]) - require.NoError(b, err) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = VerifyDeterministic(&priv.PublicKey, hash[:], r, s) - } -} - -func TestConcurrentSigning(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("concurrent test") - hash := sha256.Sum256(message) - - // Sign concurrently - const goroutines = 10 - results := make(chan struct { - r, s *big.Int - err error - }, goroutines) - - for i := 0; i < goroutines; i++ { - go func() { - r, s, err := DeterministicSign(priv, hash[:]) - results <- struct { - r, s *big.Int - err error - }{r, s, err} - }() - } - - // Collect results - var firstR, firstS *big.Int - for i := 0; i < goroutines; i++ { - result := <-results - require.NoError(t, result.err) - - if i == 0 { - firstR, firstS = result.r, result.s - } else { - // All signatures should be identical (deterministic) - assert.Equal(t, firstR, result.r) - assert.Equal(t, firstS, result.s) - } - } -} diff --git a/crypto/ecies/encrypt.go b/crypto/ecies/encrypt.go deleted file mode 100644 index 4217c7fd6..000000000 --- a/crypto/ecies/encrypt.go +++ /dev/null @@ -1,13 +0,0 @@ -package ecies - -import eciesgo "github.com/ecies/go/v2" - -// Encrypt encrypts a plaintext using a public key -func Encrypt(pub *PublicKey, plaintext []byte) ([]byte, error) { - return eciesgo.Encrypt(pub, plaintext) -} - -// Decrypt decrypts a ciphertext using a private key -func Decrypt(priv *PrivateKey, ciphertext []byte) ([]byte, error) { - return eciesgo.Decrypt(priv, ciphertext) -} diff --git a/crypto/ecies/keys.go b/crypto/ecies/keys.go deleted file mode 100644 index 36bf9d733..000000000 --- a/crypto/ecies/keys.go +++ /dev/null @@ -1,57 +0,0 @@ -package ecies - -import ( - "bytes" - "crypto/ecdsa" - "crypto/rand" - "fmt" - - eciesgo "github.com/ecies/go/v2" - "lukechampine.com/blake3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type PrivateKey = eciesgo.PrivateKey - -type PublicKey = eciesgo.PublicKey - -// GenerateKey generates secp256k1 key pair -func GenerateKey() (*PrivateKey, error) { - curve := curves.SP256() - p, err := ecdsa.GenerateKey(curve, rand.Reader) - if err != nil { - return nil, fmt.Errorf("cannot generate key pair: %w", err) - } - return &PrivateKey{ - PublicKey: &PublicKey{ - Curve: curve, - X: p.X, - Y: p.Y, - }, - D: p.D, - }, nil -} - -// GenerateKeyFromSeed generates secp256k1 key pair from []byte seed -func GenerateKeyFromSeed(seed []byte) (*PrivateKey, error) { - curve := curves.SP256() - p, err := ecdsa.GenerateKey(curve, bytes.NewReader(seed[:])) - if err != nil { - return nil, fmt.Errorf("cannot generate key pair: %w", err) - } - return &PrivateKey{ - PublicKey: &PublicKey{ - Curve: curve, - X: p.X, - Y: p.Y, - }, - D: p.D, - }, nil -} - -// HashSeed returns 512 sum hash of byte slice -func HashSeed(seed []byte) []byte { - bz := blake3.Sum512(seed) - return bz[:] -} diff --git a/crypto/ecies/keys_test.go b/crypto/ecies/keys_test.go deleted file mode 100644 index 0e723749a..000000000 --- a/crypto/ecies/keys_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package ecies_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/sonr-io/sonr/crypto/ecies" -) - -func TestGenerateKey(t *testing.T) { - _, err := ecies.GenerateKey() - assert.NoError(t, err) -} - -func TestGenerateFromSeed(t *testing.T) { - seed := ecies.HashSeed( - []byte("testasdfasdfasdfasdfasdfw234453412341testasdfasdfasdfasdfasdfw234453412341"), - ) - _, err := ecies.GenerateKeyFromSeed(seed) - assert.NoError(t, err) - _, err = ecies.GenerateKeyFromSeed(seed) - assert.NoError(t, err) -} diff --git a/crypto/empty-module/bip39.go b/crypto/empty-module/bip39.go deleted file mode 100644 index 52371aa44..000000000 --- a/crypto/empty-module/bip39.go +++ /dev/null @@ -1,33 +0,0 @@ -// Package bip39 provides BIP39 mnemonic functionality. -// This is a stub package to replace the missing tyler-smith/go-bip39 repository. -// The original repository at github.com/tyler-smith/go-bip39 no longer exists. -package bip39 - -import ( - "errors" -) - -// NewMnemonic generates a new mnemonic sequence -func NewMnemonic(bitSize int) (string, error) { - return "", errors.New("tyler-smith/go-bip39 is deprecated, use github.com/cosmos/go-bip39 instead") -} - -// NewSeed creates a seed from a mnemonic and passphrase -func NewSeed(mnemonic string, password string) []byte { - panic("tyler-smith/go-bip39 is deprecated, use github.com/cosmos/go-bip39 instead") -} - -// IsMnemonicValid validates a mnemonic sequence -func IsMnemonicValid(mnemonic string) bool { - return false -} - -// NewEntropy generates new entropy -func NewEntropy(bitSize int) ([]byte, error) { - return nil, errors.New("tyler-smith/go-bip39 is deprecated, use github.com/cosmos/go-bip39 instead") -} - -// NewMnemonicFromEntropy creates a mnemonic from entropy -func NewMnemonicFromEntropy(entropy []byte) (string, error) { - return "", errors.New("tyler-smith/go-bip39 is deprecated, use github.com/cosmos/go-bip39 instead") -} diff --git a/crypto/empty-module/go.mod b/crypto/empty-module/go.mod deleted file mode 100644 index 10d144064..000000000 --- a/crypto/empty-module/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/tyler-smith/go-bip39 - -go 1.24.7 \ No newline at end of file diff --git a/crypto/go.mod b/crypto/go.mod deleted file mode 100644 index d4f1e9c6c..000000000 --- a/crypto/go.mod +++ /dev/null @@ -1,46 +0,0 @@ -module github.com/sonr-io/sonr/crypto - -go 1.24.7 - -require ( - filippo.io/edwards25519 v1.1.0 - git.sr.ht/~sircmpwn/go-bare v0.0.0-20210406120253-ab86bc2846d9 - github.com/Oudwins/zog v0.21.6 - github.com/btcsuite/btcd/btcec/v2 v2.3.4 - github.com/bwesterb/go-ristretto v1.2.3 - github.com/consensys/gnark-crypto v0.19.0 - github.com/cosmos/btcutil v1.0.5 - github.com/cosmos/cosmos-sdk v0.53.4 - github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 - github.com/ecies/go/v2 v2.0.10 - github.com/golang-jwt/jwt/v5 v5.3.0 - github.com/gtank/merlin v0.1.1 - github.com/ipfs/go-cid v0.5.0 - github.com/libp2p/go-libp2p v0.43.0 - github.com/mr-tron/base58 v1.2.0 - github.com/multiformats/go-multibase v0.2.0 - github.com/multiformats/go-multihash v0.2.3 - github.com/multiformats/go-varint v0.1.0 - github.com/pkg/errors v0.9.1 - github.com/stretchr/testify v1.10.0 - golang.org/x/crypto v0.42.0 - lukechampine.com/blake3 v1.4.1 -) - -require ( - github.com/bits-and-blooms/bitset v1.24.0 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect - github.com/ethereum/go-ethereum v1.16.3 // indirect - github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect - github.com/minio/sha256-simd v1.0.1 // indirect - github.com/multiformats/go-base32 v0.1.0 // indirect - github.com/multiformats/go-base36 v0.2.0 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/spaolacci/murmur3 v1.1.0 // indirect - golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect - golang.org/x/sys v0.36.0 // indirect - google.golang.org/protobuf v1.36.6 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) diff --git a/crypto/go.sum b/crypto/go.sum deleted file mode 100644 index 1fc77ce69..000000000 --- a/crypto/go.sum +++ /dev/null @@ -1,102 +0,0 @@ -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -git.sr.ht/~sircmpwn/getopt v0.0.0-20191230200459-23622cc906b3/go.mod h1:wMEGFFFNuPos7vHmWXfszqImLppbc0wEhh6JBfJIUgw= -git.sr.ht/~sircmpwn/go-bare v0.0.0-20210406120253-ab86bc2846d9 h1:Ahny8Ud1LjVMMAlt8utUFKhhxJtwBAualvsbc/Sk7cE= -git.sr.ht/~sircmpwn/go-bare v0.0.0-20210406120253-ab86bc2846d9/go.mod h1:BVJwbDfVjCjoFiKrhkei6NdGcZYpkDkdyCdg1ukytRA= -github.com/Oudwins/zog v0.21.6 h1:3JVJA66fr59k2x72RojCB7v5XkVmtVsnp1YO/np595k= -github.com/Oudwins/zog v0.21.6/go.mod h1:c4ADJ2zNkJp37ZViNy1o3ZZoeMvO7UQVO7BaPtRoocg= -github.com/bits-and-blooms/bitset v1.24.0 h1:H4x4TuulnokZKvHLfzVRTHJfFfnHEeSYJizujEZvmAM= -github.com/bits-and-blooms/bitset v1.24.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= -github.com/btcsuite/btcd/btcec/v2 v2.3.4 h1:3EJjcN70HCu/mwqlUsGK8GcNVyLVxFDlWurTXGPFfiQ= -github.com/btcsuite/btcd/btcec/v2 v2.3.4/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= -github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw= -github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/consensys/gnark-crypto v0.19.0 h1:zXCqeY2txSaMl6G5wFpZzMWJU9HPNh8qxPnYJ1BL9vA= -github.com/consensys/gnark-crypto v0.19.0/go.mod h1:rT23F0XSZqE0mUA0+pRtnL56IbPxs6gp4CeRsBk4XS0= -github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= -github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= -github.com/cosmos/cosmos-sdk v0.53.4 h1:kPF6vY68+/xi1/VebSZGpoxQqA52qkhUzqkrgeBn3Mg= -github.com/cosmos/cosmos-sdk v0.53.4/go.mod h1:7U3+WHZtI44dEOnU46+lDzBb2tFh1QlMvi8Z5JugopI= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -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.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= -github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564 h1:I6KUy4CI6hHjqnyJLNCEi7YHVMkwwtfSr2k9splgdSM= -github.com/dustinxie/ecc v0.0.0-20210511000915-959544187564/go.mod h1:yekO+3ZShy19S+bsmnERmznGy9Rfg6dWWWpiGJjNAz8= -github.com/ecies/go/v2 v2.0.10 h1:AaLxGio0MLLbvWur4rKnLzw+K9zI+wMScIDAtqCqOtU= -github.com/ecies/go/v2 v2.0.10/go.mod h1:N73OyuR6tuKznit2LhXjrZ0XAQ234uKbzYz8pEPYzlI= -github.com/ethereum/go-ethereum v1.16.3 h1:nDoBSrmsrPbrDIVLTkDQCy1U9KdHN+F2PzvMbDoS42Q= -github.com/ethereum/go-ethereum v1.16.3/go.mod h1:Lrsc6bt9Gm9RyvhfFK53vboCia8kpF9nv+2Ukntnl+8= -github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= -github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= -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/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= -github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= -github.com/ipfs/go-cid v0.5.0 h1:goEKKhaGm0ul11IHA7I6p1GmKz8kEYniqFopaB5Otwg= -github.com/ipfs/go-cid v0.5.0/go.mod h1:0L7vmeNXpQpUS9vt+yEARkJ8rOg43DF3iPgn4GIN0mk= -github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= -github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -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-libp2p v0.43.0 h1:b2bg2cRNmY4HpLK8VHYQXLX2d3iND95OjodLFymvqXU= -github.com/libp2p/go-libp2p v0.43.0/go.mod h1:IiSqAXDyP2sWH+J2gs43pNmB/y4FOi2XQPbsb+8qvzc= -github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= -github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -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/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= -github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= -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.16.0 h1:oGWEVKioVQcdIOBlYM8BH1rZDWOGJSqr9/BKl6zQ4qc= -github.com/multiformats/go-multiaddr v0.16.0/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0= -github.com/multiformats/go-multibase v0.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g= -github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk= -github.com/multiformats/go-multicodec v0.9.1 h1:x/Fuxr7ZuR4jJV4Os5g444F7xC4XmyUaT/FWtE+9Zjo= -github.com/multiformats/go-multicodec v0.9.1/go.mod h1:LLWNMtyV5ithSBUo3vFIMaeDy+h3EbkMTek1m+Fybbo= -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-varint v0.1.0 h1:i2wqFp4sdl3IcIxfAonHQV9qU5OsZ4Ts9IOoETFs5dI= -github.com/multiformats/go-varint v0.1.0/go.mod h1:5KVAVXegtfmNQQm/lCY+ATvDzvJJhSkUlGQV9wgObdI= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -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/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= -github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= -golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= -golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= -golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/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= -lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= -lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= diff --git a/crypto/internal/ed25519/edwards25519/const.go b/crypto/internal/ed25519/edwards25519/const.go deleted file mode 100644 index c124e3770..000000000 --- a/crypto/internal/ed25519/edwards25519/const.go +++ /dev/null @@ -1,10217 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -// BasePointOrder is the number of points in the subgroup generated by the base point. -var BasePointOrder = [32]byte{ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16, -} - -var d = FieldElement{ - -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116, -} - -var d2 = FieldElement{ - -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199, -} - -var SqrtM1 = FieldElement{ - -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482, -} - -var A = FieldElement{ - 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0, -} - -var extendedBaseEl = ExtendedGroupElement{ - FieldElement{ - 25485296, - 5318399, - 8791791, - -8299916, - -14349720, - 6939349, - -3324311, - -7717049, - 7287234, - -6577708, - }, - FieldElement{ - -758052, - -1832720, - 13046421, - -4857925, - 6576754, - 14371947, - -13139572, - 6845540, - -2198883, - -4003719, - }, - FieldElement{ - -947565, - 6097708, - -469190, - 10704810, - -8556274, - -15589498, - -16424464, - -16608899, - 14028613, - -5004649, - }, - FieldElement{ - 6966464, - -2456167, - 7033433, - 6781840, - 28785542, - 12262365, - -2659449, - 13959020, - -21013759, - -5262166, - }, -} - -// BaseBytes can be used to hash the base point if necessary -var BaseBytes [32]byte - -func init() { - extendedBaseEl.ToBytes(&BaseBytes) -} - -var bi = [8]PreComputedGroupElement{ - { - FieldElement{ - 25967493, - -14356035, - 29566456, - 3660896, - -12694345, - 4014787, - 27544626, - -11754271, - -6079156, - 2047605, - }, - FieldElement{ - -12545711, - 934262, - -2722910, - 3049990, - -727428, - 9406986, - 12720692, - 5043384, - 19500929, - -15469378, - }, - FieldElement{ - -8738181, - 4489570, - 9688441, - -14785194, - 10184609, - -12363380, - 29287919, - 11864899, - -24514362, - -4438546, - }, - }, - { - FieldElement{ - 15636291, - -9688557, - 24204773, - -7912398, - 616977, - -16685262, - 27787600, - -14772189, - 28944400, - -1550024, - }, - FieldElement{ - 16568933, - 4717097, - -11556148, - -1102322, - 15682896, - -11807043, - 16354577, - -11775962, - 7689662, - 11199574, - }, - FieldElement{ - 30464156, - -5976125, - -11779434, - -15670865, - 23220365, - 15915852, - 7512774, - 10017326, - -17749093, - -9920357, - }, - }, - { - FieldElement{ - 10861363, - 11473154, - 27284546, - 1981175, - -30064349, - 12577861, - 32867885, - 14515107, - -15438304, - 10819380, - }, - FieldElement{ - 4708026, - 6336745, - 20377586, - 9066809, - -11272109, - 6594696, - -25653668, - 12483688, - -12668491, - 5581306, - }, - FieldElement{ - 19563160, - 16186464, - -29386857, - 4097519, - 10237984, - -4348115, - 28542350, - 13850243, - -23678021, - -15815942, - }, - }, - { - FieldElement{ - 5153746, - 9909285, - 1723747, - -2777874, - 30523605, - 5516873, - 19480852, - 5230134, - -23952439, - -15175766, - }, - FieldElement{ - -30269007, - -3463509, - 7665486, - 10083793, - 28475525, - 1649722, - 20654025, - 16520125, - 30598449, - 7715701, - }, - FieldElement{ - 28881845, - 14381568, - 9657904, - 3680757, - -20181635, - 7843316, - -31400660, - 1370708, - 29794553, - -1409300, - }, - }, - { - FieldElement{ - -22518993, - -6692182, - 14201702, - -8745502, - -23510406, - 8844726, - 18474211, - -1361450, - -13062696, - 13821877, - }, - FieldElement{ - -6455177, - -7839871, - 3374702, - -4740862, - -27098617, - -10571707, - 31655028, - -7212327, - 18853322, - -14220951, - }, - FieldElement{ - 4566830, - -12963868, - -28974889, - -12240689, - -7602672, - -2830569, - -8514358, - -10431137, - 2207753, - -3209784, - }, - }, - { - FieldElement{ - -25154831, - -4185821, - 29681144, - 7868801, - -6854661, - -9423865, - -12437364, - -663000, - -31111463, - -16132436, - }, - FieldElement{ - 25576264, - -2703214, - 7349804, - -11814844, - 16472782, - 9300885, - 3844789, - 15725684, - 171356, - 6466918, - }, - FieldElement{ - 23103977, - 13316479, - 9739013, - -16149481, - 817875, - -15038942, - 8965339, - -14088058, - -30714912, - 16193877, - }, - }, - { - FieldElement{ - -33521811, - 3180713, - -2394130, - 14003687, - -16903474, - -16270840, - 17238398, - 4729455, - -18074513, - 9256800, - }, - FieldElement{ - -25182317, - -4174131, - 32336398, - 5036987, - -21236817, - 11360617, - 22616405, - 9761698, - -19827198, - 630305, - }, - FieldElement{ - -13720693, - 2639453, - -24237460, - -7406481, - 9494427, - -5774029, - -6554551, - -15960994, - -2449256, - -14291300, - }, - }, - { - FieldElement{ - -3151181, - -5046075, - 9282714, - 6866145, - -31907062, - -863023, - -18940575, - 15033784, - 25105118, - -7894876, - }, - FieldElement{ - -24326370, - 15950226, - -31801215, - -14592823, - -11662737, - -5090925, - 1573892, - -2625887, - 2198790, - -15804619, - }, - FieldElement{ - -3099351, - 10324967, - -2241613, - 7453183, - -5446979, - -2735503, - -13812022, - -16236442, - -32461234, - -12290683, - }, - }, -} - -var base = [32][8]PreComputedGroupElement{ - { - { - FieldElement{ - 25967493, - -14356035, - 29566456, - 3660896, - -12694345, - 4014787, - 27544626, - -11754271, - -6079156, - 2047605, - }, - FieldElement{ - -12545711, - 934262, - -2722910, - 3049990, - -727428, - 9406986, - 12720692, - 5043384, - 19500929, - -15469378, - }, - FieldElement{ - -8738181, - 4489570, - 9688441, - -14785194, - 10184609, - -12363380, - 29287919, - 11864899, - -24514362, - -4438546, - }, - }, - { - FieldElement{ - -12815894, - -12976347, - -21581243, - 11784320, - -25355658, - -2750717, - -11717903, - -3814571, - -358445, - -10211303, - }, - FieldElement{ - -21703237, - 6903825, - 27185491, - 6451973, - -29577724, - -9554005, - -15616551, - 11189268, - -26829678, - -5319081, - }, - FieldElement{ - 26966642, - 11152617, - 32442495, - 15396054, - 14353839, - -12752335, - -3128826, - -9541118, - -15472047, - -4166697, - }, - }, - { - FieldElement{ - 15636291, - -9688557, - 24204773, - -7912398, - 616977, - -16685262, - 27787600, - -14772189, - 28944400, - -1550024, - }, - FieldElement{ - 16568933, - 4717097, - -11556148, - -1102322, - 15682896, - -11807043, - 16354577, - -11775962, - 7689662, - 11199574, - }, - FieldElement{ - 30464156, - -5976125, - -11779434, - -15670865, - 23220365, - 15915852, - 7512774, - 10017326, - -17749093, - -9920357, - }, - }, - { - FieldElement{ - -17036878, - 13921892, - 10945806, - -6033431, - 27105052, - -16084379, - -28926210, - 15006023, - 3284568, - -6276540, - }, - FieldElement{ - 23599295, - -8306047, - -11193664, - -7687416, - 13236774, - 10506355, - 7464579, - 9656445, - 13059162, - 10374397, - }, - FieldElement{ - 7798556, - 16710257, - 3033922, - 2874086, - 28997861, - 2835604, - 32406664, - -3839045, - -641708, - -101325, - }, - }, - { - FieldElement{ - 10861363, - 11473154, - 27284546, - 1981175, - -30064349, - 12577861, - 32867885, - 14515107, - -15438304, - 10819380, - }, - FieldElement{ - 4708026, - 6336745, - 20377586, - 9066809, - -11272109, - 6594696, - -25653668, - 12483688, - -12668491, - 5581306, - }, - FieldElement{ - 19563160, - 16186464, - -29386857, - 4097519, - 10237984, - -4348115, - 28542350, - 13850243, - -23678021, - -15815942, - }, - }, - { - FieldElement{ - -15371964, - -12862754, - 32573250, - 4720197, - -26436522, - 5875511, - -19188627, - -15224819, - -9818940, - -12085777, - }, - FieldElement{ - -8549212, - 109983, - 15149363, - 2178705, - 22900618, - 4543417, - 3044240, - -15689887, - 1762328, - 14866737, - }, - FieldElement{ - -18199695, - -15951423, - -10473290, - 1707278, - -17185920, - 3916101, - -28236412, - 3959421, - 27914454, - 4383652, - }, - }, - { - FieldElement{ - 5153746, - 9909285, - 1723747, - -2777874, - 30523605, - 5516873, - 19480852, - 5230134, - -23952439, - -15175766, - }, - FieldElement{ - -30269007, - -3463509, - 7665486, - 10083793, - 28475525, - 1649722, - 20654025, - 16520125, - 30598449, - 7715701, - }, - FieldElement{ - 28881845, - 14381568, - 9657904, - 3680757, - -20181635, - 7843316, - -31400660, - 1370708, - 29794553, - -1409300, - }, - }, - { - FieldElement{ - 14499471, - -2729599, - -33191113, - -4254652, - 28494862, - 14271267, - 30290735, - 10876454, - -33154098, - 2381726, - }, - FieldElement{ - -7195431, - -2655363, - -14730155, - 462251, - -27724326, - 3941372, - -6236617, - 3696005, - -32300832, - 15351955, - }, - FieldElement{ - 27431194, - 8222322, - 16448760, - -3907995, - -18707002, - 11938355, - -32961401, - -2970515, - 29551813, - 10109425, - }, - }, - }, - { - { - FieldElement{ - -13657040, - -13155431, - -31283750, - 11777098, - 21447386, - 6519384, - -2378284, - -1627556, - 10092783, - -4764171, - }, - FieldElement{ - 27939166, - 14210322, - 4677035, - 16277044, - -22964462, - -12398139, - -32508754, - 12005538, - -17810127, - 12803510, - }, - FieldElement{ - 17228999, - -15661624, - -1233527, - 300140, - -1224870, - -11714777, - 30364213, - -9038194, - 18016357, - 4397660, - }, - }, - { - FieldElement{ - -10958843, - -7690207, - 4776341, - -14954238, - 27850028, - -15602212, - -26619106, - 14544525, - -17477504, - 982639, - }, - FieldElement{ - 29253598, - 15796703, - -2863982, - -9908884, - 10057023, - 3163536, - 7332899, - -4120128, - -21047696, - 9934963, - }, - FieldElement{ - 5793303, - 16271923, - -24131614, - -10116404, - 29188560, - 1206517, - -14747930, - 4559895, - -30123922, - -10897950, - }, - }, - { - FieldElement{ - -27643952, - -11493006, - 16282657, - -11036493, - 28414021, - -15012264, - 24191034, - 4541697, - -13338309, - 5500568, - }, - FieldElement{ - 12650548, - -1497113, - 9052871, - 11355358, - -17680037, - -8400164, - -17430592, - 12264343, - 10874051, - 13524335, - }, - FieldElement{ - 25556948, - -3045990, - 714651, - 2510400, - 23394682, - -10415330, - 33119038, - 5080568, - -22528059, - 5376628, - }, - }, - { - FieldElement{ - -26088264, - -4011052, - -17013699, - -3537628, - -6726793, - 1920897, - -22321305, - -9447443, - 4535768, - 1569007, - }, - FieldElement{ - -2255422, - 14606630, - -21692440, - -8039818, - 28430649, - 8775819, - -30494562, - 3044290, - 31848280, - 12543772, - }, - FieldElement{ - -22028579, - 2943893, - -31857513, - 6777306, - 13784462, - -4292203, - -27377195, - -2062731, - 7718482, - 14474653, - }, - }, - { - FieldElement{ - 2385315, - 2454213, - -22631320, - 46603, - -4437935, - -15680415, - 656965, - -7236665, - 24316168, - -5253567, - }, - FieldElement{ - 13741529, - 10911568, - -33233417, - -8603737, - -20177830, - -1033297, - 33040651, - -13424532, - -20729456, - 8321686, - }, - FieldElement{ - 21060490, - -2212744, - 15712757, - -4336099, - 1639040, - 10656336, - 23845965, - -11874838, - -9984458, - 608372, - }, - }, - { - FieldElement{ - -13672732, - -15087586, - -10889693, - -7557059, - -6036909, - 11305547, - 1123968, - -6780577, - 27229399, - 23887, - }, - FieldElement{ - -23244140, - -294205, - -11744728, - 14712571, - -29465699, - -2029617, - 12797024, - -6440308, - -1633405, - 16678954, - }, - FieldElement{ - -29500620, - 4770662, - -16054387, - 14001338, - 7830047, - 9564805, - -1508144, - -4795045, - -17169265, - 4904953, - }, - }, - { - FieldElement{ - 24059557, - 14617003, - 19037157, - -15039908, - 19766093, - -14906429, - 5169211, - 16191880, - 2128236, - -4326833, - }, - FieldElement{ - -16981152, - 4124966, - -8540610, - -10653797, - 30336522, - -14105247, - -29806336, - 916033, - -6882542, - -2986532, - }, - FieldElement{ - -22630907, - 12419372, - -7134229, - -7473371, - -16478904, - 16739175, - 285431, - 2763829, - 15736322, - 4143876, - }, - }, - { - FieldElement{ - 2379352, - 11839345, - -4110402, - -5988665, - 11274298, - 794957, - 212801, - -14594663, - 23527084, - -16458268, - }, - FieldElement{ - 33431127, - -11130478, - -17838966, - -15626900, - 8909499, - 8376530, - -32625340, - 4087881, - -15188911, - -14416214, - }, - FieldElement{ - 1767683, - 7197987, - -13205226, - -2022635, - -13091350, - 448826, - 5799055, - 4357868, - -4774191, - -16323038, - }, - }, - }, - { - { - FieldElement{ - 6721966, - 13833823, - -23523388, - -1551314, - 26354293, - -11863321, - 23365147, - -3949732, - 7390890, - 2759800, - }, - FieldElement{ - 4409041, - 2052381, - 23373853, - 10530217, - 7676779, - -12885954, - 21302353, - -4264057, - 1244380, - -12919645, - }, - FieldElement{ - -4421239, - 7169619, - 4982368, - -2957590, - 30256825, - -2777540, - 14086413, - 9208236, - 15886429, - 16489664, - }, - }, - { - FieldElement{ - 1996075, - 10375649, - 14346367, - 13311202, - -6874135, - -16438411, - -13693198, - 398369, - -30606455, - -712933, - }, - FieldElement{ - -25307465, - 9795880, - -2777414, - 14878809, - -33531835, - 14780363, - 13348553, - 12076947, - -30836462, - 5113182, - }, - FieldElement{ - -17770784, - 11797796, - 31950843, - 13929123, - -25888302, - 12288344, - -30341101, - -7336386, - 13847711, - 5387222, - }, - }, - { - FieldElement{ - -18582163, - -3416217, - 17824843, - -2340966, - 22744343, - -10442611, - 8763061, - 3617786, - -19600662, - 10370991, - }, - FieldElement{ - 20246567, - -14369378, - 22358229, - -543712, - 18507283, - -10413996, - 14554437, - -8746092, - 32232924, - 16763880, - }, - FieldElement{ - 9648505, - 10094563, - 26416693, - 14745928, - -30374318, - -6472621, - 11094161, - 15689506, - 3140038, - -16510092, - }, - }, - { - FieldElement{ - -16160072, - 5472695, - 31895588, - 4744994, - 8823515, - 10365685, - -27224800, - 9448613, - -28774454, - 366295, - }, - FieldElement{ - 19153450, - 11523972, - -11096490, - -6503142, - -24647631, - 5420647, - 28344573, - 8041113, - 719605, - 11671788, - }, - FieldElement{ - 8678025, - 2694440, - -6808014, - 2517372, - 4964326, - 11152271, - -15432916, - -15266516, - 27000813, - -10195553, - }, - }, - { - FieldElement{ - -15157904, - 7134312, - 8639287, - -2814877, - -7235688, - 10421742, - 564065, - 5336097, - 6750977, - -14521026, - }, - FieldElement{ - 11836410, - -3979488, - 26297894, - 16080799, - 23455045, - 15735944, - 1695823, - -8819122, - 8169720, - 16220347, - }, - FieldElement{ - -18115838, - 8653647, - 17578566, - -6092619, - -8025777, - -16012763, - -11144307, - -2627664, - -5990708, - -14166033, - }, - }, - { - FieldElement{ - -23308498, - -10968312, - 15213228, - -10081214, - -30853605, - -11050004, - 27884329, - 2847284, - 2655861, - 1738395, - }, - FieldElement{ - -27537433, - -14253021, - -25336301, - -8002780, - -9370762, - 8129821, - 21651608, - -3239336, - -19087449, - -11005278, - }, - FieldElement{ - 1533110, - 3437855, - 23735889, - 459276, - 29970501, - 11335377, - 26030092, - 5821408, - 10478196, - 8544890, - }, - }, - { - FieldElement{ - 32173121, - -16129311, - 24896207, - 3921497, - 22579056, - -3410854, - 19270449, - 12217473, - 17789017, - -3395995, - }, - FieldElement{ - -30552961, - -2228401, - -15578829, - -10147201, - 13243889, - 517024, - 15479401, - -3853233, - 30460520, - 1052596, - }, - FieldElement{ - -11614875, - 13323618, - 32618793, - 8175907, - -15230173, - 12596687, - 27491595, - -4612359, - 3179268, - -9478891, - }, - }, - { - FieldElement{ - 31947069, - -14366651, - -4640583, - -15339921, - -15125977, - -6039709, - -14756777, - -16411740, - 19072640, - -9511060, - }, - FieldElement{ - 11685058, - 11822410, - 3158003, - -13952594, - 33402194, - -4165066, - 5977896, - -5215017, - 473099, - 5040608, - }, - FieldElement{ - -20290863, - 8198642, - -27410132, - 11602123, - 1290375, - -2799760, - 28326862, - 1721092, - -19558642, - -3131606, - }, - }, - }, - { - { - FieldElement{ - 7881532, - 10687937, - 7578723, - 7738378, - -18951012, - -2553952, - 21820786, - 8076149, - -27868496, - 11538389, - }, - FieldElement{ - -19935666, - 3899861, - 18283497, - -6801568, - -15728660, - -11249211, - 8754525, - 7446702, - -5676054, - 5797016, - }, - FieldElement{ - -11295600, - -3793569, - -15782110, - -7964573, - 12708869, - -8456199, - 2014099, - -9050574, - -2369172, - -5877341, - }, - }, - { - FieldElement{ - -22472376, - -11568741, - -27682020, - 1146375, - 18956691, - 16640559, - 1192730, - -3714199, - 15123619, - 10811505, - }, - FieldElement{ - 14352098, - -3419715, - -18942044, - 10822655, - 32750596, - 4699007, - -70363, - 15776356, - -28886779, - -11974553, - }, - FieldElement{ - -28241164, - -8072475, - -4978962, - -5315317, - 29416931, - 1847569, - -20654173, - -16484855, - 4714547, - -9600655, - }, - }, - { - FieldElement{ - 15200332, - 8368572, - 19679101, - 15970074, - -31872674, - 1959451, - 24611599, - -4543832, - -11745876, - 12340220, - }, - FieldElement{ - 12876937, - -10480056, - 33134381, - 6590940, - -6307776, - 14872440, - 9613953, - 8241152, - 15370987, - 9608631, - }, - FieldElement{ - -4143277, - -12014408, - 8446281, - -391603, - 4407738, - 13629032, - -7724868, - 15866074, - -28210621, - -8814099, - }, - }, - { - FieldElement{ - 26660628, - -15677655, - 8393734, - 358047, - -7401291, - 992988, - -23904233, - 858697, - 20571223, - 8420556, - }, - FieldElement{ - 14620715, - 13067227, - -15447274, - 8264467, - 14106269, - 15080814, - 33531827, - 12516406, - -21574435, - -12476749, - }, - FieldElement{ - 236881, - 10476226, - 57258, - -14677024, - 6472998, - 2466984, - 17258519, - 7256740, - 8791136, - 15069930, - }, - }, - { - FieldElement{ - 1276410, - -9371918, - 22949635, - -16322807, - -23493039, - -5702186, - 14711875, - 4874229, - -30663140, - -2331391, - }, - FieldElement{ - 5855666, - 4990204, - -13711848, - 7294284, - -7804282, - 1924647, - -1423175, - -7912378, - -33069337, - 9234253, - }, - FieldElement{ - 20590503, - -9018988, - 31529744, - -7352666, - -2706834, - 10650548, - 31559055, - -11609587, - 18979186, - 13396066, - }, - }, - { - FieldElement{ - 24474287, - 4968103, - 22267082, - 4407354, - 24063882, - -8325180, - -18816887, - 13594782, - 33514650, - 7021958, - }, - FieldElement{ - -11566906, - -6565505, - -21365085, - 15928892, - -26158305, - 4315421, - -25948728, - -3916677, - -21480480, - 12868082, - }, - FieldElement{ - -28635013, - 13504661, - 19988037, - -2132761, - 21078225, - 6443208, - -21446107, - 2244500, - -12455797, - -8089383, - }, - }, - { - FieldElement{ - -30595528, - 13793479, - -5852820, - 319136, - -25723172, - -6263899, - 33086546, - 8957937, - -15233648, - 5540521, - }, - FieldElement{ - -11630176, - -11503902, - -8119500, - -7643073, - 2620056, - 1022908, - -23710744, - -1568984, - -16128528, - -14962807, - }, - FieldElement{ - 23152971, - 775386, - 27395463, - 14006635, - -9701118, - 4649512, - 1689819, - 892185, - -11513277, - -15205948, - }, - }, - { - FieldElement{ - 9770129, - 9586738, - 26496094, - 4324120, - 1556511, - -3550024, - 27453819, - 4763127, - -19179614, - 5867134, - }, - FieldElement{ - -32765025, - 1927590, - 31726409, - -4753295, - 23962434, - -16019500, - 27846559, - 5931263, - -29749703, - -16108455, - }, - FieldElement{ - 27461885, - -2977536, - 22380810, - 1815854, - -23033753, - -3031938, - 7283490, - -15148073, - -19526700, - 7734629, - }, - }, - }, - { - { - FieldElement{ - -8010264, - -9590817, - -11120403, - 6196038, - 29344158, - -13430885, - 7585295, - -3176626, - 18549497, - 15302069, - }, - FieldElement{ - -32658337, - -6171222, - -7672793, - -11051681, - 6258878, - 13504381, - 10458790, - -6418461, - -8872242, - 8424746, - }, - FieldElement{ - 24687205, - 8613276, - -30667046, - -3233545, - 1863892, - -1830544, - 19206234, - 7134917, - -11284482, - -828919, - }, - }, - { - FieldElement{ - 11334899, - -9218022, - 8025293, - 12707519, - 17523892, - -10476071, - 10243738, - -14685461, - -5066034, - 16498837, - }, - FieldElement{ - 8911542, - 6887158, - -9584260, - -6958590, - 11145641, - -9543680, - 17303925, - -14124238, - 6536641, - 10543906, - }, - FieldElement{ - -28946384, - 15479763, - -17466835, - 568876, - -1497683, - 11223454, - -2669190, - -16625574, - -27235709, - 8876771, - }, - }, - { - FieldElement{ - -25742899, - -12566864, - -15649966, - -846607, - -33026686, - -796288, - -33481822, - 15824474, - -604426, - -9039817, - }, - FieldElement{ - 10330056, - 70051, - 7957388, - -9002667, - 9764902, - 15609756, - 27698697, - -4890037, - 1657394, - 3084098, - }, - FieldElement{ - 10477963, - -7470260, - 12119566, - -13250805, - 29016247, - -5365589, - 31280319, - 14396151, - -30233575, - 15272409, - }, - }, - { - FieldElement{ - -12288309, - 3169463, - 28813183, - 16658753, - 25116432, - -5630466, - -25173957, - -12636138, - -25014757, - 1950504, - }, - FieldElement{ - -26180358, - 9489187, - 11053416, - -14746161, - -31053720, - 5825630, - -8384306, - -8767532, - 15341279, - 8373727, - }, - FieldElement{ - 28685821, - 7759505, - -14378516, - -12002860, - -31971820, - 4079242, - 298136, - -10232602, - -2878207, - 15190420, - }, - }, - { - FieldElement{ - -32932876, - 13806336, - -14337485, - -15794431, - -24004620, - 10940928, - 8669718, - 2742393, - -26033313, - -6875003, - }, - FieldElement{ - -1580388, - -11729417, - -25979658, - -11445023, - -17411874, - -10912854, - 9291594, - -16247779, - -12154742, - 6048605, - }, - FieldElement{ - -30305315, - 14843444, - 1539301, - 11864366, - 20201677, - 1900163, - 13934231, - 5128323, - 11213262, - 9168384, - }, - }, - { - FieldElement{ - -26280513, - 11007847, - 19408960, - -940758, - -18592965, - -4328580, - -5088060, - -11105150, - 20470157, - -16398701, - }, - FieldElement{ - -23136053, - 9282192, - 14855179, - -15390078, - -7362815, - -14408560, - -22783952, - 14461608, - 14042978, - 5230683, - }, - FieldElement{ - 29969567, - -2741594, - -16711867, - -8552442, - 9175486, - -2468974, - 21556951, - 3506042, - -5933891, - -12449708, - }, - }, - { - FieldElement{ - -3144746, - 8744661, - 19704003, - 4581278, - -20430686, - 6830683, - -21284170, - 8971513, - -28539189, - 15326563, - }, - FieldElement{ - -19464629, - 10110288, - -17262528, - -3503892, - -23500387, - 1355669, - -15523050, - 15300988, - -20514118, - 9168260, - }, - FieldElement{ - -5353335, - 4488613, - -23803248, - 16314347, - 7780487, - -15638939, - -28948358, - 9601605, - 33087103, - -9011387, - }, - }, - { - FieldElement{ - -19443170, - -15512900, - -20797467, - -12445323, - -29824447, - 10229461, - -27444329, - -15000531, - -5996870, - 15664672, - }, - FieldElement{ - 23294591, - -16632613, - -22650781, - -8470978, - 27844204, - 11461195, - 13099750, - -2460356, - 18151676, - 13417686, - }, - FieldElement{ - -24722913, - -4176517, - -31150679, - 5988919, - -26858785, - 6685065, - 1661597, - -12551441, - 15271676, - -15452665, - }, - }, - }, - { - { - FieldElement{ - 11433042, - -13228665, - 8239631, - -5279517, - -1985436, - -725718, - -18698764, - 2167544, - -6921301, - -13440182, - }, - FieldElement{ - -31436171, - 15575146, - 30436815, - 12192228, - -22463353, - 9395379, - -9917708, - -8638997, - 12215110, - 12028277, - }, - FieldElement{ - 14098400, - 6555944, - 23007258, - 5757252, - -15427832, - -12950502, - 30123440, - 4617780, - -16900089, - -655628, - }, - }, - { - FieldElement{ - -4026201, - -15240835, - 11893168, - 13718664, - -14809462, - 1847385, - -15819999, - 10154009, - 23973261, - -12684474, - }, - FieldElement{ - -26531820, - -3695990, - -1908898, - 2534301, - -31870557, - -16550355, - 18341390, - -11419951, - 32013174, - -10103539, - }, - FieldElement{ - -25479301, - 10876443, - -11771086, - -14625140, - -12369567, - 1838104, - 21911214, - 6354752, - 4425632, - -837822, - }, - }, - { - FieldElement{ - -10433389, - -14612966, - 22229858, - -3091047, - -13191166, - 776729, - -17415375, - -12020462, - 4725005, - 14044970, - }, - FieldElement{ - 19268650, - -7304421, - 1555349, - 8692754, - -21474059, - -9910664, - 6347390, - -1411784, - -19522291, - -16109756, - }, - FieldElement{ - -24864089, - 12986008, - -10898878, - -5558584, - -11312371, - -148526, - 19541418, - 8180106, - 9282262, - 10282508, - }, - }, - { - FieldElement{ - -26205082, - 4428547, - -8661196, - -13194263, - 4098402, - -14165257, - 15522535, - 8372215, - 5542595, - -10702683, - }, - FieldElement{ - -10562541, - 14895633, - 26814552, - -16673850, - -17480754, - -2489360, - -2781891, - 6993761, - -18093885, - 10114655, - }, - FieldElement{ - -20107055, - -929418, - 31422704, - 10427861, - -7110749, - 6150669, - -29091755, - -11529146, - 25953725, - -106158, - }, - }, - { - FieldElement{ - -4234397, - -8039292, - -9119125, - 3046000, - 2101609, - -12607294, - 19390020, - 6094296, - -3315279, - 12831125, - }, - FieldElement{ - -15998678, - 7578152, - 5310217, - 14408357, - -33548620, - -224739, - 31575954, - 6326196, - 7381791, - -2421839, - }, - FieldElement{ - -20902779, - 3296811, - 24736065, - -16328389, - 18374254, - 7318640, - 6295303, - 8082724, - -15362489, - 12339664, - }, - }, - { - FieldElement{ - 27724736, - 2291157, - 6088201, - -14184798, - 1792727, - 5857634, - 13848414, - 15768922, - 25091167, - 14856294, - }, - FieldElement{ - -18866652, - 8331043, - 24373479, - 8541013, - -701998, - -9269457, - 12927300, - -12695493, - -22182473, - -9012899, - }, - FieldElement{ - -11423429, - -5421590, - 11632845, - 3405020, - 30536730, - -11674039, - -27260765, - 13866390, - 30146206, - 9142070, - }, - }, - { - FieldElement{ - 3924129, - -15307516, - -13817122, - -10054960, - 12291820, - -668366, - -27702774, - 9326384, - -8237858, - 4171294, - }, - FieldElement{ - -15921940, - 16037937, - 6713787, - 16606682, - -21612135, - 2790944, - 26396185, - 3731949, - 345228, - -5462949, - }, - FieldElement{ - -21327538, - 13448259, - 25284571, - 1143661, - 20614966, - -8849387, - 2031539, - -12391231, - -16253183, - -13582083, - }, - }, - { - FieldElement{ - 31016211, - -16722429, - 26371392, - -14451233, - -5027349, - 14854137, - 17477601, - 3842657, - 28012650, - -16405420, - }, - FieldElement{ - -5075835, - 9368966, - -8562079, - -4600902, - -15249953, - 6970560, - -9189873, - 16292057, - -8867157, - 3507940, - }, - FieldElement{ - 29439664, - 3537914, - 23333589, - 6997794, - -17555561, - -11018068, - -15209202, - -15051267, - -9164929, - 6580396, - }, - }, - }, - { - { - FieldElement{ - -12185861, - -7679788, - 16438269, - 10826160, - -8696817, - -6235611, - 17860444, - -9273846, - -2095802, - 9304567, - }, - FieldElement{ - 20714564, - -4336911, - 29088195, - 7406487, - 11426967, - -5095705, - 14792667, - -14608617, - 5289421, - -477127, - }, - FieldElement{ - -16665533, - -10650790, - -6160345, - -13305760, - 9192020, - -1802462, - 17271490, - 12349094, - 26939669, - -3752294, - }, - }, - { - FieldElement{ - -12889898, - 9373458, - 31595848, - 16374215, - 21471720, - 13221525, - -27283495, - -12348559, - -3698806, - 117887, - }, - FieldElement{ - 22263325, - -6560050, - 3984570, - -11174646, - -15114008, - -566785, - 28311253, - 5358056, - -23319780, - 541964, - }, - FieldElement{ - 16259219, - 3261970, - 2309254, - -15534474, - -16885711, - -4581916, - 24134070, - -16705829, - -13337066, - -13552195, - }, - }, - { - FieldElement{ - 9378160, - -13140186, - -22845982, - -12745264, - 28198281, - -7244098, - -2399684, - -717351, - 690426, - 14876244, - }, - FieldElement{ - 24977353, - -314384, - -8223969, - -13465086, - 28432343, - -1176353, - -13068804, - -12297348, - -22380984, - 6618999, - }, - FieldElement{ - -1538174, - 11685646, - 12944378, - 13682314, - -24389511, - -14413193, - 8044829, - -13817328, - 32239829, - -5652762, - }, - }, - { - FieldElement{ - -18603066, - 4762990, - -926250, - 8885304, - -28412480, - -3187315, - 9781647, - -10350059, - 32779359, - 5095274, - }, - FieldElement{ - -33008130, - -5214506, - -32264887, - -3685216, - 9460461, - -9327423, - -24601656, - 14506724, - 21639561, - -2630236, - }, - FieldElement{ - -16400943, - -13112215, - 25239338, - 15531969, - 3987758, - -4499318, - -1289502, - -6863535, - 17874574, - 558605, - }, - }, - { - FieldElement{ - -13600129, - 10240081, - 9171883, - 16131053, - -20869254, - 9599700, - 33499487, - 5080151, - 2085892, - 5119761, - }, - FieldElement{ - -22205145, - -2519528, - -16381601, - 414691, - -25019550, - 2170430, - 30634760, - -8363614, - -31999993, - -5759884, - }, - FieldElement{ - -6845704, - 15791202, - 8550074, - -1312654, - 29928809, - -12092256, - 27534430, - -7192145, - -22351378, - 12961482, - }, - }, - { - FieldElement{ - -24492060, - -9570771, - 10368194, - 11582341, - -23397293, - -2245287, - 16533930, - 8206996, - -30194652, - -5159638, - }, - FieldElement{ - -11121496, - -3382234, - 2307366, - 6362031, - -135455, - 8868177, - -16835630, - 7031275, - 7589640, - 8945490, - }, - FieldElement{ - -32152748, - 8917967, - 6661220, - -11677616, - -1192060, - -15793393, - 7251489, - -11182180, - 24099109, - -14456170, - }, - }, - { - FieldElement{ - 5019558, - -7907470, - 4244127, - -14714356, - -26933272, - 6453165, - -19118182, - -13289025, - -6231896, - -10280736, - }, - FieldElement{ - 10853594, - 10721687, - 26480089, - 5861829, - -22995819, - 1972175, - -1866647, - -10557898, - -3363451, - -6441124, - }, - FieldElement{ - -17002408, - 5906790, - 221599, - -6563147, - 7828208, - -13248918, - 24362661, - -2008168, - -13866408, - 7421392, - }, - }, - { - FieldElement{ - 8139927, - -6546497, - 32257646, - -5890546, - 30375719, - 1886181, - -21175108, - 15441252, - 28826358, - -4123029, - }, - FieldElement{ - 6267086, - 9695052, - 7709135, - -16603597, - -32869068, - -1886135, - 14795160, - -7840124, - 13746021, - -1742048, - }, - FieldElement{ - 28584902, - 7787108, - -6732942, - -15050729, - 22846041, - -7571236, - -3181936, - -363524, - 4771362, - -8419958, - }, - }, - }, - { - { - FieldElement{ - 24949256, - 6376279, - -27466481, - -8174608, - -18646154, - -9930606, - 33543569, - -12141695, - 3569627, - 11342593, - }, - FieldElement{ - 26514989, - 4740088, - 27912651, - 3697550, - 19331575, - -11472339, - 6809886, - 4608608, - 7325975, - -14801071, - }, - FieldElement{ - -11618399, - -14554430, - -24321212, - 7655128, - -1369274, - 5214312, - -27400540, - 10258390, - -17646694, - -8186692, - }, - }, - { - FieldElement{ - 11431204, - 15823007, - 26570245, - 14329124, - 18029990, - 4796082, - -31446179, - 15580664, - 9280358, - -3973687, - }, - FieldElement{ - -160783, - -10326257, - -22855316, - -4304997, - -20861367, - -13621002, - -32810901, - -11181622, - -15545091, - 4387441, - }, - FieldElement{ - -20799378, - 12194512, - 3937617, - -5805892, - -27154820, - 9340370, - -24513992, - 8548137, - 20617071, - -7482001, - }, - }, - { - FieldElement{ - -938825, - -3930586, - -8714311, - 16124718, - 24603125, - -6225393, - -13775352, - -11875822, - 24345683, - 10325460, - }, - FieldElement{ - -19855277, - -1568885, - -22202708, - 8714034, - 14007766, - 6928528, - 16318175, - -1010689, - 4766743, - 3552007, - }, - FieldElement{ - -21751364, - -16730916, - 1351763, - -803421, - -4009670, - 3950935, - 3217514, - 14481909, - 10988822, - -3994762, - }, - }, - { - FieldElement{ - 15564307, - -14311570, - 3101243, - 5684148, - 30446780, - -8051356, - 12677127, - -6505343, - -8295852, - 13296005, - }, - FieldElement{ - -9442290, - 6624296, - -30298964, - -11913677, - -4670981, - -2057379, - 31521204, - 9614054, - -30000824, - 12074674, - }, - FieldElement{ - 4771191, - -135239, - 14290749, - -13089852, - 27992298, - 14998318, - -1413936, - -1556716, - 29832613, - -16391035, - }, - }, - { - FieldElement{ - 7064884, - -7541174, - -19161962, - -5067537, - -18891269, - -2912736, - 25825242, - 5293297, - -27122660, - 13101590, - }, - FieldElement{ - -2298563, - 2439670, - -7466610, - 1719965, - -27267541, - -16328445, - 32512469, - -5317593, - -30356070, - -4190957, - }, - FieldElement{ - -30006540, - 10162316, - -33180176, - 3981723, - -16482138, - -13070044, - 14413974, - 9515896, - 19568978, - 9628812, - }, - }, - { - FieldElement{ - 33053803, - 199357, - 15894591, - 1583059, - 27380243, - -4580435, - -17838894, - -6106839, - -6291786, - 3437740, - }, - FieldElement{ - -18978877, - 3884493, - 19469877, - 12726490, - 15913552, - 13614290, - -22961733, - 70104, - 7463304, - 4176122, - }, - FieldElement{ - -27124001, - 10659917, - 11482427, - -16070381, - 12771467, - -6635117, - -32719404, - -5322751, - 24216882, - 5944158, - }, - }, - { - FieldElement{ - 8894125, - 7450974, - -2664149, - -9765752, - -28080517, - -12389115, - 19345746, - 14680796, - 11632993, - 5847885, - }, - FieldElement{ - 26942781, - -2315317, - 9129564, - -4906607, - 26024105, - 11769399, - -11518837, - 6367194, - -9727230, - 4782140, - }, - FieldElement{ - 19916461, - -4828410, - -22910704, - -11414391, - 25606324, - -5972441, - 33253853, - 8220911, - 6358847, - -1873857, - }, - }, - { - FieldElement{ - 801428, - -2081702, - 16569428, - 11065167, - 29875704, - 96627, - 7908388, - -4480480, - -13538503, - 1387155, - }, - FieldElement{ - 19646058, - 5720633, - -11416706, - 12814209, - 11607948, - 12749789, - 14147075, - 15156355, - -21866831, - 11835260, - }, - FieldElement{ - 19299512, - 1155910, - 28703737, - 14890794, - 2925026, - 7269399, - 26121523, - 15467869, - -26560550, - 5052483, - }, - }, - }, - { - { - FieldElement{ - -3017432, - 10058206, - 1980837, - 3964243, - 22160966, - 12322533, - -6431123, - -12618185, - 12228557, - -7003677, - }, - FieldElement{ - 32944382, - 14922211, - -22844894, - 5188528, - 21913450, - -8719943, - 4001465, - 13238564, - -6114803, - 8653815, - }, - FieldElement{ - 22865569, - -4652735, - 27603668, - -12545395, - 14348958, - 8234005, - 24808405, - 5719875, - 28483275, - 2841751, - }, - }, - { - FieldElement{ - -16420968, - -1113305, - -327719, - -12107856, - 21886282, - -15552774, - -1887966, - -315658, - 19932058, - -12739203, - }, - FieldElement{ - -11656086, - 10087521, - -8864888, - -5536143, - -19278573, - -3055912, - 3999228, - 13239134, - -4777469, - -13910208, - }, - FieldElement{ - 1382174, - -11694719, - 17266790, - 9194690, - -13324356, - 9720081, - 20403944, - 11284705, - -14013818, - 3093230, - }, - }, - { - FieldElement{ - 16650921, - -11037932, - -1064178, - 1570629, - -8329746, - 7352753, - -302424, - 16271225, - -24049421, - -6691850, - }, - FieldElement{ - -21911077, - -5927941, - -4611316, - -5560156, - -31744103, - -10785293, - 24123614, - 15193618, - -21652117, - -16739389, - }, - FieldElement{ - -9935934, - -4289447, - -25279823, - 4372842, - 2087473, - 10399484, - 31870908, - 14690798, - 17361620, - 11864968, - }, - }, - { - FieldElement{ - -11307610, - 6210372, - 13206574, - 5806320, - -29017692, - -13967200, - -12331205, - -7486601, - -25578460, - -16240689, - }, - FieldElement{ - 14668462, - -12270235, - 26039039, - 15305210, - 25515617, - 4542480, - 10453892, - 6577524, - 9145645, - -6443880, - }, - FieldElement{ - 5974874, - 3053895, - -9433049, - -10385191, - -31865124, - 3225009, - -7972642, - 3936128, - -5652273, - -3050304, - }, - }, - { - FieldElement{ - 30625386, - -4729400, - -25555961, - -12792866, - -20484575, - 7695099, - 17097188, - -16303496, - -27999779, - 1803632, - }, - FieldElement{ - -3553091, - 9865099, - -5228566, - 4272701, - -5673832, - -16689700, - 14911344, - 12196514, - -21405489, - 7047412, - }, - FieldElement{ - 20093277, - 9920966, - -11138194, - -5343857, - 13161587, - 12044805, - -32856851, - 4124601, - -32343828, - -10257566, - }, - }, - { - FieldElement{ - -20788824, - 14084654, - -13531713, - 7842147, - 19119038, - -13822605, - 4752377, - -8714640, - -21679658, - 2288038, - }, - FieldElement{ - -26819236, - -3283715, - 29965059, - 3039786, - -14473765, - 2540457, - 29457502, - 14625692, - -24819617, - 12570232, - }, - FieldElement{ - -1063558, - -11551823, - 16920318, - 12494842, - 1278292, - -5869109, - -21159943, - -3498680, - -11974704, - 4724943, - }, - }, - { - FieldElement{ - 17960970, - -11775534, - -4140968, - -9702530, - -8876562, - -1410617, - -12907383, - -8659932, - -29576300, - 1903856, - }, - FieldElement{ - 23134274, - -14279132, - -10681997, - -1611936, - 20684485, - 15770816, - -12989750, - 3190296, - 26955097, - 14109738, - }, - FieldElement{ - 15308788, - 5320727, - -30113809, - -14318877, - 22902008, - 7767164, - 29425325, - -11277562, - 31960942, - 11934971, - }, - }, - { - FieldElement{ - -27395711, - 8435796, - 4109644, - 12222639, - -24627868, - 14818669, - 20638173, - 4875028, - 10491392, - 1379718, - }, - FieldElement{ - -13159415, - 9197841, - 3875503, - -8936108, - -1383712, - -5879801, - 33518459, - 16176658, - 21432314, - 12180697, - }, - FieldElement{ - -11787308, - 11500838, - 13787581, - -13832590, - -22430679, - 10140205, - 1465425, - 12689540, - -10301319, - -13872883, - }, - }, - }, - { - { - FieldElement{ - 5414091, - -15386041, - -21007664, - 9643570, - 12834970, - 1186149, - -2622916, - -1342231, - 26128231, - 6032912, - }, - FieldElement{ - -26337395, - -13766162, - 32496025, - -13653919, - 17847801, - -12669156, - 3604025, - 8316894, - -25875034, - -10437358, - }, - FieldElement{ - 3296484, - 6223048, - 24680646, - -12246460, - -23052020, - 5903205, - -8862297, - -4639164, - 12376617, - 3188849, - }, - }, - { - FieldElement{ - 29190488, - -14659046, - 27549113, - -1183516, - 3520066, - -10697301, - 32049515, - -7309113, - -16109234, - -9852307, - }, - FieldElement{ - -14744486, - -9309156, - 735818, - -598978, - -20407687, - -5057904, - 25246078, - -15795669, - 18640741, - -960977, - }, - FieldElement{ - -6928835, - -16430795, - 10361374, - 5642961, - 4910474, - 12345252, - -31638386, - -494430, - 10530747, - 1053335, - }, - }, - { - FieldElement{ - -29265967, - -14186805, - -13538216, - -12117373, - -19457059, - -10655384, - -31462369, - -2948985, - 24018831, - 15026644, - }, - FieldElement{ - -22592535, - -3145277, - -2289276, - 5953843, - -13440189, - 9425631, - 25310643, - 13003497, - -2314791, - -15145616, - }, - FieldElement{ - -27419985, - -603321, - -8043984, - -1669117, - -26092265, - 13987819, - -27297622, - 187899, - -23166419, - -2531735, - }, - }, - { - FieldElement{ - -21744398, - -13810475, - 1844840, - 5021428, - -10434399, - -15911473, - 9716667, - 16266922, - -5070217, - 726099, - }, - FieldElement{ - 29370922, - -6053998, - 7334071, - -15342259, - 9385287, - 2247707, - -13661962, - -4839461, - 30007388, - -15823341, - }, - FieldElement{ - -936379, - 16086691, - 23751945, - -543318, - -1167538, - -5189036, - 9137109, - 730663, - 9835848, - 4555336, - }, - }, - { - FieldElement{ - -23376435, - 1410446, - -22253753, - -12899614, - 30867635, - 15826977, - 17693930, - 544696, - -11985298, - 12422646, - }, - FieldElement{ - 31117226, - -12215734, - -13502838, - 6561947, - -9876867, - -12757670, - -5118685, - -4096706, - 29120153, - 13924425, - }, - FieldElement{ - -17400879, - -14233209, - 19675799, - -2734756, - -11006962, - -5858820, - -9383939, - -11317700, - 7240931, - -237388, - }, - }, - { - FieldElement{ - -31361739, - -11346780, - -15007447, - -5856218, - -22453340, - -12152771, - 1222336, - 4389483, - 3293637, - -15551743, - }, - FieldElement{ - -16684801, - -14444245, - 11038544, - 11054958, - -13801175, - -3338533, - -24319580, - 7733547, - 12796905, - -6335822, - }, - FieldElement{ - -8759414, - -10817836, - -25418864, - 10783769, - -30615557, - -9746811, - -28253339, - 3647836, - 3222231, - -11160462, - }, - }, - { - FieldElement{ - 18606113, - 1693100, - -25448386, - -15170272, - 4112353, - 10045021, - 23603893, - -2048234, - -7550776, - 2484985, - }, - FieldElement{ - 9255317, - -3131197, - -12156162, - -1004256, - 13098013, - -9214866, - 16377220, - -2102812, - -19802075, - -3034702, - }, - FieldElement{ - -22729289, - 7496160, - -5742199, - 11329249, - 19991973, - -3347502, - -31718148, - 9936966, - -30097688, - -10618797, - }, - }, - { - FieldElement{ - 21878590, - -5001297, - 4338336, - 13643897, - -3036865, - 13160960, - 19708896, - 5415497, - -7360503, - -4109293, - }, - FieldElement{ - 27736861, - 10103576, - 12500508, - 8502413, - -3413016, - -9633558, - 10436918, - -1550276, - -23659143, - -8132100, - }, - FieldElement{ - 19492550, - -12104365, - -29681976, - -852630, - -3208171, - 12403437, - 30066266, - 8367329, - 13243957, - 8709688, - }, - }, - }, - { - { - FieldElement{ - 12015105, - 2801261, - 28198131, - 10151021, - 24818120, - -4743133, - -11194191, - -5645734, - 5150968, - 7274186, - }, - FieldElement{ - 2831366, - -12492146, - 1478975, - 6122054, - 23825128, - -12733586, - 31097299, - 6083058, - 31021603, - -9793610, - }, - FieldElement{ - -2529932, - -2229646, - 445613, - 10720828, - -13849527, - -11505937, - -23507731, - 16354465, - 15067285, - -14147707, - }, - }, - { - FieldElement{ - 7840942, - 14037873, - -33364863, - 15934016, - -728213, - -3642706, - 21403988, - 1057586, - -19379462, - -12403220, - }, - FieldElement{ - 915865, - -16469274, - 15608285, - -8789130, - -24357026, - 6060030, - -17371319, - 8410997, - -7220461, - 16527025, - }, - FieldElement{ - 32922597, - -556987, - 20336074, - -16184568, - 10903705, - -5384487, - 16957574, - 52992, - 23834301, - 6588044, - }, - }, - { - FieldElement{ - 32752030, - 11232950, - 3381995, - -8714866, - 22652988, - -10744103, - 17159699, - 16689107, - -20314580, - -1305992, - }, - FieldElement{ - -4689649, - 9166776, - -25710296, - -10847306, - 11576752, - 12733943, - 7924251, - -2752281, - 1976123, - -7249027, - }, - FieldElement{ - 21251222, - 16309901, - -2983015, - -6783122, - 30810597, - 12967303, - 156041, - -3371252, - 12331345, - -8237197, - }, - }, - { - FieldElement{ - 8651614, - -4477032, - -16085636, - -4996994, - 13002507, - 2950805, - 29054427, - -5106970, - 10008136, - -4667901, - }, - FieldElement{ - 31486080, - 15114593, - -14261250, - 12951354, - 14369431, - -7387845, - 16347321, - -13662089, - 8684155, - -10532952, - }, - FieldElement{ - 19443825, - 11385320, - 24468943, - -9659068, - -23919258, - 2187569, - -26263207, - -6086921, - 31316348, - 14219878, - }, - }, - { - FieldElement{ - -28594490, - 1193785, - 32245219, - 11392485, - 31092169, - 15722801, - 27146014, - 6992409, - 29126555, - 9207390, - }, - FieldElement{ - 32382935, - 1110093, - 18477781, - 11028262, - -27411763, - -7548111, - -4980517, - 10843782, - -7957600, - -14435730, - }, - FieldElement{ - 2814918, - 7836403, - 27519878, - -7868156, - -20894015, - -11553689, - -21494559, - 8550130, - 28346258, - 1994730, - }, - }, - { - FieldElement{ - -19578299, - 8085545, - -14000519, - -3948622, - 2785838, - -16231307, - -19516951, - 7174894, - 22628102, - 8115180, - }, - FieldElement{ - -30405132, - 955511, - -11133838, - -15078069, - -32447087, - -13278079, - -25651578, - 3317160, - -9943017, - 930272, - }, - FieldElement{ - -15303681, - -6833769, - 28856490, - 1357446, - 23421993, - 1057177, - 24091212, - -1388970, - -22765376, - -10650715, - }, - }, - { - FieldElement{ - -22751231, - -5303997, - -12907607, - -12768866, - -15811511, - -7797053, - -14839018, - -16554220, - -1867018, - 8398970, - }, - FieldElement{ - -31969310, - 2106403, - -4736360, - 1362501, - 12813763, - 16200670, - 22981545, - -6291273, - 18009408, - -15772772, - }, - FieldElement{ - -17220923, - -9545221, - -27784654, - 14166835, - 29815394, - 7444469, - 29551787, - -3727419, - 19288549, - 1325865, - }, - }, - { - FieldElement{ - 15100157, - -15835752, - -23923978, - -1005098, - -26450192, - 15509408, - 12376730, - -3479146, - 33166107, - -8042750, - }, - FieldElement{ - 20909231, - 13023121, - -9209752, - 16251778, - -5778415, - -8094914, - 12412151, - 10018715, - 2213263, - -13878373, - }, - FieldElement{ - 32529814, - -11074689, - 30361439, - -16689753, - -9135940, - 1513226, - 22922121, - 6382134, - -5766928, - 8371348, - }, - }, - }, - { - { - FieldElement{ - 9923462, - 11271500, - 12616794, - 3544722, - -29998368, - -1721626, - 12891687, - -8193132, - -26442943, - 10486144, - }, - FieldElement{ - -22597207, - -7012665, - 8587003, - -8257861, - 4084309, - -12970062, - 361726, - 2610596, - -23921530, - -11455195, - }, - FieldElement{ - 5408411, - -1136691, - -4969122, - 10561668, - 24145918, - 14240566, - 31319731, - -4235541, - 19985175, - -3436086, - }, - }, - { - FieldElement{ - -13994457, - 16616821, - 14549246, - 3341099, - 32155958, - 13648976, - -17577068, - 8849297, - 65030, - 8370684, - }, - FieldElement{ - -8320926, - -12049626, - 31204563, - 5839400, - -20627288, - -1057277, - -19442942, - 6922164, - 12743482, - -9800518, - }, - FieldElement{ - -2361371, - 12678785, - 28815050, - 4759974, - -23893047, - 4884717, - 23783145, - 11038569, - 18800704, - 255233, - }, - }, - { - FieldElement{ - -5269658, - -1773886, - 13957886, - 7990715, - 23132995, - 728773, - 13393847, - 9066957, - 19258688, - -14753793, - }, - FieldElement{ - -2936654, - -10827535, - -10432089, - 14516793, - -3640786, - 4372541, - -31934921, - 2209390, - -1524053, - 2055794, - }, - FieldElement{ - 580882, - 16705327, - 5468415, - -2683018, - -30926419, - -14696000, - -7203346, - -8994389, - -30021019, - 7394435, - }, - }, - { - FieldElement{ - 23838809, - 1822728, - -15738443, - 15242727, - 8318092, - -3733104, - -21672180, - -3492205, - -4821741, - 14799921, - }, - FieldElement{ - 13345610, - 9759151, - 3371034, - -16137791, - 16353039, - 8577942, - 31129804, - 13496856, - -9056018, - 7402518, - }, - FieldElement{ - 2286874, - -4435931, - -20042458, - -2008336, - -13696227, - 5038122, - 11006906, - -15760352, - 8205061, - 1607563, - }, - }, - { - FieldElement{ - 14414086, - -8002132, - 3331830, - -3208217, - 22249151, - -5594188, - 18364661, - -2906958, - 30019587, - -9029278, - }, - FieldElement{ - -27688051, - 1585953, - -10775053, - 931069, - -29120221, - -11002319, - -14410829, - 12029093, - 9944378, - 8024, - }, - FieldElement{ - 4368715, - -3709630, - 29874200, - -15022983, - -20230386, - -11410704, - -16114594, - -999085, - -8142388, - 5640030, - }, - }, - { - FieldElement{ - 10299610, - 13746483, - 11661824, - 16234854, - 7630238, - 5998374, - 9809887, - -16694564, - 15219798, - -14327783, - }, - FieldElement{ - 27425505, - -5719081, - 3055006, - 10660664, - 23458024, - 595578, - -15398605, - -1173195, - -18342183, - 9742717, - }, - FieldElement{ - 6744077, - 2427284, - 26042789, - 2720740, - -847906, - 1118974, - 32324614, - 7406442, - 12420155, - 1994844, - }, - }, - { - FieldElement{ - 14012521, - -5024720, - -18384453, - -9578469, - -26485342, - -3936439, - -13033478, - -10909803, - 24319929, - -6446333, - }, - FieldElement{ - 16412690, - -4507367, - 10772641, - 15929391, - -17068788, - -4658621, - 10555945, - -10484049, - -30102368, - -4739048, - }, - FieldElement{ - 22397382, - -7767684, - -9293161, - -12792868, - 17166287, - -9755136, - -27333065, - 6199366, - 21880021, - -12250760, - }, - }, - { - FieldElement{ - -4283307, - 5368523, - -31117018, - 8163389, - -30323063, - 3209128, - 16557151, - 8890729, - 8840445, - 4957760, - }, - FieldElement{ - -15447727, - 709327, - -6919446, - -10870178, - -29777922, - 6522332, - -21720181, - 12130072, - -14796503, - 5005757, - }, - FieldElement{ - -2114751, - -14308128, - 23019042, - 15765735, - -25269683, - 6002752, - 10183197, - -13239326, - -16395286, - -2176112, - }, - }, - }, - { - { - FieldElement{ - -19025756, - 1632005, - 13466291, - -7995100, - -23640451, - 16573537, - -32013908, - -3057104, - 22208662, - 2000468, - }, - FieldElement{ - 3065073, - -1412761, - -25598674, - -361432, - -17683065, - -5703415, - -8164212, - 11248527, - -3691214, - -7414184, - }, - FieldElement{ - 10379208, - -6045554, - 8877319, - 1473647, - -29291284, - -12507580, - 16690915, - 2553332, - -3132688, - 16400289, - }, - }, - { - FieldElement{ - 15716668, - 1254266, - -18472690, - 7446274, - -8448918, - 6344164, - -22097271, - -7285580, - 26894937, - 9132066, - }, - FieldElement{ - 24158887, - 12938817, - 11085297, - -8177598, - -28063478, - -4457083, - -30576463, - 64452, - -6817084, - -2692882, - }, - FieldElement{ - 13488534, - 7794716, - 22236231, - 5989356, - 25426474, - -12578208, - 2350710, - -3418511, - -4688006, - 2364226, - }, - }, - { - FieldElement{ - 16335052, - 9132434, - 25640582, - 6678888, - 1725628, - 8517937, - -11807024, - -11697457, - 15445875, - -7798101, - }, - FieldElement{ - 29004207, - -7867081, - 28661402, - -640412, - -12794003, - -7943086, - 31863255, - -4135540, - -278050, - -15759279, - }, - FieldElement{ - -6122061, - -14866665, - -28614905, - 14569919, - -10857999, - -3591829, - 10343412, - -6976290, - -29828287, - -10815811, - }, - }, - { - FieldElement{ - 27081650, - 3463984, - 14099042, - -4517604, - 1616303, - -6205604, - 29542636, - 15372179, - 17293797, - 960709, - }, - FieldElement{ - 20263915, - 11434237, - -5765435, - 11236810, - 13505955, - -10857102, - -16111345, - 6493122, - -19384511, - 7639714, - }, - FieldElement{ - -2830798, - -14839232, - 25403038, - -8215196, - -8317012, - -16173699, - 18006287, - -16043750, - 29994677, - -15808121, - }, - }, - { - FieldElement{ - 9769828, - 5202651, - -24157398, - -13631392, - -28051003, - -11561624, - -24613141, - -13860782, - -31184575, - 709464, - }, - FieldElement{ - 12286395, - 13076066, - -21775189, - -1176622, - -25003198, - 4057652, - -32018128, - -8890874, - 16102007, - 13205847, - }, - FieldElement{ - 13733362, - 5599946, - 10557076, - 3195751, - -5557991, - 8536970, - -25540170, - 8525972, - 10151379, - 10394400, - }, - }, - { - FieldElement{ - 4024660, - -16137551, - 22436262, - 12276534, - -9099015, - -2686099, - 19698229, - 11743039, - -33302334, - 8934414, - }, - FieldElement{ - -15879800, - -4525240, - -8580747, - -2934061, - 14634845, - -698278, - -9449077, - 3137094, - -11536886, - 11721158, - }, - FieldElement{ - 17555939, - -5013938, - 8268606, - 2331751, - -22738815, - 9761013, - 9319229, - 8835153, - -9205489, - -1280045, - }, - }, - { - FieldElement{ - -461409, - -7830014, - 20614118, - 16688288, - -7514766, - -4807119, - 22300304, - 505429, - 6108462, - -6183415, - }, - FieldElement{ - -5070281, - 12367917, - -30663534, - 3234473, - 32617080, - -8422642, - 29880583, - -13483331, - -26898490, - -7867459, - }, - FieldElement{ - -31975283, - 5726539, - 26934134, - 10237677, - -3173717, - -605053, - 24199304, - 3795095, - 7592688, - -14992079, - }, - }, - { - FieldElement{ - 21594432, - -14964228, - 17466408, - -4077222, - 32537084, - 2739898, - 6407723, - 12018833, - -28256052, - 4298412, - }, - FieldElement{ - -20650503, - -11961496, - -27236275, - 570498, - 3767144, - -1717540, - 13891942, - -1569194, - 13717174, - 10805743, - }, - FieldElement{ - -14676630, - -15644296, - 15287174, - 11927123, - 24177847, - -8175568, - -796431, - 14860609, - -26938930, - -5863836, - }, - }, - }, - { - { - FieldElement{ - 12962541, - 5311799, - -10060768, - 11658280, - 18855286, - -7954201, - 13286263, - -12808704, - -4381056, - 9882022, - }, - FieldElement{ - 18512079, - 11319350, - -20123124, - 15090309, - 18818594, - 5271736, - -22727904, - 3666879, - -23967430, - -3299429, - }, - FieldElement{ - -6789020, - -3146043, - 16192429, - 13241070, - 15898607, - -14206114, - -10084880, - -6661110, - -2403099, - 5276065, - }, - }, - { - FieldElement{ - 30169808, - -5317648, - 26306206, - -11750859, - 27814964, - 7069267, - 7152851, - 3684982, - 1449224, - 13082861, - }, - FieldElement{ - 10342826, - 3098505, - 2119311, - 193222, - 25702612, - 12233820, - 23697382, - 15056736, - -21016438, - -8202000, - }, - FieldElement{ - -33150110, - 3261608, - 22745853, - 7948688, - 19370557, - -15177665, - -26171976, - 6482814, - -10300080, - -11060101, - }, - }, - { - FieldElement{ - 32869458, - -5408545, - 25609743, - 15678670, - -10687769, - -15471071, - 26112421, - 2521008, - -22664288, - 6904815, - }, - FieldElement{ - 29506923, - 4457497, - 3377935, - -9796444, - -30510046, - 12935080, - 1561737, - 3841096, - -29003639, - -6657642, - }, - FieldElement{ - 10340844, - -6630377, - -18656632, - -2278430, - 12621151, - -13339055, - 30878497, - -11824370, - -25584551, - 5181966, - }, - }, - { - FieldElement{ - 25940115, - -12658025, - 17324188, - -10307374, - -8671468, - 15029094, - 24396252, - -16450922, - -2322852, - -12388574, - }, - FieldElement{ - -21765684, - 9916823, - -1300409, - 4079498, - -1028346, - 11909559, - 1782390, - 12641087, - 20603771, - -6561742, - }, - FieldElement{ - -18882287, - -11673380, - 24849422, - 11501709, - 13161720, - -4768874, - 1925523, - 11914390, - 4662781, - 7820689, - }, - }, - { - FieldElement{ - 12241050, - -425982, - 8132691, - 9393934, - 32846760, - -1599620, - 29749456, - 12172924, - 16136752, - 15264020, - }, - FieldElement{ - -10349955, - -14680563, - -8211979, - 2330220, - -17662549, - -14545780, - 10658213, - 6671822, - 19012087, - 3772772, - }, - FieldElement{ - 3753511, - -3421066, - 10617074, - 2028709, - 14841030, - -6721664, - 28718732, - -15762884, - 20527771, - 12988982, - }, - }, - { - FieldElement{ - -14822485, - -5797269, - -3707987, - 12689773, - -898983, - -10914866, - -24183046, - -10564943, - 3299665, - -12424953, - }, - FieldElement{ - -16777703, - -15253301, - -9642417, - 4978983, - 3308785, - 8755439, - 6943197, - 6461331, - -25583147, - 8991218, - }, - FieldElement{ - -17226263, - 1816362, - -1673288, - -6086439, - 31783888, - -8175991, - -32948145, - 7417950, - -30242287, - 1507265, - }, - }, - { - FieldElement{ - 29692663, - 6829891, - -10498800, - 4334896, - 20945975, - -11906496, - -28887608, - 8209391, - 14606362, - -10647073, - }, - FieldElement{ - -3481570, - 8707081, - 32188102, - 5672294, - 22096700, - 1711240, - -33020695, - 9761487, - 4170404, - -2085325, - }, - FieldElement{ - -11587470, - 14855945, - -4127778, - -1531857, - -26649089, - 15084046, - 22186522, - 16002000, - -14276837, - -8400798, - }, - }, - { - FieldElement{ - -4811456, - 13761029, - -31703877, - -2483919, - -3312471, - 7869047, - -7113572, - -9620092, - 13240845, - 10965870, - }, - FieldElement{ - -7742563, - -8256762, - -14768334, - -13656260, - -23232383, - 12387166, - 4498947, - 14147411, - 29514390, - 4302863, - }, - FieldElement{ - -13413405, - -12407859, - 20757302, - -13801832, - 14785143, - 8976368, - -5061276, - -2144373, - 17846988, - -13971927, - }, - }, - }, - { - { - FieldElement{ - -2244452, - -754728, - -4597030, - -1066309, - -6247172, - 1455299, - -21647728, - -9214789, - -5222701, - 12650267, - }, - FieldElement{ - -9906797, - -16070310, - 21134160, - 12198166, - -27064575, - 708126, - 387813, - 13770293, - -19134326, - 10958663, - }, - FieldElement{ - 22470984, - 12369526, - 23446014, - -5441109, - -21520802, - -9698723, - -11772496, - -11574455, - -25083830, - 4271862, - }, - }, - { - FieldElement{ - -25169565, - -10053642, - -19909332, - 15361595, - -5984358, - 2159192, - 75375, - -4278529, - -32526221, - 8469673, - }, - FieldElement{ - 15854970, - 4148314, - -8893890, - 7259002, - 11666551, - 13824734, - -30531198, - 2697372, - 24154791, - -9460943, - }, - FieldElement{ - 15446137, - -15806644, - 29759747, - 14019369, - 30811221, - -9610191, - -31582008, - 12840104, - 24913809, - 9815020, - }, - }, - { - FieldElement{ - -4709286, - -5614269, - -31841498, - -12288893, - -14443537, - 10799414, - -9103676, - 13438769, - 18735128, - 9466238, - }, - FieldElement{ - 11933045, - 9281483, - 5081055, - -5183824, - -2628162, - -4905629, - -7727821, - -10896103, - -22728655, - 16199064, - }, - FieldElement{ - 14576810, - 379472, - -26786533, - -8317236, - -29426508, - -10812974, - -102766, - 1876699, - 30801119, - 2164795, - }, - }, - { - FieldElement{ - 15995086, - 3199873, - 13672555, - 13712240, - -19378835, - -4647646, - -13081610, - -15496269, - -13492807, - 1268052, - }, - FieldElement{ - -10290614, - -3659039, - -3286592, - 10948818, - 23037027, - 3794475, - -3470338, - -12600221, - -17055369, - 3565904, - }, - FieldElement{ - 29210088, - -9419337, - -5919792, - -4952785, - 10834811, - -13327726, - -16512102, - -10820713, - -27162222, - -14030531, - }, - }, - { - FieldElement{ - -13161890, - 15508588, - 16663704, - -8156150, - -28349942, - 9019123, - -29183421, - -3769423, - 2244111, - -14001979, - }, - FieldElement{ - -5152875, - -3800936, - -9306475, - -6071583, - 16243069, - 14684434, - -25673088, - -16180800, - 13491506, - 4641841, - }, - FieldElement{ - 10813417, - 643330, - -19188515, - -728916, - 30292062, - -16600078, - 27548447, - -7721242, - 14476989, - -12767431, - }, - }, - { - FieldElement{ - 10292079, - 9984945, - 6481436, - 8279905, - -7251514, - 7032743, - 27282937, - -1644259, - -27912810, - 12651324, - }, - FieldElement{ - -31185513, - -813383, - 22271204, - 11835308, - 10201545, - 15351028, - 17099662, - 3988035, - 21721536, - -3148940, - }, - FieldElement{ - 10202177, - -6545839, - -31373232, - -9574638, - -32150642, - -8119683, - -12906320, - 3852694, - 13216206, - 14842320, - }, - }, - { - FieldElement{ - -15815640, - -10601066, - -6538952, - -7258995, - -6984659, - -6581778, - -31500847, - 13765824, - -27434397, - 9900184, - }, - FieldElement{ - 14465505, - -13833331, - -32133984, - -14738873, - -27443187, - 12990492, - 33046193, - 15796406, - -7051866, - -8040114, - }, - FieldElement{ - 30924417, - -8279620, - 6359016, - -12816335, - 16508377, - 9071735, - -25488601, - 15413635, - 9524356, - -7018878, - }, - }, - { - FieldElement{ - 12274201, - -13175547, - 32627641, - -1785326, - 6736625, - 13267305, - 5237659, - -5109483, - 15663516, - 4035784, - }, - FieldElement{ - -2951309, - 8903985, - 17349946, - 601635, - -16432815, - -4612556, - -13732739, - -15889334, - -22258478, - 4659091, - }, - FieldElement{ - -16916263, - -4952973, - -30393711, - -15158821, - 20774812, - 15897498, - 5736189, - 15026997, - -2178256, - -13455585, - }, - }, - }, - { - { - FieldElement{ - -8858980, - -2219056, - 28571666, - -10155518, - -474467, - -10105698, - -3801496, - 278095, - 23440562, - -290208, - }, - FieldElement{ - 10226241, - -5928702, - 15139956, - 120818, - -14867693, - 5218603, - 32937275, - 11551483, - -16571960, - -7442864, - }, - FieldElement{ - 17932739, - -12437276, - -24039557, - 10749060, - 11316803, - 7535897, - 22503767, - 5561594, - -3646624, - 3898661, - }, - }, - { - FieldElement{ - 7749907, - -969567, - -16339731, - -16464, - -25018111, - 15122143, - -1573531, - 7152530, - 21831162, - 1245233, - }, - FieldElement{ - 26958459, - -14658026, - 4314586, - 8346991, - -5677764, - 11960072, - -32589295, - -620035, - -30402091, - -16716212, - }, - FieldElement{ - -12165896, - 9166947, - 33491384, - 13673479, - 29787085, - 13096535, - 6280834, - 14587357, - -22338025, - 13987525, - }, - }, - { - FieldElement{ - -24349909, - 7778775, - 21116000, - 15572597, - -4833266, - -5357778, - -4300898, - -5124639, - -7469781, - -2858068, - }, - FieldElement{ - 9681908, - -6737123, - -31951644, - 13591838, - -6883821, - 386950, - 31622781, - 6439245, - -14581012, - 4091397, - }, - FieldElement{ - -8426427, - 1470727, - -28109679, - -1596990, - 3978627, - -5123623, - -19622683, - 12092163, - 29077877, - -14741988, - }, - }, - { - FieldElement{ - 5269168, - -6859726, - -13230211, - -8020715, - 25932563, - 1763552, - -5606110, - -5505881, - -20017847, - 2357889, - }, - FieldElement{ - 32264008, - -15407652, - -5387735, - -1160093, - -2091322, - -3946900, - 23104804, - -12869908, - 5727338, - 189038, - }, - FieldElement{ - 14609123, - -8954470, - -6000566, - -16622781, - -14577387, - -7743898, - -26745169, - 10942115, - -25888931, - -14884697, - }, - }, - { - FieldElement{ - 20513500, - 5557931, - -15604613, - 7829531, - 26413943, - -2019404, - -21378968, - 7471781, - 13913677, - -5137875, - }, - FieldElement{ - -25574376, - 11967826, - 29233242, - 12948236, - -6754465, - 4713227, - -8940970, - 14059180, - 12878652, - 8511905, - }, - FieldElement{ - -25656801, - 3393631, - -2955415, - -7075526, - -2250709, - 9366908, - -30223418, - 6812974, - 5568676, - -3127656, - }, - }, - { - FieldElement{ - 11630004, - 12144454, - 2116339, - 13606037, - 27378885, - 15676917, - -17408753, - -13504373, - -14395196, - 8070818, - }, - FieldElement{ - 27117696, - -10007378, - -31282771, - -5570088, - 1127282, - 12772488, - -29845906, - 10483306, - -11552749, - -1028714, - }, - FieldElement{ - 10637467, - -5688064, - 5674781, - 1072708, - -26343588, - -6982302, - -1683975, - 9177853, - -27493162, - 15431203, - }, - }, - { - FieldElement{ - 20525145, - 10892566, - -12742472, - 12779443, - -29493034, - 16150075, - -28240519, - 14943142, - -15056790, - -7935931, - }, - FieldElement{ - -30024462, - 5626926, - -551567, - -9981087, - 753598, - 11981191, - 25244767, - -3239766, - -3356550, - 9594024, - }, - FieldElement{ - -23752644, - 2636870, - -5163910, - -10103818, - 585134, - 7877383, - 11345683, - -6492290, - 13352335, - -10977084, - }, - }, - { - FieldElement{ - -1931799, - -5407458, - 3304649, - -12884869, - 17015806, - -4877091, - -29783850, - -7752482, - -13215537, - -319204, - }, - FieldElement{ - 20239939, - 6607058, - 6203985, - 3483793, - -18386976, - -779229, - -20723742, - 15077870, - -22750759, - 14523817, - }, - FieldElement{ - 27406042, - -6041657, - 27423596, - -4497394, - 4996214, - 10002360, - -28842031, - -4545494, - -30172742, - -4805667, - }, - }, - }, - { - { - FieldElement{ - 11374242, - 12660715, - 17861383, - -12540833, - 10935568, - 1099227, - -13886076, - -9091740, - -27727044, - 11358504, - }, - FieldElement{ - -12730809, - 10311867, - 1510375, - 10778093, - -2119455, - -9145702, - 32676003, - 11149336, - -26123651, - 4985768, - }, - FieldElement{ - -19096303, - 341147, - -6197485, - -239033, - 15756973, - -8796662, - -983043, - 13794114, - -19414307, - -15621255, - }, - }, - { - FieldElement{ - 6490081, - 11940286, - 25495923, - -7726360, - 8668373, - -8751316, - 3367603, - 6970005, - -1691065, - -9004790, - }, - FieldElement{ - 1656497, - 13457317, - 15370807, - 6364910, - 13605745, - 8362338, - -19174622, - -5475723, - -16796596, - -5031438, - }, - FieldElement{ - -22273315, - -13524424, - -64685, - -4334223, - -18605636, - -10921968, - -20571065, - -7007978, - -99853, - -10237333, - }, - }, - { - FieldElement{ - 17747465, - 10039260, - 19368299, - -4050591, - -20630635, - -16041286, - 31992683, - -15857976, - -29260363, - -5511971, - }, - FieldElement{ - 31932027, - -4986141, - -19612382, - 16366580, - 22023614, - 88450, - 11371999, - -3744247, - 4882242, - -10626905, - }, - FieldElement{ - 29796507, - 37186, - 19818052, - 10115756, - -11829032, - 3352736, - 18551198, - 3272828, - -5190932, - -4162409, - }, - }, - { - FieldElement{ - 12501286, - 4044383, - -8612957, - -13392385, - -32430052, - 5136599, - -19230378, - -3529697, - 330070, - -3659409, - }, - FieldElement{ - 6384877, - 2899513, - 17807477, - 7663917, - -2358888, - 12363165, - 25366522, - -8573892, - -271295, - 12071499, - }, - FieldElement{ - -8365515, - -4042521, - 25133448, - -4517355, - -6211027, - 2265927, - -32769618, - 1936675, - -5159697, - 3829363, - }, - }, - { - FieldElement{ - 28425966, - -5835433, - -577090, - -4697198, - -14217555, - 6870930, - 7921550, - -6567787, - 26333140, - 14267664, - }, - FieldElement{ - -11067219, - 11871231, - 27385719, - -10559544, - -4585914, - -11189312, - 10004786, - -8709488, - -21761224, - 8930324, - }, - FieldElement{ - -21197785, - -16396035, - 25654216, - -1725397, - 12282012, - 11008919, - 1541940, - 4757911, - -26491501, - -16408940, - }, - }, - { - FieldElement{ - 13537262, - -7759490, - -20604840, - 10961927, - -5922820, - -13218065, - -13156584, - 6217254, - -15943699, - 13814990, - }, - FieldElement{ - -17422573, - 15157790, - 18705543, - 29619, - 24409717, - -260476, - 27361681, - 9257833, - -1956526, - -1776914, - }, - FieldElement{ - -25045300, - -10191966, - 15366585, - 15166509, - -13105086, - 8423556, - -29171540, - 12361135, - -18685978, - 4578290, - }, - }, - { - FieldElement{ - 24579768, - 3711570, - 1342322, - -11180126, - -27005135, - 14124956, - -22544529, - 14074919, - 21964432, - 8235257, - }, - FieldElement{ - -6528613, - -2411497, - 9442966, - -5925588, - 12025640, - -1487420, - -2981514, - -1669206, - 13006806, - 2355433, - }, - FieldElement{ - -16304899, - -13605259, - -6632427, - -5142349, - 16974359, - -10911083, - 27202044, - 1719366, - 1141648, - -12796236, - }, - }, - { - FieldElement{ - -12863944, - -13219986, - -8318266, - -11018091, - -6810145, - -4843894, - 13475066, - -3133972, - 32674895, - 13715045, - }, - FieldElement{ - 11423335, - -5468059, - 32344216, - 8962751, - 24989809, - 9241752, - -13265253, - 16086212, - -28740881, - -15642093, - }, - FieldElement{ - -1409668, - 12530728, - -6368726, - 10847387, - 19531186, - -14132160, - -11709148, - 7791794, - -27245943, - 4383347, - }, - }, - }, - { - { - FieldElement{ - -28970898, - 5271447, - -1266009, - -9736989, - -12455236, - 16732599, - -4862407, - -4906449, - 27193557, - 6245191, - }, - FieldElement{ - -15193956, - 5362278, - -1783893, - 2695834, - 4960227, - 12840725, - 23061898, - 3260492, - 22510453, - 8577507, - }, - FieldElement{ - -12632451, - 11257346, - -32692994, - 13548177, - -721004, - 10879011, - 31168030, - 13952092, - -29571492, - -3635906, - }, - }, - { - FieldElement{ - 3877321, - -9572739, - 32416692, - 5405324, - -11004407, - -13656635, - 3759769, - 11935320, - 5611860, - 8164018, - }, - FieldElement{ - -16275802, - 14667797, - 15906460, - 12155291, - -22111149, - -9039718, - 32003002, - -8832289, - 5773085, - -8422109, - }, - FieldElement{ - -23788118, - -8254300, - 1950875, - 8937633, - 18686727, - 16459170, - -905725, - 12376320, - 31632953, - 190926, - }, - }, - { - FieldElement{ - -24593607, - -16138885, - -8423991, - 13378746, - 14162407, - 6901328, - -8288749, - 4508564, - -25341555, - -3627528, - }, - FieldElement{ - 8884438, - -5884009, - 6023974, - 10104341, - -6881569, - -4941533, - 18722941, - -14786005, - -1672488, - 827625, - }, - FieldElement{ - -32720583, - -16289296, - -32503547, - 7101210, - 13354605, - 2659080, - -1800575, - -14108036, - -24878478, - 1541286, - }, - }, - { - FieldElement{ - 2901347, - -1117687, - 3880376, - -10059388, - -17620940, - -3612781, - -21802117, - -3567481, - 20456845, - -1885033, - }, - FieldElement{ - 27019610, - 12299467, - -13658288, - -1603234, - -12861660, - -4861471, - -19540150, - -5016058, - 29439641, - 15138866, - }, - FieldElement{ - 21536104, - -6626420, - -32447818, - -10690208, - -22408077, - 5175814, - -5420040, - -16361163, - 7779328, - 109896, - }, - }, - { - FieldElement{ - 30279744, - 14648750, - -8044871, - 6425558, - 13639621, - -743509, - 28698390, - 12180118, - 23177719, - -554075, - }, - FieldElement{ - 26572847, - 3405927, - -31701700, - 12890905, - -19265668, - 5335866, - -6493768, - 2378492, - 4439158, - -13279347, - }, - FieldElement{ - -22716706, - 3489070, - -9225266, - -332753, - 18875722, - -1140095, - 14819434, - -12731527, - -17717757, - -5461437, - }, - }, - { - FieldElement{ - -5056483, - 16566551, - 15953661, - 3767752, - -10436499, - 15627060, - -820954, - 2177225, - 8550082, - -15114165, - }, - FieldElement{ - -18473302, - 16596775, - -381660, - 15663611, - 22860960, - 15585581, - -27844109, - -3582739, - -23260460, - -8428588, - }, - FieldElement{ - -32480551, - 15707275, - -8205912, - -5652081, - 29464558, - 2713815, - -22725137, - 15860482, - -21902570, - 1494193, - }, - }, - { - FieldElement{ - -19562091, - -14087393, - -25583872, - -9299552, - 13127842, - 759709, - 21923482, - 16529112, - 8742704, - 12967017, - }, - FieldElement{ - -28464899, - 1553205, - 32536856, - -10473729, - -24691605, - -406174, - -8914625, - -2933896, - -29903758, - 15553883, - }, - FieldElement{ - 21877909, - 3230008, - 9881174, - 10539357, - -4797115, - 2841332, - 11543572, - 14513274, - 19375923, - -12647961, - }, - }, - { - FieldElement{ - 8832269, - -14495485, - 13253511, - 5137575, - 5037871, - 4078777, - 24880818, - -6222716, - 2862653, - 9455043, - }, - FieldElement{ - 29306751, - 5123106, - 20245049, - -14149889, - 9592566, - 8447059, - -2077124, - -2990080, - 15511449, - 4789663, - }, - FieldElement{ - -20679756, - 7004547, - 8824831, - -9434977, - -4045704, - -3750736, - -5754762, - 108893, - 23513200, - 16652362, - }, - }, - }, - { - { - FieldElement{ - -33256173, - 4144782, - -4476029, - -6579123, - 10770039, - -7155542, - -6650416, - -12936300, - -18319198, - 10212860, - }, - FieldElement{ - 2756081, - 8598110, - 7383731, - -6859892, - 22312759, - -1105012, - 21179801, - 2600940, - -9988298, - -12506466, - }, - FieldElement{ - -24645692, - 13317462, - -30449259, - -15653928, - 21365574, - -10869657, - 11344424, - 864440, - -2499677, - -16710063, - }, - }, - { - FieldElement{ - -26432803, - 6148329, - -17184412, - -14474154, - 18782929, - -275997, - -22561534, - 211300, - 2719757, - 4940997, - }, - FieldElement{ - -1323882, - 3911313, - -6948744, - 14759765, - -30027150, - 7851207, - 21690126, - 8518463, - 26699843, - 5276295, - }, - FieldElement{ - -13149873, - -6429067, - 9396249, - 365013, - 24703301, - -10488939, - 1321586, - 149635, - -15452774, - 7159369, - }, - }, - { - FieldElement{ - 9987780, - -3404759, - 17507962, - 9505530, - 9731535, - -2165514, - 22356009, - 8312176, - 22477218, - -8403385, - }, - FieldElement{ - 18155857, - -16504990, - 19744716, - 9006923, - 15154154, - -10538976, - 24256460, - -4864995, - -22548173, - 9334109, - }, - FieldElement{ - 2986088, - -4911893, - 10776628, - -3473844, - 10620590, - -7083203, - -21413845, - 14253545, - -22587149, - 536906, - }, - }, - { - FieldElement{ - 4377756, - 8115836, - 24567078, - 15495314, - 11625074, - 13064599, - 7390551, - 10589625, - 10838060, - -15420424, - }, - FieldElement{ - -19342404, - 867880, - 9277171, - -3218459, - -14431572, - -1986443, - 19295826, - -15796950, - 6378260, - 699185, - }, - FieldElement{ - 7895026, - 4057113, - -7081772, - -13077756, - -17886831, - -323126, - -716039, - 15693155, - -5045064, - -13373962, - }, - }, - { - FieldElement{ - -7737563, - -5869402, - -14566319, - -7406919, - 11385654, - 13201616, - 31730678, - -10962840, - -3918636, - -9669325, - }, - FieldElement{ - 10188286, - -15770834, - -7336361, - 13427543, - 22223443, - 14896287, - 30743455, - 7116568, - -21786507, - 5427593, - }, - FieldElement{ - 696102, - 13206899, - 27047647, - -10632082, - 15285305, - -9853179, - 10798490, - -4578720, - 19236243, - 12477404, - }, - }, - { - FieldElement{ - -11229439, - 11243796, - -17054270, - -8040865, - -788228, - -8167967, - -3897669, - 11180504, - -23169516, - 7733644, - }, - FieldElement{ - 17800790, - -14036179, - -27000429, - -11766671, - 23887827, - 3149671, - 23466177, - -10538171, - 10322027, - 15313801, - }, - FieldElement{ - 26246234, - 11968874, - 32263343, - -5468728, - 6830755, - -13323031, - -15794704, - -101982, - -24449242, - 10890804, - }, - }, - { - FieldElement{ - -31365647, - 10271363, - -12660625, - -6267268, - 16690207, - -13062544, - -14982212, - 16484931, - 25180797, - -5334884, - }, - FieldElement{ - -586574, - 10376444, - -32586414, - -11286356, - 19801893, - 10997610, - 2276632, - 9482883, - 316878, - 13820577, - }, - FieldElement{ - -9882808, - -4510367, - -2115506, - 16457136, - -11100081, - 11674996, - 30756178, - -7515054, - 30696930, - -3712849, - }, - }, - { - FieldElement{ - 32988917, - -9603412, - 12499366, - 7910787, - -10617257, - -11931514, - -7342816, - -9985397, - -32349517, - 7392473, - }, - FieldElement{ - -8855661, - 15927861, - 9866406, - -3649411, - -2396914, - -16655781, - -30409476, - -9134995, - 25112947, - -2926644, - }, - FieldElement{ - -2504044, - -436966, - 25621774, - -5678772, - 15085042, - -5479877, - -24884878, - -13526194, - 5537438, - -13914319, - }, - }, - }, - { - { - FieldElement{ - -11225584, - 2320285, - -9584280, - 10149187, - -33444663, - 5808648, - -14876251, - -1729667, - 31234590, - 6090599, - }, - FieldElement{ - -9633316, - 116426, - 26083934, - 2897444, - -6364437, - -2688086, - 609721, - 15878753, - -6970405, - -9034768, - }, - FieldElement{ - -27757857, - 247744, - -15194774, - -9002551, - 23288161, - -10011936, - -23869595, - 6503646, - 20650474, - 1804084, - }, - }, - { - FieldElement{ - -27589786, - 15456424, - 8972517, - 8469608, - 15640622, - 4439847, - 3121995, - -10329713, - 27842616, - -202328, - }, - FieldElement{ - -15306973, - 2839644, - 22530074, - 10026331, - 4602058, - 5048462, - 28248656, - 5031932, - -11375082, - 12714369, - }, - FieldElement{ - 20807691, - -7270825, - 29286141, - 11421711, - -27876523, - -13868230, - -21227475, - 1035546, - -19733229, - 12796920, - }, - }, - { - FieldElement{ - 12076899, - -14301286, - -8785001, - -11848922, - -25012791, - 16400684, - -17591495, - -12899438, - 3480665, - -15182815, - }, - FieldElement{ - -32361549, - 5457597, - 28548107, - 7833186, - 7303070, - -11953545, - -24363064, - -15921875, - -33374054, - 2771025, - }, - FieldElement{ - -21389266, - 421932, - 26597266, - 6860826, - 22486084, - -6737172, - -17137485, - -4210226, - -24552282, - 15673397, - }, - }, - { - FieldElement{ - -20184622, - 2338216, - 19788685, - -9620956, - -4001265, - -8740893, - -20271184, - 4733254, - 3727144, - -12934448, - }, - FieldElement{ - 6120119, - 814863, - -11794402, - -622716, - 6812205, - -15747771, - 2019594, - 7975683, - 31123697, - -10958981, - }, - FieldElement{ - 30069250, - -11435332, - 30434654, - 2958439, - 18399564, - -976289, - 12296869, - 9204260, - -16432438, - 9648165, - }, - }, - { - FieldElement{ - 32705432, - -1550977, - 30705658, - 7451065, - -11805606, - 9631813, - 3305266, - 5248604, - -26008332, - -11377501, - }, - FieldElement{ - 17219865, - 2375039, - -31570947, - -5575615, - -19459679, - 9219903, - 294711, - 15298639, - 2662509, - -16297073, - }, - FieldElement{ - -1172927, - -7558695, - -4366770, - -4287744, - -21346413, - -8434326, - 32087529, - -1222777, - 32247248, - -14389861, - }, - }, - { - FieldElement{ - 14312628, - 1221556, - 17395390, - -8700143, - -4945741, - -8684635, - -28197744, - -9637817, - -16027623, - -13378845, - }, - FieldElement{ - -1428825, - -9678990, - -9235681, - 6549687, - -7383069, - -468664, - 23046502, - 9803137, - 17597934, - 2346211, - }, - FieldElement{ - 18510800, - 15337574, - 26171504, - 981392, - -22241552, - 7827556, - -23491134, - -11323352, - 3059833, - -11782870, - }, - }, - { - FieldElement{ - 10141598, - 6082907, - 17829293, - -1947643, - 9830092, - 13613136, - -25556636, - -5544586, - -33502212, - 3592096, - }, - FieldElement{ - 33114168, - -15889352, - -26525686, - -13343397, - 33076705, - 8716171, - 1151462, - 1521897, - -982665, - -6837803, - }, - FieldElement{ - -32939165, - -4255815, - 23947181, - -324178, - -33072974, - -12305637, - -16637686, - 3891704, - 26353178, - 693168, - }, - }, - { - FieldElement{ - 30374239, - 1595580, - -16884039, - 13186931, - 4600344, - 406904, - 9585294, - -400668, - 31375464, - 14369965, - }, - FieldElement{ - -14370654, - -7772529, - 1510301, - 6434173, - -18784789, - -6262728, - 32732230, - -13108839, - 17901441, - 16011505, - }, - FieldElement{ - 18171223, - -11934626, - -12500402, - 15197122, - -11038147, - -15230035, - -19172240, - -16046376, - 8764035, - 12309598, - }, - }, - }, - { - { - FieldElement{ - 5975908, - -5243188, - -19459362, - -9681747, - -11541277, - 14015782, - -23665757, - 1228319, - 17544096, - -10593782, - }, - FieldElement{ - 5811932, - -1715293, - 3442887, - -2269310, - -18367348, - -8359541, - -18044043, - -15410127, - -5565381, - 12348900, - }, - FieldElement{ - -31399660, - 11407555, - 25755363, - 6891399, - -3256938, - 14872274, - -24849353, - 8141295, - -10632534, - -585479, - }, - }, - { - FieldElement{ - -12675304, - 694026, - -5076145, - 13300344, - 14015258, - -14451394, - -9698672, - -11329050, - 30944593, - 1130208, - }, - FieldElement{ - 8247766, - -6710942, - -26562381, - -7709309, - -14401939, - -14648910, - 4652152, - 2488540, - 23550156, - -271232, - }, - FieldElement{ - 17294316, - -3788438, - 7026748, - 15626851, - 22990044, - 113481, - 2267737, - -5908146, - -408818, - -137719, - }, - }, - { - FieldElement{ - 16091085, - -16253926, - 18599252, - 7340678, - 2137637, - -1221657, - -3364161, - 14550936, - 3260525, - -7166271, - }, - FieldElement{ - -4910104, - -13332887, - 18550887, - 10864893, - -16459325, - -7291596, - -23028869, - -13204905, - -12748722, - 2701326, - }, - FieldElement{ - -8574695, - 16099415, - 4629974, - -16340524, - -20786213, - -6005432, - -10018363, - 9276971, - 11329923, - 1862132, - }, - }, - { - FieldElement{ - 14763076, - -15903608, - -30918270, - 3689867, - 3511892, - 10313526, - -21951088, - 12219231, - -9037963, - -940300, - }, - FieldElement{ - 8894987, - -3446094, - 6150753, - 3013931, - 301220, - 15693451, - -31981216, - -2909717, - -15438168, - 11595570, - }, - FieldElement{ - 15214962, - 3537601, - -26238722, - -14058872, - 4418657, - -15230761, - 13947276, - 10730794, - -13489462, - -4363670, - }, - }, - { - FieldElement{ - -2538306, - 7682793, - 32759013, - 263109, - -29984731, - -7955452, - -22332124, - -10188635, - 977108, - 699994, - }, - FieldElement{ - -12466472, - 4195084, - -9211532, - 550904, - -15565337, - 12917920, - 19118110, - -439841, - -30534533, - -14337913, - }, - FieldElement{ - 31788461, - -14507657, - 4799989, - 7372237, - 8808585, - -14747943, - 9408237, - -10051775, - 12493932, - -5409317, - }, - }, - { - FieldElement{ - -25680606, - 5260744, - -19235809, - -6284470, - -3695942, - 16566087, - 27218280, - 2607121, - 29375955, - 6024730, - }, - FieldElement{ - 842132, - -2794693, - -4763381, - -8722815, - 26332018, - -12405641, - 11831880, - 6985184, - -9940361, - 2854096, - }, - FieldElement{ - -4847262, - -7969331, - 2516242, - -5847713, - 9695691, - -7221186, - 16512645, - 960770, - 12121869, - 16648078, - }, - }, - { - FieldElement{ - -15218652, - 14667096, - -13336229, - 2013717, - 30598287, - -464137, - -31504922, - -7882064, - 20237806, - 2838411, - }, - FieldElement{ - -19288047, - 4453152, - 15298546, - -16178388, - 22115043, - -15972604, - 12544294, - -13470457, - 1068881, - -12499905, - }, - FieldElement{ - -9558883, - -16518835, - 33238498, - 13506958, - 30505848, - -1114596, - -8486907, - -2630053, - 12521378, - 4845654, - }, - }, - { - FieldElement{ - -28198521, - 10744108, - -2958380, - 10199664, - 7759311, - -13088600, - 3409348, - -873400, - -6482306, - -12885870, - }, - FieldElement{ - -23561822, - 6230156, - -20382013, - 10655314, - -24040585, - -11621172, - 10477734, - -1240216, - -3113227, - 13974498, - }, - FieldElement{ - 12966261, - 15550616, - -32038948, - -1615346, - 21025980, - -629444, - 5642325, - 7188737, - 18895762, - 12629579, - }, - }, - }, - { - { - FieldElement{ - 14741879, - -14946887, - 22177208, - -11721237, - 1279741, - 8058600, - 11758140, - 789443, - 32195181, - 3895677, - }, - FieldElement{ - 10758205, - 15755439, - -4509950, - 9243698, - -4879422, - 6879879, - -2204575, - -3566119, - -8982069, - 4429647, - }, - FieldElement{ - -2453894, - 15725973, - -20436342, - -10410672, - -5803908, - -11040220, - -7135870, - -11642895, - 18047436, - -15281743, - }, - }, - { - FieldElement{ - -25173001, - -11307165, - 29759956, - 11776784, - -22262383, - -15820455, - 10993114, - -12850837, - -17620701, - -9408468, - }, - FieldElement{ - 21987233, - 700364, - -24505048, - 14972008, - -7774265, - -5718395, - 32155026, - 2581431, - -29958985, - 8773375, - }, - FieldElement{ - -25568350, - 454463, - -13211935, - 16126715, - 25240068, - 8594567, - 20656846, - 12017935, - -7874389, - -13920155, - }, - }, - { - FieldElement{ - 6028182, - 6263078, - -31011806, - -11301710, - -818919, - 2461772, - -31841174, - -5468042, - -1721788, - -2776725, - }, - FieldElement{ - -12278994, - 16624277, - 987579, - -5922598, - 32908203, - 1248608, - 7719845, - -4166698, - 28408820, - 6816612, - }, - FieldElement{ - -10358094, - -8237829, - 19549651, - -12169222, - 22082623, - 16147817, - 20613181, - 13982702, - -10339570, - 5067943, - }, - }, - { - FieldElement{ - -30505967, - -3821767, - 12074681, - 13582412, - -19877972, - 2443951, - -19719286, - 12746132, - 5331210, - -10105944, - }, - FieldElement{ - 30528811, - 3601899, - -1957090, - 4619785, - -27361822, - -15436388, - 24180793, - -12570394, - 27679908, - -1648928, - }, - FieldElement{ - 9402404, - -13957065, - 32834043, - 10838634, - -26580150, - -13237195, - 26653274, - -8685565, - 22611444, - -12715406, - }, - }, - { - FieldElement{ - 22190590, - 1118029, - 22736441, - 15130463, - -30460692, - -5991321, - 19189625, - -4648942, - 4854859, - 6622139, - }, - FieldElement{ - -8310738, - -2953450, - -8262579, - -3388049, - -10401731, - -271929, - 13424426, - -3567227, - 26404409, - 13001963, - }, - FieldElement{ - -31241838, - -15415700, - -2994250, - 8939346, - 11562230, - -12840670, - -26064365, - -11621720, - -15405155, - 11020693, - }, - }, - { - FieldElement{ - 1866042, - -7949489, - -7898649, - -10301010, - 12483315, - 13477547, - 3175636, - -12424163, - 28761762, - 1406734, - }, - FieldElement{ - -448555, - -1777666, - 13018551, - 3194501, - -9580420, - -11161737, - 24760585, - -4347088, - 25577411, - -13378680, - }, - FieldElement{ - -24290378, - 4759345, - -690653, - -1852816, - 2066747, - 10693769, - -29595790, - 9884936, - -9368926, - 4745410, - }, - }, - { - FieldElement{ - -9141284, - 6049714, - -19531061, - -4341411, - -31260798, - 9944276, - -15462008, - -11311852, - 10931924, - -11931931, - }, - FieldElement{ - -16561513, - 14112680, - -8012645, - 4817318, - -8040464, - -11414606, - -22853429, - 10856641, - -20470770, - 13434654, - }, - FieldElement{ - 22759489, - -10073434, - -16766264, - -1871422, - 13637442, - -10168091, - 1765144, - -12654326, - 28445307, - -5364710, - }, - }, - { - FieldElement{ - 29875063, - 12493613, - 2795536, - -3786330, - 1710620, - 15181182, - -10195717, - -8788675, - 9074234, - 1167180, - }, - FieldElement{ - -26205683, - 11014233, - -9842651, - -2635485, - -26908120, - 7532294, - -18716888, - -9535498, - 3843903, - 9367684, - }, - FieldElement{ - -10969595, - -6403711, - 9591134, - 9582310, - 11349256, - 108879, - 16235123, - 8601684, - -139197, - 4242895, - }, - }, - }, - { - { - FieldElement{ - 22092954, - -13191123, - -2042793, - -11968512, - 32186753, - -11517388, - -6574341, - 2470660, - -27417366, - 16625501, - }, - FieldElement{ - -11057722, - 3042016, - 13770083, - -9257922, - 584236, - -544855, - -7770857, - 2602725, - -27351616, - 14247413, - }, - FieldElement{ - 6314175, - -10264892, - -32772502, - 15957557, - -10157730, - 168750, - -8618807, - 14290061, - 27108877, - -1180880, - }, - }, - { - FieldElement{ - -8586597, - -7170966, - 13241782, - 10960156, - -32991015, - -13794596, - 33547976, - -11058889, - -27148451, - 981874, - }, - FieldElement{ - 22833440, - 9293594, - -32649448, - -13618667, - -9136966, - 14756819, - -22928859, - -13970780, - -10479804, - -16197962, - }, - FieldElement{ - -7768587, - 3326786, - -28111797, - 10783824, - 19178761, - 14905060, - 22680049, - 13906969, - -15933690, - 3797899, - }, - }, - { - FieldElement{ - 21721356, - -4212746, - -12206123, - 9310182, - -3882239, - -13653110, - 23740224, - -2709232, - 20491983, - -8042152, - }, - FieldElement{ - 9209270, - -15135055, - -13256557, - -6167798, - -731016, - 15289673, - 25947805, - 15286587, - 30997318, - -6703063, - }, - FieldElement{ - 7392032, - 16618386, - 23946583, - -8039892, - -13265164, - -1533858, - -14197445, - -2321576, - 17649998, - -250080, - }, - }, - { - FieldElement{ - -9301088, - -14193827, - 30609526, - -3049543, - -25175069, - -1283752, - -15241566, - -9525724, - -2233253, - 7662146, - }, - FieldElement{ - -17558673, - 1763594, - -33114336, - 15908610, - -30040870, - -12174295, - 7335080, - -8472199, - -3174674, - 3440183, - }, - FieldElement{ - -19889700, - -5977008, - -24111293, - -9688870, - 10799743, - -16571957, - 40450, - -4431835, - 4862400, - 1133, - }, - }, - { - FieldElement{ - -32856209, - -7873957, - -5422389, - 14860950, - -16319031, - 7956142, - 7258061, - 311861, - -30594991, - -7379421, - }, - FieldElement{ - -3773428, - -1565936, - 28985340, - 7499440, - 24445838, - 9325937, - 29727763, - 16527196, - 18278453, - 15405622, - }, - FieldElement{ - -4381906, - 8508652, - -19898366, - -3674424, - -5984453, - 15149970, - -13313598, - 843523, - -21875062, - 13626197, - }, - }, - { - FieldElement{ - 2281448, - -13487055, - -10915418, - -2609910, - 1879358, - 16164207, - -10783882, - 3953792, - 13340839, - 15928663, - }, - FieldElement{ - 31727126, - -7179855, - -18437503, - -8283652, - 2875793, - -16390330, - -25269894, - -7014826, - -23452306, - 5964753, - }, - FieldElement{ - 4100420, - -5959452, - -17179337, - 6017714, - -18705837, - 12227141, - -26684835, - 11344144, - 2538215, - -7570755, - }, - }, - { - FieldElement{ - -9433605, - 6123113, - 11159803, - -2156608, - 30016280, - 14966241, - -20474983, - 1485421, - -629256, - -15958862, - }, - FieldElement{ - -26804558, - 4260919, - 11851389, - 9658551, - -32017107, - 16367492, - -20205425, - -13191288, - 11659922, - -11115118, - }, - FieldElement{ - 26180396, - 10015009, - -30844224, - -8581293, - 5418197, - 9480663, - 2231568, - -10170080, - 33100372, - -1306171, - }, - }, - { - FieldElement{ - 15121113, - -5201871, - -10389905, - 15427821, - -27509937, - -15992507, - 21670947, - 4486675, - -5931810, - -14466380, - }, - FieldElement{ - 16166486, - -9483733, - -11104130, - 6023908, - -31926798, - -1364923, - 2340060, - -16254968, - -10735770, - -10039824, - }, - FieldElement{ - 28042865, - -3557089, - -12126526, - 12259706, - -3717498, - -6945899, - 6766453, - -8689599, - 18036436, - 5803270, - }, - }, - }, - { - { - FieldElement{ - -817581, - 6763912, - 11803561, - 1585585, - 10958447, - -2671165, - 23855391, - 4598332, - -6159431, - -14117438, - }, - FieldElement{ - -31031306, - -14256194, - 17332029, - -2383520, - 31312682, - -5967183, - 696309, - 50292, - -20095739, - 11763584, - }, - FieldElement{ - -594563, - -2514283, - -32234153, - 12643980, - 12650761, - 14811489, - 665117, - -12613632, - -19773211, - -10713562, - }, - }, - { - FieldElement{ - 30464590, - -11262872, - -4127476, - -12734478, - 19835327, - -7105613, - -24396175, - 2075773, - -17020157, - 992471, - }, - FieldElement{ - 18357185, - -6994433, - 7766382, - 16342475, - -29324918, - 411174, - 14578841, - 8080033, - -11574335, - -10601610, - }, - FieldElement{ - 19598397, - 10334610, - 12555054, - 2555664, - 18821899, - -10339780, - 21873263, - 16014234, - 26224780, - 16452269, - }, - }, - { - FieldElement{ - -30223925, - 5145196, - 5944548, - 16385966, - 3976735, - 2009897, - -11377804, - -7618186, - -20533829, - 3698650, - }, - FieldElement{ - 14187449, - 3448569, - -10636236, - -10810935, - -22663880, - -3433596, - 7268410, - -10890444, - 27394301, - 12015369, - }, - FieldElement{ - 19695761, - 16087646, - 28032085, - 12999827, - 6817792, - 11427614, - 20244189, - -1312777, - -13259127, - -3402461, - }, - }, - { - FieldElement{ - 30860103, - 12735208, - -1888245, - -4699734, - -16974906, - 2256940, - -8166013, - 12298312, - -8550524, - -10393462, - }, - FieldElement{ - -5719826, - -11245325, - -1910649, - 15569035, - 26642876, - -7587760, - -5789354, - -15118654, - -4976164, - 12651793, - }, - FieldElement{ - -2848395, - 9953421, - 11531313, - -5282879, - 26895123, - -12697089, - -13118820, - -16517902, - 9768698, - -2533218, - }, - }, - { - FieldElement{ - -24719459, - 1894651, - -287698, - -4704085, - 15348719, - -8156530, - 32767513, - 12765450, - 4940095, - 10678226, - }, - FieldElement{ - 18860224, - 15980149, - -18987240, - -1562570, - -26233012, - -11071856, - -7843882, - 13944024, - -24372348, - 16582019, - }, - FieldElement{ - -15504260, - 4970268, - -29893044, - 4175593, - -20993212, - -2199756, - -11704054, - 15444560, - -11003761, - 7989037, - }, - }, - { - FieldElement{ - 31490452, - 5568061, - -2412803, - 2182383, - -32336847, - 4531686, - -32078269, - 6200206, - -19686113, - -14800171, - }, - FieldElement{ - -17308668, - -15879940, - -31522777, - -2831, - -32887382, - 16375549, - 8680158, - -16371713, - 28550068, - -6857132, - }, - FieldElement{ - -28126887, - -5688091, - 16837845, - -1820458, - -6850681, - 12700016, - -30039981, - 4364038, - 1155602, - 5988841, - }, - }, - { - FieldElement{ - 21890435, - -13272907, - -12624011, - 12154349, - -7831873, - 15300496, - 23148983, - -4470481, - 24618407, - 8283181, - }, - FieldElement{ - -33136107, - -10512751, - 9975416, - 6841041, - -31559793, - 16356536, - 3070187, - -7025928, - 1466169, - 10740210, - }, - FieldElement{ - -1509399, - -15488185, - -13503385, - -10655916, - 32799044, - 909394, - -13938903, - -5779719, - -32164649, - -15327040, - }, - }, - { - FieldElement{ - 3960823, - -14267803, - -28026090, - -15918051, - -19404858, - 13146868, - 15567327, - 951507, - -3260321, - -573935, - }, - FieldElement{ - 24740841, - 5052253, - -30094131, - 8961361, - 25877428, - 6165135, - -24368180, - 14397372, - -7380369, - -6144105, - }, - FieldElement{ - -28888365, - 3510803, - -28103278, - -1158478, - -11238128, - -10631454, - -15441463, - -14453128, - -1625486, - -6494814, - }, - }, - }, - { - { - FieldElement{ - 793299, - -9230478, - 8836302, - -6235707, - -27360908, - -2369593, - 33152843, - -4885251, - -9906200, - -621852, - }, - FieldElement{ - 5666233, - 525582, - 20782575, - -8038419, - -24538499, - 14657740, - 16099374, - 1468826, - -6171428, - -15186581, - }, - FieldElement{ - -4859255, - -3779343, - -2917758, - -6748019, - 7778750, - 11688288, - -30404353, - -9871238, - -1558923, - -9863646, - }, - }, - { - FieldElement{ - 10896332, - -7719704, - 824275, - 472601, - -19460308, - 3009587, - 25248958, - 14783338, - -30581476, - -15757844, - }, - FieldElement{ - 10566929, - 12612572, - -31944212, - 11118703, - -12633376, - 12362879, - 21752402, - 8822496, - 24003793, - 14264025, - }, - FieldElement{ - 27713862, - -7355973, - -11008240, - 9227530, - 27050101, - 2504721, - 23886875, - -13117525, - 13958495, - -5732453, - }, - }, - { - FieldElement{ - -23481610, - 4867226, - -27247128, - 3900521, - 29838369, - -8212291, - -31889399, - -10041781, - 7340521, - -15410068, - }, - FieldElement{ - 4646514, - -8011124, - -22766023, - -11532654, - 23184553, - 8566613, - 31366726, - -1381061, - -15066784, - -10375192, - }, - FieldElement{ - -17270517, - 12723032, - -16993061, - 14878794, - 21619651, - -6197576, - 27584817, - 3093888, - -8843694, - 3849921, - }, - }, - { - FieldElement{ - -9064912, - 2103172, - 25561640, - -15125738, - -5239824, - 9582958, - 32477045, - -9017955, - 5002294, - -15550259, - }, - FieldElement{ - -12057553, - -11177906, - 21115585, - -13365155, - 8808712, - -12030708, - 16489530, - 13378448, - -25845716, - 12741426, - }, - FieldElement{ - -5946367, - 10645103, - -30911586, - 15390284, - -3286982, - -7118677, - 24306472, - 15852464, - 28834118, - -7646072, - }, - }, - { - FieldElement{ - -17335748, - -9107057, - -24531279, - 9434953, - -8472084, - -583362, - -13090771, - 455841, - 20461858, - 5491305, - }, - FieldElement{ - 13669248, - -16095482, - -12481974, - -10203039, - -14569770, - -11893198, - -24995986, - 11293807, - -28588204, - -9421832, - }, - FieldElement{ - 28497928, - 6272777, - -33022994, - 14470570, - 8906179, - -1225630, - 18504674, - -14165166, - 29867745, - -8795943, - }, - }, - { - FieldElement{ - -16207023, - 13517196, - -27799630, - -13697798, - 24009064, - -6373891, - -6367600, - -13175392, - 22853429, - -4012011, - }, - FieldElement{ - 24191378, - 16712145, - -13931797, - 15217831, - 14542237, - 1646131, - 18603514, - -11037887, - 12876623, - -2112447, - }, - FieldElement{ - 17902668, - 4518229, - -411702, - -2829247, - 26878217, - 5258055, - -12860753, - 608397, - 16031844, - 3723494, - }, - }, - { - FieldElement{ - -28632773, - 12763728, - -20446446, - 7577504, - 33001348, - -13017745, - 17558842, - -7872890, - 23896954, - -4314245, - }, - FieldElement{ - -20005381, - -12011952, - 31520464, - 605201, - 2543521, - 5991821, - -2945064, - 7229064, - -9919646, - -8826859, - }, - FieldElement{ - 28816045, - 298879, - -28165016, - -15920938, - 19000928, - -1665890, - -12680833, - -2949325, - -18051778, - -2082915, - }, - }, - { - FieldElement{ - 16000882, - -344896, - 3493092, - -11447198, - -29504595, - -13159789, - 12577740, - 16041268, - -19715240, - 7847707, - }, - FieldElement{ - 10151868, - 10572098, - 27312476, - 7922682, - 14825339, - 4723128, - -32855931, - -6519018, - -10020567, - 3852848, - }, - FieldElement{ - -11430470, - 15697596, - -21121557, - -4420647, - 5386314, - 15063598, - 16514493, - -15932110, - 29330899, - -15076224, - }, - }, - }, - { - { - FieldElement{ - -25499735, - -4378794, - -15222908, - -6901211, - 16615731, - 2051784, - 3303702, - 15490, - -27548796, - 12314391, - }, - FieldElement{ - 15683520, - -6003043, - 18109120, - -9980648, - 15337968, - -5997823, - -16717435, - 15921866, - 16103996, - -3731215, - }, - FieldElement{ - -23169824, - -10781249, - 13588192, - -1628807, - -3798557, - -1074929, - -19273607, - 5402699, - -29815713, - -9841101, - }, - }, - { - FieldElement{ - 23190676, - 2384583, - -32714340, - 3462154, - -29903655, - -1529132, - -11266856, - 8911517, - -25205859, - 2739713, - }, - FieldElement{ - 21374101, - -3554250, - -33524649, - 9874411, - 15377179, - 11831242, - -33529904, - 6134907, - 4931255, - 11987849, - }, - FieldElement{ - -7732, - -2978858, - -16223486, - 7277597, - 105524, - -322051, - -31480539, - 13861388, - -30076310, - 10117930, - }, - }, - { - FieldElement{ - -29501170, - -10744872, - -26163768, - 13051539, - -25625564, - 5089643, - -6325503, - 6704079, - 12890019, - 15728940, - }, - FieldElement{ - -21972360, - -11771379, - -951059, - -4418840, - 14704840, - 2695116, - 903376, - -10428139, - 12885167, - 8311031, - }, - FieldElement{ - -17516482, - 5352194, - 10384213, - -13811658, - 7506451, - 13453191, - 26423267, - 4384730, - 1888765, - -5435404, - }, - }, - { - FieldElement{ - -25817338, - -3107312, - -13494599, - -3182506, - 30896459, - -13921729, - -32251644, - -12707869, - -19464434, - -3340243, - }, - FieldElement{ - -23607977, - -2665774, - -526091, - 4651136, - 5765089, - 4618330, - 6092245, - 14845197, - 17151279, - -9854116, - }, - FieldElement{ - -24830458, - -12733720, - -15165978, - 10367250, - -29530908, - -265356, - 22825805, - -7087279, - -16866484, - 16176525, - }, - }, - { - FieldElement{ - -23583256, - 6564961, - 20063689, - 3798228, - -4740178, - 7359225, - 2006182, - -10363426, - -28746253, - -10197509, - }, - FieldElement{ - -10626600, - -4486402, - -13320562, - -5125317, - 3432136, - -6393229, - 23632037, - -1940610, - 32808310, - 1099883, - }, - FieldElement{ - 15030977, - 5768825, - -27451236, - -2887299, - -6427378, - -15361371, - -15277896, - -6809350, - 2051441, - -15225865, - }, - }, - { - FieldElement{ - -3362323, - -7239372, - 7517890, - 9824992, - 23555850, - 295369, - 5148398, - -14154188, - -22686354, - 16633660, - }, - FieldElement{ - 4577086, - -16752288, - 13249841, - -15304328, - 19958763, - -14537274, - 18559670, - -10759549, - 8402478, - -9864273, - }, - FieldElement{ - -28406330, - -1051581, - -26790155, - -907698, - -17212414, - -11030789, - 9453451, - -14980072, - 17983010, - 9967138, - }, - }, - { - FieldElement{ - -25762494, - 6524722, - 26585488, - 9969270, - 24709298, - 1220360, - -1677990, - 7806337, - 17507396, - 3651560, - }, - FieldElement{ - -10420457, - -4118111, - 14584639, - 15971087, - -15768321, - 8861010, - 26556809, - -5574557, - -18553322, - -11357135, - }, - FieldElement{ - 2839101, - 14284142, - 4029895, - 3472686, - 14402957, - 12689363, - -26642121, - 8459447, - -5605463, - -7621941, - }, - }, - { - FieldElement{ - -4839289, - -3535444, - 9744961, - 2871048, - 25113978, - 3187018, - -25110813, - -849066, - 17258084, - -7977739, - }, - FieldElement{ - 18164541, - -10595176, - -17154882, - -1542417, - 19237078, - -9745295, - 23357533, - -15217008, - 26908270, - 12150756, - }, - FieldElement{ - -30264870, - -7647865, - 5112249, - -7036672, - -1499807, - -6974257, - 43168, - -5537701, - -32302074, - 16215819, - }, - }, - }, - { - { - FieldElement{ - -6898905, - 9824394, - -12304779, - -4401089, - -31397141, - -6276835, - 32574489, - 12532905, - -7503072, - -8675347, - }, - FieldElement{ - -27343522, - -16515468, - -27151524, - -10722951, - 946346, - 16291093, - 254968, - 7168080, - 21676107, - -1943028, - }, - FieldElement{ - 21260961, - -8424752, - -16831886, - -11920822, - -23677961, - 3968121, - -3651949, - -6215466, - -3556191, - -7913075, - }, - }, - { - FieldElement{ - 16544754, - 13250366, - -16804428, - 15546242, - -4583003, - 12757258, - -2462308, - -8680336, - -18907032, - -9662799, - }, - FieldElement{ - -2415239, - -15577728, - 18312303, - 4964443, - -15272530, - -12653564, - 26820651, - 16690659, - 25459437, - -4564609, - }, - FieldElement{ - -25144690, - 11425020, - 28423002, - -11020557, - -6144921, - -15826224, - 9142795, - -2391602, - -6432418, - -1644817, - }, - }, - { - FieldElement{ - -23104652, - 6253476, - 16964147, - -3768872, - -25113972, - -12296437, - -27457225, - -16344658, - 6335692, - 7249989, - }, - FieldElement{ - -30333227, - 13979675, - 7503222, - -12368314, - -11956721, - -4621693, - -30272269, - 2682242, - 25993170, - -12478523, - }, - FieldElement{ - 4364628, - 5930691, - 32304656, - -10044554, - -8054781, - 15091131, - 22857016, - -10598955, - 31820368, - 15075278, - }, - }, - { - FieldElement{ - 31879134, - -8918693, - 17258761, - 90626, - -8041836, - -4917709, - 24162788, - -9650886, - -17970238, - 12833045, - }, - FieldElement{ - 19073683, - 14851414, - -24403169, - -11860168, - 7625278, - 11091125, - -19619190, - 2074449, - -9413939, - 14905377, - }, - FieldElement{ - 24483667, - -11935567, - -2518866, - -11547418, - -1553130, - 15355506, - -25282080, - 9253129, - 27628530, - -7555480, - }, - }, - { - FieldElement{ - 17597607, - 8340603, - 19355617, - 552187, - 26198470, - -3176583, - 4593324, - -9157582, - -14110875, - 15297016, - }, - FieldElement{ - 510886, - 14337390, - -31785257, - 16638632, - 6328095, - 2713355, - -20217417, - -11864220, - 8683221, - 2921426, - }, - FieldElement{ - 18606791, - 11874196, - 27155355, - -5281482, - -24031742, - 6265446, - -25178240, - -1278924, - 4674690, - 13890525, - }, - }, - { - FieldElement{ - 13609624, - 13069022, - -27372361, - -13055908, - 24360586, - 9592974, - 14977157, - 9835105, - 4389687, - 288396, - }, - FieldElement{ - 9922506, - -519394, - 13613107, - 5883594, - -18758345, - -434263, - -12304062, - 8317628, - 23388070, - 16052080, - }, - FieldElement{ - 12720016, - 11937594, - -31970060, - -5028689, - 26900120, - 8561328, - -20155687, - -11632979, - -14754271, - -10812892, - }, - }, - { - FieldElement{ - 15961858, - 14150409, - 26716931, - -665832, - -22794328, - 13603569, - 11829573, - 7467844, - -28822128, - 929275, - }, - FieldElement{ - 11038231, - -11582396, - -27310482, - -7316562, - -10498527, - -16307831, - -23479533, - -9371869, - -21393143, - 2465074, - }, - FieldElement{ - 20017163, - -4323226, - 27915242, - 1529148, - 12396362, - 15675764, - 13817261, - -9658066, - 2463391, - -4622140, - }, - }, - { - FieldElement{ - -16358878, - -12663911, - -12065183, - 4996454, - -1256422, - 1073572, - 9583558, - 12851107, - 4003896, - 12673717, - }, - FieldElement{ - -1731589, - -15155870, - -3262930, - 16143082, - 19294135, - 13385325, - 14741514, - -9103726, - 7903886, - 2348101, - }, - FieldElement{ - 24536016, - -16515207, - 12715592, - -3862155, - 1511293, - 10047386, - -3842346, - -7129159, - -28377538, - 10048127, - }, - }, - }, - { - { - FieldElement{ - -12622226, - -6204820, - 30718825, - 2591312, - -10617028, - 12192840, - 18873298, - -7297090, - -32297756, - 15221632, - }, - FieldElement{ - -26478122, - -11103864, - 11546244, - -1852483, - 9180880, - 7656409, - -21343950, - 2095755, - 29769758, - 6593415, - }, - FieldElement{ - -31994208, - -2907461, - 4176912, - 3264766, - 12538965, - -868111, - 26312345, - -6118678, - 30958054, - 8292160, - }, - }, - { - FieldElement{ - 31429822, - -13959116, - 29173532, - 15632448, - 12174511, - -2760094, - 32808831, - 3977186, - 26143136, - -3148876, - }, - FieldElement{ - 22648901, - 1402143, - -22799984, - 13746059, - 7936347, - 365344, - -8668633, - -1674433, - -3758243, - -2304625, - }, - FieldElement{ - -15491917, - 8012313, - -2514730, - -12702462, - -23965846, - -10254029, - -1612713, - -1535569, - -16664475, - 8194478, - }, - }, - { - FieldElement{ - 27338066, - -7507420, - -7414224, - 10140405, - -19026427, - -6589889, - 27277191, - 8855376, - 28572286, - 3005164, - }, - FieldElement{ - 26287124, - 4821776, - 25476601, - -4145903, - -3764513, - -15788984, - -18008582, - 1182479, - -26094821, - -13079595, - }, - FieldElement{ - -7171154, - 3178080, - 23970071, - 6201893, - -17195577, - -4489192, - -21876275, - -13982627, - 32208683, - -1198248, - }, - }, - { - FieldElement{ - -16657702, - 2817643, - -10286362, - 14811298, - 6024667, - 13349505, - -27315504, - -10497842, - -27672585, - -11539858, - }, - FieldElement{ - 15941029, - -9405932, - -21367050, - 8062055, - 31876073, - -238629, - -15278393, - -1444429, - 15397331, - -4130193, - }, - FieldElement{ - 8934485, - -13485467, - -23286397, - -13423241, - -32446090, - 14047986, - 31170398, - -1441021, - -27505566, - 15087184, - }, - }, - { - FieldElement{ - -18357243, - -2156491, - 24524913, - -16677868, - 15520427, - -6360776, - -15502406, - 11461896, - 16788528, - -5868942, - }, - FieldElement{ - -1947386, - 16013773, - 21750665, - 3714552, - -17401782, - -16055433, - -3770287, - -10323320, - 31322514, - -11615635, - }, - FieldElement{ - 21426655, - -5650218, - -13648287, - -5347537, - -28812189, - -4920970, - -18275391, - -14621414, - 13040862, - -12112948, - }, - }, - { - FieldElement{ - 11293895, - 12478086, - -27136401, - 15083750, - -29307421, - 14748872, - 14555558, - -13417103, - 1613711, - 4896935, - }, - FieldElement{ - -25894883, - 15323294, - -8489791, - -8057900, - 25967126, - -13425460, - 2825960, - -4897045, - -23971776, - -11267415, - }, - FieldElement{ - -15924766, - -5229880, - -17443532, - 6410664, - 3622847, - 10243618, - 20615400, - 12405433, - -23753030, - -8436416, - }, - }, - { - FieldElement{ - -7091295, - 12556208, - -20191352, - 9025187, - -17072479, - 4333801, - 4378436, - 2432030, - 23097949, - -566018, - }, - FieldElement{ - 4565804, - -16025654, - 20084412, - -7842817, - 1724999, - 189254, - 24767264, - 10103221, - -18512313, - 2424778, - }, - FieldElement{ - 366633, - -11976806, - 8173090, - -6890119, - 30788634, - 5745705, - -7168678, - 1344109, - -3642553, - 12412659, - }, - }, - { - FieldElement{ - -24001791, - 7690286, - 14929416, - -168257, - -32210835, - -13412986, - 24162697, - -15326504, - -3141501, - 11179385, - }, - FieldElement{ - 18289522, - -14724954, - 8056945, - 16430056, - -21729724, - 7842514, - -6001441, - -1486897, - -18684645, - -11443503, - }, - FieldElement{ - 476239, - 6601091, - -6152790, - -9723375, - 17503545, - -4863900, - 27672959, - 13403813, - 11052904, - 5219329, - }, - }, - }, - { - { - FieldElement{ - 20678546, - -8375738, - -32671898, - 8849123, - -5009758, - 14574752, - 31186971, - -3973730, - 9014762, - -8579056, - }, - FieldElement{ - -13644050, - -10350239, - -15962508, - 5075808, - -1514661, - -11534600, - -33102500, - 9160280, - 8473550, - -3256838, - }, - FieldElement{ - 24900749, - 14435722, - 17209120, - -15292541, - -22592275, - 9878983, - -7689309, - -16335821, - -24568481, - 11788948, - }, - }, - { - FieldElement{ - -3118155, - -11395194, - -13802089, - 14797441, - 9652448, - -6845904, - -20037437, - 10410733, - -24568470, - -1458691, - }, - FieldElement{ - -15659161, - 16736706, - -22467150, - 10215878, - -9097177, - 7563911, - 11871841, - -12505194, - -18513325, - 8464118, - }, - FieldElement{ - -23400612, - 8348507, - -14585951, - -861714, - -3950205, - -6373419, - 14325289, - 8628612, - 33313881, - -8370517, - }, - }, - { - FieldElement{ - -20186973, - -4967935, - 22367356, - 5271547, - -1097117, - -4788838, - -24805667, - -10236854, - -8940735, - -5818269, - }, - FieldElement{ - -6948785, - -1795212, - -32625683, - -16021179, - 32635414, - -7374245, - 15989197, - -12838188, - 28358192, - -4253904, - }, - FieldElement{ - -23561781, - -2799059, - -32351682, - -1661963, - -9147719, - 10429267, - -16637684, - 4072016, - -5351664, - 5596589, - }, - }, - { - FieldElement{ - -28236598, - -3390048, - 12312896, - 6213178, - 3117142, - 16078565, - 29266239, - 2557221, - 1768301, - 15373193, - }, - FieldElement{ - -7243358, - -3246960, - -4593467, - -7553353, - -127927, - -912245, - -1090902, - -4504991, - -24660491, - 3442910, - }, - FieldElement{ - -30210571, - 5124043, - 14181784, - 8197961, - 18964734, - -11939093, - 22597931, - 7176455, - -18585478, - 13365930, - }, - }, - { - FieldElement{ - -7877390, - -1499958, - 8324673, - 4690079, - 6261860, - 890446, - 24538107, - -8570186, - -9689599, - -3031667, - }, - FieldElement{ - 25008904, - -10771599, - -4305031, - -9638010, - 16265036, - 15721635, - 683793, - -11823784, - 15723479, - -15163481, - }, - FieldElement{ - -9660625, - 12374379, - -27006999, - -7026148, - -7724114, - -12314514, - 11879682, - 5400171, - 519526, - -1235876, - }, - }, - { - FieldElement{ - 22258397, - -16332233, - -7869817, - 14613016, - -22520255, - -2950923, - -20353881, - 7315967, - 16648397, - 7605640, - }, - FieldElement{ - -8081308, - -8464597, - -8223311, - 9719710, - 19259459, - -15348212, - 23994942, - -5281555, - -9468848, - 4763278, - }, - FieldElement{ - -21699244, - 9220969, - -15730624, - 1084137, - -25476107, - -2852390, - 31088447, - -7764523, - -11356529, - 728112, - }, - }, - { - FieldElement{ - 26047220, - -11751471, - -6900323, - -16521798, - 24092068, - 9158119, - -4273545, - -12555558, - -29365436, - -5498272, - }, - FieldElement{ - 17510331, - -322857, - 5854289, - 8403524, - 17133918, - -3112612, - -28111007, - 12327945, - 10750447, - 10014012, - }, - FieldElement{ - -10312768, - 3936952, - 9156313, - -8897683, - 16498692, - -994647, - -27481051, - -666732, - 3424691, - 7540221, - }, - }, - { - FieldElement{ - 30322361, - -6964110, - 11361005, - -4143317, - 7433304, - 4989748, - -7071422, - -16317219, - -9244265, - 15258046, - }, - FieldElement{ - 13054562, - -2779497, - 19155474, - 469045, - -12482797, - 4566042, - 5631406, - 2711395, - 1062915, - -5136345, - }, - FieldElement{ - -19240248, - -11254599, - -29509029, - -7499965, - -5835763, - 13005411, - -6066489, - 12194497, - 32960380, - 1459310, - }, - }, - }, - { - { - FieldElement{ - 19852034, - 7027924, - 23669353, - 10020366, - 8586503, - -6657907, - 394197, - -6101885, - 18638003, - -11174937, - }, - FieldElement{ - 31395534, - 15098109, - 26581030, - 8030562, - -16527914, - -5007134, - 9012486, - -7584354, - -6643087, - -5442636, - }, - FieldElement{ - -9192165, - -2347377, - -1997099, - 4529534, - 25766844, - 607986, - -13222, - 9677543, - -32294889, - -6456008, - }, - }, - { - FieldElement{ - -2444496, - -149937, - 29348902, - 8186665, - 1873760, - 12489863, - -30934579, - -7839692, - -7852844, - -8138429, - }, - FieldElement{ - -15236356, - -15433509, - 7766470, - 746860, - 26346930, - -10221762, - -27333451, - 10754588, - -9431476, - 5203576, - }, - FieldElement{ - 31834314, - 14135496, - -770007, - 5159118, - 20917671, - -16768096, - -7467973, - -7337524, - 31809243, - 7347066, - }, - }, - { - FieldElement{ - -9606723, - -11874240, - 20414459, - 13033986, - 13716524, - -11691881, - 19797970, - -12211255, - 15192876, - -2087490, - }, - FieldElement{ - -12663563, - -2181719, - 1168162, - -3804809, - 26747877, - -14138091, - 10609330, - 12694420, - 33473243, - -13382104, - }, - FieldElement{ - 33184999, - 11180355, - 15832085, - -11385430, - -1633671, - 225884, - 15089336, - -11023903, - -6135662, - 14480053, - }, - }, - { - FieldElement{ - 31308717, - -5619998, - 31030840, - -1897099, - 15674547, - -6582883, - 5496208, - 13685227, - 27595050, - 8737275, - }, - FieldElement{ - -20318852, - -15150239, - 10933843, - -16178022, - 8335352, - -7546022, - -31008351, - -12610604, - 26498114, - 66511, - }, - FieldElement{ - 22644454, - -8761729, - -16671776, - 4884562, - -3105614, - -13559366, - 30540766, - -4286747, - -13327787, - -7515095, - }, - }, - { - FieldElement{ - -28017847, - 9834845, - 18617207, - -2681312, - -3401956, - -13307506, - 8205540, - 13585437, - -17127465, - 15115439, - }, - FieldElement{ - 23711543, - -672915, - 31206561, - -8362711, - 6164647, - -9709987, - -33535882, - -1426096, - 8236921, - 16492939, - }, - FieldElement{ - -23910559, - -13515526, - -26299483, - -4503841, - 25005590, - -7687270, - 19574902, - 10071562, - 6708380, - -6222424, - }, - }, - { - FieldElement{ - 2101391, - -4930054, - 19702731, - 2367575, - -15427167, - 1047675, - 5301017, - 9328700, - 29955601, - -11678310, - }, - FieldElement{ - 3096359, - 9271816, - -21620864, - -15521844, - -14847996, - -7592937, - -25892142, - -12635595, - -9917575, - 6216608, - }, - FieldElement{ - -32615849, - 338663, - -25195611, - 2510422, - -29213566, - -13820213, - 24822830, - -6146567, - -26767480, - 7525079, - }, - }, - { - FieldElement{ - -23066649, - -13985623, - 16133487, - -7896178, - -3389565, - 778788, - -910336, - -2782495, - -19386633, - 11994101, - }, - FieldElement{ - 21691500, - -13624626, - -641331, - -14367021, - 3285881, - -3483596, - -25064666, - 9718258, - -7477437, - 13381418, - }, - FieldElement{ - 18445390, - -4202236, - 14979846, - 11622458, - -1727110, - -3582980, - 23111648, - -6375247, - 28535282, - 15779576, - }, - }, - { - FieldElement{ - 30098053, - 3089662, - -9234387, - 16662135, - -21306940, - 11308411, - -14068454, - 12021730, - 9955285, - -16303356, - }, - FieldElement{ - 9734894, - -14576830, - -7473633, - -9138735, - 2060392, - 11313496, - -18426029, - 9924399, - 20194861, - 13380996, - }, - FieldElement{ - -26378102, - -7965207, - -22167821, - 15789297, - -18055342, - -6168792, - -1984914, - 15707771, - 26342023, - 10146099, - }, - }, - }, - { - { - FieldElement{ - -26016874, - -219943, - 21339191, - -41388, - 19745256, - -2878700, - -29637280, - 2227040, - 21612326, - -545728, - }, - FieldElement{ - -13077387, - 1184228, - 23562814, - -5970442, - -20351244, - -6348714, - 25764461, - 12243797, - -20856566, - 11649658, - }, - FieldElement{ - -10031494, - 11262626, - 27384172, - 2271902, - 26947504, - -15997771, - 39944, - 6114064, - 33514190, - 2333242, - }, - }, - { - FieldElement{ - -21433588, - -12421821, - 8119782, - 7219913, - -21830522, - -9016134, - -6679750, - -12670638, - 24350578, - -13450001, - }, - FieldElement{ - -4116307, - -11271533, - -23886186, - 4843615, - -30088339, - 690623, - -31536088, - -10406836, - 8317860, - 12352766, - }, - FieldElement{ - 18200138, - -14475911, - -33087759, - -2696619, - -23702521, - -9102511, - -23552096, - -2287550, - 20712163, - 6719373, - }, - }, - { - FieldElement{ - 26656208, - 6075253, - -7858556, - 1886072, - -28344043, - 4262326, - 11117530, - -3763210, - 26224235, - -3297458, - }, - FieldElement{ - -17168938, - -14854097, - -3395676, - -16369877, - -19954045, - 14050420, - 21728352, - 9493610, - 18620611, - -16428628, - }, - FieldElement{ - -13323321, - 13325349, - 11432106, - 5964811, - 18609221, - 6062965, - -5269471, - -9725556, - -30701573, - -16479657, - }, - }, - { - FieldElement{ - -23860538, - -11233159, - 26961357, - 1640861, - -32413112, - -16737940, - 12248509, - -5240639, - 13735342, - 1934062, - }, - FieldElement{ - 25089769, - 6742589, - 17081145, - -13406266, - 21909293, - -16067981, - -15136294, - -3765346, - -21277997, - 5473616, - }, - FieldElement{ - 31883677, - -7961101, - 1083432, - -11572403, - 22828471, - 13290673, - -7125085, - 12469656, - 29111212, - -5451014, - }, - }, - { - FieldElement{ - 24244947, - -15050407, - -26262976, - 2791540, - -14997599, - 16666678, - 24367466, - 6388839, - -10295587, - 452383, - }, - FieldElement{ - -25640782, - -3417841, - 5217916, - 16224624, - 19987036, - -4082269, - -24236251, - -5915248, - 15766062, - 8407814, - }, - FieldElement{ - -20406999, - 13990231, - 15495425, - 16395525, - 5377168, - 15166495, - -8917023, - -4388953, - -8067909, - 2276718, - }, - }, - { - FieldElement{ - 30157918, - 12924066, - -17712050, - 9245753, - 19895028, - 3368142, - -23827587, - 5096219, - 22740376, - -7303417, - }, - FieldElement{ - 2041139, - -14256350, - 7783687, - 13876377, - -25946985, - -13352459, - 24051124, - 13742383, - -15637599, - 13295222, - }, - FieldElement{ - 33338237, - -8505733, - 12532113, - 7977527, - 9106186, - -1715251, - -17720195, - -4612972, - -4451357, - -14669444, - }, - }, - { - FieldElement{ - -20045281, - 5454097, - -14346548, - 6447146, - 28862071, - 1883651, - -2469266, - -4141880, - 7770569, - 9620597, - }, - FieldElement{ - 23208068, - 7979712, - 33071466, - 8149229, - 1758231, - -10834995, - 30945528, - -1694323, - -33502340, - -14767970, - }, - FieldElement{ - 1439958, - -16270480, - -1079989, - -793782, - 4625402, - 10647766, - -5043801, - 1220118, - 30494170, - -11440799, - }, - }, - { - FieldElement{ - -5037580, - -13028295, - -2970559, - -3061767, - 15640974, - -6701666, - -26739026, - 926050, - -1684339, - -13333647, - }, - FieldElement{ - 13908495, - -3549272, - 30919928, - -6273825, - -21521863, - 7989039, - 9021034, - 9078865, - 3353509, - 4033511, - }, - FieldElement{ - -29663431, - -15113610, - 32259991, - -344482, - 24295849, - -12912123, - 23161163, - 8839127, - 27485041, - 7356032, - }, - }, - }, - { - { - FieldElement{ - 9661027, - 705443, - 11980065, - -5370154, - -1628543, - 14661173, - -6346142, - 2625015, - 28431036, - -16771834, - }, - FieldElement{ - -23839233, - -8311415, - -25945511, - 7480958, - -17681669, - -8354183, - -22545972, - 14150565, - 15970762, - 4099461, - }, - FieldElement{ - 29262576, - 16756590, - 26350592, - -8793563, - 8529671, - -11208050, - 13617293, - -9937143, - 11465739, - 8317062, - }, - }, - { - FieldElement{ - -25493081, - -6962928, - 32500200, - -9419051, - -23038724, - -2302222, - 14898637, - 3848455, - 20969334, - -5157516, - }, - FieldElement{ - -20384450, - -14347713, - -18336405, - 13884722, - -33039454, - 2842114, - -21610826, - -3649888, - 11177095, - 14989547, - }, - FieldElement{ - -24496721, - -11716016, - 16959896, - 2278463, - 12066309, - 10137771, - 13515641, - 2581286, - -28487508, - 9930240, - }, - }, - { - FieldElement{ - -17751622, - -2097826, - 16544300, - -13009300, - -15914807, - -14949081, - 18345767, - -13403753, - 16291481, - -5314038, - }, - FieldElement{ - -33229194, - 2553288, - 32678213, - 9875984, - 8534129, - 6889387, - -9676774, - 6957617, - 4368891, - 9788741, - }, - FieldElement{ - 16660756, - 7281060, - -10830758, - 12911820, - 20108584, - -8101676, - -21722536, - -8613148, - 16250552, - -11111103, - }, - }, - { - FieldElement{ - -19765507, - 2390526, - -16551031, - 14161980, - 1905286, - 6414907, - 4689584, - 10604807, - -30190403, - 4782747, - }, - FieldElement{ - -1354539, - 14736941, - -7367442, - -13292886, - 7710542, - -14155590, - -9981571, - 4383045, - 22546403, - 437323, - }, - FieldElement{ - 31665577, - -12180464, - -16186830, - 1491339, - -18368625, - 3294682, - 27343084, - 2786261, - -30633590, - -14097016, - }, - }, - { - FieldElement{ - -14467279, - -683715, - -33374107, - 7448552, - 19294360, - 14334329, - -19690631, - 2355319, - -19284671, - -6114373, - }, - FieldElement{ - 15121312, - -15796162, - 6377020, - -6031361, - -10798111, - -12957845, - 18952177, - 15496498, - -29380133, - 11754228, - }, - FieldElement{ - -2637277, - -13483075, - 8488727, - -14303896, - 12728761, - -1622493, - 7141596, - 11724556, - 22761615, - -10134141, - }, - }, - { - FieldElement{ - 16918416, - 11729663, - -18083579, - 3022987, - -31015732, - -13339659, - -28741185, - -12227393, - 32851222, - 11717399, - }, - FieldElement{ - 11166634, - 7338049, - -6722523, - 4531520, - -29468672, - -7302055, - 31474879, - 3483633, - -1193175, - -4030831, - }, - FieldElement{ - -185635, - 9921305, - 31456609, - -13536438, - -12013818, - 13348923, - 33142652, - 6546660, - -19985279, - -3948376, - }, - }, - { - FieldElement{ - -32460596, - 11266712, - -11197107, - -7899103, - 31703694, - 3855903, - -8537131, - -12833048, - -30772034, - -15486313, - }, - FieldElement{ - -18006477, - 12709068, - 3991746, - -6479188, - -21491523, - -10550425, - -31135347, - -16049879, - 10928917, - 3011958, - }, - FieldElement{ - -6957757, - -15594337, - 31696059, - 334240, - 29576716, - 14796075, - -30831056, - -12805180, - 18008031, - 10258577, - }, - }, - { - FieldElement{ - -22448644, - 15655569, - 7018479, - -4410003, - -30314266, - -1201591, - -1853465, - 1367120, - 25127874, - 6671743, - }, - FieldElement{ - 29701166, - -14373934, - -10878120, - 9279288, - -17568, - 13127210, - 21382910, - 11042292, - 25838796, - 4642684, - }, - FieldElement{ - -20430234, - 14955537, - -24126347, - 8124619, - -5369288, - -5990470, - 30468147, - -13900640, - 18423289, - 4177476, - }, - }, - }, -} diff --git a/crypto/internal/ed25519/edwards25519/edwards25519.go b/crypto/internal/ed25519/edwards25519/edwards25519.go deleted file mode 100644 index 4db8b8f99..000000000 --- a/crypto/internal/ed25519/edwards25519/edwards25519.go +++ /dev/null @@ -1,2308 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package edwards25519 implements operations in GF(2**255-19) and on an -// Edwards curve that is isomorphic to curve25519. See -// http://ed25519.cr.yp.to/. -package edwards25519 - -import "math" - -// This code is a port of the public domain, "ref10" implementation of ed25519 -// from SUPERCOP. - -// FieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type FieldElement [10]int32 - -func FeZero(fe *FieldElement) { - for i := range fe { - fe[i] = 0 - } -} - -func FeOne(fe *FieldElement) { - FeZero(fe) - fe[0] = 1 -} - -func FeAdd(dst, a, b *FieldElement) { - for i := range dst { - dst[i] = a[i] + b[i] - } -} - -func FeSub(dst, a, b *FieldElement) { - for i := range dst { - dst[i] = a[i] - b[i] - } -} - -func FeCopy(dst, src *FieldElement) { - for i := range dst { - dst[i] = src[i] - } -} - -// Replace (f,g) with (g,g) if b == 1; -// replace (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func FeCMove(f, g *FieldElement, b int32) { - var x FieldElement - b = -b - for i := range x { - x[i] = b & (f[i] ^ g[i]) - } - - for i := range f { - f[i] ^= x[i] - } -} - -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -func load4(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -func FeFromBytes(dst *FieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 8388607) << 2 - - var carry [10]int64 - carry[9] = (h9 + 1<<24) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + 1<<24) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + 1<<24) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + 1<<24) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + 1<<24) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + 1<<25) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + 1<<25) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + 1<<25) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + 1<<25) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + 1<<25) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - dst[0] = int32(h0) - dst[1] = int32(h1) - dst[2] = int32(h2) - dst[3] = int32(h3) - dst[4] = int32(h4) - dst[5] = int32(h5) - dst[6] = int32(h6) - dst[7] = int32(h7) - dst[8] = int32(h8) - dst[9] = int32(h9) -} - -// FeToBytes marshals h to s. -// Preconditions: -// -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) -} - -func FeIsNegative(f *FieldElement) byte { - var s [32]byte - FeToBytes(&s, f) - return s[0] & 1 -} - -func FeIsNonZero(f *FieldElement) int32 { - var s [32]byte - FeToBytes(&s, f) - var x uint8 - for _, b := range s { - x |= b - } - x |= x >> 4 - x |= x >> 2 - x |= x >> 1 - return int32(x & 1) -} - -// FeNeg sets h = -f -// -// Preconditions: -// -// |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Postconditions: -// -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeNeg(h, f *FieldElement) { - for i := range h { - h[i] = -f[i] - } -} - -// FeMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. -// -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs can squeeze carries into int32. -func FeMul(h, f, g *FieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - g0 := g[0] - g1 := g[1] - g2 := g[2] - g3 := g[3] - g4 := g[4] - g5 := g[5] - g6 := g[6] - g7 := g[7] - g8 := g[8] - g9 := g[9] - g1_19 := 19 * g1 /* 1.4*2^29 */ - g2_19 := 19 * g2 /* 1.4*2^30; still ok */ - g3_19 := 19 * g3 - g4_19 := 19 * g4 - g5_19 := 19 * g5 - g6_19 := 19 * g6 - g7_19 := 19 * g7 - g8_19 := 19 * g8 - g9_19 := 19 * g9 - f1_2 := 2 * f1 - f3_2 := 2 * f3 - f5_2 := 2 * f5 - f7_2 := 2 * f7 - f9_2 := 2 * f9 - f0g0 := int64(f0) * int64(g0) - f0g1 := int64(f0) * int64(g1) - f0g2 := int64(f0) * int64(g2) - f0g3 := int64(f0) * int64(g3) - f0g4 := int64(f0) * int64(g4) - f0g5 := int64(f0) * int64(g5) - f0g6 := int64(f0) * int64(g6) - f0g7 := int64(f0) * int64(g7) - f0g8 := int64(f0) * int64(g8) - f0g9 := int64(f0) * int64(g9) - f1g0 := int64(f1) * int64(g0) - f1g1_2 := int64(f1_2) * int64(g1) - f1g2 := int64(f1) * int64(g2) - f1g3_2 := int64(f1_2) * int64(g3) - f1g4 := int64(f1) * int64(g4) - f1g5_2 := int64(f1_2) * int64(g5) - f1g6 := int64(f1) * int64(g6) - f1g7_2 := int64(f1_2) * int64(g7) - f1g8 := int64(f1) * int64(g8) - f1g9_38 := int64(f1_2) * int64(g9_19) - f2g0 := int64(f2) * int64(g0) - f2g1 := int64(f2) * int64(g1) - f2g2 := int64(f2) * int64(g2) - f2g3 := int64(f2) * int64(g3) - f2g4 := int64(f2) * int64(g4) - f2g5 := int64(f2) * int64(g5) - f2g6 := int64(f2) * int64(g6) - f2g7 := int64(f2) * int64(g7) - f2g8_19 := int64(f2) * int64(g8_19) - f2g9_19 := int64(f2) * int64(g9_19) - f3g0 := int64(f3) * int64(g0) - f3g1_2 := int64(f3_2) * int64(g1) - f3g2 := int64(f3) * int64(g2) - f3g3_2 := int64(f3_2) * int64(g3) - f3g4 := int64(f3) * int64(g4) - f3g5_2 := int64(f3_2) * int64(g5) - f3g6 := int64(f3) * int64(g6) - f3g7_38 := int64(f3_2) * int64(g7_19) - f3g8_19 := int64(f3) * int64(g8_19) - f3g9_38 := int64(f3_2) * int64(g9_19) - f4g0 := int64(f4) * int64(g0) - f4g1 := int64(f4) * int64(g1) - f4g2 := int64(f4) * int64(g2) - f4g3 := int64(f4) * int64(g3) - f4g4 := int64(f4) * int64(g4) - f4g5 := int64(f4) * int64(g5) - f4g6_19 := int64(f4) * int64(g6_19) - f4g7_19 := int64(f4) * int64(g7_19) - f4g8_19 := int64(f4) * int64(g8_19) - f4g9_19 := int64(f4) * int64(g9_19) - f5g0 := int64(f5) * int64(g0) - f5g1_2 := int64(f5_2) * int64(g1) - f5g2 := int64(f5) * int64(g2) - f5g3_2 := int64(f5_2) * int64(g3) - f5g4 := int64(f5) * int64(g4) - f5g5_38 := int64(f5_2) * int64(g5_19) - f5g6_19 := int64(f5) * int64(g6_19) - f5g7_38 := int64(f5_2) * int64(g7_19) - f5g8_19 := int64(f5) * int64(g8_19) - f5g9_38 := int64(f5_2) * int64(g9_19) - f6g0 := int64(f6) * int64(g0) - f6g1 := int64(f6) * int64(g1) - f6g2 := int64(f6) * int64(g2) - f6g3 := int64(f6) * int64(g3) - f6g4_19 := int64(f6) * int64(g4_19) - f6g5_19 := int64(f6) * int64(g5_19) - f6g6_19 := int64(f6) * int64(g6_19) - f6g7_19 := int64(f6) * int64(g7_19) - f6g8_19 := int64(f6) * int64(g8_19) - f6g9_19 := int64(f6) * int64(g9_19) - f7g0 := int64(f7) * int64(g0) - f7g1_2 := int64(f7_2) * int64(g1) - f7g2 := int64(f7) * int64(g2) - f7g3_38 := int64(f7_2) * int64(g3_19) - f7g4_19 := int64(f7) * int64(g4_19) - f7g5_38 := int64(f7_2) * int64(g5_19) - f7g6_19 := int64(f7) * int64(g6_19) - f7g7_38 := int64(f7_2) * int64(g7_19) - f7g8_19 := int64(f7) * int64(g8_19) - f7g9_38 := int64(f7_2) * int64(g9_19) - f8g0 := int64(f8) * int64(g0) - f8g1 := int64(f8) * int64(g1) - f8g2_19 := int64(f8) * int64(g2_19) - f8g3_19 := int64(f8) * int64(g3_19) - f8g4_19 := int64(f8) * int64(g4_19) - f8g5_19 := int64(f8) * int64(g5_19) - f8g6_19 := int64(f8) * int64(g6_19) - f8g7_19 := int64(f8) * int64(g7_19) - f8g8_19 := int64(f8) * int64(g8_19) - f8g9_19 := int64(f8) * int64(g9_19) - f9g0 := int64(f9) * int64(g0) - f9g1_38 := int64(f9_2) * int64(g1_19) - f9g2_19 := int64(f9) * int64(g2_19) - f9g3_38 := int64(f9_2) * int64(g3_19) - f9g4_19 := int64(f9) * int64(g4_19) - f9g5_38 := int64(f9_2) * int64(g5_19) - f9g6_19 := int64(f9) * int64(g6_19) - f9g7_38 := int64(f9_2) * int64(g7_19) - f9g8_19 := int64(f9) * int64(g8_19) - f9g9_38 := int64(f9_2) * int64(g9_19) - h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 - h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 - h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 - h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 - h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 - h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 - h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 - h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 - h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 - h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 - var carry [10]int64 - - /* - |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - */ - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - /* |h0| <= 2^25 */ - /* |h4| <= 2^25 */ - /* |h1| <= 1.51*2^58 */ - /* |h5| <= 1.51*2^58 */ - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - /* |h1| <= 2^24; from now on fits into int32 */ - /* |h5| <= 2^24; from now on fits into int32 */ - /* |h2| <= 1.21*2^59 */ - /* |h6| <= 1.21*2^59 */ - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - /* |h2| <= 2^25; from now on fits into int32 unchanged */ - /* |h6| <= 2^25; from now on fits into int32 unchanged */ - /* |h3| <= 1.51*2^58 */ - /* |h7| <= 1.51*2^58 */ - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - /* |h3| <= 2^24; from now on fits into int32 unchanged */ - /* |h7| <= 2^24; from now on fits into int32 unchanged */ - /* |h4| <= 1.52*2^33 */ - /* |h8| <= 1.52*2^33 */ - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - /* |h4| <= 2^25; from now on fits into int32 unchanged */ - /* |h8| <= 2^25; from now on fits into int32 unchanged */ - /* |h5| <= 1.01*2^24 */ - /* |h9| <= 1.51*2^58 */ - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - /* |h9| <= 2^24; from now on fits into int32 unchanged */ - /* |h0| <= 1.8*2^37 */ - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - /* |h0| <= 2^25; from now on fits into int32 unchanged */ - /* |h1| <= 1.01*2^24 */ - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// FeSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func FeSquare(h, f *FieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// FeSquare2 sets h = 2 * f * f -// -// Can overlap h with f. -// -// Preconditions: -// -// |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. -// -// Postconditions: -// -// |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. -// -// See fe_mul.c for discussion of implementation strategy. -func FeSquare2(h, f *FieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.959375*2^30 - f6_19 := 19 * f6 // 1.959375*2^30 - f7_38 := 38 * f7 // 1.959375*2^30 - f8_19 := 19 * f8 // 1.959375*2^30 - f9_38 := 38 * f9 // 1.959375*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - h0 += h0 - h1 += h1 - h2 += h2 - h3 += h3 - h4 += h4 - h5 += h5 - h6 += h6 - h7 += h7 - h8 += h8 - h9 += h9 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -func FeInvert(out, z *FieldElement) { - var t0, t1, t2, t3 FieldElement - var i int - - FeSquare(&t0, z) // 2^1 - FeSquare(&t1, &t0) // 2^2 - for i = 1; i < 2; i++ { // 2^3 - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) // 2^3 + 2^0 - FeMul(&t0, &t0, &t1) // 2^3 + 2^1 + 2^0 - FeSquare(&t2, &t0) // 2^4 + 2^2 + 2^1 - FeMul(&t1, &t1, &t2) // 2^4 + 2^3 + 2^2 + 2^1 + 2^0 - FeSquare(&t2, &t1) // 5,4,3,2,1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 19..0 - FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 39..0 - FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 49..0 - FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - FeSquare(&t2, &t2) - } - FeMul(&t2, &t2, &t1) // 99..0 - FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - FeSquare(&t3, &t3) - } - FeMul(&t2, &t3, &t2) // 199..0 - FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) // 249..0 - FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 5; i++ { // 254..5 - FeSquare(&t1, &t1) - } - FeMul(out, &t1, &t0) // 254..5,3,1,0 -} - -func fePow22523(out, z *FieldElement) { - var t0, t1, t2 FieldElement - var i int - - FeSquare(&t0, z) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeSquare(&t1, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, z, &t1) - FeMul(&t0, &t0, &t1) - FeSquare(&t0, &t0) - for i = 1; i < 1; i++ { - FeSquare(&t0, &t0) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 5; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 20; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 10; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t1, &t0) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t1, &t1, &t0) - FeSquare(&t2, &t1) - for i = 1; i < 100; i++ { - FeSquare(&t2, &t2) - } - FeMul(&t1, &t2, &t1) - FeSquare(&t1, &t1) - for i = 1; i < 50; i++ { - FeSquare(&t1, &t1) - } - FeMul(&t0, &t1, &t0) - FeSquare(&t0, &t0) - for i = 1; i < 2; i++ { - FeSquare(&t0, &t0) - } - FeMul(out, &t0, z) -} - -// Group elements are members of the elliptic curve -x^2 + y^2 = 1 + d * x^2 * -// y^2 where d = -121665/121666. -// -// Several representations are used: -// ProjectiveGroupElement: (X:Y:Z) satisfying x=X/Z, y=Y/Z -// ExtendedGroupElement: (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT -// CompletedGroupElement: ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T -// PreComputedGroupElement: (y+x,y-x,2dxy) - -type ProjectiveGroupElement struct { - X, Y, Z FieldElement -} - -type ExtendedGroupElement struct { - X, Y, Z, T FieldElement -} - -type CompletedGroupElement struct { - X, Y, Z, T FieldElement -} - -type PreComputedGroupElement struct { - yPlusX, yMinusX, xy2d FieldElement -} - -type CachedGroupElement struct { - yPlusX, yMinusX, Z, T2d FieldElement -} - -func (p *ProjectiveGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) -} - -func (p *ProjectiveGroupElement) Double(r *CompletedGroupElement) { - var t0 FieldElement - - FeSquare(&r.X, &p.X) - FeSquare(&r.Z, &p.Y) - FeSquare2(&r.T, &p.Z) - FeAdd(&r.Y, &p.X, &p.Y) - FeSquare(&t0, &r.Y) - FeAdd(&r.Y, &r.Z, &r.X) - FeSub(&r.Z, &r.Z, &r.X) - FeSub(&r.X, &t0, &r.Y) - FeSub(&r.T, &r.T, &r.Z) -} - -func (p *ProjectiveGroupElement) ToExtended(s *ExtendedGroupElement) { - var b [32]byte - p.ToBytes(&b) - s.FromBytes(&b) -} - -func (p *ProjectiveGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -func (p *ExtendedGroupElement) Zero() { - FeZero(&p.X) - FeOne(&p.Y) - FeOne(&p.Z) - FeZero(&p.T) -} - -func (p *ExtendedGroupElement) Double(r *CompletedGroupElement) { - var q ProjectiveGroupElement - p.ToProjective(&q) - q.Double(r) -} - -func GeDouble(r, p *ExtendedGroupElement) { - var q ProjectiveGroupElement - p.ToProjective(&q) - var rco CompletedGroupElement - q.Double(&rco) - rco.ToExtended(r) -} - -func (p *ExtendedGroupElement) ToCached(r *CachedGroupElement) { - FeAdd(&r.yPlusX, &p.Y, &p.X) - FeSub(&r.yMinusX, &p.Y, &p.X) - FeCopy(&r.Z, &p.Z) - FeMul(&r.T2d, &p.T, &d2) -} - -func (p *ExtendedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeCopy(&r.X, &p.X) - FeCopy(&r.Y, &p.Y) - FeCopy(&r.Z, &p.Z) -} - -func (p *ExtendedGroupElement) ToBytes(s *[32]byte) { - var recip, x, y FieldElement - - FeInvert(&recip, &p.Z) - FeMul(&x, &p.X, &recip) - FeMul(&y, &p.Y, &recip) - FeToBytes(s, &y) - s[31] ^= FeIsNegative(&x) << 7 -} - -// FromBytesBaseGroup unmarshals an elliptic curve point returns true iff the -// point point is in the order l subgroup generated by the base point. This -// implementation is based on -// https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf Definition 1. -// Validation of an elliptic curve public key P ensures that P is a point of -// order BasePointOrder in E. -func (p *ExtendedGroupElement) FromBytesBaseGroup(s *[32]byte) bool { - // condition 1: P != infinity - if *s == [32]byte{1} { - return false - } - - // condition 3 is implied by successful point decompression - if !p.FromBytes(s) { - return false - } - // condition 2: ToBytes produces canonical encodings, check against that - var sCheck [32]byte - p.ToBytes(&sCheck) - if sCheck != *s { - return false - } - - // condition 4: order * P == infinity - var out ExtendedGroupElement - GeScalarMult(&out, &BasePointOrder, p) - out.ToBytes(&sCheck) - if sCheck != [32]byte{1} { - return false - } - - // an array of all zeros would not result from any randomly generated point - // and might easily be caused by bugs in ToBytes or FromBytes - if *s == [32]byte{} { - return false - } - return true -} - -func (p *ExtendedGroupElement) FromBytes(s *[32]byte) bool { - FeFromBytes(&p.Y, s) - return p.FromParityAndY(s[31]>>7, &p.Y) -} - -func (p *ExtendedGroupElement) FromParityAndY(bit byte, y *FieldElement) bool { - var u, v, v3, vxx, check FieldElement - - FeCopy(&p.Y, y) - FeOne(&p.Z) - FeSquare(&u, &p.Y) - FeMul(&v, &u, &d) - FeSub(&u, &u, &p.Z) // y = y^2-1 - FeAdd(&v, &v, &p.Z) // v = dy^2+1 - - FeSquare(&v3, &v) - FeMul(&v3, &v3, &v) // v3 = v^3 - FeSquare(&p.X, &v3) - FeMul(&p.X, &p.X, &v) - FeMul(&p.X, &p.X, &u) // x = uv^7 - - fePow22523(&p.X, &p.X) // x = (uv^7)^((q-5)/8) - FeMul(&p.X, &p.X, &v3) - FeMul(&p.X, &p.X, &u) // x = uv^3(uv^7)^((q-5)/8) - - var tmpX, tmp2 [32]byte - - FeSquare(&vxx, &p.X) - FeMul(&vxx, &vxx, &v) - FeSub(&check, &vxx, &u) // vx^2-u - if FeIsNonZero(&check) == 1 { - FeAdd(&check, &vxx, &u) // vx^2+u - if FeIsNonZero(&check) == 1 { - return false - } - FeMul(&p.X, &p.X, &SqrtM1) - - FeToBytes(&tmpX, &p.X) - for i, v := range tmpX { - tmp2[31-i] = v - } - } - - if FeIsNegative(&p.X) != bit { - FeNeg(&p.X, &p.X) - } - - FeMul(&p.T, &p.X, &p.Y) - return true -} - -func (p *CompletedGroupElement) ToProjective(r *ProjectiveGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) -} - -func (p *CompletedGroupElement) ToExtended(r *ExtendedGroupElement) { - FeMul(&r.X, &p.X, &p.T) - FeMul(&r.Y, &p.Y, &p.Z) - FeMul(&r.Z, &p.Z, &p.T) - FeMul(&r.T, &p.X, &p.Y) -} - -func (p *PreComputedGroupElement) Zero() { - FeOne(&p.yPlusX) - FeOne(&p.yMinusX) - FeZero(&p.xy2d) -} - -func geAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *CachedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.T2d, &p.T) - FeMul(&r.X, &p.Z, &q.Z) - FeAdd(&t0, &r.X, &r.X) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func geMixedAdd(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yPlusX) - FeMul(&r.Y, &r.Y, &q.yMinusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeAdd(&r.Z, &t0, &r.T) - FeSub(&r.T, &t0, &r.T) -} - -func geMixedSub(r *CompletedGroupElement, p *ExtendedGroupElement, q *PreComputedGroupElement) { - var t0 FieldElement - - FeAdd(&r.X, &p.Y, &p.X) - FeSub(&r.Y, &p.Y, &p.X) - FeMul(&r.Z, &r.X, &q.yMinusX) - FeMul(&r.Y, &r.Y, &q.yPlusX) - FeMul(&r.T, &q.xy2d, &p.T) - FeAdd(&t0, &p.Z, &p.Z) - FeSub(&r.X, &r.Z, &r.Y) - FeAdd(&r.Y, &r.Z, &r.Y) - FeSub(&r.Z, &t0, &r.T) - FeAdd(&r.T, &t0, &r.T) -} - -func slide(r *[256]int8, a *[32]byte) { - for i := range r { - r[i] = int8(1 & (a[i>>3] >> uint(i&7))) - } - - for i := range r { - if r[i] != 0 { - for b := 1; b <= 6 && i+b < 256; b++ { - if r[i+b] != 0 { - if r[i]+(r[i+b]<= -15 { - r[i] -= r[i+b] << uint(b) - for k := i + b; k < 256; k++ { - if r[k] == 0 { - r[k] = 1 - break - } - r[k] = 0 - } - } else { - break - } - } - } - } - } -} - -// GeAdd sets r = a+b. r may overlaop with a and b. -func GeAdd(r, a, b *ExtendedGroupElement) { - var bca CachedGroupElement - b.ToCached(&bca) - var rc CompletedGroupElement - geAdd(&rc, a, &bca) - rc.ToExtended(r) -} - -func ExtendedGroupElementCopy(t, u *ExtendedGroupElement) { - FeCopy(&t.X, &u.X) - FeCopy(&t.Y, &u.Y) - FeCopy(&t.Z, &u.Z) - FeCopy(&t.T, &u.T) -} - -func ExtendedGroupElementCMove(t, u *ExtendedGroupElement, b int32) { - FeCMove(&t.X, &u.X, b) - FeCMove(&t.Y, &u.Y, b) - FeCMove(&t.Z, &u.Z, b) - FeCMove(&t.T, &u.T, b) -} - -// GeScalarMult sets r = a*A -// where a = a[0]+256*a[1]+...+256^31 a[31]. -func GeScalarMult(r *ExtendedGroupElement, a *[32]byte, A *ExtendedGroupElement) { - var p, q ExtendedGroupElement - q.Zero() - ExtendedGroupElementCopy(&p, A) - for i := uint(0); i < 256; i++ { - bit := int32(a[i>>3]>>(i&7)) & 1 - var t ExtendedGroupElement - GeAdd(&t, &q, &p) - ExtendedGroupElementCMove(&q, &t, bit) - GeDouble(&p, &p) - } - ExtendedGroupElementCopy(r, &q) -} - -// GeDoubleScalarMultVartime sets r = a*A + b*B -// where a = a[0]+256*a[1]+...+256^31 a[31]. -// and b = b[0]+256*b[1]+...+256^31 b[31]. -// B is the Ed25519 base point (x,4/5) with x positive. -func GeDoubleScalarMultVartime( - r *ProjectiveGroupElement, - a *[32]byte, - A *ExtendedGroupElement, - b *[32]byte, -) { - var aSlide, bSlide [256]int8 - var Ai [8]CachedGroupElement // A,3A,5A,7A,9A,11A,13A,15A - var t CompletedGroupElement - var u, A2 ExtendedGroupElement - var i int - - slide(&aSlide, a) - slide(&bSlide, b) - - A.ToCached(&Ai[0]) - A.Double(&t) - t.ToExtended(&A2) - - for i := 0; i < 7; i++ { - geAdd(&t, &A2, &Ai[i]) - t.ToExtended(&u) - u.ToCached(&Ai[i+1]) - } - - r.Zero() - - for i = 255; i >= 0; i-- { - if aSlide[i] != 0 || bSlide[i] != 0 { - break - } - } - - for ; i >= 0; i-- { - r.Double(&t) - - if aSlide[i] > 0 { - t.ToExtended(&u) - geAdd(&t, &u, &Ai[aSlide[i]/2]) - } else if aSlide[i] < 0 { - t.ToExtended(&u) - geSub(&t, &u, &Ai[(-aSlide[i])/2]) - } - - if bSlide[i] > 0 { - t.ToExtended(&u) - geMixedAdd(&t, &u, &bi[bSlide[i]/2]) - } else if bSlide[i] < 0 { - t.ToExtended(&u) - geMixedSub(&t, &u, &bi[(-bSlide[i])/2]) - } - - t.ToProjective(r) - } -} - -// equal returns 1 if b == c and 0 otherwise. -func equal(b, c int32) int32 { - x := uint32(b ^ c) - x-- - return int32(x >> 31) -} - -// negative returns 1 if b < 0 and 0 otherwise. -func negative(b int32) int32 { - return (b >> 31) & 1 -} - -func PreComputedGroupElementCMove(t, u *PreComputedGroupElement, b int32) { - FeCMove(&t.yPlusX, &u.yPlusX, b) - FeCMove(&t.yMinusX, &u.yMinusX, b) - FeCMove(&t.xy2d, &u.xy2d, b) -} - -func selectPoint(t *PreComputedGroupElement, pos int32, b int32) { - var minusT PreComputedGroupElement - bNegative := negative(b) - bAbs := b - (((-bNegative) & b) << 1) - - t.Zero() - for i := int32(0); i < 8; i++ { - PreComputedGroupElementCMove(t, &base[pos][i], equal(bAbs, i+1)) - } - FeCopy(&minusT.yPlusX, &t.yMinusX) - FeCopy(&minusT.yMinusX, &t.yPlusX) - FeNeg(&minusT.xy2d, &t.xy2d) - PreComputedGroupElementCMove(t, &minusT, bNegative) -} - -// GeScalarMultBase computes h = a*B, where -// -// a = a[0]+256*a[1]+...+256^31 a[31] -// B is the Ed25519 base point (x,4/5) with x positive. -// -// Preconditions: -// -// a[31] <= 127 -func GeScalarMultBase(h *ExtendedGroupElement, a *[32]byte) { - var e [64]int8 - - for i, v := range a { - e[2*i] = int8(v & 15) - e[2*i+1] = int8((v >> 4) & 15) - } - - // each e[i] is between 0 and 15 and e[63] is between 0 and 7. - - carry := int8(0) - for i := 0; i < 63; i++ { - e[i] += carry - carry = (e[i] + 8) >> 4 - e[i] -= carry << 4 - } - e[63] += carry - // each e[i] is between -8 and 8. - - h.Zero() - var t PreComputedGroupElement - var r CompletedGroupElement - for i := int32(1); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } - - var s ProjectiveGroupElement - - h.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToProjective(&s) - s.Double(&r) - r.ToExtended(h) - - for i := int32(0); i < 64; i += 2 { - selectPoint(&t, i/2, int32(e[i])) - geMixedAdd(&r, h, &t) - r.ToExtended(h) - } -} - -// The scalars are GF(2^252 + 27742317777372353535851937790883648493). - -// Input: -// -// a[0]+256*a[1]+...+256^31*a[31] = a -// b[0]+256*b[1]+...+256^31*b[31] = b -// c[0]+256*c[1]+...+256^31*c[31] = c -// -// Output: -// -// s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScMulAdd(s, a, b, c *[32]byte) { - a0 := 2097151 & load3(a[:]) - a1 := 2097151 & (load4(a[2:]) >> 5) - a2 := 2097151 & (load3(a[5:]) >> 2) - a3 := 2097151 & (load4(a[7:]) >> 7) - a4 := 2097151 & (load4(a[10:]) >> 4) - a5 := 2097151 & (load3(a[13:]) >> 1) - a6 := 2097151 & (load4(a[15:]) >> 6) - a7 := 2097151 & (load3(a[18:]) >> 3) - a8 := 2097151 & load3(a[21:]) - a9 := 2097151 & (load4(a[23:]) >> 5) - a10 := 2097151 & (load3(a[26:]) >> 2) - a11 := (load4(a[28:]) >> 7) - b0 := 2097151 & load3(b[:]) - b1 := 2097151 & (load4(b[2:]) >> 5) - b2 := 2097151 & (load3(b[5:]) >> 2) - b3 := 2097151 & (load4(b[7:]) >> 7) - b4 := 2097151 & (load4(b[10:]) >> 4) - b5 := 2097151 & (load3(b[13:]) >> 1) - b6 := 2097151 & (load4(b[15:]) >> 6) - b7 := 2097151 & (load3(b[18:]) >> 3) - b8 := 2097151 & load3(b[21:]) - b9 := 2097151 & (load4(b[23:]) >> 5) - b10 := 2097151 & (load3(b[26:]) >> 2) - b11 := (load4(b[28:]) >> 7) - c0 := 2097151 & load3(c[:]) - c1 := 2097151 & (load4(c[2:]) >> 5) - c2 := 2097151 & (load3(c[5:]) >> 2) - c3 := 2097151 & (load4(c[7:]) >> 7) - c4 := 2097151 & (load4(c[10:]) >> 4) - c5 := 2097151 & (load3(c[13:]) >> 1) - c6 := 2097151 & (load4(c[15:]) >> 6) - c7 := 2097151 & (load3(c[18:]) >> 3) - c8 := 2097151 & load3(c[21:]) - c9 := 2097151 & (load4(c[23:]) >> 5) - c10 := 2097151 & (load3(c[26:]) >> 2) - c11 := (load4(c[28:]) >> 7) - var carry [23]int64 - - s0 := c0 + a0*b0 - s1 := c1 + a0*b1 + a1*b0 - s2 := c2 + a0*b2 + a1*b1 + a2*b0 - s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 - s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 - s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 - s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 - s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 - s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 - s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 - s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 - s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 - s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 - s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 - s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 - s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 - s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 - s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 - s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 - s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 - s20 := a9*b11 + a10*b10 + a11*b9 - s21 := a10*b11 + a11*b10 - s22 := a11 * b11 - s23 := int64(0) - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - carry[18] = (s18 + (1 << 20)) >> 21 - s19 += carry[18] - s18 -= carry[18] << 21 - carry[20] = (s20 + (1 << 20)) >> 21 - s21 += carry[20] - s20 -= carry[20] << 21 - carry[22] = (s22 + (1 << 20)) >> 21 - s23 += carry[22] - s22 -= carry[22] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - carry[17] = (s17 + (1 << 20)) >> 21 - s18 += carry[17] - s17 -= carry[17] << 21 - carry[19] = (s19 + (1 << 20)) >> 21 - s20 += carry[19] - s19 -= carry[19] << 21 - carry[21] = (s21 + (1 << 20)) >> 21 - s22 += carry[21] - s21 -= carry[21] << 21 - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - s[0] = byte(s0 >> 0) - s[1] = byte(s0 >> 8) - s[2] = byte((s0 >> 16) | (s1 << 5)) - s[3] = byte(s1 >> 3) - s[4] = byte(s1 >> 11) - s[5] = byte((s1 >> 19) | (s2 << 2)) - s[6] = byte(s2 >> 6) - s[7] = byte((s2 >> 14) | (s3 << 7)) - s[8] = byte(s3 >> 1) - s[9] = byte(s3 >> 9) - s[10] = byte((s3 >> 17) | (s4 << 4)) - s[11] = byte(s4 >> 4) - s[12] = byte(s4 >> 12) - s[13] = byte((s4 >> 20) | (s5 << 1)) - s[14] = byte(s5 >> 7) - s[15] = byte((s5 >> 15) | (s6 << 6)) - s[16] = byte(s6 >> 2) - s[17] = byte(s6 >> 10) - s[18] = byte((s6 >> 18) | (s7 << 3)) - s[19] = byte(s7 >> 5) - s[20] = byte(s7 >> 13) - s[21] = byte(s8 >> 0) - s[22] = byte(s8 >> 8) - s[23] = byte((s8 >> 16) | (s9 << 5)) - s[24] = byte(s9 >> 3) - s[25] = byte(s9 >> 11) - s[26] = byte((s9 >> 19) | (s10 << 2)) - s[27] = byte(s10 >> 6) - s[28] = byte((s10 >> 14) | (s11 << 7)) - s[29] = byte(s11 >> 1) - s[30] = byte(s11 >> 9) - s[31] = byte(s11 >> 17) -} - -// Input: -// -// s[0]+256*s[1]+...+256^63*s[63] = s -// s <= l -// -// Output: -// -// s[0]+256*s[1]+...+256^31*s[31] = l - s -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScNeg(r, s *[32]byte) { - l := [32]byte{ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16, - } - var carry int32 - for i := 0; i < 32; i++ { - carry = carry + int32(l[i]) - int32(s[i]) - negative := carry & math.MinInt32 // extract the sign bit (min=0b100...) - negative |= negative >> 16 - negative |= negative >> 8 - negative |= negative >> 4 - negative |= negative >> 2 - negative |= negative >> 1 - carry += negative & 256 // +=256 if negative, unmodified otherwise - r[i] = byte(carry) - // carry for next iteration - carry = negative & (-1) // -1 if negative, 0 otherwise - } -} - -// Input: -// -// s[0]+256*s[1]+...+256^63*s[63] = s -// -// Output: -// -// s[0]+256*s[1]+...+256^31*s[31] = s mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func ScReduce(out *[32]byte, s *[64]byte) { - s0 := 2097151 & load3(s[:]) - s1 := 2097151 & (load4(s[2:]) >> 5) - s2 := 2097151 & (load3(s[5:]) >> 2) - s3 := 2097151 & (load4(s[7:]) >> 7) - s4 := 2097151 & (load4(s[10:]) >> 4) - s5 := 2097151 & (load3(s[13:]) >> 1) - s6 := 2097151 & (load4(s[15:]) >> 6) - s7 := 2097151 & (load3(s[18:]) >> 3) - s8 := 2097151 & load3(s[21:]) - s9 := 2097151 & (load4(s[23:]) >> 5) - s10 := 2097151 & (load3(s[26:]) >> 2) - s11 := 2097151 & (load4(s[28:]) >> 7) - s12 := 2097151 & (load4(s[31:]) >> 4) - s13 := 2097151 & (load3(s[34:]) >> 1) - s14 := 2097151 & (load4(s[36:]) >> 6) - s15 := 2097151 & (load3(s[39:]) >> 3) - s16 := 2097151 & load3(s[42:]) - s17 := 2097151 & (load4(s[44:]) >> 5) - s18 := 2097151 & (load3(s[47:]) >> 2) - s19 := 2097151 & (load4(s[49:]) >> 7) - s20 := 2097151 & (load4(s[52:]) >> 4) - s21 := 2097151 & (load3(s[55:]) >> 1) - s22 := 2097151 & (load4(s[57:]) >> 6) - s23 := (load4(s[60:]) >> 3) - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - var carry [17]int64 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - out[0] = byte(s0 >> 0) - out[1] = byte(s0 >> 8) - out[2] = byte((s0 >> 16) | (s1 << 5)) - out[3] = byte(s1 >> 3) - out[4] = byte(s1 >> 11) - out[5] = byte((s1 >> 19) | (s2 << 2)) - out[6] = byte(s2 >> 6) - out[7] = byte((s2 >> 14) | (s3 << 7)) - out[8] = byte(s3 >> 1) - out[9] = byte(s3 >> 9) - out[10] = byte((s3 >> 17) | (s4 << 4)) - out[11] = byte(s4 >> 4) - out[12] = byte(s4 >> 12) - out[13] = byte((s4 >> 20) | (s5 << 1)) - out[14] = byte(s5 >> 7) - out[15] = byte((s5 >> 15) | (s6 << 6)) - out[16] = byte(s6 >> 2) - out[17] = byte(s6 >> 10) - out[18] = byte((s6 >> 18) | (s7 << 3)) - out[19] = byte(s7 >> 5) - out[20] = byte(s7 >> 13) - out[21] = byte(s8 >> 0) - out[22] = byte(s8 >> 8) - out[23] = byte((s8 >> 16) | (s9 << 5)) - out[24] = byte(s9 >> 3) - out[25] = byte(s9 >> 11) - out[26] = byte((s9 >> 19) | (s10 << 2)) - out[27] = byte(s10 >> 6) - out[28] = byte((s10 >> 14) | (s11 << 7)) - out[29] = byte(s11 >> 1) - out[30] = byte(s11 >> 9) - out[31] = byte(s11 >> 17) -} diff --git a/crypto/internal/ed25519/edwards25519/edwards25519_test.go b/crypto/internal/ed25519/edwards25519/edwards25519_test.go deleted file mode 100644 index 357f9f089..000000000 --- a/crypto/internal/ed25519/edwards25519/edwards25519_test.go +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package edwards25519 - -import ( - "crypto/rand" - "testing" -) - -func TestScNegMulAddIdentity(t *testing.T) { - one := [32]byte{1} - var seed [64]byte - var a, minusA, x [32]byte - - rand.Reader.Read(seed[:]) - ScReduce(&a, &seed) - copy(minusA[:], a[:]) - ScNeg(&minusA, &minusA) - ScMulAdd(&x, &one, &a, &minusA) - if x != [32]byte{} { - t.Errorf("%x --neg--> %x --sum--> %x", a, minusA, x) - } -} - -func TestGeAddAgainstgeAdd(t *testing.T) { - var x, y [32]byte - rand.Reader.Read(x[:]) - rand.Reader.Read(y[:]) - var X, Y ExtendedGroupElement - x[31] &= 127 - y[31] &= 127 - GeScalarMultBase(&X, &x) - GeScalarMultBase(&Y, &y) - - var SBytesRef [32]byte - var SRef ExtendedGroupElement - var Ycached CachedGroupElement - var SCompletedRef CompletedGroupElement - Y.ToCached(&Ycached) - geAdd(&SCompletedRef, &X, &Ycached) - SCompletedRef.ToExtended(&SRef) - SRef.ToBytes(&SBytesRef) - - var SBytes [32]byte - var S ExtendedGroupElement - GeAdd(&S, &X, &Y) - S.ToBytes(&SBytes) - - if SBytes != SBytesRef { - t.Errorf("GeAdd does not match geAdd: %x != %x", SBytes, SBytesRef) - } -} - -func TestGeScalarMultAgainstDoubleScalarMult(t *testing.T) { - var zero [32]byte - - var x [32]byte - rand.Reader.Read(x[:]) - var X ExtendedGroupElement - x[31] &= 127 - GeScalarMultBase(&X, &x) - - var a [32]byte - rand.Reader.Read(a[:]) - a[31] &= 127 - - var ABytesRef [32]byte - var Aref ProjectiveGroupElement - GeDoubleScalarMultVartime(&Aref, &a, &X, &zero) - Aref.ToBytes(&ABytesRef) - - var ABytes [32]byte - var A ExtendedGroupElement - GeScalarMult(&A, &a, &X) - A.ToBytes(&ABytes) - - if ABytes != ABytesRef { - t.Errorf( - "GeScalarMult does not match GeDoubleScalarMultVartime: %x != %x", - ABytes, - ABytesRef, - ) - } -} - -func inc(b *[32]byte) { - acc := uint(1) - for i := 0; i < 32; i++ { - acc += uint(b[i]) - acc, b[i] = uint(acc>>8), byte(acc) - } -} - -func TestGeAddAgainstScalarMult(t *testing.T) { - var x, s [32]byte - rand.Reader.Read(x[:]) - x[31] &= 127 - var X ExtendedGroupElement - GeScalarMultBase(&X, &x) - var A ExtendedGroupElement - A.Zero() - var ABytes, ABytesMult [32]byte - A.ToBytes(&ABytes) - var AMult ExtendedGroupElement - GeScalarMult(&AMult, &s, &X) - AMult.ToBytes(&ABytesMult) - if ABytes != ABytesMult { - t.Errorf("addition does not match multiplication (%x) -> %x != %x", s, ABytes, ABytesMult) - } - - GeAdd(&A, &A, &X) - inc(&s) -} - -func TestGeAddAgainstDoubleScalarMult(t *testing.T) { - var zero, x, s [32]byte - rand.Reader.Read(x[:]) - x[31] &= 127 - var X ExtendedGroupElement - GeScalarMultBase(&X, &x) - var A ExtendedGroupElement - A.Zero() - var ABytes, ABytesMult [32]byte - A.ToBytes(&ABytes) - var AMult ProjectiveGroupElement - GeDoubleScalarMultVartime(&AMult, &s, &X, &zero) - AMult.ToBytes(&ABytesMult) - if ABytes != ABytesMult { - t.Errorf("addition does not match multiplication (%x)", s) - } - - GeAdd(&A, &A, &X) - inc(&s) -} - -func TestGeScalarMultiBaseScalarMultDH(t *testing.T) { - var a, b [32]byte - rand.Reader.Read(a[:]) - rand.Reader.Read(b[:]) - - var A, B ExtendedGroupElement - a[31] &= 127 - b[31] &= 127 - GeScalarMultBase(&A, &a) - GeScalarMultBase(&B, &b) - - var kA, kB ExtendedGroupElement - GeScalarMult(&kA, &a, &B) - GeScalarMult(&kB, &b, &A) - - var ka, kb [32]byte - kA.ToBytes(&ka) - kB.ToBytes(&kb) - - if ka != kb { - t.Fatal("DH shared secrets do not match") - } -} - -func TestGeScalarMultDH(t *testing.T) { - var one [32]byte - one[0] = 1 - var base ExtendedGroupElement - GeScalarMultBase(&base, &one) - - var a, b [32]byte - rand.Reader.Read(a[:]) - rand.Reader.Read(b[:]) - - var A, B ExtendedGroupElement - GeScalarMult(&A, &a, &base) - GeScalarMult(&B, &b, &base) - - var kA, kB ExtendedGroupElement - GeScalarMult(&kA, &a, &B) - GeScalarMult(&kB, &b, &A) - - var ka, kb [32]byte - kA.ToBytes(&ka) - kB.ToBytes(&kb) - - if ka != kb { - t.Fatal("DH shared secrets do not match") - } - - var bytesA, bytesB [32]byte - A.ToBytes(&bytesA) - B.ToBytes(&bytesB) - - if bytesA == bytesB { - t.Fatalf("DH public key collision: g^%x = g^%x = %x", a, b, A) - } -} - -func BenchmarkGeScalarMultBase(b *testing.B) { - var s [32]byte - rand.Reader.Read(s[:]) - var P ExtendedGroupElement - - b.ResetTimer() - for i := 0; i < b.N; i++ { - GeScalarMultBase(&P, &s) - } -} - -func BenchmarkGeScalarMult(b *testing.B) { - var s [32]byte - rand.Reader.Read(s[:]) - - var P ExtendedGroupElement - s[31] &= 127 - GeScalarMultBase(&P, &s) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - GeScalarMult(&P, &s, &P) - } -} - -func BenchmarkGeDoubleScalarMultVartime(b *testing.B) { - var s [32]byte - rand.Reader.Read(s[:]) - - var P, Pout ExtendedGroupElement - s[31] &= 127 - GeScalarMultBase(&P, &s) - - var out ProjectiveGroupElement - - b.ResetTimer() - for i := 0; i < b.N; i++ { - GeDoubleScalarMultVartime(&out, &s, &P, &[32]byte{}) - out.ToExtended(&Pout) - } -} - -func BenchmarkGeAdd(b *testing.B) { - var s [32]byte - rand.Reader.Read(s[:]) - - var R, P ExtendedGroupElement - s[31] &= 127 - GeScalarMultBase(&P, &s) - R = P - - b.ResetTimer() - for i := 0; i < b.N; i++ { - GeAdd(&R, &R, &P) - } -} - -func BenchmarkGeDouble(b *testing.B) { - var s [32]byte - rand.Reader.Read(s[:]) - - var R, P ExtendedGroupElement - s[31] &= 127 - GeScalarMultBase(&P, &s) - R = P - - b.ResetTimer() - for i := 0; i < b.N; i++ { - GeDouble(&R, &P) - } -} diff --git a/crypto/internal/ed25519/extra25519/extra25519.go b/crypto/internal/ed25519/extra25519/extra25519.go deleted file mode 100644 index a02423884..000000000 --- a/crypto/internal/ed25519/extra25519/extra25519.go +++ /dev/null @@ -1,377 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package extra25519 implements fast arithmetic on the extended twisted Edwards curve. -package extra25519 - -import ( - "crypto/sha512" - - "github.com/sonr-io/sonr/crypto/internal/ed25519/edwards25519" -) - -// PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding -// curve25519 private key such that the resulting curve25519 public key will -// equal the result from PublicKeyToCurve25519. -func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey *[64]byte) { - h := sha512.New() - h.Write(privateKey[:32]) - digest := h.Sum(nil) - - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - copy(curve25519Private[:], digest) -} - -func edwardsToMontgomeryX(outX, y *edwards25519.FieldElement) { - // We only need the x-coordinate of the curve25519 point, which I'll - // call u. The isomorphism is u=(y+1)/(1-y), since y=Y/Z, this gives - // u=(Y+Z)/(Z-Y). We know that Z=1, thus u=(Y+1)/(1-Y). - var oneMinusY edwards25519.FieldElement - edwards25519.FeOne(&oneMinusY) - edwards25519.FeSub(&oneMinusY, &oneMinusY, y) - edwards25519.FeInvert(&oneMinusY, &oneMinusY) - - edwards25519.FeOne(outX) - edwards25519.FeAdd(outX, outX, y) - - edwards25519.FeMul(outX, outX, &oneMinusY) -} - -// PublicKeyToCurve25519 converts an Ed25519 public key into the curve25519 -// public key that would be generated from the same private key. -func PublicKeyToCurve25519(curve25519Public *[32]byte, publicKey *[32]byte) bool { - var A edwards25519.ExtendedGroupElement - if !A.FromBytes(publicKey) { - return false - } - - // A.Z = 1 as a postcondition of FromBytes. - var x edwards25519.FieldElement - edwardsToMontgomeryX(&x, &A.Y) - edwards25519.FeToBytes(curve25519Public, &x) - return true -} - -// sqrtMinusA is sqrt(-486662) -var sqrtMinusA = edwards25519.FieldElement{ - 12222970, 8312128, 11511410, -9067497, 15300785, 241793, -25456130, -14121551, 12187136, -3972024, -} - -// sqrtMinusHalf is sqrt(-1/2) -var sqrtMinusHalf = edwards25519.FieldElement{ - -17256545, 3971863, 28865457, -1750208, 27359696, -16640980, 12573105, 1002827, -163343, 11073975, -} - -// halfQMinus1Bytes is (2^255-20)/2 expressed in little endian form. -var halfQMinus1Bytes = [32]byte{ - 0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, -} - -// feBytesLess returns one if a <= b and zero otherwise. -func feBytesLE(a, b *[32]byte) int32 { - equalSoFar := int32(-1) - greater := int32(0) - - for i := uint(31); i < 32; i-- { - x := int32(a[i]) - y := int32(b[i]) - - greater = (^equalSoFar & greater) | (equalSoFar & ((x - y) >> 31)) - equalSoFar = equalSoFar & (((x ^ y) - 1) >> 31) - } - - return int32(^equalSoFar & 1 & greater) -} - -// ScalarBaseMult computes a curve25519 public key from a private key and also -// a uniform representative for that public key. Note that this function will -// fail and return false for about half of private keys. -// See http://elligator.cr.yp.to/elligator-20130828.pdf. -func ScalarBaseMult(publicKey, representative, privateKey *[32]byte) bool { - var maskedPrivateKey [32]byte - copy(maskedPrivateKey[:], privateKey[:]) - - maskedPrivateKey[0] &= 248 - maskedPrivateKey[31] &= 127 - maskedPrivateKey[31] |= 64 - - var A edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&A, &maskedPrivateKey) - - var inv1 edwards25519.FieldElement - edwards25519.FeSub(&inv1, &A.Z, &A.Y) - edwards25519.FeMul(&inv1, &inv1, &A.X) - edwards25519.FeInvert(&inv1, &inv1) - - var t0, u edwards25519.FieldElement - edwards25519.FeMul(&u, &inv1, &A.X) - edwards25519.FeAdd(&t0, &A.Y, &A.Z) - edwards25519.FeMul(&u, &u, &t0) - - var v edwards25519.FieldElement - edwards25519.FeMul(&v, &t0, &inv1) - edwards25519.FeMul(&v, &v, &A.Z) - edwards25519.FeMul(&v, &v, &sqrtMinusA) - - var b edwards25519.FieldElement - edwards25519.FeAdd(&b, &u, &edwards25519.A) - - var c, b3, b8 edwards25519.FieldElement - edwards25519.FeSquare(&b3, &b) // 2 - edwards25519.FeMul(&b3, &b3, &b) // 3 - edwards25519.FeSquare(&c, &b3) // 6 - edwards25519.FeMul(&c, &c, &b) // 7 - edwards25519.FeMul(&b8, &c, &b) // 8 - edwards25519.FeMul(&c, &c, &u) - q58(&c, &c) - - var chi edwards25519.FieldElement - edwards25519.FeSquare(&chi, &c) - edwards25519.FeSquare(&chi, &chi) - - edwards25519.FeSquare(&t0, &u) - edwards25519.FeMul(&chi, &chi, &t0) - - edwards25519.FeSquare(&t0, &b) // 2 - edwards25519.FeMul(&t0, &t0, &b) // 3 - edwards25519.FeSquare(&t0, &t0) // 6 - edwards25519.FeMul(&t0, &t0, &b) // 7 - edwards25519.FeSquare(&t0, &t0) // 14 - edwards25519.FeMul(&chi, &chi, &t0) - edwards25519.FeNeg(&chi, &chi) - - var chiBytes [32]byte - edwards25519.FeToBytes(&chiBytes, &chi) - // chi[1] is either 0 or 0xff - if chiBytes[1] == 0xff { - return false - } - - // Calculate r1 = sqrt(-u/(2*(u+A))) - var r1 edwards25519.FieldElement - edwards25519.FeMul(&r1, &c, &u) - edwards25519.FeMul(&r1, &r1, &b3) - edwards25519.FeMul(&r1, &r1, &sqrtMinusHalf) - - var maybeSqrtM1 edwards25519.FieldElement - edwards25519.FeSquare(&t0, &r1) - edwards25519.FeMul(&t0, &t0, &b) - edwards25519.FeAdd(&t0, &t0, &t0) - edwards25519.FeAdd(&t0, &t0, &u) - - edwards25519.FeOne(&maybeSqrtM1) - edwards25519.FeCMove(&maybeSqrtM1, &edwards25519.SqrtM1, edwards25519.FeIsNonZero(&t0)) - edwards25519.FeMul(&r1, &r1, &maybeSqrtM1) - - // Calculate r = sqrt(-(u+A)/(2u)) - var r edwards25519.FieldElement - edwards25519.FeSquare(&t0, &c) // 2 - edwards25519.FeMul(&t0, &t0, &c) // 3 - edwards25519.FeSquare(&t0, &t0) // 6 - edwards25519.FeMul(&r, &t0, &c) // 7 - - edwards25519.FeSquare(&t0, &u) // 2 - edwards25519.FeMul(&t0, &t0, &u) // 3 - edwards25519.FeMul(&r, &r, &t0) - - edwards25519.FeSquare(&t0, &b8) // 16 - edwards25519.FeMul(&t0, &t0, &b8) // 24 - edwards25519.FeMul(&t0, &t0, &b) // 25 - edwards25519.FeMul(&r, &r, &t0) - edwards25519.FeMul(&r, &r, &sqrtMinusHalf) - - edwards25519.FeSquare(&t0, &r) - edwards25519.FeMul(&t0, &t0, &u) - edwards25519.FeAdd(&t0, &t0, &t0) - edwards25519.FeAdd(&t0, &t0, &b) - edwards25519.FeOne(&maybeSqrtM1) - edwards25519.FeCMove(&maybeSqrtM1, &edwards25519.SqrtM1, edwards25519.FeIsNonZero(&t0)) - edwards25519.FeMul(&r, &r, &maybeSqrtM1) - - var vBytes [32]byte - edwards25519.FeToBytes(&vBytes, &v) - vInSquareRootImage := feBytesLE(&vBytes, &halfQMinus1Bytes) - edwards25519.FeCMove(&r, &r1, vInSquareRootImage) - - edwards25519.FeToBytes(publicKey, &u) - edwards25519.FeToBytes(representative, &r) - return true -} - -// q58 calculates out = z^((p-5)/8). -func q58(out, z *edwards25519.FieldElement) { - var t1, t2, t3 edwards25519.FieldElement - var i int - - edwards25519.FeSquare(&t1, z) // 2^1 - edwards25519.FeMul(&t1, &t1, z) // 2^1 + 2^0 - edwards25519.FeSquare(&t1, &t1) // 2^2 + 2^1 - edwards25519.FeSquare(&t2, &t1) // 2^3 + 2^2 - edwards25519.FeSquare(&t2, &t2) // 2^4 + 2^3 - edwards25519.FeMul(&t2, &t2, &t1) // 4,3,2,1 - edwards25519.FeMul(&t1, &t2, z) // 4..0 - edwards25519.FeSquare(&t2, &t1) // 5..1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - edwards25519.FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 19..0 - edwards25519.FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 39..0 - edwards25519.FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 49..0 - edwards25519.FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 99..0 - edwards25519.FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 199..0 - edwards25519.FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 249..0 - edwards25519.FeSquare(&t1, &t1) // 250..1 - edwards25519.FeSquare(&t1, &t1) // 251..2 - edwards25519.FeMul(out, &t1, z) // 251..2,0 -} - -// chi calculates out = z^((p-1)/2). The result is either 1, 0, or -1 depending -// on whether z is a non-zero square, zero, or a non-square. -func chi(out, z *edwards25519.FieldElement) { - var t0, t1, t2, t3 edwards25519.FieldElement - var i int - - edwards25519.FeSquare(&t0, z) // 2^1 - edwards25519.FeMul(&t1, &t0, z) // 2^1 + 2^0 - edwards25519.FeSquare(&t0, &t1) // 2^2 + 2^1 - edwards25519.FeSquare(&t2, &t0) // 2^3 + 2^2 - edwards25519.FeSquare(&t2, &t2) // 4,3 - edwards25519.FeMul(&t2, &t2, &t0) // 4,3,2,1 - edwards25519.FeMul(&t1, &t2, z) // 4..0 - edwards25519.FeSquare(&t2, &t1) // 5..1 - for i = 1; i < 5; i++ { // 9,8,7,6,5 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 9,8,7,6,5,4,3,2,1,0 - edwards25519.FeSquare(&t2, &t1) // 10..1 - for i = 1; i < 10; i++ { // 19..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 19..0 - edwards25519.FeSquare(&t3, &t2) // 20..1 - for i = 1; i < 20; i++ { // 39..20 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 39..0 - edwards25519.FeSquare(&t2, &t2) // 40..1 - for i = 1; i < 10; i++ { // 49..10 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 49..0 - edwards25519.FeSquare(&t2, &t1) // 50..1 - for i = 1; i < 50; i++ { // 99..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t2, &t2, &t1) // 99..0 - edwards25519.FeSquare(&t3, &t2) // 100..1 - for i = 1; i < 100; i++ { // 199..100 - edwards25519.FeSquare(&t3, &t3) - } - edwards25519.FeMul(&t2, &t3, &t2) // 199..0 - edwards25519.FeSquare(&t2, &t2) // 200..1 - for i = 1; i < 50; i++ { // 249..50 - edwards25519.FeSquare(&t2, &t2) - } - edwards25519.FeMul(&t1, &t2, &t1) // 249..0 - edwards25519.FeSquare(&t1, &t1) // 250..1 - for i = 1; i < 4; i++ { // 253..4 - edwards25519.FeSquare(&t1, &t1) - } - edwards25519.FeMul(out, &t1, &t0) // 253..4,2,1 -} - -// RepresentativeToPublicKey converts a uniform representative value for a -// curve25519 public key, as produced by ScalarBaseMult, to a curve25519 public -// key. -func RepresentativeToPublicKey(publicKey, representative *[32]byte) { - var rr2, v edwards25519.FieldElement - edwards25519.FeFromBytes(&rr2, representative) - representativeToMontgomeryX(&v, &rr2) - edwards25519.FeToBytes(publicKey, &v) -} - -// representativeToMontgomeryX consumes the rr2 input -func representativeToMontgomeryX(v, rr2 *edwards25519.FieldElement) { - var e edwards25519.FieldElement - edwards25519.FeSquare2(rr2, rr2) - rr2[0]++ - edwards25519.FeInvert(rr2, rr2) - edwards25519.FeMul(v, &edwards25519.A, rr2) - edwards25519.FeNeg(v, v) - - var v2, v3 edwards25519.FieldElement - edwards25519.FeSquare(&v2, v) - edwards25519.FeMul(&v3, v, &v2) - edwards25519.FeAdd(&e, &v3, v) - edwards25519.FeMul(&v2, &v2, &edwards25519.A) - edwards25519.FeAdd(&e, &v2, &e) - chi(&e, &e) - var eBytes [32]byte - edwards25519.FeToBytes(&eBytes, &e) - // eBytes[1] is either 0 (for e = 1) or 0xff (for e = -1) - eIsMinus1 := int32(eBytes[1]) & 1 - var negV edwards25519.FieldElement - edwards25519.FeNeg(&negV, v) - edwards25519.FeCMove(v, &negV, eIsMinus1) - - edwards25519.FeZero(&v2) - edwards25519.FeCMove(&v2, &edwards25519.A, eIsMinus1) - edwards25519.FeSub(v, v, &v2) -} - -func montgomeryXToEdwardsY(out, x *edwards25519.FieldElement) { - var t, tt edwards25519.FieldElement - edwards25519.FeOne(&t) - edwards25519.FeAdd(&tt, x, &t) // u+1 - edwards25519.FeInvert(&tt, &tt) // 1/(u+1) - edwards25519.FeSub(&t, x, &t) // u-1 - edwards25519.FeMul(out, &tt, &t) // (u-1)/(u+1) -} - -// HashToEdwards converts a 256-bit hash output into a point on the Edwards -// curve isomorphic to Curve25519 in a manner that preserves -// collision-resistance. The returned curve points are NOT indistinguishable -// from random even if the hash value is. -// Specifically, first one bit of the hash output is set aside for parity and -// the rest is truncated and fed into the elligator bijection (which covers half -// of the points on the elliptic curve). -func HashToEdwards(out *edwards25519.ExtendedGroupElement, h *[32]byte) { - hh := *h - bit := hh[31] >> 7 - hh[31] &= 127 - edwards25519.FeFromBytes(&out.Y, &hh) - representativeToMontgomeryX(&out.X, &out.Y) - montgomeryXToEdwardsY(&out.Y, &out.X) - if ok := out.FromParityAndY(bit, &out.Y); !ok { - panic("HashToEdwards: point not on curve") - } -} diff --git a/crypto/internal/ed25519/extra25519/extra25519_test.go b/crypto/internal/ed25519/extra25519/extra25519_test.go deleted file mode 100644 index e38740d0a..000000000 --- a/crypto/internal/ed25519/extra25519/extra25519_test.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package extra25519 - -import ( - "bytes" - "crypto/rand" - "crypto/sha512" - "testing" - - "github.com/sonr-io/sonr/crypto/internal/ed25519/edwards25519" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/ed25519" -) - -func TestCurve25519Conversion(t *testing.T) { - public, private, _ := ed25519.GenerateKey(rand.Reader) - var pubBytes [32]byte - copy(pubBytes[:], public) - var privBytes [64]byte - copy(privBytes[:], private) - - var curve25519Public, curve25519Public2, curve25519Private [32]byte - PrivateKeyToCurve25519(&curve25519Private, &privBytes) - curve25519.ScalarBaseMult(&curve25519Public, &curve25519Private) - - if !PublicKeyToCurve25519(&curve25519Public2, &pubBytes) { - t.Fatalf("PublicKeyToCurve25519 failed") - } - - if !bytes.Equal(curve25519Public[:], curve25519Public2[:]) { - t.Errorf( - "Values didn't match: curve25519 produced %x, conversion produced %x", - curve25519Public[:], - curve25519Public2[:], - ) - } -} - -func TestHashNoCollisions(t *testing.T) { - type intpair struct { - i int - j uint - } - rainbow := make(map[[32]byte]intpair) - N := 25 - if testing.Short() { - N = 3 - } - var h [32]byte - // NOTE: hash values 0b100000000000... and 0b00000000000... both map to - // the identity. this is a core part of the elligator function and not a - // collision we need to worry about because an attacker would need to find - // the preimages of these hashes to exploit it. - h[0] = 1 - for i := 0; i < N; i++ { - for j := range uint(257) { - if j < 256 { - h[j>>3] ^= byte(1) << (j & 7) - } - - var P edwards25519.ExtendedGroupElement - HashToEdwards(&P, &h) - var p [32]byte - P.ToBytes(&p) - if c, ok := rainbow[p]; ok { - t.Fatalf("found collision: (%d, %d) and (%d, %d)", i, j, c.i, c.j) - } - rainbow[p] = intpair{i, j} - - if j < 256 { - h[j>>3] ^= byte(1) << (j & 7) - } - } - hh := sha512.Sum512(h[:]) // this package already imports sha512 - copy(h[:], hh[:]) - } -} - -func TestElligator(t *testing.T) { - var publicKey, publicKey2, publicKey3, representative, privateKey [32]byte - - for range 1000 { - rand.Reader.Read(privateKey[:]) - - if !ScalarBaseMult(&publicKey, &representative, &privateKey) { - continue - } - RepresentativeToPublicKey(&publicKey2, &representative) - if !bytes.Equal(publicKey[:], publicKey2[:]) { - t.Fatal("The resulting public key doesn't match the initial one.") - } - - curve25519.ScalarBaseMult(&publicKey3, &privateKey) - if !bytes.Equal(publicKey[:], publicKey3[:]) { - t.Fatal("The public key doesn't match the value that curve25519 produced.") - } - } -} - -func BenchmarkKeyGeneration(b *testing.B) { - var publicKey, representative, privateKey [32]byte - - // Find the private key that results in a point that's in the image of the map. - for { - rand.Reader.Read(privateKey[:]) - if ScalarBaseMult(&publicKey, &representative, &privateKey) { - break - } - } - - for b.Loop() { - ScalarBaseMult(&publicKey, &representative, &privateKey) - } -} - -func BenchmarkMap(b *testing.B) { - var publicKey, representative [32]byte - rand.Reader.Read(representative[:]) - - for b.Loop() { - RepresentativeToPublicKey(&publicKey, &representative) - } -} diff --git a/crypto/internal/err.go b/crypto/internal/err.go deleted file mode 100755 index b5b693418..000000000 --- a/crypto/internal/err.go +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package internal - -import "fmt" - -var ( - ErrNotOnCurve = fmt.Errorf("point not on the curve") - ErrPointsDistinctCurves = fmt.Errorf("points must be from the same curve") - ErrZmMembership = fmt.Errorf("x ∉ Z_m") - ErrResidueOne = fmt.Errorf("value must be 1 (mod N)") - ErrNCannotBeZero = fmt.Errorf("n cannot be 0") - ErrNilArguments = fmt.Errorf("arguments cannot be nil") - ErrZeroValue = fmt.Errorf("arguments cannot be 0") - ErrInvalidRound = fmt.Errorf("invalid round method called") - ErrIncorrectCount = fmt.Errorf("incorrect number of inputs") - ErrInvalidJson = fmt.Errorf("json format does not contain the necessary data") -) diff --git a/crypto/internal/hash.go b/crypto/internal/hash.go deleted file mode 100755 index b05f66fa4..000000000 --- a/crypto/internal/hash.go +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package internal - -import ( - "bytes" - "crypto/sha256" - "fmt" - - "golang.org/x/crypto/hkdf" -) - -// Hash computes the HKDF over many values -// iteratively such that each value is hashed separately -// and based on preceding values -// -// The first value is computed as okm_0 = KDF(f || value) where -// f is a byte slice of 32 0xFF -// salt is zero-filled byte slice with length equal to the hash output length -// info is the protocol name -// okm is the 32 byte output -// -// The each subsequent iteration is computed by as okm_i = KDF(f_i || value || okm_{i-1}) -// where f_i = 2^b - 1 - i such that there are 0xFF bytes prior to the value. -// f_1 changes the first byte to 0xFE, f_2 to 0xFD. The previous okm is appended to the value -// to provide cryptographic domain separation. -// See https://signal.org/docs/specifications/x3dh/#cryptographic-notation -// and https://signal.org/docs/specifications/xeddsa/#hash-functions -// for more details. -// This uses the KDF function similar to X3DH for each `value` -// But changes the key just like XEdDSA where the prefix bytes change by a single bit -func Hash(info []byte, values ...[]byte) ([]byte, error) { - // Don't accept any nil arguments - if anyNil(values...) { - return nil, ErrNilArguments - } - - salt := make([]byte, 32) - okm := make([]byte, 32) - f := bytes.Repeat([]byte{0xFF}, 32) - - for _, b := range values { - ikm := append(f, b...) - ikm = append(ikm, okm...) - kdf := hkdf.New(sha256.New, ikm, salt, info) - n, err := kdf.Read(okm) - if err != nil { - return nil, err - } - if n != len(okm) { - return nil, fmt.Errorf( - "unable to read expected number of bytes want=%v got=%v", - len(okm), - n, - ) - } - ByteSub(f) - } - return okm, nil -} - -func anyNil(values ...[]byte) bool { - for _, x := range values { - if x == nil { - return true - } - } - return false -} - -// ByteSub is a constant time algorithm for subtracting -// 1 from the array as if it were a big number. -// 0 is considered a wrap which resets to 0xFF -func ByteSub(b []byte) { - m := byte(1) - for i := 0; i < len(b); i++ { - b[i] -= m - - // If b[i] > 0, s == 0 - // If b[i] == 0, s == 1 - // Computing IsNonZero(b[i]) - s1 := int8(b[i]) >> 7 - s2 := -int8(b[i]) >> 7 - s := byte((s1 | s2) + 1) - - // If s == 0, don't subtract anymore - // s == 1, continue subtracting - m = s & m - // If s == 0 this does nothing - // If s == 1 reset this value to 0xFF - b[i] |= -s - } -} diff --git a/crypto/internal/hash_test.go b/crypto/internal/hash_test.go deleted file mode 100755 index 638cc909e..000000000 --- a/crypto/internal/hash_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package internal - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestByteSub(t *testing.T) { - f := bytes.Repeat([]byte{0xFF}, 32) - ByteSub(f) - require.Equal(t, f[0], byte(0xFE)) - for i := 1; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } - ByteSub(f) - require.Equal(t, f[0], byte(0xFD)) - for i := 1; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } - f[0] = 0x2 - ByteSub(f) - for i := 1; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } - ByteSub(f) - require.Equal(t, f[0], byte(0xFF)) - require.Equal(t, f[1], byte(0xFE)) - for i := 2; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } - ByteSub(f) - require.Equal(t, f[0], byte(0xFE)) - require.Equal(t, f[1], byte(0xFE)) - for i := 2; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } - f[0] = 1 - f[1] = 1 - ByteSub(f) - require.Equal(t, f[0], byte(0xFF)) - require.Equal(t, f[1], byte(0xFF)) - require.Equal(t, f[2], byte(0xFE)) - for i := 3; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } -} - -func TestByteSubAll1(t *testing.T) { - f := bytes.Repeat([]byte{0x1}, 32) - ByteSub(f) - for i := 0; i < len(f); i++ { - require.Equal(t, f[i], byte(0xFF)) - } -} diff --git a/crypto/internal/point.go b/crypto/internal/point.go deleted file mode 100755 index 6393e803a..000000000 --- a/crypto/internal/point.go +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package internal - -import ( - "crypto/elliptic" - "math/big" - - "filippo.io/edwards25519" -) - -func CalcFieldSize(curve elliptic.Curve) int { - bits := curve.Params().BitSize - return (bits + 7) / 8 -} - -func ReverseScalarBytes(inBytes []byte) []byte { - outBytes := make([]byte, len(inBytes)) - - for i, j := 0, len(inBytes)-1; j >= 0; i, j = i+1, j-1 { - outBytes[i] = inBytes[j] - } - - return outBytes -} - -func BigInt2Ed25519Point(y *big.Int) (*edwards25519.Point, error) { - b := y.Bytes() - var arr [32]byte - copy(arr[32-len(b):], b) - return edwards25519.NewIdentityPoint().SetBytes(arr[:]) -} - -func BigInt2Ed25519Scalar(x *big.Int) (*edwards25519.Scalar, error) { - // big.Int is big endian; ed25519 assumes little endian encoding - kBytes := ReverseScalarBytes(x.Bytes()) - var arr [32]byte - copy(arr[:], kBytes) - return edwards25519.NewScalar().SetCanonicalBytes(arr[:]) -} diff --git a/crypto/internal/testutils.go b/crypto/internal/testutils.go deleted file mode 100755 index eec48970e..000000000 --- a/crypto/internal/testutils.go +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package internal - -import ( - "math/big" -) - -// B10 creating a big.Int from a base 10 string. panics on failure to -// ensure zero-values aren't used in place of malformed strings. -func B10(s string) *big.Int { - x, ok := new(big.Int).SetString(s, 10) - if !ok { - panic("Couldn't derive big.Int from string") - } - return x -} diff --git a/crypto/keys/didkey.go b/crypto/keys/didkey.go deleted file mode 100644 index c4fb29802..000000000 --- a/crypto/keys/didkey.go +++ /dev/null @@ -1,300 +0,0 @@ -package keys - -import ( - "crypto/ed25519" - "crypto/rsa" - "crypto/x509" - "fmt" - "strings" - - "github.com/libp2p/go-libp2p/core/crypto" - mb "github.com/multiformats/go-multibase" - varint "github.com/multiformats/go-varint" -) - -const ( - // KeyPrefix indicates a decentralized identifier that uses the key method - KeyPrefix = "did:key" - // MulticodecKindRSAPubKey rsa-x509-pub https://github.com/multiformats/multicodec/pull/226 - MulticodecKindRSAPubKey = 0x1205 - // MulticodecKindEd25519PubKey ed25519-pub - MulticodecKindEd25519PubKey = 0xed - // MulticodecKindSecp256k1PubKey secp256k1-pub - MulticodecKindSecp256k1PubKey = 0xe7 -) - -// DID is a DID:key identifier -type DID struct { - crypto.PubKey -} - -// NewDID constructs an Identifier from a public key -func NewDID(pub crypto.PubKey) (DID, error) { - switch pub.Type() { - case crypto.Ed25519, crypto.RSA, crypto.Secp256k1: - return DID{PubKey: pub}, nil - default: - return DID{}, fmt.Errorf("unsupported key type: %s", pub.Type()) - } -} - -// NewFromPubKey constructs an Identifier from a public key -func NewFromPubKey(pub PubKey) DID { - return DID{PubKey: pub} -} - -// MulticodecType indicates the type for this multicodec -func (id DID) MulticodecType() uint64 { - switch id.Type() { - case crypto.RSA: - return MulticodecKindRSAPubKey - case crypto.Ed25519: - return MulticodecKindEd25519PubKey - case crypto.Secp256k1: - return MulticodecKindSecp256k1PubKey - default: - panic("unexpected crypto type") - } -} - -// String returns this did:key formatted as a string -func (id DID) String() string { - raw, err := id.Raw() - if err != nil { - return "" - } - - t := id.MulticodecType() - size := varint.UvarintSize(t) - data := make([]byte, size+len(raw)) - n := varint.PutUvarint(data, t) - copy(data[n:], raw) - - b58BKeyStr, err := mb.Encode(mb.Base58BTC, data) - if err != nil { - return "" - } - - return fmt.Sprintf("%s:%s", KeyPrefix, b58BKeyStr) -} - -// PublicKey returns the underlying crypto.PubKey -func (id DID) PublicKey() crypto.PubKey { - return id.PubKey -} - -// VerifyKey returns the backing implementation for a public key, one of: -// *rsa.PublicKey, ed25519.PublicKey -func (id DID) VerifyKey() (any, error) { - rawPubBytes, err := id.Raw() - if err != nil { - return nil, err - } - switch id.Type() { - case crypto.RSA: - verifyKeyiface, err := x509.ParsePKIXPublicKey(rawPubBytes) - if err != nil { - return nil, err - } - verifyKey, ok := verifyKeyiface.(*rsa.PublicKey) - if !ok { - return nil, fmt.Errorf("public key is not an RSA key. got type: %T", verifyKeyiface) - } - return verifyKey, nil - case crypto.Ed25519: - return ed25519.PublicKey(rawPubBytes), nil - case crypto.Secp256k1: - // Handle both compressed and uncompressed Secp256k1 public keys - if len(rawPubBytes) == 65 || len(rawPubBytes) == 33 { - return rawPubBytes, nil - } - return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes)) - default: - return nil, fmt.Errorf("unrecognized Public Key type: %s", id.Type()) - } -} - -// Parse turns a string into a key method ID -func Parse(keystr string) (DID, error) { - var id DID - if !strings.HasPrefix(keystr, KeyPrefix) { - return id, fmt.Errorf("decentralized identifier is not a 'key' type") - } - - keystr = strings.TrimPrefix(keystr, KeyPrefix+":") - - enc, data, err := mb.Decode(keystr) - if err != nil { - return id, fmt.Errorf("decoding multibase: %w", err) - } - - if enc != mb.Base58BTC { - return id, fmt.Errorf("unexpected multibase encoding: %s", mb.EncodingToStr[enc]) - } - - keyType, n, err := varint.FromUvarint(data) - if err != nil { - return id, err - } - - switch keyType { - case MulticodecKindRSAPubKey: - pub, err := crypto.UnmarshalRsaPublicKey(data[n:]) - if err != nil { - return id, err - } - return DID{pub}, nil - case MulticodecKindEd25519PubKey: - pub, err := crypto.UnmarshalEd25519PublicKey(data[n:]) - if err != nil { - return id, err - } - return DID{pub}, nil - case MulticodecKindSecp256k1PubKey: - // Handle both compressed and uncompressed formats - keyData := data[n:] - if len(keyData) != 33 && len(keyData) != 65 { - return id, fmt.Errorf("invalid Secp256k1 public key length: %d", len(keyData)) - } - pub, err := crypto.UnmarshalSecp256k1PublicKey(keyData) - if err != nil { - return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err) - } - return DID{pub}, nil - } - - return id, fmt.Errorf("unrecognized key type multicodec prefix: %x", data[0]) -} - -// NewFromMPCPubKey creates a DID from MPC enclave public key bytes. -// This is specifically designed for MPC enclave integration where public key bytes -// are provided directly from the enclave without additional encoding. -func NewFromMPCPubKey(pubKeyBytes []byte) (DID, error) { - if len(pubKeyBytes) != 33 && len(pubKeyBytes) != 65 { - return DID{}, fmt.Errorf( - "invalid Secp256k1 public key length: %d, expected 33 or 65 bytes", - len(pubKeyBytes), - ) - } - - pub, err := crypto.UnmarshalSecp256k1PublicKey(pubKeyBytes) - if err != nil { - return DID{}, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err) - } - - return DID{PubKey: pub}, nil -} - -// Address derives a blockchain-compatible address from the DID. -// This provides a consistent address format for use across different blockchain contexts. -func (id DID) Address() (string, error) { - rawPubBytes, err := id.Raw() - if err != nil { - return "", fmt.Errorf("failed to get raw public key: %w", err) - } - - switch id.Type() { - case crypto.Secp256k1: - // For Secp256k1, derive address from compressed public key - if len(rawPubBytes) == 65 { - // Convert uncompressed to compressed format if needed - pubKey := rawPubBytes[1:] // Remove 0x04 prefix - x := pubKey[:32] - y := pubKey[32:] - - // Determine compression prefix (0x02 for even y, 0x03 for odd y) - prefix := byte(0x02) - if y[31]&1 == 1 { - prefix = 0x03 - } - - compressedKey := make([]byte, 33) - compressedKey[0] = prefix - copy(compressedKey[1:], x) - rawPubBytes = compressedKey - } - - // Create address using first 20 bytes of Keccak-256 hash (Ethereum-style) - return fmt.Sprintf("sonr1%x", rawPubBytes[:8]), nil - - case crypto.Ed25519: - // For Ed25519, use the raw public key bytes - return fmt.Sprintf("sonr1%x", rawPubBytes[:8]), nil - - case crypto.RSA: - // For RSA, hash the public key and use first 8 bytes - return fmt.Sprintf("sonr1%x", rawPubBytes[:8]), nil - - default: - return "", fmt.Errorf("unsupported key type for address derivation: %s", id.Type()) - } -} - -// CompressedPubKey returns the compressed public key bytes for Secp256k1 keys. -// For other key types, returns the raw public key bytes. -func (id DID) CompressedPubKey() ([]byte, error) { - rawPubBytes, err := id.Raw() - if err != nil { - return nil, fmt.Errorf("failed to get raw public key: %w", err) - } - - switch id.Type() { - case crypto.Secp256k1: - if len(rawPubBytes) == 33 { - // Already compressed - return rawPubBytes, nil - } else if len(rawPubBytes) == 65 { - // Convert uncompressed to compressed - pubKey := rawPubBytes[1:] // Remove 0x04 prefix - x := pubKey[:32] - y := pubKey[32:] - - // Determine compression prefix (0x02 for even y, 0x03 for odd y) - prefix := byte(0x02) - if y[31]&1 == 1 { - prefix = 0x03 - } - - compressedKey := make([]byte, 33) - compressedKey[0] = prefix - copy(compressedKey[1:], x) - return compressedKey, nil - } - return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes)) - - default: - // For non-Secp256k1 keys, return raw bytes - return rawPubBytes, nil - } -} - -// ValidateFormat validates that the DID string conforms to proper did:key format. -// This ensures the DID follows the W3C DID specification with proper multicodec encoding. -func ValidateFormat(didString string) error { - if !strings.HasPrefix(didString, KeyPrefix) { - return fmt.Errorf("DID must start with '%s'", KeyPrefix) - } - - // Try to parse the DID to validate its structure - _, err := Parse(didString) - if err != nil { - return fmt.Errorf("invalid DID format: %w", err) - } - - return nil -} - -// GetMulticodecType returns the multicodec type for a given crypto key type. -// This is useful for external validation and encoding operations. -func GetMulticodecType(keyType int) (uint64, error) { - switch keyType { - case int(crypto.RSA): - return MulticodecKindRSAPubKey, nil - case int(crypto.Ed25519): - return MulticodecKindEd25519PubKey, nil - case int(crypto.Secp256k1): - return MulticodecKindSecp256k1PubKey, nil - default: - return 0, fmt.Errorf("unsupported key type: %d", keyType) - } -} diff --git a/crypto/keys/didkey_test.go b/crypto/keys/didkey_test.go deleted file mode 100644 index 1e2468fb1..000000000 --- a/crypto/keys/didkey_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package keys - -import ( - "crypto/rand" - "testing" - - "github.com/libp2p/go-libp2p/core/crypto" -) - -// generateSecp256k1Key generates a test Secp256k1 key pair -func generateSecp256k1Key(t *testing.T) crypto.PrivKey { - privKey, _, err := crypto.GenerateSecp256k1Key(rand.Reader) - if err != nil { - t.Fatalf("Failed to generate Secp256k1 key: %v", err) - } - return privKey -} - -// TestNewFromMPCPubKey tests creating DIDs from MPC public key bytes -func TestNewFromMPCPubKey(t *testing.T) { - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - // Get raw public key bytes - pubKeyBytes, err := pubKey.Raw() - if err != nil { - t.Fatalf("Failed to get raw public key: %v", err) - } - - // Test with compressed key (33 bytes) - if len(pubKeyBytes) == 33 { - did, err := NewFromMPCPubKey(pubKeyBytes) - if err != nil { - t.Errorf("NewFromMPCPubKey failed with compressed key: %v", err) - } - - if did.Type() != crypto.Secp256k1 { - t.Errorf("Expected Secp256k1 key type, got %v", did.Type()) - } - } - - // Test with invalid key lengths - invalidKeys := [][]byte{ - make([]byte, 32), // Too short - make([]byte, 34), // Wrong length - make([]byte, 66), // Too long - } - - for _, invalidKey := range invalidKeys { - _, err := NewFromMPCPubKey(invalidKey) - if err == nil { - t.Errorf("Expected error with invalid key length %d, got nil", len(invalidKey)) - } - } -} - -// TestSecp256k1MulticodecFix tests that the multicodec value is correct -func TestSecp256k1MulticodecFix(t *testing.T) { - if MulticodecKindSecp256k1PubKey != 0xe7 { - t.Errorf( - "Expected Secp256k1 multicodec to be 0xe7, got 0x%x", - MulticodecKindSecp256k1PubKey, - ) - } - - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - did := DID{PubKey: pubKey} - multicodecType := did.MulticodecType() - - if multicodecType != 0xe7 { - t.Errorf("Expected multicodec type 0xe7, got 0x%x", multicodecType) - } -} - -// TestAddress tests blockchain-compatible address derivation -func TestAddress(t *testing.T) { - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - did := DID{PubKey: pubKey} - - address, err := did.Address() - if err != nil { - t.Fatalf("Failed to derive address: %v", err) - } - - // Check that address starts with "sonr1" - if len(address) < 5 || address[:5] != "sonr1" { - t.Errorf("Expected address to start with 'sonr1', got %s", address) - } - - // Check that address is deterministic - address2, err := did.Address() - if err != nil { - t.Fatalf("Failed to derive address second time: %v", err) - } - - if address != address2 { - t.Errorf("Address derivation not deterministic: %s != %s", address, address2) - } -} - -// TestCompressedPubKey tests public key compression -func TestCompressedPubKey(t *testing.T) { - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - did := DID{PubKey: pubKey} - - compressed, err := did.CompressedPubKey() - if err != nil { - t.Fatalf("Failed to get compressed public key: %v", err) - } - - // Check that compressed key is 33 bytes for Secp256k1 - if len(compressed) != 33 { - t.Errorf("Expected compressed key length 33, got %d", len(compressed)) - } - - // Check that compression prefix is valid (0x02 or 0x03) - if compressed[0] != 0x02 && compressed[0] != 0x03 { - t.Errorf("Invalid compression prefix: 0x%02x", compressed[0]) - } -} - -// TestValidateFormat tests DID string format validation -func TestValidateFormat(t *testing.T) { - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - did := DID{PubKey: pubKey} - didString := did.String() - - // Valid DID should pass validation - err := ValidateFormat(didString) - if err != nil { - t.Errorf("Valid DID failed validation: %v", err) - } - - // Invalid DIDs should fail validation - invalidDIDs := []string{ - "invalid:key:z123", // Wrong method - "did:invalid:z123", // Wrong key method - "did:key:invalid", // Invalid encoding - "not-a-did-at-all", // Not a DID - "", // Empty string - } - - for _, invalidDID := range invalidDIDs { - err := ValidateFormat(invalidDID) - if err == nil { - t.Errorf("Invalid DID '%s' passed validation", invalidDID) - } - } -} - -// TestGetMulticodecType tests multicodec type lookup -func TestGetMulticodecType(t *testing.T) { - testCases := []struct { - keyType int - expected uint64 - }{ - {int(crypto.RSA), MulticodecKindRSAPubKey}, - {int(crypto.Ed25519), MulticodecKindEd25519PubKey}, - {int(crypto.Secp256k1), MulticodecKindSecp256k1PubKey}, - } - - for _, tc := range testCases { - result, err := GetMulticodecType(tc.keyType) - if err != nil { - t.Errorf("GetMulticodecType failed for type %d: %v", tc.keyType, err) - } - if result != tc.expected { - t.Errorf( - "GetMulticodecType for type %d: expected 0x%x, got 0x%x", - tc.keyType, - tc.expected, - result, - ) - } - } - - // Test invalid key type - _, err := GetMulticodecType(999) - if err == nil { - t.Errorf("GetMulticodecType should fail for invalid key type") - } -} - -// TestDIDStringFormat tests complete DID string generation and parsing -func TestDIDStringFormat(t *testing.T) { - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - - did := DID{PubKey: pubKey} - didString := did.String() - - // Check that DID starts with "did:key:z" - if len(didString) < 9 || didString[:9] != "did:key:z" { - t.Errorf("DID string should start with 'did:key:z', got %s", didString) - } - - // Parse the DID back - parsedDID, err := Parse(didString) - if err != nil { - t.Fatalf("Failed to parse generated DID: %v", err) - } - - // Verify parsed DID generates same string - parsedString := parsedDID.String() - if parsedString != didString { - t.Errorf("Parsed DID string mismatch: %s != %s", parsedString, didString) - } - - // Verify key types match - if parsedDID.Type() != did.Type() { - t.Errorf("Parsed DID key type mismatch: %v != %v", parsedDID.Type(), did.Type()) - } -} - -// TestMPCIntegration tests end-to-end MPC public key integration -func TestMPCIntegration(t *testing.T) { - // Generate a valid MPC enclave public key for testing - privKey := generateSecp256k1Key(t) - pubKey := privKey.GetPublic() - mpcPubKeyBytes, err := pubKey.Raw() - if err != nil { - t.Fatalf("Failed to get raw public key: %v", err) - } - - // Create DID from MPC public key - did, err := NewFromMPCPubKey(mpcPubKeyBytes) - if err != nil { - t.Fatalf("Failed to create DID from MPC public key: %v", err) - } - - // Test DID string generation - didString := did.String() - if len(didString) == 0 { - t.Error("Generated DID string is empty") - } - - // Test address derivation - address, err := did.Address() - if err != nil { - t.Fatalf("Failed to derive address: %v", err) - } - - if len(address) == 0 || address[:5] != "sonr1" { - t.Errorf("Invalid address format: %s", address) - } - - // Test compressed public key - compressed, err := did.CompressedPubKey() - if err != nil { - t.Fatalf("Failed to get compressed key: %v", err) - } - - if len(compressed) != 33 { - t.Errorf("Expected 33-byte compressed key, got %d bytes", len(compressed)) - } - - // Verify round-trip: DID -> string -> parse -> DID - parsedDID, err := Parse(didString) - if err != nil { - t.Fatalf("Failed to parse generated DID: %v", err) - } - - parsedAddress, err := parsedDID.Address() - if err != nil { - t.Fatalf("Failed to derive address from parsed DID: %v", err) - } - - if address != parsedAddress { - t.Errorf("Address mismatch after round-trip: %s != %s", address, parsedAddress) - } -} diff --git a/crypto/keys/methods.go b/crypto/keys/methods.go deleted file mode 100644 index 7c972e8a6..000000000 --- a/crypto/keys/methods.go +++ /dev/null @@ -1,17 +0,0 @@ -package keys - -type DIDMethod string - -const ( - DIDMethodKey DIDMethod = "key" - DIDMethodSonr DIDMethod = "sonr" - DIDMehthodBitcoin DIDMethod = "btcr" - DIDMethodEthereum DIDMethod = "ethr" - DIDMethodCbor DIDMethod = "cbor" - DIDMethodCID DIDMethod = "cid" - DIDMethodIPFS DIDMethod = "ipfs" -) - -func (d DIDMethod) String() string { - return string(d) -} diff --git a/crypto/keys/parsers/btc_parser.go b/crypto/keys/parsers/btc_parser.go deleted file mode 100644 index 3ece6e2d4..000000000 --- a/crypto/keys/parsers/btc_parser.go +++ /dev/null @@ -1 +0,0 @@ -package parsers diff --git a/crypto/keys/parsers/cosmos_parser.go b/crypto/keys/parsers/cosmos_parser.go deleted file mode 100644 index a66145cea..000000000 --- a/crypto/keys/parsers/cosmos_parser.go +++ /dev/null @@ -1,12 +0,0 @@ -package parsers - -type CosmosPrefix string - -const ( - ATOMPrefix CosmosPrefix = "cosmos" - AXELARPrefix CosmosPrefix = "axelar" - EVMOSPrefix CosmosPrefix = "evmos" - OSMOPrefix CosmosPrefix = "osmo" - SONRPrefix CosmosPrefix = "idx" - STARSPrefix CosmosPrefix = "stars" -) diff --git a/crypto/keys/parsers/eth_parser.go b/crypto/keys/parsers/eth_parser.go deleted file mode 100644 index 3ece6e2d4..000000000 --- a/crypto/keys/parsers/eth_parser.go +++ /dev/null @@ -1 +0,0 @@ -package parsers diff --git a/crypto/keys/parsers/fil_parser.go b/crypto/keys/parsers/fil_parser.go deleted file mode 100644 index 3ece6e2d4..000000000 --- a/crypto/keys/parsers/fil_parser.go +++ /dev/null @@ -1 +0,0 @@ -package parsers diff --git a/crypto/keys/parsers/key_parser.go b/crypto/keys/parsers/key_parser.go deleted file mode 100644 index 017f1cec3..000000000 --- a/crypto/keys/parsers/key_parser.go +++ /dev/null @@ -1,157 +0,0 @@ -package parsers - -import ( - "crypto/ed25519" - "crypto/rsa" - "crypto/x509" - "fmt" - "strings" - - "github.com/libp2p/go-libp2p/core/crypto" - mb "github.com/multiformats/go-multibase" - varint "github.com/multiformats/go-varint" -) - -const ( - // KeyPrefix indicates a decentralized identifier that uses the key method - KeyPrefix = "did:key" - // MulticodecKindRSAPubKey rsa-x509-pub https://github.com/multiformats/multicodec/pull/226 - MulticodecKindRSAPubKey = 0x1205 - // MulticodecKindEd25519PubKey ed25519-pub - MulticodecKindEd25519PubKey = 0xed - // MulticodecKindSecp256k1PubKey secp256k1-pub - MulticodecKindSecp256k1PubKey = 0x1206 -) - -// DIDKey is a DID:key identifier -type DIDKey struct { - crypto.PubKey -} - -// NewKeyDID constructs an Identifier from a public key -func NewKeyDID(pub crypto.PubKey) (DIDKey, error) { - switch pub.Type() { - case crypto.Ed25519, crypto.RSA, crypto.Secp256k1: - return DIDKey{PubKey: pub}, nil - default: - return DIDKey{}, fmt.Errorf("unsupported key type: %s", pub.Type()) - } -} - -// MulticodecType indicates the type for this multicodec -func (id DIDKey) MulticodecType() uint64 { - switch id.Type() { - case crypto.RSA: - return MulticodecKindRSAPubKey - case crypto.Ed25519: - return MulticodecKindEd25519PubKey - case crypto.Secp256k1: - return MulticodecKindSecp256k1PubKey - default: - panic("unexpected crypto type") - } -} - -// String returns this did:key formatted as a string -func (id DIDKey) String() string { - raw, err := id.Raw() - if err != nil { - return "" - } - - t := id.MulticodecType() - size := varint.UvarintSize(t) - data := make([]byte, size+len(raw)) - n := varint.PutUvarint(data, t) - copy(data[n:], raw) - - b58BKeyStr, err := mb.Encode(mb.Base58BTC, data) - if err != nil { - return "" - } - - return fmt.Sprintf("%s:%s", KeyPrefix, b58BKeyStr) -} - -// VerifyKey returns the backing implementation for a public key, one of: -// *rsa.PublicKey, ed25519.PublicKey -func (id DIDKey) VerifyKey() (any, error) { - rawPubBytes, err := id.PubKey.Raw() - if err != nil { - return nil, err - } - switch id.PubKey.Type() { - case crypto.RSA: - verifyKeyiface, err := x509.ParsePKIXPublicKey(rawPubBytes) - if err != nil { - return nil, err - } - verifyKey, ok := verifyKeyiface.(*rsa.PublicKey) - if !ok { - return nil, fmt.Errorf("public key is not an RSA key. got type: %T", verifyKeyiface) - } - return verifyKey, nil - case crypto.Ed25519: - return ed25519.PublicKey(rawPubBytes), nil - case crypto.Secp256k1: - // Handle both compressed and uncompressed Secp256k1 public keys - if len(rawPubBytes) == 65 || len(rawPubBytes) == 33 { - return rawPubBytes, nil - } - return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes)) - default: - return nil, fmt.Errorf("unrecognized Public Key type: %s", id.Type()) - } -} - -// Parse turns a string into a key method ID -func Parse(keystr string) (DIDKey, error) { - var id DIDKey - if !strings.HasPrefix(keystr, KeyPrefix) { - return id, fmt.Errorf("decentralized identifier is not a 'key' type") - } - - keystr = strings.TrimPrefix(keystr, KeyPrefix+":") - - enc, data, err := mb.Decode(keystr) - if err != nil { - return id, fmt.Errorf("decoding multibase: %w", err) - } - - if enc != mb.Base58BTC { - return id, fmt.Errorf("unexpected multibase encoding: %s", mb.EncodingToStr[enc]) - } - - keyType, n, err := varint.FromUvarint(data) - if err != nil { - return id, err - } - - switch keyType { - case MulticodecKindRSAPubKey: - pub, err := crypto.UnmarshalRsaPublicKey(data[n:]) - if err != nil { - return id, err - } - return DIDKey{pub}, nil - case MulticodecKindEd25519PubKey: - pub, err := crypto.UnmarshalEd25519PublicKey(data[n:]) - if err != nil { - return id, err - } - return DIDKey{pub}, nil - case MulticodecKindSecp256k1PubKey: - // Handle both compressed and uncompressed formats - keyData := data[n:] - if len(keyData) != 33 && len(keyData) != 65 { - return id, fmt.Errorf("invalid Secp256k1 public key length: %d", len(keyData)) - } - pub, err := crypto.UnmarshalSecp256k1PublicKey(keyData) - if err != nil { - return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err) - } - return DIDKey{pub}, nil - } - - return id, fmt.Errorf("unrecognized key type multicodec prefix: %x", data[0]) -} diff --git a/crypto/keys/parsers/sol_parser.go b/crypto/keys/parsers/sol_parser.go deleted file mode 100644 index 3ece6e2d4..000000000 --- a/crypto/keys/parsers/sol_parser.go +++ /dev/null @@ -1 +0,0 @@ -package parsers diff --git a/crypto/keys/parsers/ton_parser.go b/crypto/keys/parsers/ton_parser.go deleted file mode 100644 index 3ece6e2d4..000000000 --- a/crypto/keys/parsers/ton_parser.go +++ /dev/null @@ -1 +0,0 @@ -package parsers diff --git a/crypto/keys/pubkey.go b/crypto/keys/pubkey.go deleted file mode 100644 index 580dece01..000000000 --- a/crypto/keys/pubkey.go +++ /dev/null @@ -1,85 +0,0 @@ -package keys - -import ( - "bytes" - "crypto/ecdsa" - "encoding/hex" - - p2pcrypto "github.com/libp2p/go-libp2p/core/crypto" - p2ppb "github.com/libp2p/go-libp2p/core/crypto/pb" - "github.com/sonr-io/sonr/crypto/core/curves" - "golang.org/x/crypto/sha3" -) - -type PubKey interface { - Bytes() []byte - Raw() ([]byte, error) - Equals(b p2pcrypto.Key) bool - Type() p2ppb.KeyType - Hex() string - Verify(msg []byte, sig []byte) (bool, error) -} - -type pubKey struct { - publicPoint curves.Point -} - -func NewPubKey(pk curves.Point) PubKey { - return &pubKey{ - publicPoint: pk, - } -} - -func (p pubKey) Bytes() []byte { - return p.publicPoint.ToAffineCompressed() -} - -func (p pubKey) Raw() ([]byte, error) { - return p.publicPoint.ToAffineCompressed(), nil -} - -func (p pubKey) Equals(b p2pcrypto.Key) bool { - if b == nil { - return false - } - apbz, err := b.Raw() - if err != nil { - return false - } - bbz, err := p.Raw() - if err != nil { - return false - } - return bytes.Equal(apbz, bbz) -} - -func (p pubKey) Hex() string { - return hex.EncodeToString(p.publicPoint.ToAffineCompressed()) -} - -func (p pubKey) Type() p2ppb.KeyType { - return p2ppb.KeyType_Secp256k1 -} - -func (p pubKey) Verify(data []byte, sigBz []byte) (bool, error) { - sig, err := deserializeSignature(sigBz) - if err != nil { - return false, err - } - pp, err := getEcdsaPoint(p.Bytes()) - if err != nil { - return false, err - } - pk := &ecdsa.PublicKey{ - Curve: pp.Curve, - X: pp.X, - Y: pp.Y, - } - - // Hash the message using SHA3-256 - hash := sha3.New256() - hash.Write(data) - digest := hash.Sum(nil) - - return ecdsa.Verify(pk, digest, sig.R, sig.S), nil -} diff --git a/crypto/keys/utils.go b/crypto/keys/utils.go deleted file mode 100644 index 8be76a0cc..000000000 --- a/crypto/keys/utils.go +++ /dev/null @@ -1,34 +0,0 @@ -package keys - -import ( - "errors" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// getEcdsaPoint builds an elliptic curve point from a compressed byte slice -func getEcdsaPoint(pubKey []byte) (*curves.EcPoint, error) { - crv := curves.K256() - x := new(big.Int).SetBytes(pubKey[1:33]) - y := new(big.Int).SetBytes(pubKey[33:]) - ecCurve, err := crv.ToEllipticCurve() - if err != nil { - return nil, fmt.Errorf("error converting curve: %v", err) - } - return &curves.EcPoint{X: x, Y: y, Curve: ecCurve}, nil -} - -// DeserializeSecp256k1Signature deserializes an ECDSA signature from a byte slice -func deserializeSignature(sigBytes []byte) (*curves.EcdsaSignature, error) { - if len(sigBytes) != 66 { - return nil, errors.New("malformed signature: not the correct size") - } - sig := &curves.EcdsaSignature{ - V: int(sigBytes[0]), - R: new(big.Int).SetBytes(sigBytes[1:33]), - S: new(big.Int).SetBytes(sigBytes[33:66]), - } - return sig, nil -} diff --git a/crypto/mpc/README.md b/crypto/mpc/README.md deleted file mode 100644 index 7ea42ba61..000000000 --- a/crypto/mpc/README.md +++ /dev/null @@ -1,499 +0,0 @@ -# MPC (Multi-Party Computation) Cryptographic Library - -![Go](https://img.shields.io/badge/Go-1.24+-green) -![MPC](https://img.shields.io/badge/MPC-Threshold_Signing-blue) -![Encryption](https://img.shields.io/badge/Encryption-AES--GCM-red) -![ECDSA](https://img.shields.io/badge/Curve-secp256k1-yellow) - -A comprehensive Go implementation of Multi-Party Computation (MPC) primitives for secure distributed cryptography. This package provides threshold signing, encrypted key management, and secure keyshare operations for decentralized applications. - -## Features - -- ✅ **Threshold Cryptography** - 2-of-2 MPC key generation and signing -- ✅ **Secure Enclaves** - Encrypted keyshare storage and management -- ✅ **Multiple Curves** - Support for secp256k1, P-256, Ed25519, BLS12-381, and more -- ✅ **Key Refresh** - Proactive security through keyshare rotation -- ✅ **ECDSA Signing** - Distributed signature generation with SHA3-256 -- ✅ **Encrypted Export/Import** - Secure enclave serialization with AES-GCM -- ✅ **UCAN Integration** - MPC-based JWT signing for User-Controlled Authorization Networks - -## Architecture - -The package is built around the concept of secure **Enclaves** that manage distributed keyshares: - -``` -┌─────────────────────────────────────────────────────────┐ -│ MPC Enclave │ -├─────────────────────────────────────────────────────────┤ -│ ┌─────────────┐ ┌─────────────┐ │ -│ │ Alice Share │ │ Bob Share │ ←── Threshold 2/2 │ -│ │ (Validator) │ │ (User) │ │ -│ └─────────────┘ └─────────────┘ │ -├─────────────────────────────────────────────────────────┤ -│ • Distributed Key Generation (DKG) │ -│ • Threshold Signing (2-of-2) │ -│ • Key Refresh (Proactive Security) │ -│ • Encrypted Storage (AES-GCM) │ -└─────────────────────────────────────────────────────────┘ -``` - -## Quick Start - -### Installation - -```bash -go get github.com/sonr-io/sonr/crypto/mpc -``` - -### Basic Usage - -#### Creating a New MPC Enclave - -```go -package main - -import ( - "fmt" - "github.com/sonr-io/sonr/crypto/mpc" -) - -func main() { - // Generate a new MPC enclave with distributed keyshares - enclave, err := mpc.NewEnclave() - if err != nil { - panic(err) - } - - // Get the public key - pubKeyHex := enclave.PubKeyHex() - fmt.Printf("Public Key: %s\n", pubKeyHex) - - // Verify the enclave is valid - if enclave.IsValid() { - fmt.Println("✅ Enclave successfully created!") - } -} -``` - -#### Signing and Verification - -```go -// Sign data using distributed MPC protocol -message := []byte("Hello, distributed world!") -signature, err := enclave.Sign(message) -if err != nil { - panic(err) -} - -// Verify the signature -isValid, err := enclave.Verify(message, signature) -if err != nil { - panic(err) -} - -fmt.Printf("Signature valid: %t\n", isValid) -``` - -#### Secure Export and Import - -```go -// Export enclave with encryption -secretKey := []byte("my-super-secret-key-32-bytes-long") -encryptedData, err := enclave.Encrypt(secretKey) -if err != nil { - panic(err) -} - -// Import from encrypted data -restoredEnclave, err := mpc.ImportEnclave( - mpc.WithEncryptedData(encryptedData, secretKey), -) -if err != nil { - panic(err) -} - -fmt.Printf("Restored public key: %s\n", restoredEnclave.PubKeyHex()) -``` - -## Core Concepts - -### Enclaves - -An **Enclave** represents a secure MPC keyshare environment that manages distributed cryptographic operations: - -```go -type Enclave interface { - // Key Management - PubKeyHex() string // Get public key as hex string - PubKeyBytes() []byte // Get public key as bytes - IsValid() bool // Check if enclave has valid keyshares - - // Cryptographic Operations - Sign(data []byte) ([]byte, error) // Threshold signing - Verify(data []byte, sig []byte) (bool, error) // Signature verification - Refresh() (Enclave, error) // Proactive key refresh - - // Secure Storage - Encrypt(key []byte) ([]byte, error) // Export encrypted - Decrypt(key []byte, data []byte) ([]byte, error) // Import encrypted - - // Serialization - Marshal() ([]byte, error) // JSON serialization - Unmarshal(data []byte) error // JSON deserialization - - // Data Access - GetData() *EnclaveData // Access enclave internals - GetEnclave() Enclave // Self-reference -} -``` - -### Multi-Party Computation Protocol - -The package implements a 2-of-2 threshold scheme: - -1. **Alice (Validator)** - Server-side keyshare -2. **Bob (User)** - Client-side keyshare - -Both parties must participate in: -- **Distributed Key Generation (DKG)** - Creates shared public key -- **Threshold Signing** - Generates valid signatures cooperatively -- **Key Refresh** - Rotates keyshares while preserving public key - -### Supported Curves - -The package supports multiple elliptic curves: - -```go -type CurveName string - -const ( - K256Name CurveName = "secp256k1" // Bitcoin/Ethereum - P256Name CurveName = "P-256" // NIST P-256 - ED25519Name CurveName = "ed25519" // EdDSA - BLS12381G1Name CurveName = "BLS12381G1" // BLS12-381 G1 - BLS12381G2Name CurveName = "BLS12381G2" // BLS12-381 G2 - // ... more curves supported -) -``` - -## Advanced Usage - -### Custom Import Options - -The package provides flexible import mechanisms: - -```go -// Import from initial keyshares (after DKG) -enclave, err := mpc.ImportEnclave( - mpc.WithInitialShares(validatorShare, userShare, mpc.K256Name), -) - -// Import from existing enclave data -enclave, err := mpc.ImportEnclave( - mpc.WithEnclaveData(enclaveData), -) - -// Import from encrypted backup -enclave, err := mpc.ImportEnclave( - mpc.WithEncryptedData(encryptedBytes, secretKey), -) -``` - -### Key Refresh for Proactive Security - -```go -// Refresh keyshares while keeping the same public key -refreshedEnclave, err := enclave.Refresh() -if err != nil { - panic(err) -} - -// Public key remains the same -fmt.Printf("Original: %s\n", enclave.PubKeyHex()) -fmt.Printf("Refreshed: %s\n", refreshedEnclave.PubKeyHex()) -// Both should be identical! - -// But the enclave now has fresh keyshares -// This provides forward secrecy against key compromise -``` - -### Standalone Verification - -```go -// Verify signatures without the full enclave -pubKeyBytes := enclave.PubKeyBytes() -isValid, err := mpc.VerifyWithPubKey(pubKeyBytes, message, signature) -if err != nil { - panic(err) -} -``` - -### UCAN Integration - -The package includes MPC-based JWT signing for UCAN tokens: - -```go -import "github.com/sonr-io/sonr/crypto/mpc/spec" - -// Create MPC-backed UCAN token source -// (Implementation details in spec package) -keyshareSource := spec.KeyshareSource{ - // ... MPC enclave integration -} - -// Use with UCAN token creation -token, err := keyshareSource.NewOriginToken( - "did:key:audience", - attenuations, - facts, - notBefore, - expires, -) -``` - -## Security Features - -### Encryption - -All encrypted operations use **AES-GCM** with **SHA3-256** key derivation: - -```go -// Secure key derivation -func GetHashKey(key []byte) []byte { - hash := sha3.New256() - hash.Write(key) - return hash.Sum(nil)[:32] // 256-bit key -} -``` - -### Threshold Security - -- **2-of-2 threshold** - Both parties required for operations -- **No single point of failure** - Neither party alone can sign -- **Proactive refresh** - Regular keyshare rotation without changing public key -- **Forward secrecy** - Old keyshares cannot be used after refresh - -### Cryptographic Primitives - -- **ECDSA Signing** with **SHA3-256** message hashing -- **AES-GCM** encryption with 12-byte nonces -- **Secure random nonce generation** -- **Multiple curve support** for different use cases - -## Public API Reference - -### Core Functions - -```go -// Generate new MPC enclave -func NewEnclave() (Enclave, error) - -// Import enclave from various sources -func ImportEnclave(options ...ImportOption) (Enclave, error) - -// Execute distributed signing protocol -func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) ([]byte, error) - -// Execute keyshare refresh protocol -func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc, - curve CurveName) (Enclave, error) - -// Standalone signature verification -func VerifyWithPubKey(pubKeyCompressed []byte, data []byte, sig []byte) (bool, error) -``` - -### Import Options - -```go -type ImportOption func(Options) Options - -// Create from initial DKG results -func WithInitialShares(valKeyshare Message, userKeyshare Message, - curve CurveName) ImportOption - -// Create from encrypted backup -func WithEncryptedData(data []byte, key []byte) ImportOption - -// Create from existing data structure -func WithEnclaveData(data *EnclaveData) ImportOption -``` - -### EnclaveData Structure - -```go -type EnclaveData struct { - PubHex string `json:"pub_hex"` // Compressed public key (hex) - PubBytes []byte `json:"pub_bytes"` // Uncompressed public key - ValShare Message `json:"val_share"` // Alice (validator) keyshare - UserShare Message `json:"user_share"`// Bob (user) keyshare - Nonce []byte `json:"nonce"` // Encryption nonce - Curve CurveName `json:"curve"` // Elliptic curve name -} -``` - -### Protocol Types - -```go -type Message *protocol.Message // MPC protocol message -type Signature *curves.EcdsaSignature // ECDSA signature -type RefreshFunc interface{ protocol.Iterator } // Key refresh protocol -type SignFunc interface{ protocol.Iterator } // Signing protocol -type Point curves.Point // Elliptic curve point -``` - -### Utility Functions - -```go -// Cryptographic utilities -func GetHashKey(key []byte) []byte -func SerializeSignature(sig *curves.EcdsaSignature) ([]byte, error) -func DeserializeSignature(sigBytes []byte) (*curves.EcdsaSignature, error) - -// Key conversion utilities -func GetECDSAPoint(pubKey []byte) (*curves.EcPoint, error) - -// Protocol error handling -func CheckIteratedErrors(aErr, bErr error) error -``` - -## Error Handling - -The package provides comprehensive error handling: - -```go -// Common error patterns -enclave, err := mpc.NewEnclave() -if err != nil { - // Handle DKG failure - log.Fatalf("Failed to generate enclave: %v", err) -} - -signature, err := enclave.Sign(data) -if err != nil { - // Handle signing protocol failure - log.Fatalf("Failed to sign: %v", err) -} - -// Validation errors -if !enclave.IsValid() { - log.Fatal("Enclave has invalid keyshares") -} -``` - -## Performance Considerations - -### Memory Usage - -- **Minimal footprint** - Only active keyshares kept in memory -- **Efficient serialization** - JSON-based with compression -- **Secure cleanup** - Sensitive data cleared after use - -### Network Communication - -- **Minimal rounds** - Optimized protocol with few message exchanges -- **Small messages** - Compact protocol message format -- **Stateless operations** - No persistent connections required - -### Cryptographic Performance - -- **Hardware acceleration** - Leverages optimized curve implementations -- **Efficient hashing** - SHA3-256 with minimal overhead -- **Fast verification** - Public key operations optimized - -## Testing - -The package includes comprehensive tests: - -```bash -# Run all tests -go test -v ./crypto/mpc - -# Run specific test suites -go test -v ./crypto/mpc -run TestEnclaveData -go test -v ./crypto/mpc -run TestKeyShareGeneration -go test -v ./crypto/mpc -run TestEnclaveOperations - -# Run with race detection -go test -race ./crypto/mpc - -# Generate coverage report -go test -cover ./crypto/mpc -``` - -## Use Cases - -### Decentralized Identity - -- **DID key management** - Secure distributed identity keys -- **Threshold signing** - Multi-party authorization for identity operations -- **Key recovery** - Distributed backup and restore mechanisms - -### Cryptocurrency Wallets - -- **Multi-signature wallets** - True threshold custody solutions -- **Exchange security** - Hot wallet protection with distributed keys -- **Institutional custody** - Compliance-friendly key management - -### Blockchain Infrastructure - -- **Validator signing** - Secure consensus participation -- **Cross-chain bridges** - Multi-party custody of bridged assets -- **DAO governance** - Distributed decision-making mechanisms - -### Enterprise Applications - -- **Document signing** - Distributed digital signatures -- **API authentication** - Threshold-based service authentication -- **Secure communication** - End-to-end encrypted messaging - -## Dependencies - -- **Core Cryptography**: `github.com/sonr-io/sonr/crypto/core/curves` -- **Protocol Framework**: `github.com/sonr-io/sonr/crypto/core/protocol` -- **Threshold ECDSA**: `github.com/sonr-io/sonr/crypto/tecdsa/dklsv1` -- **UCAN Integration**: `github.com/sonr-io/sonr/crypto/ucan` -- **Standard Crypto**: `golang.org/x/crypto/sha3` -- **JWT Support**: `github.com/golang-jwt/jwt` - -## Security Considerations - -### Threat Model - -The package is designed to protect against: - -- **Key compromise** - Distributed keyshares prevent single points of failure -- **Insider threats** - No single party can perform operations alone -- **Network attacks** - Protocol messages are cryptographically protected -- **Side-channel attacks** - Secure implementations of cryptographic primitives - -### Best Practices - -1. **Regular key refresh** - Rotate keyshares periodically -2. **Secure communication** - Use TLS for protocol message exchange -3. **Access controls** - Implement proper authentication for MPC operations -4. **Audit logging** - Log all cryptographic operations -5. **Backup strategies** - Securely store encrypted enclave exports - -### Limitations - -- **2-of-2 threshold only** - Currently supports only 2-party protocols -- **Network dependency** - Requires communication between parties -- **No byzantine fault tolerance** - Assumes honest-but-curious adversaries - -## Contributing - -We welcome contributions! Please ensure: - -1. **Security first** - All cryptographic code must be carefully reviewed -2. **Comprehensive testing** - Include unit tests and integration tests -3. **Documentation** - Document all public APIs and security assumptions -4. **Performance** - Benchmark critical cryptographic operations -5. **Compatibility** - Maintain backward compatibility with existing enclaves - -## License - -This project follows the same license as the main Sonr project. - ---- - -**⚠️ Security Notice**: This is cryptographic software. While extensively tested, it should be used with appropriate security measures and understanding of the underlying protocols. For production deployments, consider additional security audits and operational security measures. \ No newline at end of file diff --git a/crypto/mpc/codec.go b/crypto/mpc/codec.go deleted file mode 100644 index 2973e6d73..000000000 --- a/crypto/mpc/codec.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package mpc implements the Sonr MPC protocol -package mpc - -import ( - "crypto/rand" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" -) - -type CurveName string - -const ( - K256Name CurveName = "secp256k1" - BLS12381G1Name CurveName = "BLS12381G1" - BLS12381G2Name CurveName = "BLS12381G2" - BLS12831Name CurveName = "BLS12831" - P256Name CurveName = "P-256" - ED25519Name CurveName = "ed25519" - PallasName CurveName = "pallas" - BLS12377G1Name CurveName = "BLS12377G1" - BLS12377G2Name CurveName = "BLS12377G2" - BLS12377Name CurveName = "BLS12377" -) - -func (c CurveName) String() string { - return string(c) -} - -func (c CurveName) Curve() *curves.Curve { - switch c { - case K256Name: - return curves.K256() - case BLS12381G1Name: - return curves.BLS12381G1() - case BLS12381G2Name: - return curves.BLS12381G2() - case BLS12831Name: - return curves.BLS12381G1() - case P256Name: - return curves.P256() - case ED25519Name: - return curves.ED25519() - case PallasName: - return curves.PALLAS() - case BLS12377G1Name: - return curves.BLS12377G1() - case BLS12377G2Name: - return curves.BLS12377G2() - case BLS12377Name: - return curves.BLS12377G1() - default: - return curves.K256() - } -} - -// ╭───────────────────────────────────────────────────────────╮ -// │ Exported Generics │ -// ╰───────────────────────────────────────────────────────────╯ - -type ( - AliceOut *dkg.AliceOutput - BobOut *dkg.BobOutput - Point curves.Point - Role string // Role is the type for the role - Message *protocol.Message // Message is the protocol.Message that is used for MPC - Signature *curves.EcdsaSignature // Signature is the type for the signature - RefreshFunc interface{ protocol.Iterator } // RefreshFunc is the type for the refresh function - SignFunc interface{ protocol.Iterator } // SignFunc is the type for the sign function -) - -const ( - RoleVal = "validator" - RoleUser = "user" -) - -func randNonce() []byte { - nonce := make([]byte, 12) - rand.Read(nonce) - return nonce -} - -// Enclave defines the interface for key management operations -type Enclave interface { - GetData() *EnclaveData // GetData returns the data of the keyEnclave - GetEnclave() Enclave // GetEnclave returns the enclave of the keyEnclave - Decrypt( - key []byte, - encryptedData []byte, - ) ([]byte, error) // Decrypt returns decrypted enclave data - Encrypt( - key []byte, - ) ([]byte, error) // Encrypt returns encrypted enclave data - IsValid() bool // IsValid returns true if the keyEnclave is valid - PubKeyBytes() []byte // PubKeyBytes returns the public key of the keyEnclave - PubKeyHex() string // PubKeyHex returns the public key of the keyEnclave - Refresh() (Enclave, error) // Refresh returns a new keyEnclave - Marshal() ([]byte, error) // Serialize returns the serialized keyEnclave - Sign( - data []byte, - ) ([]byte, error) // Sign returns the signature of the data - Unmarshal( - data []byte, - ) error // Verify returns true if the signature is valid - Verify( - data []byte, - sig []byte, - ) (bool, error) // Verify returns true if the signature is valid -} diff --git a/crypto/mpc/codec_test.go b/crypto/mpc/codec_test.go deleted file mode 100644 index 933b93a85..000000000 --- a/crypto/mpc/codec_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package mpc - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestKeyShareGeneration(t *testing.T) { - t.Run("Generate Valid Enclave", func(t *testing.T) { - // Generate enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Validate enclave contents - assert.True(t, enclave.IsValid()) - }) - - t.Run("Export and Import", func(t *testing.T) { - // Generate original enclave - original, err := NewEnclave() - require.NoError(t, err) - - // Test key for encryption/decryption (32 bytes) - testKey := []byte("test-key-12345678-test-key-123456") - - // Test Export/Import - t.Run("Full Enclave", func(t *testing.T) { - // Export enclave - data, err := original.Encrypt(testKey) - require.NoError(t, err) - require.NotEmpty(t, data) - - // Create new empty enclave - newEnclave, err := NewEnclave() - require.NoError(t, err) - - // Verify the imported enclave works by signing - testData := []byte("test message") - sig, err := newEnclave.Sign(testData) - require.NoError(t, err) - valid, err := newEnclave.Verify(testData, sig) - require.NoError(t, err) - assert.True(t, valid) - }) - }) - - t.Run("Encrypt and Decrypt", func(t *testing.T) { - // Generate original enclave - original, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, original) - - // Test key for encryption/decryption (32 bytes) - testKey := []byte("test-key-12345678-test-key-123456") - - // Test Encrypt - encrypted, err := original.Encrypt(testKey) - require.NoError(t, err) - require.NotEmpty(t, encrypted) - - // Test Decrypt - decrypted, err := original.Decrypt(testKey, encrypted) - require.NoError(t, err) - require.NotEmpty(t, decrypted) - - // Verify decrypted data matches original - originalData, err := original.Marshal() - require.NoError(t, err) - assert.Equal(t, originalData, decrypted) - - // Test with wrong key should fail - wrongKey := []byte("wrong-key-12345678-wrong-key-123456") - _, err = original.Decrypt(wrongKey, encrypted) - assert.Error(t, err, "Decryption with wrong key should fail") - }) -} - -func TestEnclaveOperations(t *testing.T) { - t.Run("Signing and Verification", func(t *testing.T) { - // Generate valid enclave - enclave, err := NewEnclave() - require.NoError(t, err) - - // Test signing - testData := []byte("test message") - signature, err := enclave.Sign(testData) - require.NoError(t, err) - require.NotNil(t, signature) - - // Verify the signature - valid, err := enclave.Verify(testData, signature) - require.NoError(t, err) - assert.True(t, valid) - - // Test invalid data verification - invalidData := []byte("wrong message") - valid, err = enclave.Verify(invalidData, signature) - require.NoError(t, err) - assert.False(t, valid) - }) - - t.Run("Refresh Operation", func(t *testing.T) { - enclave, err := NewEnclave() - require.NoError(t, err) - - // Test refresh - refreshedEnclave, err := enclave.Refresh() - require.NoError(t, err) - require.NotNil(t, refreshedEnclave) - - // Verify refreshed enclave is valid - assert.True(t, refreshedEnclave.IsValid()) - }) -} - -func TestEnclaveDataAccess(t *testing.T) { - t.Run("GetData", func(t *testing.T) { - // Generate enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data, "GetData should return non-nil value") - - // Verify the data is valid - assert.True(t, data.IsValid(), "Enclave data should be valid") - - // Verify the public key in the data matches the enclave's public key - assert.Equal(t, enclave.PubKeyHex(), data.PubKeyHex(), "Public keys should match") - }) - - t.Run("PubKeyHex", func(t *testing.T) { - // Generate enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the public key hex - pubKeyHex := enclave.PubKeyHex() - require.NotEmpty(t, pubKeyHex, "PubKeyHex should return non-empty string") - - // Check that it's a valid hex string (should be 66 chars for compressed point: 0x02/0x03 + 32 bytes) - assert.GreaterOrEqual( - t, - len(pubKeyHex), - 66, - "Public key hex should be at least 66 characters", - ) - assert.True(t, len(pubKeyHex)%2 == 0, "Hex string should have even length") - - // Compare with the enclave data's public key - data := enclave.GetData() - assert.Equal( - t, - data.PubKeyHex(), - pubKeyHex, - "Public key hex should match the one from GetData", - ) - - // Verify that two different enclaves have different public keys - enclave2, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave2) - - pubKeyHex2 := enclave2.PubKeyHex() - assert.NotEqual( - t, - pubKeyHex, - pubKeyHex2, - "Different enclaves should have different public keys", - ) - }) -} diff --git a/crypto/mpc/enclave.go b/crypto/mpc/enclave.go deleted file mode 100644 index d169d2441..000000000 --- a/crypto/mpc/enclave.go +++ /dev/null @@ -1,158 +0,0 @@ -package mpc - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/ecdsa" - "encoding/json" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "golang.org/x/crypto/sha3" -) - -// EnclaveData implements the Enclave interface -type EnclaveData struct { - PubHex string `json:"pub_hex"` // PubHex is the hex-encoded compressed public key - PubBytes []byte `json:"pub_bytes"` // PubBytes is the uncompressed public key - ValShare Message `json:"val_share"` - UserShare Message `json:"user_share"` - Nonce []byte `json:"nonce"` - Curve CurveName `json:"curve"` -} - -// GetData returns the data of the keyEnclave -func (k *EnclaveData) GetData() *EnclaveData { - return k -} - -// GetEnclave returns the enclave of the keyEnclave -func (k *EnclaveData) GetEnclave() Enclave { - return k -} - -// GetPubPoint returns the public point of the keyEnclave -func (k *EnclaveData) GetPubPoint() (curves.Point, error) { - curve := k.Curve.Curve() - return curve.NewIdentityPoint().FromAffineUncompressed(k.PubBytes) -} - -// PubKeyHex returns the public key of the keyEnclave -func (k *EnclaveData) PubKeyHex() string { - return k.PubHex -} - -// PubKeyBytes returns the public key of the keyEnclave -func (k *EnclaveData) PubKeyBytes() []byte { - return k.PubBytes -} - -// Decrypt returns decrypted enclave data -func (k *EnclaveData) Decrypt(key []byte, encryptedData []byte) ([]byte, error) { - hashedKey := GetHashKey(key) - block, err := aes.NewCipher(hashedKey) - if err != nil { - return nil, err - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, err - } - - // Decrypt the data using AES-GCM - plaintext, err := aesgcm.Open(nil, k.Nonce, encryptedData, nil) - if err != nil { - return nil, fmt.Errorf("decryption failed: %w", err) - } - return plaintext, nil -} - -// Encrypt returns encrypted enclave data -func (k *EnclaveData) Encrypt(key []byte) ([]byte, error) { - data, err := k.Marshal() - if err != nil { - return nil, fmt.Errorf("failed to serialize enclave: %w", err) - } - - hashedKey := GetHashKey(key) - block, err := aes.NewCipher(hashedKey) - if err != nil { - return nil, err - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, err - } - - return aesgcm.Seal(nil, k.Nonce, data, nil), nil -} - -// IsValid returns true if the keyEnclave is valid -func (k *EnclaveData) IsValid() bool { - return k.ValShare != nil && k.UserShare != nil -} - -// Refresh returns a new keyEnclave -func (k *EnclaveData) Refresh() (Enclave, error) { - refreshFuncVal, err := GetAliceRefreshFunc(k) - if err != nil { - return nil, err - } - refreshFuncUser, err := GetBobRefreshFunc(k) - if err != nil { - return nil, err - } - return ExecuteRefresh(refreshFuncVal, refreshFuncUser, k.Curve) -} - -// Sign returns the signature of the data -func (k *EnclaveData) Sign(data []byte) ([]byte, error) { - userSign, err := GetBobSignFunc(k, data) - if err != nil { - return nil, err - } - valSign, err := GetAliceSignFunc(k, data) - if err != nil { - return nil, err - } - return ExecuteSigning(valSign, userSign) -} - -// Verify returns true if the signature is valid -func (k *EnclaveData) Verify(data []byte, sig []byte) (bool, error) { - edSig, err := DeserializeSignature(sig) - if err != nil { - return false, err - } - ePub, err := GetECDSAPoint(k.PubBytes) - if err != nil { - return false, err - } - pk := &ecdsa.PublicKey{ - Curve: ePub.Curve, - X: ePub.X, - Y: ePub.Y, - } - - // Hash the message using SHA3-256 - hash := sha3.New256() - hash.Write(data) - digest := hash.Sum(nil) - - return ecdsa.Verify(pk, digest, edSig.R, edSig.S), nil -} - -// Marshal returns the JSON encoding of keyEnclave -func (k *EnclaveData) Marshal() ([]byte, error) { - return json.Marshal(k) -} - -// Unmarshal unmarshals the JSON encoding of keyEnclave -func (k *EnclaveData) Unmarshal(data []byte) error { - if err := json.Unmarshal(data, k); err != nil { - return err - } - return nil -} diff --git a/crypto/mpc/enclave_test.go b/crypto/mpc/enclave_test.go deleted file mode 100644 index 39dc11592..000000000 --- a/crypto/mpc/enclave_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package mpc - -import ( - "bytes" - "encoding/hex" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestEnclaveData_GetData(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the data - data := enclave.GetData() - require.NotNil(t, data) - - // Ensure the data is the same instance - assert.Equal(t, enclave, data.GetEnclave()) - - // Ensure the data is valid - assert.True(t, data.IsValid()) -} - -func TestEnclaveData_GetEnclave(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Get the enclave back - returnedEnclave := data.GetEnclave() - require.NotNil(t, returnedEnclave) - - // Verify the returned enclave is the same - assert.Equal(t, enclave, returnedEnclave) -} - -func TestEnclaveData_GetPubPoint(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Get the public point - pubPoint, err := data.GetPubPoint() - require.NoError(t, err) - require.NotNil(t, pubPoint) - - // Verify the public point's serialization matches the stored public bytes - pointBytes := pubPoint.ToAffineUncompressed() - assert.Equal(t, data.PubBytes, pointBytes) -} - -func TestEnclaveData_PubKeyHex(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Get the public key hex - pubKeyHex := data.PubKeyHex() - require.NotEmpty(t, pubKeyHex) - - // Verify it's a valid hex string - _, err = hex.DecodeString(pubKeyHex) - require.NoError(t, err) - - // Verify it matches the stored PubHex - assert.Equal(t, data.PubHex, pubKeyHex) -} - -func TestEnclaveData_PubKeyBytes(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Get the public key bytes - pubKeyBytes := data.PubKeyBytes() - require.NotEmpty(t, pubKeyBytes) - - // Verify it matches the stored PubBytes - assert.Equal(t, data.PubBytes, pubKeyBytes) -} - -func TestEnclaveData_EncryptDecrypt(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Test key for encryption/decryption - testKey := []byte("test-key-12345678-test-key-123456") - - // Test encryption - encrypted, err := data.Encrypt(testKey) - require.NoError(t, err) - require.NotEmpty(t, encrypted) - - // Test decryption - decrypted, err := data.Decrypt(testKey, encrypted) - require.NoError(t, err) - require.NotEmpty(t, decrypted) - - // Serialize the original data for comparison - originalData, err := data.Marshal() - require.NoError(t, err) - - // Verify the decrypted data matches the original - assert.Equal(t, originalData, decrypted) - - // Test decryption with wrong key (should fail) - wrongKey := []byte("wrong-key-12345678-wrong-key-123456") - _, err = data.Decrypt(wrongKey, encrypted) - assert.Error(t, err, "Decryption with wrong key should fail") -} - -func TestEnclaveData_IsValid(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Verify it's valid - assert.True(t, data.IsValid()) - - // Create an invalid enclave - invalidEnclave := &EnclaveData{ - PubHex: "invalid", - PubBytes: []byte("invalid"), - Nonce: []byte("nonce"), - Curve: K256Name, - } - - // Verify it's invalid - assert.False(t, invalidEnclave.IsValid()) -} - -func TestEnclaveData_RefreshAndSign(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the original public key - originalPubKeyHex := enclave.PubKeyHex() - originalPubKeyBytes := enclave.PubKeyBytes() - require.NotEmpty(t, originalPubKeyHex) - require.NotEmpty(t, originalPubKeyBytes) - - // Sign a message with the original enclave to verify it works - testMessage := []byte("test message before refresh") - originalSignature, err := enclave.Sign(testMessage) - require.NoError(t, err) - require.NotEmpty(t, originalSignature) - - // Verify the original signature - valid, err := enclave.Verify(testMessage, originalSignature) - require.NoError(t, err) - assert.True(t, valid, "Original signature should be valid") - - // Refresh the enclave - refreshedEnclave, err := enclave.Refresh() - require.NoError(t, err) - require.NotNil(t, refreshedEnclave) - - // CRITICAL TEST: The public key should remain the same after refresh - refreshedPubKeyHex := refreshedEnclave.PubKeyHex() - refreshedPubKeyBytes := refreshedEnclave.PubKeyBytes() - - assert.Equal(t, originalPubKeyHex, refreshedPubKeyHex, - "Public key hex should not change after refresh") - assert.Equal(t, originalPubKeyBytes, refreshedPubKeyBytes, - "Public key bytes should not change after refresh") - - // Verify the refreshed enclave is valid - assert.True(t, refreshedEnclave.IsValid(), "Refreshed enclave should be valid") - - // Test that the refreshed enclave can still sign messages - testMessage2 := []byte("test message after refresh") - refreshedSignature, err := refreshedEnclave.Sign(testMessage2) - require.NoError(t, err) - require.NotEmpty(t, refreshedSignature) - - // Verify the signature from the refreshed enclave with its own key - valid, err = refreshedEnclave.Verify(testMessage2, refreshedSignature) - require.NoError(t, err) - assert.True(t, valid, "Signature from refreshed enclave should be valid") - - // CRITICAL TEST: The original enclave should be able to verify the signature - // from the refreshed enclave since they have the same public key - valid, err = enclave.Verify(testMessage2, refreshedSignature) - require.NoError(t, err) - assert.True(t, valid, "Original enclave should be able to verify refreshed enclave's signature") - - // CRITICAL TEST: The refreshed enclave should be able to verify the signature - // from the original enclave since they have the same public key - valid, err = refreshedEnclave.Verify(testMessage, originalSignature) - require.NoError(t, err) - assert.True(t, valid, "Refreshed enclave should be able to verify original enclave's signature") - - // Test with wrong message (should fail) - wrongMessage := []byte("wrong message") - valid, err = refreshedEnclave.Verify(wrongMessage, refreshedSignature) - require.NoError(t, err) - assert.False(t, valid, "Wrong message verification should fail") -} - -func TestEnclaveData_MarshalUnmarshal(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Get the enclave data - data := enclave.GetData() - require.NotNil(t, data) - - // Marshal the enclave - encoded, err := data.Marshal() - require.NoError(t, err) - require.NotEmpty(t, encoded) - - // Create a new empty enclave - newEnclave := &EnclaveData{} - - // Unmarshal the encoded data - err = newEnclave.Unmarshal(encoded) - require.NoError(t, err) - - // Verify the unmarshaled enclave matches the original - assert.Equal(t, data.PubHex, newEnclave.PubHex) - assert.Equal(t, data.Curve, newEnclave.Curve) - assert.True(t, bytes.Equal(data.PubBytes, newEnclave.PubBytes)) - assert.True(t, bytes.Equal(data.Nonce, newEnclave.Nonce)) - assert.True(t, newEnclave.IsValid()) - - // Verify the public key matches - assert.Equal(t, data.PubKeyHex(), newEnclave.PubKeyHex()) -} - -func TestEnclaveData_Verify(t *testing.T) { - // Create a new enclave - enclave, err := NewEnclave() - require.NoError(t, err) - require.NotNil(t, enclave) - - // Sign a message - testMessage := []byte("test message") - signature, err := enclave.Sign(testMessage) - require.NoError(t, err) - require.NotEmpty(t, signature) - - // Verify the signature - valid, err := enclave.Verify(testMessage, signature) - require.NoError(t, err) - assert.True(t, valid) - - // Verify with wrong message - wrongMessage := []byte("wrong message") - valid, err = enclave.Verify(wrongMessage, signature) - require.NoError(t, err) - assert.False(t, valid) - - // Corrupt the signature - corruptedSig := make([]byte, len(signature)) - copy(corruptedSig, signature) - corruptedSig[0] ^= 0x01 // flip a bit - - // Verify with corrupted signature (should fail) - valid, err = enclave.Verify(testMessage, corruptedSig) - require.NoError(t, err) - assert.False(t, valid) - - // We don't need to manually create ECDSA signatures here - // as we already verified the Sign and Verify functions work together. - // This completes the verification of the enclave's signature functionality. -} diff --git a/crypto/mpc/import.go b/crypto/mpc/import.go deleted file mode 100644 index ccc116deb..000000000 --- a/crypto/mpc/import.go +++ /dev/null @@ -1,140 +0,0 @@ -package mpc - -import ( - "encoding/hex" - "errors" - "fmt" -) - -// ImportEnclave creates an Enclave instance from various import options. -// It prioritizes enclave bytes over keyshares if both are provided. -func ImportEnclave(options ...ImportOption) (Enclave, error) { - if len(options) == 0 { - return nil, errors.New("no import options provided") - } - - opts := Options{} - for _, opt := range options { - opts = opt(opts) - } - return opts.Apply() -} - -// Options is a struct that holds the import options -type Options struct { - valKeyshare Message - userKeyshare Message - enclaveBytes []byte - enclaveData *EnclaveData - initialShares bool - isEncrypted bool - secretKey []byte - curve CurveName -} - -// ImportOption is a function that modifies the import options -type ImportOption func(Options) Options - -// WithInitialShares creates an option to import an enclave from validator and user keyshares. -func WithInitialShares(valKeyshare Message, userKeyshare Message, curve CurveName) ImportOption { - return func(opts Options) Options { - opts.valKeyshare = valKeyshare - opts.userKeyshare = userKeyshare - opts.initialShares = true - opts.curve = curve - return opts - } -} - -// WithEncryptedData creates an option to import an enclave from encrypted data. -func WithEncryptedData(data []byte, key []byte) ImportOption { - return func(opts Options) Options { - opts.enclaveBytes = data - opts.initialShares = false - opts.isEncrypted = true - opts.secretKey = key - return opts - } -} - -// WithEnclaveData creates an option to import an enclave from a data struct. -func WithEnclaveData(data *EnclaveData) ImportOption { - return func(opts Options) Options { - opts.enclaveData = data - opts.initialShares = false - return opts - } -} - -// Apply applies the import options to create an Enclave instance. -func (opts Options) Apply() (Enclave, error) { - // Load from encrypted data if provided - if opts.isEncrypted { - if len(opts.enclaveBytes) == 0 { - return nil, errors.New("enclave bytes cannot be empty") - } - return RestoreEncryptedEnclave(opts.enclaveBytes, opts.secretKey) - } - // Generate from keyshares if provided - if opts.initialShares { - // Then try to build from keyshares - if opts.valKeyshare == nil { - return nil, errors.New("validator share cannot be nil") - } - if opts.userKeyshare == nil { - return nil, errors.New("user share cannot be nil") - } - return BuildEnclave(opts.valKeyshare, opts.userKeyshare, opts) - } - // Load from enclave data if provided - return RestoreEnclaveFromData(opts.enclaveData) -} - -// BuildEnclave creates a new enclave from validator and user keyshares. -func BuildEnclave(valShare, userShare Message, options Options) (Enclave, error) { - if valShare == nil { - return nil, errors.New("validator share cannot be nil") - } - if userShare == nil { - return nil, errors.New("user share cannot be nil") - } - - pubPoint, err := GetAlicePublicPoint(valShare) - if err != nil { - return nil, fmt.Errorf("failed to get public point: %w", err) - } - return &EnclaveData{ - PubBytes: pubPoint.ToAffineUncompressed(), - PubHex: hex.EncodeToString(pubPoint.ToAffineCompressed()), - ValShare: valShare, - UserShare: userShare, - Nonce: randNonce(), - Curve: options.curve, - }, nil -} - -// RestoreEnclaveFromData deserializes an enclave from its data struct. -func RestoreEnclaveFromData(data *EnclaveData) (Enclave, error) { - if data == nil { - return nil, errors.New("enclave data cannot be nil") - } - return data, nil -} - -// RestoreEncryptedEnclave decrypts an enclave from its binary representation. and key -func RestoreEncryptedEnclave(data []byte, key []byte) (Enclave, error) { - keyclave := &EnclaveData{} - err := keyclave.Unmarshal(data) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal enclave: %w", err) - } - decryptedData, err := keyclave.Decrypt(key, data) - if err != nil { - return nil, fmt.Errorf("failed to decrypt enclave: %w", err) - } - err = keyclave.Unmarshal(decryptedData) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal decrypted enclave: %w", err) - } - return keyclave, nil -} diff --git a/crypto/mpc/protocol.go b/crypto/mpc/protocol.go deleted file mode 100644 index bbf1cdcd3..000000000 --- a/crypto/mpc/protocol.go +++ /dev/null @@ -1,91 +0,0 @@ -package mpc - -import ( - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1" -) - -// NewEnclave generates a new MPC keyshare -func NewEnclave() (Enclave, error) { - curve := K256Name.Curve() - valKs := dklsv1.NewAliceDkg(curve, protocol.Version1) - userKs := dklsv1.NewBobDkg(curve, protocol.Version1) - aErr, bErr := RunProtocol(userKs, valKs) - if err := CheckIteratedErrors(aErr, bErr); err != nil { - return nil, err - } - valRes, err := valKs.Result(protocol.Version1) - if err != nil { - return nil, err - } - userRes, err := userKs.Result(protocol.Version1) - if err != nil { - return nil, err - } - return ImportEnclave(WithInitialShares(valRes, userRes, K256Name)) -} - -// ExecuteSigning runs the MPC signing protocol -func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) ([]byte, error) { - aErr, bErr := RunProtocol(signFuncVal, signFuncUser) - if err := CheckIteratedErrors(aErr, bErr); err != nil { - return nil, err - } - out, err := signFuncUser.Result(protocol.Version1) - if err != nil { - return nil, err - } - s, err := dklsv1.DecodeSignature(out) - if err != nil { - return nil, err - } - sig, err := SerializeSignature(s) - if err != nil { - return nil, err - } - return sig, nil -} - -// ExecuteRefresh runs the MPC refresh protocol -func ExecuteRefresh( - refreshFuncVal RefreshFunc, - refreshFuncUser RefreshFunc, - curve CurveName, -) (Enclave, error) { - aErr, bErr := RunProtocol(refreshFuncVal, refreshFuncUser) - if err := CheckIteratedErrors(aErr, bErr); err != nil { - return nil, err - } - valRefreshResult, err := refreshFuncVal.Result(protocol.Version1) - if err != nil { - return nil, err - } - userRefreshResult, err := refreshFuncUser.Result(protocol.Version1) - if err != nil { - return nil, err - } - return ImportEnclave(WithInitialShares(valRefreshResult, userRefreshResult, curve)) -} - -// RunProtocol runs the MPC protocol -func RunProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) { - var ( - message *protocol.Message - aErr error - bErr error - ) - - for aErr != protocol.ErrProtocolFinished || bErr != protocol.ErrProtocolFinished { - // Crank each protocol forward one iteration - message, bErr = firstParty.Next(message) - if bErr != nil && bErr != protocol.ErrProtocolFinished { - return nil, bErr - } - - message, aErr = secondParty.Next(message) - if aErr != nil && aErr != protocol.ErrProtocolFinished { - return aErr, nil - } - } - return aErr, bErr -} diff --git a/crypto/mpc/spec/jwt.go b/crypto/mpc/spec/jwt.go deleted file mode 100644 index e1e66de79..000000000 --- a/crypto/mpc/spec/jwt.go +++ /dev/null @@ -1,116 +0,0 @@ -package spec - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - - "github.com/golang-jwt/jwt/v5" - "github.com/sonr-io/sonr/crypto/mpc" -) - -// MPCSigningMethod implements the SigningMethod interface for MPC-based signing -type MPCSigningMethod struct { - Name string - enclave mpc.Enclave -} - -// NewJWTSigningMethod creates a new MPC signing method with the given enclave -func NewJWTSigningMethod(name string, enclave mpc.Enclave) *MPCSigningMethod { - return &MPCSigningMethod{ - Name: name, - enclave: enclave, - } -} - -// WithEnclave sets the enclave for an existing signing method -func (m *MPCSigningMethod) WithEnclave(enclave mpc.Enclave) *MPCSigningMethod { - return &MPCSigningMethod{ - Name: m.Name, - enclave: enclave, - } -} - -// NewMPCSigningMethod is an alias for NewJWTSigningMethod for compatibility -func NewMPCSigningMethod(name string, enclave mpc.Enclave) *MPCSigningMethod { - return NewJWTSigningMethod(name, enclave) -} - -// Alg returns the signing method's name -func (m *MPCSigningMethod) Alg() string { - return m.Name -} - -// Verify verifies the signature using the MPC public key -func (m *MPCSigningMethod) Verify(signingString string, signature []byte, key any) error { - // Check if enclave is available - if m.enclave == nil { - return fmt.Errorf("MPC enclave not available for signature verification") - } - - // Decode the signature - sig, err := base64.RawURLEncoding.DecodeString(string(signature)) - if err != nil { - return fmt.Errorf("failed to decode signature: %w", err) - } - - // Hash the signing string using SHA-256 - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to verify signature - valid, err := m.enclave.Verify(digest, sig) - if err != nil { - return fmt.Errorf("failed to verify signature: %w", err) - } - - if !valid { - return fmt.Errorf("signature verification failed") - } - - return nil -} - -// Sign signs the data using MPC -func (m *MPCSigningMethod) Sign(signingString string, key any) ([]byte, error) { - // Check if enclave is available - if m.enclave == nil { - return nil, fmt.Errorf("MPC enclave not available for signing") - } - - // Hash the signing string using SHA-256 - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to sign the digest - sig, err := m.enclave.Sign(digest) - if err != nil { - return nil, fmt.Errorf("failed to sign with MPC: %w", err) - } - - // Encode the signature as base64url - encoded := base64.RawURLEncoding.EncodeToString(sig) - return []byte(encoded), nil -} - -func init() { - // Register the MPC signing method factory - jwt.RegisterSigningMethod("MPC256", func() jwt.SigningMethod { - // This factory creates a new instance without enclave - // The enclave will be provided when creating tokens - return &MPCSigningMethod{ - Name: "MPC256", - } - }) -} - -// RegisterMPCMethod registers an MPC signing method for the given algorithm name -func RegisterMPCMethod(alg string) { - jwt.RegisterSigningMethod(alg, func() jwt.SigningMethod { - return &MPCSigningMethod{ - Name: alg, - } - }) -} diff --git a/crypto/mpc/spec/source.go b/crypto/mpc/spec/source.go deleted file mode 100644 index 098c08594..000000000 --- a/crypto/mpc/spec/source.go +++ /dev/null @@ -1,305 +0,0 @@ -package spec - -import ( - "fmt" - "strings" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/libp2p/go-libp2p/core/crypto" - "github.com/sonr-io/sonr/crypto/keys" - "github.com/sonr-io/sonr/crypto/mpc" - "lukechampine.com/blake3" -) - -// KeyshareSource provides MPC-based UCAN token creation and validation -type KeyshareSource interface { - Address() string - Issuer() string - ChainCode() ([]byte, error) - OriginToken() (*Token, error) - SignData(data []byte) ([]byte, error) - VerifyData(data []byte, sig []byte) (bool, error) - Enclave() mpc.Enclave - - // UCAN token creation methods - NewOriginToken( - audienceDID string, - att []Attenuation, - fct []Fact, - notBefore, expires time.Time, - ) (*Token, error) - NewAttenuatedToken( - parent *Token, - audienceDID string, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, - ) (*Token, error) -} - -// NewSource creates a new MPC-based keyshare source from an enclave -func NewSource(enclave mpc.Enclave) (KeyshareSource, error) { - if !enclave.IsValid() { - return nil, fmt.Errorf("invalid MPC enclave provided") - } - - pubKeyBytes := enclave.PubKeyBytes() - issuerDID, addr, err := getIssuerDIDFromBytes(pubKeyBytes) - if err != nil { - return nil, fmt.Errorf("failed to derive issuer DID: %w", err) - } - - return &mpcKeyshareSource{ - enclave: enclave, - issuerDID: issuerDID, - addr: addr, - }, nil -} - -// mpcKeyshareSource implements KeyshareSource using MPC enclave -type mpcKeyshareSource struct { - enclave mpc.Enclave - issuerDID string - addr string -} - -// Address returns the address derived from the enclave public key -func (k *mpcKeyshareSource) Address() string { - return k.addr -} - -// Issuer returns the DID of the issuer derived from the enclave public key -func (k *mpcKeyshareSource) Issuer() string { - return k.issuerDID -} - -// Enclave returns the underlying MPC enclave -func (k *mpcKeyshareSource) Enclave() mpc.Enclave { - return k.enclave -} - -// ChainCode derives a deterministic chain code from the enclave -func (k *mpcKeyshareSource) ChainCode() ([]byte, error) { - // Sign the address to create a deterministic chain code - sig, err := k.SignData([]byte(k.addr)) - if err != nil { - return nil, fmt.Errorf("failed to sign address for chain code: %w", err) - } - - // Hash the signature to create a 32-byte chain code - hash := blake3.Sum256(sig) - return hash[:32], nil -} - -// OriginToken creates a default origin token with basic capabilities -func (k *mpcKeyshareSource) OriginToken() (*Token, error) { - // Create basic capability for the MPC keyshare - resource := &SimpleResource{ - Scheme: "mpc", - Value: k.addr, - URI: fmt.Sprintf("mpc://%s", k.addr), - } - - capability := &SimpleCapability{Action: "sign"} - - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - // Create token with no expiration for origin token - zero := time.Time{} - return k.NewOriginToken(k.issuerDID, []Attenuation{attenuation}, nil, zero, zero) -} - -// SignData signs data using the MPC enclave -func (k *mpcKeyshareSource) SignData(data []byte) ([]byte, error) { - if !k.enclave.IsValid() { - return nil, fmt.Errorf("enclave is not valid") - } - - return k.enclave.Sign(data) -} - -// VerifyData verifies a signature using the MPC enclave -func (k *mpcKeyshareSource) VerifyData(data []byte, sig []byte) (bool, error) { - if !k.enclave.IsValid() { - return false, fmt.Errorf("enclave is not valid") - } - - return k.enclave.Verify(data, sig) -} - -// NewOriginToken creates a new UCAN origin token using MPC signing -func (k *mpcKeyshareSource) NewOriginToken( - audienceDID string, - att []Attenuation, - fct []Fact, - notBefore, expires time.Time, -) (*Token, error) { - return k.newToken(audienceDID, nil, att, fct, notBefore, expires) -} - -// NewAttenuatedToken creates a new attenuated UCAN token using MPC signing -func (k *mpcKeyshareSource) NewAttenuatedToken( - parent *Token, - audienceDID string, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, -) (*Token, error) { - // Validate that new attenuations are more restrictive than parent - if !isAttenuationSubset(att, parent.Attenuations) { - return nil, fmt.Errorf("scope of ucan attenuations must be less than its parent") - } - - // Add parent as proof - proofs := []Proof{} - if parent.Raw != "" { - proofs = append(proofs, Proof(parent.Raw)) - } - proofs = append(proofs, parent.Proofs...) - - return k.newToken(audienceDID, proofs, att, fct, nbf, exp) -} - -// newToken creates a new UCAN token with MPC signing -func (k *mpcKeyshareSource) newToken( - audienceDID string, - proofs []Proof, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, -) (*Token, error) { - // Validate audience DID - if !isValidDID(audienceDID) { - return nil, fmt.Errorf("invalid audience DID: %s", audienceDID) - } - - // Create JWT with MPC signing method - t := jwt.New(NewJWTSigningMethod("MPC256", k.enclave)) - - // Set UCAN version header - t.Header[UCANVersionKey] = UCANVersion - - var ( - nbfUnix int64 - expUnix int64 - ) - - if !nbf.IsZero() { - nbfUnix = nbf.Unix() - } - if !exp.IsZero() { - expUnix = exp.Unix() - } - - // Convert attenuations to claim format - attClaims := make([]map[string]any, len(att)) - for i, a := range att { - attClaims[i] = map[string]any{ - "can": a.Capability.GetActions(), - "with": a.Resource.GetURI(), - } - } - - // Convert proofs to strings - proofStrings := make([]string, len(proofs)) - for i, proof := range proofs { - proofStrings[i] = string(proof) - } - - // Convert facts to any slice - factData := make([]any, len(fct)) - for i, fact := range fct { - factData[i] = string(fact.Data) - } - - // Set claims - claims := jwt.MapClaims{ - "iss": k.issuerDID, - "aud": audienceDID, - "att": attClaims, - } - - if nbfUnix > 0 { - claims["nbf"] = nbfUnix - } - if expUnix > 0 { - claims["exp"] = expUnix - } - if len(proofStrings) > 0 { - claims["prf"] = proofStrings - } - if len(factData) > 0 { - claims["fct"] = factData - } - - t.Claims = claims - - // Sign the token using MPC enclave - tokenString, err := t.SignedString(nil) - if err != nil { - return nil, fmt.Errorf("failed to sign token: %w", err) - } - - return &Token{ - Raw: tokenString, - Issuer: k.issuerDID, - Audience: audienceDID, - ExpiresAt: expUnix, - NotBefore: nbfUnix, - Attenuations: att, - Proofs: proofs, - Facts: fct, - }, nil -} - -// isAttenuationSubset checks if child attenuations are a subset of parent attenuations -func isAttenuationSubset(child, parent []Attenuation) bool { - for _, childAtt := range child { - if !containsAttenuation(parent, childAtt) { - return false - } - } - return true -} - -// containsAttenuation checks if the parent list contains an equivalent attenuation -func containsAttenuation(parent []Attenuation, att Attenuation) bool { - for _, parentAtt := range parent { - if parentAtt.Resource.Matches(att.Resource) && - parentAtt.Capability.Contains(att.Capability) { - return true - } - } - return false -} - -// isValidDID validates DID format -func isValidDID(did string) bool { - return did != "" && len(did) > 5 && strings.HasPrefix(did, "did:") -} - -// getIssuerDIDFromBytes creates an issuer DID and address from public key bytes -func getIssuerDIDFromBytes(pubKeyBytes []byte) (string, string, error) { - // Convert MPC public key bytes to libp2p crypto.PubKey - pubKey, err := crypto.UnmarshalSecp256k1PublicKey(pubKeyBytes) - if err != nil { - return "", "", fmt.Errorf("failed to unmarshal secp256k1 key: %w", err) - } - - // Create DID using the crypto/keys package - did, err := keys.NewDID(pubKey) - if err != nil { - return "", "", fmt.Errorf("failed to create DID: %w", err) - } - - didStr := did.String() - - // Generate address from DID (simplified implementation) - address := fmt.Sprintf("addr_%x", pubKeyBytes[:8]) - - return didStr, address, nil -} diff --git a/crypto/mpc/spec/ucan.go b/crypto/mpc/spec/ucan.go deleted file mode 100644 index 01d9463f3..000000000 --- a/crypto/mpc/spec/ucan.go +++ /dev/null @@ -1,125 +0,0 @@ -package spec - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/cosmos/cosmos-sdk/types/bech32" -) - -// Token represents a UCAN JWT token with parsed claims -type Token struct { - Raw string `json:"raw"` - Issuer string `json:"iss"` - Audience string `json:"aud"` - ExpiresAt int64 `json:"exp,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Attenuations []Attenuation `json:"att"` - Proofs []Proof `json:"prf,omitempty"` - Facts []Fact `json:"fct,omitempty"` -} - -// Attenuation represents a UCAN capability attenuation -type Attenuation struct { - Capability Capability `json:"can"` - Resource Resource `json:"with"` -} - -// Proof represents a UCAN delegation proof (either JWT or CID) -type Proof string - -// Fact represents arbitrary facts in UCAN tokens -type Fact struct { - Data json.RawMessage `json:"data"` -} - -// Capability defines what actions can be performed -type Capability interface { - GetActions() []string - Grants(abilities []string) bool - Contains(other Capability) bool - String() string -} - -// Resource defines what resource the capability applies to -type Resource interface { - GetScheme() string - GetValue() string - GetURI() string - Matches(other Resource) bool -} - -// SimpleCapability implements Capability for single actions -type SimpleCapability struct { - Action string `json:"action"` -} - -func (c *SimpleCapability) GetActions() []string { return []string{c.Action} } -func (c *SimpleCapability) Grants(abilities []string) bool { - return len(abilities) == 1 && c.Action == abilities[0] -} - -func (c *SimpleCapability) Contains( - other Capability, -) bool { - return c.Action == other.GetActions()[0] -} -func (c *SimpleCapability) String() string { return c.Action } - -// SimpleResource implements Resource for basic URI resources -type SimpleResource struct { - Scheme string `json:"scheme"` - Value string `json:"value"` - URI string `json:"uri"` -} - -func (r *SimpleResource) GetScheme() string { return r.Scheme } -func (r *SimpleResource) GetValue() string { return r.Value } -func (r *SimpleResource) GetURI() string { return r.URI } -func (r *SimpleResource) Matches(other Resource) bool { return r.URI == other.GetURI() } - -// UCAN constants -const ( - UCANVersion = "0.9.0" - UCANVersionKey = "ucv" - PrfKey = "prf" - FctKey = "fct" - AttKey = "att" - CapKey = "cap" -) - -// CreateSimpleAttenuation creates a basic attenuation -func CreateSimpleAttenuation(action, resourceURI string) Attenuation { - return Attenuation{ - Capability: &SimpleCapability{Action: action}, - Resource: parseResourceURI(resourceURI), - } -} - -// parseResourceURI creates a Resource from URI string -func parseResourceURI(uri string) Resource { - parts := strings.SplitN(uri, "://", 2) - if len(parts) != 2 { - return &SimpleResource{ - Scheme: "unknown", - Value: uri, - URI: uri, - } - } - - return &SimpleResource{ - Scheme: parts[0], - Value: parts[1], - URI: uri, - } -} - -// getIssuerDIDFromBytes creates an issuer DID and address from public key bytes (alternative implementation) -func getIssuerDIDFromBytesAlt(pubKeyBytes []byte) (string, string, error) { - addr, err := bech32.ConvertAndEncode("idx", pubKeyBytes) - if err != nil { - return "", "", fmt.Errorf("failed to encode address: %w", err) - } - return fmt.Sprintf("did:sonr:%s", addr), addr, nil -} diff --git a/crypto/mpc/utils.go b/crypto/mpc/utils.go deleted file mode 100644 index 854e1d6e1..000000000 --- a/crypto/mpc/utils.go +++ /dev/null @@ -1,160 +0,0 @@ -package mpc - -import ( - "crypto/aes" - "crypto/cipher" - "errors" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1" - "golang.org/x/crypto/sha3" -) - -func CheckIteratedErrors(aErr, bErr error) error { - if aErr == protocol.ErrProtocolFinished && bErr == protocol.ErrProtocolFinished { - return nil - } - if aErr != protocol.ErrProtocolFinished { - return aErr - } - if bErr != protocol.ErrProtocolFinished { - return bErr - } - return nil -} - -func GetHashKey(key []byte) []byte { - hash := sha3.New256() - hash.Write(key) - return hash.Sum(nil)[:32] // Use first 32 bytes of hash -} - -func DecryptKeyshare(msg []byte, key []byte, nonce []byte) ([]byte, error) { - hashedKey := GetHashKey(key) - block, err := aes.NewCipher(hashedKey) - if err != nil { - return nil, err - } - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, err - } - plaintext, err := aesgcm.Open(nil, nonce, msg, nil) - if err != nil { - return nil, err - } - return plaintext, nil -} - -func EncryptKeyshare(msg Message, key []byte, nonce []byte) ([]byte, error) { - hashedKey := GetHashKey(key) - msgBytes, err := protocol.EncodeMessage(msg) - if err != nil { - return nil, err - } - block, err := aes.NewCipher(hashedKey) - if err != nil { - return nil, err - } - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, err - } - ciphertext := aesgcm.Seal(nil, nonce, []byte(msgBytes), nil) - return ciphertext, nil -} - -func GetAliceOut(msg *protocol.Message) (AliceOut, error) { - return dklsv1.DecodeAliceDkgResult(msg) -} - -func GetAlicePublicPoint(msg *protocol.Message) (Point, error) { - out, err := dklsv1.DecodeAliceDkgResult(msg) - if err != nil { - return nil, err - } - return out.PublicKey, nil -} - -func GetBobOut(msg *protocol.Message) (BobOut, error) { - return dklsv1.DecodeBobDkgResult(msg) -} - -func GetBobPubPoint(msg *protocol.Message) (Point, error) { - out, err := dklsv1.DecodeBobDkgResult(msg) - if err != nil { - return nil, err - } - return out.PublicKey, nil -} - -// GetECDSAPoint builds an elliptic curve point from a compressed byte slice -func GetECDSAPoint(pubKey []byte) (*curves.EcPoint, error) { - crv := curves.K256() - x := new(big.Int).SetBytes(pubKey[1:33]) - y := new(big.Int).SetBytes(pubKey[33:]) - ecCurve, err := crv.ToEllipticCurve() - if err != nil { - return nil, fmt.Errorf("error converting curve: %v", err) - } - return &curves.EcPoint{X: x, Y: y, Curve: ecCurve}, nil -} - -func SerializeSignature(sig *curves.EcdsaSignature) ([]byte, error) { - if sig == nil { - return nil, errors.New("nil signature") - } - - rBytes := sig.R.Bytes() - sBytes := sig.S.Bytes() - - // Ensure both components are 32 bytes - rPadded := make([]byte, 32) - sPadded := make([]byte, 32) - copy(rPadded[32-len(rBytes):], rBytes) - copy(sPadded[32-len(sBytes):], sBytes) - - // Concatenate R and S - result := make([]byte, 64) - copy(result[0:32], rPadded) - copy(result[32:64], sPadded) - - return result, nil -} - -func DeserializeSignature(sigBytes []byte) (*curves.EcdsaSignature, error) { - if len(sigBytes) != 64 { - return nil, fmt.Errorf("invalid signature length: expected 64 bytes, got %d", len(sigBytes)) - } - - r := new(big.Int).SetBytes(sigBytes[:32]) - s := new(big.Int).SetBytes(sigBytes[32:]) - - return &curves.EcdsaSignature{ - R: r, - S: s, - }, nil -} - -func GetAliceSignFunc(k *EnclaveData, bz []byte) (SignFunc, error) { - curve := k.Curve.Curve() - return dklsv1.NewAliceSign(curve, sha3.New256(), bz, k.ValShare, protocol.Version1) -} - -func GetAliceRefreshFunc(k *EnclaveData) (RefreshFunc, error) { - curve := k.Curve.Curve() - return dklsv1.NewAliceRefresh(curve, k.ValShare, protocol.Version1) -} - -func GetBobSignFunc(k *EnclaveData, bz []byte) (SignFunc, error) { - curve := curves.K256() - return dklsv1.NewBobSign(curve, sha3.New256(), bz, k.UserShare, protocol.Version1) -} - -func GetBobRefreshFunc(k *EnclaveData) (RefreshFunc, error) { - curve := curves.K256() - return dklsv1.NewBobRefresh(curve, k.UserShare, protocol.Version1) -} diff --git a/crypto/mpc/verify.go b/crypto/mpc/verify.go deleted file mode 100644 index 416375982..000000000 --- a/crypto/mpc/verify.go +++ /dev/null @@ -1,29 +0,0 @@ -package mpc - -import ( - "crypto/ecdsa" - - "golang.org/x/crypto/sha3" -) - -func VerifyWithPubKey(pubKeyCompressed []byte, data []byte, sig []byte) (bool, error) { - edSig, err := DeserializeSignature(sig) - if err != nil { - return false, err - } - ePub, err := GetECDSAPoint(pubKeyCompressed) - if err != nil { - return false, err - } - pk := &ecdsa.PublicKey{ - Curve: ePub.Curve, - X: ePub.X, - Y: ePub.Y, - } - - // Hash the message using SHA3-256 - hash := sha3.New256() - hash.Write(data) - digest := hash.Sum(nil) - return ecdsa.Verify(pk, digest, edSig.R, edSig.S), nil -} diff --git a/crypto/ot/base/simplest/ot.go b/crypto/ot/base/simplest/ot.go deleted file mode 100644 index 35c8b1b5d..000000000 --- a/crypto/ot/base/simplest/ot.go +++ /dev/null @@ -1,437 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package simplest implements the "Verified Simplest OT", as defined in "protocol 7" of [DKLs18](https://eprint.iacr.org/2018/499.pdf). -// The original "Simplest OT" protocol is presented in [CC15](https://eprint.iacr.org/2015/267.pdf). -// In our implementation, we run OTs for multiple choice bits in parallel. Furthermore, as described in the DKLs paper, -// we implement this as Random OT protocol. We also add encryption and decryption steps as defined in the protocol, but -// emphasise that these steps are optional. Specifically, in the setting where this OT is used as the seed OT in an -// OT Extension protocol, the encryption and decryption steps are not needed. -// -// Limitation: currently we only support batch OTs that are multiples of 8. -// -// Ideal functionalities: -// - We have used ZKP Schnorr for the F^{R_{DL}}_{ZK} -// - We have used HMAC for realizing the Random Oracle Hash function, the key for HMAC is received as input to the protocol. -package simplest - -import ( - "crypto/rand" - "crypto/subtle" - "fmt" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -const ( - // keyCount is the number of encryption keys created. Since this is a 1-out-of-2 OT, the key count is set to 2. - keyCount = 2 - - // DigestSize is the length of hash. Similarly, when it comes to encrypting and decryption, it is the size of the - // plaintext and ciphertext. - DigestSize = 32 -) - -type ( - // OneTimePadDecryptionKey is the type of Rho^w, Rho^0, and RHo^1 in the paper. - OneTimePadDecryptionKey = [DigestSize]byte - - // OneTimePadEncryptionKeys is the type of Rho^0, and RHo^1 in the paper. - OneTimePadEncryptionKeys = [keyCount][DigestSize]byte - - // OtChallenge is the type of xi in the paper. - OtChallenge = [DigestSize]byte - - // OtChallengeResponse is the type of Rho' in the paper. - OtChallengeResponse = [DigestSize]byte - - // ChallengeOpening is the type of hashed Rho^0 and Rho^1 - ChallengeOpening = [keyCount][DigestSize]byte - - // ReceiversMaskedChoices corresponds to the "A" value in the paper in compressed format. - ReceiversMaskedChoices = []byte -) - -// SenderOutput are the outputs that the sender will obtain as a result of running the "random" OT protocol. -type SenderOutput struct { - // OneTimePadEncryptionKeys are Rho^0 and Rho^1, the output of the random OT. - // These can be used to encrypt and send two messages to the receiver. - // Therefore, for readability they are called OneTimePadEncryptionKeys in the code. - OneTimePadEncryptionKeys []OneTimePadEncryptionKeys -} - -// ReceiverOutput are the outputs that the receiver will obtain as a result of running the "random" OT protocol. -type ReceiverOutput struct { - // PackedRandomChoiceBits is a packed version of the choice vector, the packing is done for performance reasons. - PackedRandomChoiceBits []byte - - // RandomChoiceBits is the choice vector represented as unpacked int array. Initialed from PackedRandomChoiceBits. - RandomChoiceBits []int - - // OneTimePadDecryptionKey is Rho^w, the output of the random OT. For the receiver, there is just 1 output per execution. - // This value will be used to decrypt one of the messages sent by the sender. - // Therefore, for readability this is called OneTimePadDecryptionKey in the code. - OneTimePadDecryptionKey []OneTimePadDecryptionKey -} - -// Sender stores state for the "sender" role in OT. see Protocol 7 in Appendix A of DKLs18. -type Sender struct { - // Output is the output that is produced as a result of running random OT protocol. - Output *SenderOutput - - curve *curves.Curve - - // secretKey is the value `b` in the paper, which is the discrete log of B, which will be (re)used in _all_ executions of the OT. - secretKey curves.Scalar - - // publicKey is the public key of the secretKey. - publicKey curves.Point - - // batchSize is the number of parallel OTs. - batchSize int - - transcript *merlin.Transcript -} - -// Receiver stores state for the "receiver" role in OT. Protocol 7, Appendix A, of DKLs. -type Receiver struct { - // Output is the output that is produced as a result of running random OT protocol. - Output *ReceiverOutput - - curve *curves.Curve - - // senderPublicKey corresponds to "B" in the paper. - senderPublicKey curves.Point - - // senderChallenge is "xi" in the protocol. - senderChallenge []OtChallenge - - // batchSize is the number of parallel OTs. - batchSize int - - transcript *merlin.Transcript -} - -// NewSender creates a new "sender" object, ready to participate in a _random_ verified simplest OT in the role of the sender. -// no messages are specified by the sender, because random ones will be sent (hence the random OT). -// ultimately, the `Sender`'s `Output` field will be appropriately populated. -// you can use it directly, or alternatively bootstrap it into an _actual_ (non-random) OT using `Round7Encrypt` below -func NewSender( - curve *curves.Curve, - batchSize int, - uniqueSessionId [DigestSize]byte, -) (*Sender, error) { - if batchSize&0x07 != 0 { // This is the same as `batchSize % 8 != 0`, but is constant time - return nil, errors.New("batch size should be a multiple of 8") - } - transcript := merlin.NewTranscript("Coinbase_DKLs_SeedOT") - transcript.AppendMessage([]byte("session_id"), uniqueSessionId[:]) - return &Sender{ - Output: &SenderOutput{}, - curve: curve, - batchSize: batchSize, - transcript: transcript, - }, nil -} - -// NewReceiver is a Random OT receiver. Therefore, the choice bits are created randomly. -// The choice bits are stored in a packed format (e.g., each choice is a single bit in a byte array). -func NewReceiver( - curve *curves.Curve, - batchSize int, - uniqueSessionId [DigestSize]byte, -) (*Receiver, error) { - // This is the same as `batchSize % 8 != 0`, but is constant time - if batchSize&0x07 != 0 { - return nil, errors.New("batch size should be a multiple of 8") - } - - transcript := merlin.NewTranscript("Coinbase_DKLs_SeedOT") - transcript.AppendMessage([]byte("session_id"), uniqueSessionId[:]) - - receiver := &Receiver{ - Output: &ReceiverOutput{}, - curve: curve, - batchSize: batchSize, - transcript: transcript, - } - batchSizeBytes := batchSize >> 3 // divide by 8 - receiver.Output.PackedRandomChoiceBits = make([]byte, batchSizeBytes) - if _, err := rand.Read(receiver.Output.PackedRandomChoiceBits[:]); err != nil { - return nil, errors.Wrap(err, "choosing random choice bits") - } - // Unpack into Choice bits - receiver.initChoice() - return receiver, nil -} - -// Round1ComputeAndZkpToPublicKey is the first phase of the protocol. -// computes and stores public key and returns the schnorr proof. serialized / packed. -// This implements step 1 of Protocol 7 of DKLs18, page 16. -func (sender *Sender) Round1ComputeAndZkpToPublicKey() (*schnorr.Proof, error) { - var err error - // Sample the secret key and compute the public key. - sender.secretKey = sender.curve.Scalar.Random(rand.Reader) - sender.publicKey = sender.curve.ScalarBaseMult(sender.secretKey) - - // Generate the ZKP proof. - uniqueSessionId := [DigestSize]byte{} - copy( - uniqueSessionId[:], - sender.transcript.ExtractBytes([]byte("sender schnorr proof"), DigestSize), - ) - prover := schnorr.NewProver(sender.curve, nil, uniqueSessionId[:]) - proof, err := prover.Prove(sender.secretKey) - if err != nil { - return nil, errors.Wrap(err, "creating zkp proof for secret key in seed OT sender round 1") - } - return proof, nil -} - -// Round2VerifySchnorrAndPadTransfer verifies the schnorr proof of the public key sent by the sender, i.e., step 2), -// and then does receiver's "Pad Transfer" phase in OT, i.e., step 3), of Protocol 7 (page 16) of the paper. -func (receiver *Receiver) Round2VerifySchnorrAndPadTransfer( - proof *schnorr.Proof, -) ([]ReceiversMaskedChoices, error) { - receiver.senderPublicKey = proof.Statement - uniqueSessionId := [DigestSize]byte{} - copy( - uniqueSessionId[:], - receiver.transcript.ExtractBytes([]byte("sender schnorr proof"), DigestSize), - ) - if err := schnorr.Verify(proof, receiver.curve, nil, uniqueSessionId[:]); err != nil { - return nil, errors.Wrap(err, "verifying schnorr proof in seed OT receiver round 2") - } - - result := make([]ReceiversMaskedChoices, receiver.batchSize) - receiver.Output.OneTimePadDecryptionKey = make([]OneTimePadDecryptionKey, receiver.batchSize) - copy( - uniqueSessionId[:], - receiver.transcript.ExtractBytes([]byte("random oracle salts"), DigestSize), - ) - for i := 0; i < receiver.batchSize; i++ { - a := receiver.curve.Scalar.Random(rand.Reader) - // Computing `A := a . G + w . B` in constant time, by first computing option0 = a.G and option1 = a.G+B and then - // constant time choosing one of them by first assuming that the output is option0, and overwrite it if the choice bit is 1. - - option0 := receiver.curve.ScalarBaseMult(a) - option0Bytes := option0.ToAffineCompressed() - option1 := option0.Add(receiver.senderPublicKey) - option1Bytes := option1.ToAffineCompressed() - - result[i] = option0Bytes - subtle.ConstantTimeCopy(receiver.Output.RandomChoiceBits[i], result[i], option1Bytes) - // compute the internal rho - rho := receiver.senderPublicKey.Mul(a) - hash := sha3.New256() - if _, err := hash.Write(uniqueSessionId[:]); err != nil { - return nil, errors.Wrap(err, "writing seed to hash in round 2 pad transfer") - } - if _, err := hash.Write([]byte{byte(i)}); err != nil { - return nil, errors.Wrap(err, "writing i to hash in round 2 pad transfer") - } - if _, err := hash.Write(rho.ToAffineCompressed()); err != nil { - return nil, errors.Wrap(err, "writing point to hash in round 2 pad transfer") - } - copy(receiver.Output.OneTimePadDecryptionKey[i][:], hash.Sum(nil)) - } - return result, nil -} - -// Round3PadTransfer is the sender's "Pad Transfer" phase in OT; see steps 4 and 5 of page 16 of the paper. -// Returns the challenges xi -func (sender *Sender) Round3PadTransfer( - compressedReceiversMaskedChoice []ReceiversMaskedChoices, -) ([]OtChallenge, error) { - var err error - challenge := make([]OtChallenge, sender.batchSize) - sender.Output.OneTimePadEncryptionKeys = make([]OneTimePadEncryptionKeys, sender.batchSize) - negSenderPublicKey := sender.publicKey.Neg() - - receiversMaskedChoice := make([]curves.Point, len(compressedReceiversMaskedChoice)) - for i := 0; i < len(compressedReceiversMaskedChoice); i++ { - if receiversMaskedChoice[i], err = sender.curve.Point.FromAffineCompressed(compressedReceiversMaskedChoice[i]); err != nil { - return nil, errors.Wrap(err, "uncompress the point") - } - } - - baseEncryptionKeyMaterial := make([]curves.Point, keyCount) - var hashedKey [keyCount][DigestSize]byte - uniqueSessionId := [DigestSize]byte{} - copy( - uniqueSessionId[:], - sender.transcript.ExtractBytes([]byte("random oracle salts"), DigestSize), - ) - - for i := 0; i < sender.batchSize; i++ { - // Sender creates two options that will eventually be used as her encryption keys. - // `baseEncryptionKeyMaterial[0]` and `baseEncryptionKeyMaterial[0]` correspond to rho_0 and rho_1 in the paper, respectively. - baseEncryptionKeyMaterial[0] = receiversMaskedChoice[i].Mul(sender.secretKey) - - receiverChoiceMinusSenderPublicKey := receiversMaskedChoice[i].Add(negSenderPublicKey) - baseEncryptionKeyMaterial[1] = receiverChoiceMinusSenderPublicKey.Mul(sender.secretKey) - - for k := 0; k < keyCount; k++ { - hash := sha3.New256() - if _, err = hash.Write(uniqueSessionId[:]); err != nil { - return nil, errors.Wrap(err, "writing seed to hash in round 3 pad transfer") - } - if _, err = hash.Write([]byte{byte(i)}); err != nil { - return nil, errors.Wrap(err, "writing i to hash in round 3 pad transfer") - } - if _, err = hash.Write(baseEncryptionKeyMaterial[k].ToAffineCompressed()); err != nil { - return nil, errors.Wrap(err, "writing point to hash in round 3 pad transfer") - } - copy(sender.Output.OneTimePadEncryptionKeys[i][k][:], hash.Sum(nil)) - if err != nil { - return nil, errors.Wrap(err, "compute the encryption keys") - } - - // Compute a challenge by XORing the hash of the hash of the key. Not a typo ;) - hashedKey[k] = sha3.Sum256(sender.Output.OneTimePadEncryptionKeys[i][k][:]) - hashedKey[k] = sha3.Sum256(hashedKey[k][:]) - } - - challenge[i] = xorBytes(hashedKey[0], hashedKey[1]) - } - return challenge, nil -} - -// Round4RespondToChallenge corresponds to initial round of the receiver's "Verify" phase; see step 6 of page 16 of the paper. -// this is just the start of Verification. In this round, the receiver outputs "rho'", which the sender will check. -func (receiver *Receiver) Round4RespondToChallenge( - challenge []OtChallenge, -) ([]OtChallengeResponse, error) { - // store to be used in future steps - receiver.senderChallenge = challenge - // challengeResponses is Rho' in the paper. - challengeResponses := make([]OtChallengeResponse, receiver.batchSize) - for i := 0; i < receiver.batchSize; i++ { - // Constant-time xor of the hashed key and the challenge, based on the choice bit. - hashedKey := sha3.Sum256(receiver.Output.OneTimePadDecryptionKey[i][:]) - hashedKey = sha3.Sum256(hashedKey[:]) - challengeResponses[i] = hashedKey - alternativeChallengeResponse := xorBytes(receiver.senderChallenge[i], hashedKey) - subtle.ConstantTimeCopy( - receiver.Output.RandomChoiceBits[i], - challengeResponses[i][:], - alternativeChallengeResponse[:], - ) - } - return challengeResponses, nil -} - -// Round5Verify verifies the challenge response. If the verification passes, sender opens his challenges to the receiver. -// See step 7 of page 16 of the paper. -// Abort if Rho' != H(H(Rho^0)) in other words, if challengeResponse != H(H(encryption key 0)). -// opening is H(encryption key) -func (sender *Sender) Round5Verify( - challengeResponses []OtChallengeResponse, -) ([]ChallengeOpening, error) { - opening := make([]ChallengeOpening, sender.batchSize) - for i := 0; i < sender.batchSize; i++ { - for k := 0; k < keyCount; k++ { - opening[i][k] = sha3.Sum256(sender.Output.OneTimePadEncryptionKeys[i][k][:]) - } - - // Verify - hashedKey0 := sha3.Sum256(opening[i][0][:]) - if subtle.ConstantTimeCompare(hashedKey0[:], challengeResponses[i][:]) != 1 { - return nil, errors.New("receiver's challenge response didn't match H(H(rho^0))") - } - } - return opening, nil -} - -// Round6Verify is the _last_ part of the "Verification" phase of OT; see p. 16 of https://eprint.iacr.org/2018/499.pdf. -// See step 8 of page 16 of the paper. -// Abort if H(Rho^w) != the one it calculated itself or -// -// if Xi != H(H(Rho^0)) XOR H(H(Rho^1)) -// -// In other words, -// -// if opening_w != H(decryption key) or -// if challenge != H(opening 0) XOR H(opening 0) -func (receiver *Receiver) Round6Verify(challengeOpenings []ChallengeOpening) error { - for i := 0; i < receiver.batchSize; i++ { - hashedDecryptionKey := sha3.Sum256(receiver.Output.OneTimePadDecryptionKey[i][:]) - w := receiver.Output.RandomChoiceBits[i] - if subtle.ConstantTimeCompare(hashedDecryptionKey[:], challengeOpenings[i][w][:]) != 1 { - return fmt.Errorf("sender's supposed H(rho^omega) doesn't match our own") - } - hashedKey0 := sha3.Sum256(challengeOpenings[i][0][:]) - hashedKey1 := sha3.Sum256(challengeOpenings[i][1][:]) - reconstructedChallenge := xorBytes(hashedKey0, hashedKey1) - if subtle.ConstantTimeCompare( - reconstructedChallenge[:], - receiver.senderChallenge[i][:], - ) != 1 { - return fmt.Errorf( - "sender's openings H(rho^0) and H(rho^1) didn't decommit to its prior message", - ) - } - } - return nil -} - -// Round7Encrypt wraps an `Encrypt` operation on the Sender's underlying output from the random OT; see `Encrypt` below. -// this is optional; it will be used only in circumstances when you want to run "actual" (i.e., non-random) OT -func (sender *Sender) Round7Encrypt( - messages [][keyCount][DigestSize]byte, -) ([][keyCount][DigestSize]byte, error) { - return sender.Output.Encrypt(messages) -} - -// Round8Decrypt wraps a `Decrypt` operation on the Receiver's underlying output from the random OT; see `Decrypt` below -// this is optional; it will be used only in circumstances when you want to run "actual" (i.e., non-random) OT -func (receiver *Receiver) Round8Decrypt( - ciphertext [][keyCount][DigestSize]byte, -) ([][DigestSize]byte, error) { - return receiver.Output.Decrypt(ciphertext) -} - -// Encrypt runs step 9) of the seed OT Protocol 7) of https://eprint.iacr.org/2018/499.pdf, -// in which the seed OT sender "encrypts" both messages under the "one-time keys" output by the random OT. -func (s *SenderOutput) Encrypt( - plaintexts [][keyCount][DigestSize]byte, -) ([][keyCount][DigestSize]byte, error) { - batchSize := len(s.OneTimePadEncryptionKeys) - if len(plaintexts) != batchSize { - return nil, errors.New("message size should be same as batch size") - } - ciphertexts := make([][keyCount][DigestSize]byte, batchSize) - - for i := 0; i < len(plaintexts); i++ { - for k := 0; k < keyCount; k++ { - ciphertexts[i][k] = xorBytes(s.OneTimePadEncryptionKeys[i][k], plaintexts[i][k]) - } - } - return ciphertexts, nil -} - -// Decrypt is step 10) of the seed OT Protocol 7) of https://eprint.iacr.org/2018/499.pdf, -// where the seed OT receiver "decrypts" the message it's receiving using the "key" it received in the random OT. -func (r *ReceiverOutput) Decrypt( - ciphertexts [][keyCount][DigestSize]byte, -) ([][DigestSize]byte, error) { - batchSize := len(r.OneTimePadDecryptionKey) - if len(ciphertexts) != batchSize { - return nil, errors.New("number of ciphertexts should be same as batch size") - } - plaintexts := make([][DigestSize]byte, batchSize) - - for i := 0; i < len(ciphertexts); i++ { - choice := r.RandomChoiceBits[i] - plaintexts[i] = xorBytes(r.OneTimePadDecryptionKey[i], ciphertexts[i][choice]) - } - return plaintexts, nil -} diff --git a/crypto/ot/base/simplest/ot_test.go b/crypto/ot/base/simplest/ot_test.go deleted file mode 100644 index 687e759ac..000000000 --- a/crypto/ot/base/simplest/ot_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package simplest_test - -import ( - "crypto/rand" - "crypto/sha256" - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/ottest" -) - -func TestOtOnMultipleCurves(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - batchSize := 256 - hashKeySeed := [32]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(t, err) - sender, receiver, err := ottest.RunSimplestOT(curve, batchSize, hashKeySeed) - require.NoError(t, err) - - for i := 0; i < batchSize; i++ { - require.Equal( - t, - receiver.OneTimePadDecryptionKey[i], - sender.OneTimePadEncryptionKeys[i][receiver.RandomChoiceBits[i]], - ) - } - - // Transfer messages - messages := make([][2][32]byte, batchSize) - for i := 0; i < batchSize; i++ { - messages[i] = [2][32]byte{ - sha256.Sum256([]byte(fmt.Sprintf("message[%d][0]", i))), - sha256.Sum256([]byte(fmt.Sprintf("message[%d][1]", i))), - } - } - ciphertexts, err := sender.Encrypt(messages) - require.NoError(t, err) - decrypted, err := receiver.Decrypt(ciphertexts) - require.NoError(t, err) - - for i := 0; i < batchSize; i++ { - choice := receiver.RandomChoiceBits[i] - require.Equal(t, messages[i][choice], decrypted[i]) - require.NotEqual(t, messages[i][1-choice], decrypted[i]) - } - } -} - -func TestOTStreaming(t *testing.T) { - batchSize := 256 - curve := curves.K256() - hashKeySeed := [32]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(t, err) - sender, err := simplest.NewSender(curve, batchSize, hashKeySeed) - require.Nil(t, err) - receiver, err := simplest.NewReceiver(curve, batchSize, hashKeySeed) - require.Nil(t, err) - - senderPipe, receiverPipe := simplest.NewPipeWrappers() - errorsChannel := make( - chan error, - 2, - ) // warning: if one party errors, the other will sit there forever. add timeouts. - go func() { - errorsChannel <- simplest.SenderStreamOTRun(sender, senderPipe) - }() - go func() { - errorsChannel <- simplest.ReceiverStreamOTRun(receiver, receiverPipe) - }() - for i := 0; i < 2; i++ { - require.Nil(t, <-errorsChannel) - } - for i := 0; i < batchSize; i++ { - require.Equal( - t, - receiver.Output.OneTimePadDecryptionKey[i], - sender.Output.OneTimePadEncryptionKeys[i][receiver.Output.RandomChoiceBits[i]], - ) - } -} diff --git a/crypto/ot/base/simplest/stream.go b/crypto/ot/base/simplest/stream.go deleted file mode 100644 index d3f360d57..000000000 --- a/crypto/ot/base/simplest/stream.go +++ /dev/null @@ -1,100 +0,0 @@ -package simplest - -import ( - "encoding/gob" - "io" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -// ReceiverStreamOTRun exposes the entire seed OT process for the receiver in "stream mode" to the user. -// what this means is that instead of calling the component methods in the process manually, and manually handling -// the encoding and decoding of the resulting output and input structs, the user needs _only_ to pass a ReadWriter -// (in practice this will be something like a websocket object), and this method will handle the entire process. -// this serves the dual (though related) purpose of conveniently bundling up the entire seed OT process, -// for use in tests, both in this package, as well as in the other packages which use this one (like cOT and mult). -func ReceiverStreamOTRun(receiver *Receiver, rw io.ReadWriter) error { - enc := gob.NewEncoder(rw) - dec := gob.NewDecoder(rw) - gob.Register(&curves.ScalarK256{}) - gob.Register(&curves.PointK256{}) - - proof := &schnorr.Proof{} - - if err := dec.Decode(proof); err != nil { - return errors.Wrap(err, "failed to decode proof in receiver stream OT") - } - - receiversMaskedChoice, err := receiver.Round2VerifySchnorrAndPadTransfer(proof) - if err != nil { - return errors.Wrap(err, "error in round 2 in receiver stream OT") - } - if err = enc.Encode(receiversMaskedChoice); err != nil { - return errors.Wrap(err, "error encoding result of round 1 in receiver stream OT") - } - var challenge []OtChallenge - err = dec.Decode(&challenge) - if err != nil { - return errors.Wrap(err, "error decoding challenge in receiver stream OT") - } - challengeResponse, err := receiver.Round4RespondToChallenge(challenge) - if err != nil { - return errors.Wrap(err, "error computing round 2 challenge response in receiver stream OT") - } - if err = enc.Encode(challengeResponse); err != nil { - return errors.Wrap(err, "error encoding challenge response in receiver stream OT") - } - var openings []ChallengeOpening - err = dec.Decode(&openings) - if err != nil { - return errors.Wrap(err, "error decoding challenge openings in receiver stream OT") - } - return receiver.Round6Verify(openings) -} - -// SenderStreamOTRun exposes the entire seed OT process for the sender in "stream mode" to the user. -// similarly to the above, this means that the user needs only to pass a `ReadWriter` representing the comm channel; -// this method will handle all encoding and decoding + writing and reading to the channel. -func SenderStreamOTRun(sender *Sender, rw io.ReadWriter) error { - // again a high-level helper method showing the overall flow, this time for the sender. - enc := gob.NewEncoder(rw) - dec := gob.NewDecoder(rw) - gob.Register(&curves.ScalarK256{}) - gob.Register(&curves.PointK256{}) - - proof, err := sender.Round1ComputeAndZkpToPublicKey() - if err != nil { - return err - } - if err = enc.Encode(proof); err != nil { - return err - } - - var receiversMaskedChoice []ReceiversMaskedChoices - err = dec.Decode(&receiversMaskedChoice) - if err != nil { - return errors.Wrap(err, "error decoding receiver's masked choice in sender stream OT") - } - - challenge, err := sender.Round3PadTransfer(receiversMaskedChoice) - if err != nil { - return errors.Wrap(err, "error during round 2 pad transfer in sender stream OT") - } - err = enc.Encode(challenge) - if err != nil { - return errors.Wrap(err, "error encoding challenge in sender stream OT") - } - var challengeResponses []OtChallengeResponse - err = dec.Decode(&challengeResponses) - if err != nil { - return errors.Wrap(err, "error decoding challenges responses in sender stream OT") - } - opening, err := sender.Round5Verify(challengeResponses) - if err != nil { - return errors.Wrap(err, "error in round 3 verify in sender stream OT") - } - return enc.Encode(opening) -} diff --git a/crypto/ot/base/simplest/util.go b/crypto/ot/base/simplest/util.go deleted file mode 100755 index f852e27a5..000000000 --- a/crypto/ot/base/simplest/util.go +++ /dev/null @@ -1,55 +0,0 @@ -package simplest - -import ( - "io" -) - -// xorBytes computes c = a xor b. -func xorBytes(a, b [DigestSize]byte) (c [DigestSize]byte) { - for i := 0; i < DigestSize; i++ { - c[i] = a[i] ^ b[i] - } - return c -} - -// initChoice initializes the receiver's choice array from the PackedRandomChoiceBits array -func (receiver *Receiver) initChoice() { - // unpack the random values in PackedRandomChoiceBits into bits in Choice - receiver.Output.RandomChoiceBits = make([]int, receiver.batchSize) - for i := 0; i < len(receiver.Output.RandomChoiceBits); i++ { - receiver.Output.RandomChoiceBits[i] = int( - ExtractBitFromByteVector(receiver.Output.PackedRandomChoiceBits, i), - ) - } -} - -// ExtractBitFromByteVector interprets the byte-vector `vector` as if it were a _bit_-vector with len(vector) * 8 bits. -// it extracts the `index`th such bit, interpreted in the little-endian way (i.e., both across bytes and within bytes). -func ExtractBitFromByteVector(vector []byte, index int) byte { - // the bitwise tricks index >> 3 == index // 8 and index & 0x07 == index % 8 are designed to avoid CPU division. - return vector[index>>3] >> (index & 0x07) & 0x01 -} - -type pipeWrapper struct { - r *io.PipeReader - w *io.PipeWriter - exchanged int // used this during testing, to track bytes exchanged -} - -func (wrapper *pipeWrapper) Write(p []byte) (n int, err error) { - n, err = wrapper.w.Write(p) - wrapper.exchanged += n - return n, err -} - -func (wrapper *pipeWrapper) Read(p []byte) (n int, err error) { - n, err = wrapper.r.Read(p) - wrapper.exchanged += n - return n, err -} - -func NewPipeWrappers() (*pipeWrapper, *pipeWrapper) { - leftOut, leftIn := io.Pipe() - rightOut, rightIn := io.Pipe() - return &pipeWrapper{r: leftOut, w: rightIn}, &pipeWrapper{r: rightOut, w: leftIn} -} diff --git a/crypto/ot/extension/kos/kos.go b/crypto/ot/extension/kos/kos.go deleted file mode 100644 index f40fc0e39..000000000 --- a/crypto/ot/extension/kos/kos.go +++ /dev/null @@ -1,475 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package kos in an implementation of maliciously secure OT extension protocol defined in "Protocol 9" of -// [DKLs18](https://eprint.iacr.org/2018/499.pdf). The original protocol was presented in -// [KOS15](https://eprint.iacr.org/2015/546.pdf). -package kos - -import ( - "crypto/rand" - "crypto/subtle" - "encoding/binary" - "fmt" - - "golang.org/x/crypto/sha3" - - "github.com/pkg/errors" - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" -) - -const ( - // below are the "cryptographic parameters", including computational and statistical, - // as well as the cOT block size parameters, which depend on these in a pre-defined way. - - // Kappa is the computational security parameter. - Kappa = 256 - - // KappaBytes is same as Kappa // 8, but avoids cpu division. - KappaBytes = Kappa >> 3 - - // L is the batch size used in the cOT functionality. - L = 2*Kappa + 2*s - - // COtBlockSizeBytes is same as L // 8, but avoids cpu division. - COtBlockSizeBytes = L >> 3 - - // OtWidth is the number of scalars processed per "slot" of the cOT. by definition of this parameter, - // for each of the receiver's choice bits, the sender will provide `OTWidth` scalars. - // in turn, both the sender and receiver will obtain `OTWidth` shares _per_ slot / bit of the cOT. - // by definition of the cOT, these "vectors of" scalars will add (componentwise) to the sender's original scalars. - OtWidth = 2 - - s = 80 // statistical security parameter. - kappaOT = Kappa + s - lPrime = L + kappaOT // length of pseudorandom seed expansion, used within cOT protocol - cOtExtendedBlockSizeBytes = lPrime >> 3 -) - -type Receiver struct { - // OutputAdditiveShares are the ultimate output received. basically just the "pads". - OutputAdditiveShares [L][OtWidth]curves.Scalar - - // seedOtResults are the results that this party has received by playing the sender role in a base OT protocol. - seedOtResults *simplest.SenderOutput - - // extendedPackedChoices is storage for "choice vector || gamma^{ext}" in a packed format. - extendedPackedChoices [cOtExtendedBlockSizeBytes]byte - psi [lPrime][KappaBytes]byte // transpose of v^0. gets retained between messages - - curve *curves.Curve - uniqueSessionId [simplest.DigestSize]byte // store this between rounds -} - -type Sender struct { - // OutputAdditiveShares are the ultimate output received. basically just the "pads". - OutputAdditiveShares [L][OtWidth]curves.Scalar - - // seedOtResults are the results that this party has received by playing the receiver role in a base OT protocol. - seedOtResults *simplest.ReceiverOutput - - curve *curves.Curve -} - -func binaryFieldMul(A []byte, B []byte) []byte { - // multiplies `A` and `B` in the finite field of order 2^256. - // The reference is Hankerson, Vanstone and Menezes, Guide to Elliptic Curve Cryptography. https://link.springer.com/book/10.1007/b97644 - // `A` and `B` are both assumed to be 32-bytes slices. here we view them as little-endian coordinate representations of degree-255 polynomials. - // the multiplication takes place modulo the irreducible (over F_2) polynomial f(X) = X^256 + X^10 + X^5 + X^2 + 1. see Table A.1. - // the techniques we use are given in section 2.3, Binary field arithmetic. - // for the multiplication part, we use Algorithm 2.34, "Right-to-left comb method for polynomial multiplication". - // for the reduction part, we use a variant of the idea of Figure 2.9, customized to our setting. - const W = 64 // the machine word width, in bits. - const t = 4 // the number of words needed to represent a polynomial. - c := make([]uint64, 2*t) // result - a := make([]uint64, t) - b := make([]uint64, t+1) // will hold a copy of b, shifted by some amount - for i := 0; i < 32; i++ { // "condense" `A` and `B` into word-vectors, instead of byte-vectors - a[i>>3] |= uint64(A[i]) << (i & 0x07 << 3) - b[i>>3] |= uint64(B[i]) << (i & 0x07 << 3) - } - for k := 0; k < W; k++ { - for j := 0; j < t; j++ { - // conditionally add a copy of (the appropriately shifted) B to C, depending on the appropriate bit of A - // do this in constant-time; i.e., independent of A. - // technically, in each time we call this, the right-hand argument is a public datum, - // so we could arrange things so that it's _not_ constant-time, but the variable-time stuff always depends on something public. - // better to just be safe here though and make it constant-time anyway. - mask := -(a[j] >> k & 0x01) // if A[j] >> k & 0x01 == 1 then 0xFFFFFFFFFFFFFFFF else 0x0000000000000000 - for i := 0; i < t+1; i++ { - c[j+i] ^= b[i] & mask // conditionally add B to C{j} - } - } - for i := t; i > 0; i-- { - b[i] = b[i]<<1 | b[i-1]>>63 - } - b[0] <<= 1 - } - // multiplication complete; begin reduction. - // things become actually somewhat simpler in our case, because the degree of the polynomial is a multiple of the word size - // the technique to come up with the numbers below comes essentially from going through the exact same process as on page 54, - // but with the polynomial f(X) = X^256 + X^10 + X^5 + X^2 + 1 above instead, and with parameters m = 256, W = 64, t = 4. - // the idea is exactly as described informally on that page, even though this particular polynomial isn't explicitly treated. - for i := 2*t - 1; i >= t; i-- { - c[i-4] ^= c[i] << 10 - c[i-3] ^= c[i] >> 54 - c[i-4] ^= c[i] << 5 - c[i-3] ^= c[i] >> 59 - c[i-4] ^= c[i] << 2 - c[i-3] ^= c[i] >> 62 - c[i-4] ^= c[i] - } - C := make([]byte, 32) - for i := 0; i < 32; i++ { - C[i] = byte(c[i>>3] >> (i & 0x07 << 3)) // truncate word to byte - } - return C -} - -// NewCOtReceiver creates a `Receiver` instance, ready for use as the receiver in the KOS cOT protocol -// you must supply the output gotten by running an instance of seed OT as the _sender_ (note the reversal of roles) -func NewCOtReceiver(seedOTResults *simplest.SenderOutput, curve *curves.Curve) *Receiver { - return &Receiver{ - seedOtResults: seedOTResults, - curve: curve, - } -} - -// NewCOtSender creates a `Sender` instance, ready for use as the sender in the KOS cOT protocol. -// you must supply the output gotten by running an instance of seed OT as the _receiver_ (note the reversal of roles) -func NewCOtSender(seedOTResults *simplest.ReceiverOutput, curve *curves.Curve) *Sender { - return &Sender{ - seedOtResults: seedOTResults, - curve: curve, - } -} - -// Round1Output is Bob's first message to Alice during cOT extension; -// these outputs are described in step 4) of Protocol 9) https://eprint.iacr.org/2018/499.pdf -type Round1Output struct { - U [Kappa][cOtExtendedBlockSizeBytes]byte - WPrime [simplest.DigestSize]byte - VPrime [simplest.DigestSize]byte -} - -// Round2Output this is Alice's response to Bob in cOT extension; -// the values `tau` are specified in Alice's step 6) of Protocol 9) https://eprint.iacr.org/2018/499.pdf -type Round2Output struct { - Tau [L][OtWidth]curves.Scalar -} - -// convertBitToBitmask converts a "bit"---i.e., a `byte` which is _assumed to be_ either 0 or 1---into a bitmask, -// namely, it outputs 0x00 if `bit == 0` and 0xFF if `bit == 1`. -func convertBitToBitmask(bit byte) byte { - return ^(bit - 0x01) -} - -// the below code takes as input a `kappa` by `lPrime` _boolean_ matrix, whose rows are actually "compacted" as bytes. -// so in actuality, it's a `kappa` by `lPrime >> 3 == cOtExtendedBlockSizeBytes` matrix of _bytes_. -// its output is the same boolean matrix, but transposed, so it has dimensions `lPrime` by `kappa`. -// but likewise we want to compact the output matrix as bytes, again _row-wise_. -// so the output matrix's dimensions are lPrime by `kappa >> 3 == KappaBytes`, as a _byte_ matrix. -// the technique is fairly straightforward, but involves some bitwise operations. -func transposeBooleanMatrix(input [Kappa][cOtExtendedBlockSizeBytes]byte) [lPrime][KappaBytes]byte { - output := [lPrime][KappaBytes]byte{} - for rowByte := 0; rowByte < KappaBytes; rowByte++ { - for rowBitWithinByte := 0; rowBitWithinByte < 8; rowBitWithinByte++ { - for columnByte := 0; columnByte < cOtExtendedBlockSizeBytes; columnByte++ { - for columnBitWithinByte := 0; columnBitWithinByte < 8; columnBitWithinByte++ { - rowBit := rowByte<<3 + rowBitWithinByte - columnBit := columnByte<<3 + columnBitWithinByte - // the below code grabs the _bit_ at input[rowBit][columnBit], if input were a viewed as a boolean matrix. - // in reality, it's packed into bytes, so instead we have to grab the `columnBitWithinByte`th bit within the appropriate byte. - bitAtInputRowBitColumnBit := input[rowBit][columnByte] >> columnBitWithinByte & 0x01 - // now that we've grabbed the bit we care about, we need to write it into the appropriate place in the output matrix - // the output matrix is also packed---but in the "opposite" way (the short dimension is packed, instead of the long one) - // what we're going to do is take the _bit_ we got, and shift it by rowBitWithinByte. - // this has the effect of preparing for us to write it into the appropriate place into the output matrix. - shiftedBit := bitAtInputRowBitColumnBit << rowBitWithinByte - output[columnBit][rowByte] |= shiftedBit - } - } - } - } - return output -} - -// Round1Initialize initializes the OT Extension. see page 17, steps 1), 2), 3) and 4) of Protocol 9 of the paper. -// The input `choice` vector is "packed" (i.e., the underlying abstract vector of `L` bits is represented as a `cOTBlockSizeBytes` bytes). -func (receiver *Receiver) Round1Initialize( - uniqueSessionId [simplest.DigestSize]byte, - choice [COtBlockSizeBytes]byte, -) (*Round1Output, error) { - // salt the transcript with the OT-extension session ID - receiver.uniqueSessionId = uniqueSessionId - - // write the input choice vector into our local data. Since `otBatchSize` is the number of bits, we are working with - // bytes, we first need to calculate how many bytes are needed to store that many bits. - copy(receiver.extendedPackedChoices[0:COtBlockSizeBytes], choice[:]) - - // Fill the rest of the extended choice vector with random values. These random values correspond to `gamma^{ext}`. - if _, err := rand.Read(receiver.extendedPackedChoices[COtBlockSizeBytes:]); err != nil { - return nil, errors.Wrap(err, "sampling random coins for gamma^{ext}") - } - - v := [2][Kappa][cOtExtendedBlockSizeBytes]byte{} // kappa * L array of _bits_, in "dense" form. contains _both_ v_0 and v_1. - result := &Round1Output{} - - hash := sha3.New256() // basically this will contain a hash of the matrix U. - for i := 0; i < Kappa; i++ { - for j := 0; j < 2; j++ { - shake := sha3.NewCShake256(uniqueSessionId[:], []byte("Coinbase_DKLs_cOT")) - if _, err := shake.Write(receiver.seedOtResults.OneTimePadEncryptionKeys[i][j][:]); err != nil { - return nil, errors.Wrap(err, "writing seed OT into shake in cOT receiver round 1") - } - // this is the core pseudorandom expansion of the secret OT input seeds s_i^0 and s_i^1 - // see Extension, 2), in Protocol 9, page 17 of DKLs https://eprint.iacr.org/2018/499.pdf - // use the uniqueSessionId as the "domain separator", and the _secret_ seed rho as the input! - if _, err := shake.Read(v[j][i][:]); err != nil { - return nil, errors.Wrap( - err, - "reading from shake to compute v^j in cOT receiver round 1", - ) - } - } - for j := 0; j < cOtExtendedBlockSizeBytes; j++ { - result.U[i][j] = v[0][i][j] ^ v[1][i][j] ^ receiver.extendedPackedChoices[j] - // U := v_i^0 ^ v_i^1 ^ w. note: in step 4) of Prot. 9, i think `w` should be bolded? - } - if _, err := hash.Write(result.U[i][:]); err != nil { - return nil, err - } - } - receiver.psi = transposeBooleanMatrix(v[0]) - digest := hash.Sum( - nil, - ) // go ahead and record this, so that we only have to hash the big matrix U once. - for j := 0; j < lPrime; j++ { - hash = sha3.New256() - jBytes := [2]byte{} - binary.BigEndian.PutUint16(jBytes[:], uint16(j)) - if _, err := hash.Write(jBytes[:]); err != nil { // write j into shake - return nil, errors.Wrap( - err, - "writing nonce into hash while computing chiJ in cOT receiver round 1", - ) - } - if _, err := hash.Write(digest); err != nil { - return nil, errors.Wrap( - err, - "writing input digest into hash while computing chiJ in cOT receiver round 1", - ) - } - chiJ := hash.Sum(nil) - wJ := convertBitToBitmask( - simplest.ExtractBitFromByteVector(receiver.extendedPackedChoices[:], j), - ) // extract j^th bit from vector of bytes w. - psiJTimesChiJ := binaryFieldMul(receiver.psi[j][:], chiJ) - for k := 0; k < KappaBytes; k++ { - result.WPrime[k] ^= wJ & chiJ[k] - result.VPrime[k] ^= psiJTimesChiJ[k] - } - } - return result, nil -} - -// Round2Transfer computes the OT sender ("Alice")'s part of cOT; this includes steps 2) 5) and 6) of Protocol 9 -// `input` is the sender's main vector of inputs alpha_j; these are the things tA_j and tB_j will add to if w_j == 1. -// `message` contains the message the receiver ("Bob") sent us. this itself contains Bob's values WPrime, VPrime, and U -// the output is just the values `Tau` we send back to Bob. -// as a side effect of this function, our (i.e., the sender's) outputs tA_j from the cOT will be populated. -func (sender *Sender) Round2Transfer( - uniqueSessionId [simplest.DigestSize]byte, - input [L][OtWidth]curves.Scalar, - round1Output *Round1Output, -) (*Round2Output, error) { - z := [Kappa][cOtExtendedBlockSizeBytes]byte{} - hash := sha3.New256() // basically this will contain a hash of the matrix U. - - for i := 0; i < Kappa; i++ { - v := make( - []byte, - cOtExtendedBlockSizeBytes, - ) // will contain alice's expanded PRG output for the row i, namely v_i^{\Nabla_i}. - shake := sha3.NewCShake256(uniqueSessionId[:], []byte("Coinbase_DKLs_cOT")) - if _, err := shake.Write(sender.seedOtResults.OneTimePadDecryptionKey[i][:]); err != nil { - return nil, errors.Wrap( - err, - "sender writing seed OT decryption key into shake in sender round 2 transfer", - ) - } - if _, err := shake.Read(v); err != nil { - return nil, errors.Wrap( - err, - "reading from shake into row `v` in sender round 2 transfer", - ) - } - // use the idExt as the domain separator, and the _secret_ seed rho as the input! - mask := convertBitToBitmask(byte(sender.seedOtResults.RandomChoiceBits[i])) - for j := 0; j < cOtExtendedBlockSizeBytes; j++ { - z[i][j] = v[j] ^ mask&round1Output.U[i][j] - } - if _, err := hash.Write(round1Output.U[i][:]); err != nil { - return nil, errors.Wrap(err, "writing matrix U to hash in cOT sender round 2 transfer") - } - } - zeta := transposeBooleanMatrix(z) - digest := hash.Sum( - nil, - ) // go ahead and record this, so that we only have to hash the big matrix U once. - zPrime := [simplest.DigestSize]byte{} - for j := 0; j < lPrime; j++ { - hash = sha3.New256() - jBytes := [2]byte{} - binary.BigEndian.PutUint16(jBytes[:], uint16(j)) - if _, err := hash.Write(jBytes[:]); err != nil { // write j into hash - return nil, errors.Wrap( - err, - "writing nonce into hash while computing chiJ in cOT sender round 2 transfer", - ) - } - if _, err := hash.Write(digest); err != nil { - return nil, errors.Wrap( - err, - "writing input digest into hash while computing chiJ in cOT sender round 2 transfer", - ) - } - chiJ := hash.Sum(nil) - zetaJTimesChiJ := binaryFieldMul(zeta[j][:], chiJ) - for k := 0; k < KappaBytes; k++ { - zPrime[k] ^= zetaJTimesChiJ[k] - } - } - rhs := [simplest.DigestSize]byte{} - nablaTimesWPrime := binaryFieldMul( - sender.seedOtResults.PackedRandomChoiceBits, - round1Output.WPrime[:], - ) - for i := 0; i < KappaBytes; i++ { - rhs[i] = round1Output.VPrime[i] ^ nablaTimesWPrime[i] - } - if subtle.ConstantTimeCompare(zPrime[:], rhs[:]) != 1 { - return nil, fmt.Errorf( - "cOT receiver's consistency check failed; this may be an attempted attack; do NOT re-run the protocol", - ) - } - result := &Round2Output{} - for j := 0; j < L; j++ { - column := make([]byte, OtWidth*simplest.DigestSize) - shake := sha3.NewCShake256(uniqueSessionId[:], []byte("Coinbase_DKLs_cOT")) - jBytes := [2]byte{} - binary.BigEndian.PutUint16(jBytes[:], uint16(j)) - if _, err := shake.Write(jBytes[:]); err != nil { // write j into hash - return nil, errors.Wrap( - err, - "writing nonce into shake while computing OutputAdditiveShares in cOT sender round 2 transfer", - ) - } - if _, err := shake.Write(zeta[j][:]); err != nil { - return nil, errors.Wrap( - err, - "writing input zeta_j into shake while computing OutputAdditiveShares in cOT sender round 2 transfer", - ) - } - if _, err := shake.Read(column[:]); err != nil { - return nil, errors.Wrap( - err, - "reading shake into column while computing OutputAdditiveShares in cOT sender round 2 transfer", - ) - } - var err error - for k := 0; k < OtWidth; k++ { - sender.OutputAdditiveShares[j][k], err = sender.curve.Scalar.SetBytes( - column[k*simplest.DigestSize : (k+1)*simplest.DigestSize], - ) - if err != nil { - return nil, errors.Wrap(err, "OutputAdditiveShares scalar from bytes") - } - } - for i := 0; i < KappaBytes; i++ { - zeta[j][i] ^= sender.seedOtResults.PackedRandomChoiceBits[i] // note: overwrites zeta_j. just using it as a place to store - } - column = make([]byte, OtWidth*simplest.DigestSize) - shake = sha3.NewCShake256(uniqueSessionId[:], []byte("Coinbase_DKLs_cOT")) - binary.BigEndian.PutUint16(jBytes[:], uint16(j)) - if _, err := shake.Write(jBytes[:]); err != nil { // write j into hash - return nil, errors.Wrap( - err, - "writing nonce into shake while computing tau in cOT sender round 2 transfer", - ) - } - if _, err := shake.Write(zeta[j][:]); err != nil { - return nil, errors.Wrap( - err, - "writing input zeta_j into shake while computing tau in cOT sender round 2 transfer", - ) - } - if _, err := shake.Read(column[:]); err != nil { - return nil, errors.Wrap( - err, - "reading shake into column while computing tau in cOT sender round 2 transfer", - ) - } - for k := 0; k < OtWidth; k++ { - result.Tau[j][k], err = sender.curve.Scalar.SetBytes( - column[k*simplest.DigestSize : (k+1)*simplest.DigestSize], - ) - if err != nil { - return nil, errors.Wrap(err, "scalar Tau from bytes") - } - result.Tau[j][k] = result.Tau[j][k].Sub(sender.OutputAdditiveShares[j][k]) - result.Tau[j][k] = result.Tau[j][k].Add(input[j][k]) - } - } - return result, nil -} - -// Round3Transfer does the receiver (Bob)'s step 7) of Protocol 9, namely the computation of the outputs tB. -func (receiver *Receiver) Round3Transfer(round2Output *Round2Output) error { - for j := 0; j < L; j++ { - column := make([]byte, OtWidth*simplest.DigestSize) - shake := sha3.NewCShake256(receiver.uniqueSessionId[:], []byte("Coinbase_DKLs_cOT")) - jBytes := [2]byte{} - binary.BigEndian.PutUint16(jBytes[:], uint16(j)) - if _, err := shake.Write(jBytes[:]); err != nil { // write j into hash - return errors.Wrap( - err, - "writing nonce into shake while computing tB in cOT receiver round 3 transfer", - ) - } - if _, err := shake.Write(receiver.psi[j][:]); err != nil { - return errors.Wrap( - err, - "writing input zeta_j into shake while computing tB in cOT receiver round 3 transfer", - ) - } - if _, err := shake.Read(column[:]); err != nil { - return errors.Wrap( - err, - "reading shake into column while computing tB in cOT receiver round 3 transfer", - ) - } - bit := int(simplest.ExtractBitFromByteVector(receiver.extendedPackedChoices[:], j)) - var err error - for k := 0; k < OtWidth; k++ { - receiver.OutputAdditiveShares[j][k], err = receiver.curve.Scalar.SetBytes( - column[k*simplest.DigestSize : (k+1)*simplest.DigestSize], - ) - if err != nil { - return errors.Wrap(err, "scalar output additive shares from bytes") - } - receiver.OutputAdditiveShares[j][k] = receiver.OutputAdditiveShares[j][k].Neg() - wj0 := receiver.OutputAdditiveShares[j][k].Bytes() - wj1 := receiver.OutputAdditiveShares[j][k].Add(round2Output.Tau[j][k]).Bytes() - subtle.ConstantTimeCopy(bit, wj0, wj1) - if receiver.OutputAdditiveShares[j][k], err = receiver.curve.Scalar.SetBytes(wj0); err != nil { - return errors.Wrap(err, "scalar output additive shares from bytes") - } - } - } - return nil -} diff --git a/crypto/ot/extension/kos/kos_test.go b/crypto/ot/extension/kos/kos_test.go deleted file mode 100644 index 5129982f7..000000000 --- a/crypto/ot/extension/kos/kos_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package kos - -import ( - "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/ottest" -) - -func TestBinaryMult(t *testing.T) { - for i := 0; i < 100; i++ { - temp := make([]byte, 32) - _, err := rand.Read(temp) - require.NoError(t, err) - expected := make([]byte, 32) - copy(expected, temp) - // this test is based on Fermat's little theorem. - // the multiplicative group of units of a finite field has order |F| - 1 - // (in fact, it's necessarily cyclic; see e.g. https://math.stackexchange.com/a/59911, but this test doesn't rely on that fact) - // thus raising any element to the |F|th power should yield that element itself. - // this is a good test because it relies on subtle facts about the field structure, and will fail if anything goes wrong. - for j := 0; j < 256; j++ { - expected = binaryFieldMul(expected, expected) - } - require.Equal(t, temp, expected) - } -} - -func TestCOTExtension(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - uniqueSessionId := [simplest.DigestSize]byte{} - _, err := rand.Read(uniqueSessionId[:]) - require.NoError(t, err) - baseOtSenderOutput, baseOtReceiverOutput, err := ottest.RunSimplestOT( - curve, - Kappa, - uniqueSessionId, - ) - require.NoError(t, err) - for i := 0; i < Kappa; i++ { - require.Equal( - t, - baseOtReceiverOutput.OneTimePadDecryptionKey[i], - baseOtSenderOutput.OneTimePadEncryptionKeys[i][baseOtReceiverOutput.RandomChoiceBits[i]], - ) - } - - sender := NewCOtSender(baseOtReceiverOutput, curve) - receiver := NewCOtReceiver(baseOtSenderOutput, curve) - choice := [COtBlockSizeBytes]byte{} // receiver's input, namely choice vector. just random - _, err = rand.Read(choice[:]) - require.NoError(t, err) - input := [L][OtWidth]curves.Scalar{} // sender's input, namely integer "sums" in case w_j == 1. - for i := 0; i < L; i++ { - for j := 0; j < OtWidth; j++ { - input[i][j] = curve.Scalar.Random(rand.Reader) - require.NoError(t, err) - } - } - firstMessage, err := receiver.Round1Initialize(uniqueSessionId, choice) - require.NoError(t, err) - responseTau, err := sender.Round2Transfer(uniqueSessionId, input, firstMessage) - require.NoError(t, err) - err = receiver.Round3Transfer(responseTau) - require.NoError(t, err) - for j := 0; j < L; j++ { - bit := simplest.ExtractBitFromByteVector(choice[:], j) == 1 - for k := 0; k < OtWidth; k++ { - temp := sender.OutputAdditiveShares[j][k].Add(receiver.OutputAdditiveShares[j][k]) - if bit { - require.Equal(t, temp, input[j][k]) - } else { - require.Equal(t, temp, curve.Scalar.Zero()) - } - } - } - } -} - -func TestCOTExtensionStreaming(t *testing.T) { - curve := curves.K256() - hashKeySeed := [simplest.DigestSize]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(t, err) - baseOtReceiver, err := simplest.NewReceiver(curve, Kappa, hashKeySeed) - require.NoError(t, err) - sender := NewCOtSender(baseOtReceiver.Output, curve) - baseOtSender, err := simplest.NewSender(curve, Kappa, hashKeySeed) - require.NoError(t, err) - receiver := NewCOtReceiver(baseOtSender.Output, curve) - - // first run the seed OT - senderPipe, receiverPipe := simplest.NewPipeWrappers() - errorsChannel := make(chan error, 2) - go func() { - errorsChannel <- simplest.SenderStreamOTRun(baseOtSender, senderPipe) - }() - go func() { - errorsChannel <- simplest.ReceiverStreamOTRun(baseOtReceiver, receiverPipe) - }() - for i := 0; i < 2; i++ { - require.Nil(t, <-errorsChannel) - } - for i := 0; i < Kappa; i++ { - require.Equal( - t, - baseOtReceiver.Output.OneTimePadDecryptionKey[i], - baseOtSender.Output.OneTimePadEncryptionKeys[i][baseOtReceiver.Output.RandomChoiceBits[i]], - ) - } - - // begin test of cOT extension. first populate both parties' inputs randomly - choice := [COtBlockSizeBytes]byte{} // receiver's input, namely choice vector. just random - _, err = rand.Read(choice[:]) - require.NoError(t, err) - input := [L][OtWidth]curves.Scalar{} // sender's input, namely integer "sums" in case w_j == 1. random for the test - for i := 0; i < L; i++ { - for j := 0; j < OtWidth; j++ { - input[i][j] = curve.Scalar.Random(rand.Reader) - require.NoError(t, err) - } - } - - // now actually run it, stream-wise - go func() { - errorsChannel <- SenderStreamCOtRun(sender, hashKeySeed, input, receiverPipe) - }() - go func() { - errorsChannel <- ReceiverStreamCOtRun(receiver, hashKeySeed, choice, senderPipe) - }() - for i := 0; i < 2; i++ { - require.Nil(t, <-errorsChannel) - } - for j := 0; j < L; j++ { - bit := simplest.ExtractBitFromByteVector(choice[:], j) == 1 - for k := 0; k < OtWidth; k++ { - temp := sender.OutputAdditiveShares[j][k].Add(receiver.OutputAdditiveShares[j][k]) - if bit { - require.Equal(t, temp, input[j][k]) - } else { - require.Equal(t, temp, curve.Scalar.Zero()) - } - } - } -} diff --git a/crypto/ot/extension/kos/stream.go b/crypto/ot/extension/kos/stream.go deleted file mode 100644 index 108138321..000000000 --- a/crypto/ot/extension/kos/stream.go +++ /dev/null @@ -1,67 +0,0 @@ -package kos - -import ( - "encoding/gob" - "io" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" -) - -// ReceiverStreamCOtRun exposes an end-to-end "streaming" version of the cOT process for the receiver. -// this is similar to what we're also doing in the base OT side. the user only passes an arbitrary `ReadWriter` here, -// together with the relevant inputs (namely a choice vector); this method handles all parts of the process, -// including both encoding / decoding and writing to / reading from the stream. -func ReceiverStreamCOtRun( - receiver *Receiver, - hashKeySeed [simplest.DigestSize]byte, - choice [COtBlockSizeBytes]byte, - rw io.ReadWriter, -) error { - enc := gob.NewEncoder(rw) - dec := gob.NewDecoder(rw) - - firstMessage, err := receiver.Round1Initialize(hashKeySeed, choice) - if err != nil { - return errors.Wrap(err, "computing first message in receiver stream cOT") - } - if err = enc.Encode(firstMessage); err != nil { - return errors.Wrap(err, "encoding first message in receiver stream cOT") - } - responseTau := &Round2Output{} - if err = dec.Decode(responseTau); err != nil { - return errors.Wrap(err, "decoding responseTau in receiver stream OT") - } - if err = receiver.Round3Transfer(responseTau); err != nil { - return errors.Wrap(err, "error during round 3 in receiver stream OT") - } - return nil -} - -// SenderStreamCOtRun exposes the end-to-end "streaming" version of cOT for the sender. -// the sender should pass an arbitrary ReadWriter together with their input; this will handle the whole process, -// including all component methods, plus reading to and writing from the network. -func SenderStreamCOtRun( - sender *Sender, - hashKeySeed [simplest.DigestSize]byte, - input [L][OtWidth]curves.Scalar, - rw io.ReadWriter, -) error { - enc := gob.NewEncoder(rw) - dec := gob.NewDecoder(rw) - - firstMessage := &Round1Output{} - if err := dec.Decode(firstMessage); err != nil { - return errors.Wrap(err, "decoding first message in sender stream cOT") - } - responseTau, err := sender.Round2Transfer(hashKeySeed, input, firstMessage) - if err != nil { - return errors.Wrap(err, "error in round 2 in sender stream cOT") - } - if err = enc.Encode(responseTau); err != nil { - return errors.Wrap(err, "encoding responseTau in sender stream cOT") - } - return nil -} diff --git a/crypto/ot/ottest/util.go b/crypto/ot/ottest/util.go deleted file mode 100644 index f075c59c2..000000000 --- a/crypto/ot/ottest/util.go +++ /dev/null @@ -1,54 +0,0 @@ -// Package ottest contains some utilities to test ot functions. The main goal is to reduce the code duplication in -// various other packages that need to run an OT in their test setup stage. -package ottest - -import ( - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" -) - -// RunSimplestOT is a utility function used _only_ during various tests. -// essentially, it encapsulates the entire process of running a base OT, so that other tests can use it / bootstrap themselves. -// it handles the creation of the base OT sender and receiver, as well as orchestrates the rounds on them; -// it returns their outsputs, so that others can use them. -func RunSimplestOT( - curve *curves.Curve, - batchSize int, - uniqueSessionId [simplest.DigestSize]byte, -) (*simplest.SenderOutput, *simplest.ReceiverOutput, error) { - receiver, err := simplest.NewReceiver(curve, batchSize, uniqueSessionId) - if err != nil { - return nil, nil, errors.Wrap(err, "constructing OT receiver in run simplest OT") - } - sender, err := simplest.NewSender(curve, batchSize, uniqueSessionId) - if err != nil { - return nil, nil, errors.Wrap(err, "constructing OT sender in run simplest OT") - } - proof, err := sender.Round1ComputeAndZkpToPublicKey() - if err != nil { - return nil, nil, errors.Wrap(err, "sender round 1 in run simplest OT") - } - receiversMaskedChoice, err := receiver.Round2VerifySchnorrAndPadTransfer(proof) - if err != nil { - return nil, nil, errors.Wrap(err, "receiver round 2 in run simplest OT") - } - challenge, err := sender.Round3PadTransfer(receiversMaskedChoice) - if err != nil { - return nil, nil, errors.Wrap(err, "sender round 3 in run simplest OT") - } - challengeResponse, err := receiver.Round4RespondToChallenge(challenge) - if err != nil { - return nil, nil, errors.Wrap(err, "receiver round 4 in run simplest OT") - } - challengeOpenings, err := sender.Round5Verify(challengeResponse) - if err != nil { - return nil, nil, errors.Wrap(err, "sender round 5 in run simplest OT") - } - err = receiver.Round6Verify(challengeOpenings) - if err != nil { - return nil, nil, errors.Wrap(err, "receiver round 6 in run simplest OT") - } - return sender.Output, receiver.Output, nil -} diff --git a/crypto/paillier/README.md b/crypto/paillier/README.md deleted file mode 100755 index f59761cf0..000000000 --- a/crypto/paillier/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Paillier Cryptosystem - -Package paillier contains [Paillier's cryptosystem (1999)](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.112.4035&rep=rep1&type=pdf). -All routines here from pseudocode §2.5. Fig 1: The Paillier Cryptosystem. - -This module provides APIs for: - -- generating a safe key pair -- encryption and decryption -- adding two encrypted values, `Enc(a)` and `Enc(b)`, and obtaining `Enc(a + b)`, and -- multiplying a plain value, `a`, and an encrypted value `Enc(b)`, and obtaining `Enc(a * b)`. - -The encrypted values are represented as `big.Int` and are serializable. -This module also provides JSON serialization for the PublicKey and the SecretKey. diff --git a/crypto/paillier/paillier.go b/crypto/paillier/paillier.go deleted file mode 100644 index c646cb59e..000000000 --- a/crypto/paillier/paillier.go +++ /dev/null @@ -1,377 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package paillier contains Paillier's cryptosystem (1999) [P99]. -// Public-Key Cryptosystems Based on Composite Degree Residuosity Class. -// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.112.4035&rep=rep1&type=pdf -// All routines here from pseudocode §2.5. Fig 1: The Paillier Cryptosystem. -// -// This module provides APIs for: -// -// - generating a safe keypair, -// - encryption and decryption, -// - adding two encrypted values, Enc(a) and Enc(b), and obtaining Enc(a + b), and -// - multiplying a plain value, a, and an encrypted value Enc(b), and obtaining Enc(a * b). -// -// The encrypted values are represented as big.Int and are serializable. This module also provides -// JSON serialization for the PublicKey and the SecretKey. -package paillier - -import ( - "encoding/json" - "fmt" - "math/big" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/internal" -) - -// PaillierPrimeBits is the number of bits used to generate Paillier Safe Primes. -const PaillierPrimeBits = 1024 - -type ( - // PublicKey is a Paillier public key: N = P*Q; for safe primes P,Q. - PublicKey struct { - N *big.Int // N = PQ - N2 *big.Int // N² computed and cached to prevent re-computation. - } - - // PublicKeyJson encapsulates the data that is serialized to JSON. - // It is used internally and not for external use. Public so other pieces - // can use for serialization. - PublicKeyJson struct { - N *big.Int - } - - // SecretKey is a Paillier secret key. - SecretKey struct { - PublicKey - Lambda *big.Int // lcm(P - 1, Q - 1) - Totient *big.Int // Euler's totient: (P - 1) * (Q - 1) - U *big.Int // L((N + 1)^λ(N) mod N²)−1 mod N - } - - // SecretKeyJson encapsulates the data that is serialized to JSON. - // It is used internally and not for external use. Public so other pieces - // can use for serialization. - SecretKeyJson struct { - N, Lambda, Totient, U *big.Int - } - - // Ciphertext in Pailler's cryptosystem: a value $c \in Z_{N²}$ . - Ciphertext *big.Int -) - -// NewKeys generates Paillier keys with `bits` sized safe primes. -func NewKeys() (*PublicKey, *SecretKey, error) { - return keyGenerator(core.GenerateSafePrime, PaillierPrimeBits) -} - -// keyGenerator generates Paillier keys with `bits` sized safe primes using function -// `genSafePrime` to generate the safe primes. -func keyGenerator( - genSafePrime func(uint) (*big.Int, error), - bits uint, -) (*PublicKey, *SecretKey, error) { - values := make(chan *big.Int, 2) - errors := make(chan error, 2) - - var p, q *big.Int - - for p == q { - for range []int{1, 2} { - go func() { - value, err := genSafePrime(bits) - values <- value - errors <- err - }() - } - - for _, err := range []error{<-errors, <-errors} { - if err != nil { - return nil, nil, err - } - } - - p, q = <-values, <-values - } - - // Assemble the secret/public key pair. - sk, err := NewSecretKey(p, q) - if err != nil { - return nil, nil, err - } - return &sk.PublicKey, sk, nil -} - -// NewSecretKey computes intermediate values based on safe primes p, q. -func NewSecretKey(p, q *big.Int) (*SecretKey, error) { - if p == nil || q == nil { - return nil, internal.ErrNilArguments - } - // Pre-compute necessary values. - pm1 := new(big.Int).Sub(p, core.One) // P - 1 - qm1 := new(big.Int).Sub(q, core.One) // Q - 1 - n := new(big.Int).Mul(p, q) // N = PQ - nn := new(big.Int).Mul(n, n) // N² - lambda, err := lcm(pm1, qm1) // λ(N) = lcm(P-1, Q-1) - if err != nil { - // Code coverage note: lcm returns error only if the inputs are nil, which can never happen here. - return nil, err - } - totient := new(big.Int).Mul(pm1, qm1) // 𝝋(N) = (P-1)(Q-1) - pk := PublicKey{ - N: n, - N2: nn, - } - - // (N+1)^λ(N) mod N² - t := new(big.Int).Add(n, core.One) - t.Exp(t, lambda, nn) - - // L((N+1)^λ(N) mod N²) - u, err := pk.l(t) - if err != nil { - return nil, err - } - // L((N+1)^λ(N) mod N²)^-1 mod N - u.ModInverse(u, n) - - return &SecretKey{pk, lambda, totient, u}, nil -} - -// MarshalJSON converts the public key into json format. -func (pk PublicKey) MarshalJSON() ([]byte, error) { - data := PublicKeyJson{pk.N} - return json.Marshal(data) -} - -// UnmarshalJSON converts the json data into this public key. -func (pk *PublicKey) UnmarshalJSON(bytes []byte) error { - data := new(PublicKeyJson) - if err := json.Unmarshal(bytes, data); err != nil { - return err - } - if data.N == nil { - return nil - } - pk.N = data.N - pk.N2 = new(big.Int).Mul(data.N, data.N) - return nil -} - -// lcm calculates the least common multiple. -func lcm(x, y *big.Int) (*big.Int, error) { - if x == nil || y == nil { - return nil, internal.ErrNilArguments - } - gcd := new(big.Int).GCD(nil, nil, x, y) - if core.ConstantTimeEq(gcd, core.Zero) { - return core.Zero, nil - } - // Compute least common multiple: https://en.wikipedia.org/wiki/Least_common_multiple#Calculation . - b := new(big.Int) - return b.Abs(b.Mul(b.Div(x, gcd), y)), nil -} - -// l computes a residuosity class of n^2: (x - 1) / n. -// Where it is the quotient x - 1 divided by n not modular multiplication of x - 1 times -// the modular multiplicative inverse of n. The function name comes from [P99]. -func (pk *PublicKey) l(x *big.Int) (*big.Int, error) { - if x == nil { - return nil, internal.ErrNilArguments - } - - if core.ConstantTimeEq(pk.N, core.Zero) { - return nil, internal.ErrNCannotBeZero - } - - // Ensure x = 1 mod N - if !core.ConstantTimeEq(new(big.Int).Mod(x, pk.N), core.One) { - return nil, internal.ErrResidueOne - } - - // Ensure x ∈ Z_N² - if err := core.In(x, pk.N2); err != nil { - return nil, err - } - - // (x - 1) / n - b := new(big.Int).Sub(x, core.One) - return b.Div(b, pk.N), nil -} - -// NewPubkey initializes a Paillier public key with a given n. -func NewPubkey(n *big.Int) (*PublicKey, error) { - if n == nil { - return nil, errors.New("n cannot be nil") - } - return &PublicKey{ - N: n, - N2: new(big.Int).Mul(n, n), // Compute and cache N² - }, nil -} - -// Add combines two Paillier ciphertexts. -func (pk *PublicKey) Add(c, d Ciphertext) (Ciphertext, error) { - if c == nil || d == nil { - return nil, internal.ErrNilArguments - } - // Ensure c,d ∈ Z_N² - cErr := core.In(c, pk.N2) - dErr := core.In(d, pk.N2) - // Constant time error check - var err error - if cErr != nil { - err = cErr - } - if dErr != nil { - err = dErr - } - if err != nil { - return nil, err - } - - ctxt, err := core.Mul(c, d, pk.N2) - if err != nil { - // Code coverage note: core.Mul returns error only if the inputs are nil, which can never happen here. - return nil, err - } - return ctxt, nil -} - -// Mul is equivalent to adding two Paillier exponents. -func (pk *PublicKey) Mul(a *big.Int, c Ciphertext) (Ciphertext, error) { - if a == nil || c == nil { - return nil, internal.ErrNilArguments - } - - // Ensure a ∈ Z_N - aErr := core.In(a, pk.N) - // Ensure c ∈ Z_N² - cErr := core.In(c, pk.N2) - - var err error - - // Constant time error check - if aErr != nil { - err = aErr - } - if cErr != nil { - err = cErr - } - if err != nil { - return nil, err - } - return new(big.Int).Exp(c, a, pk.N2), nil -} - -// Encrypt produces a ciphertext on input message. -func (pk *PublicKey) Encrypt(msg *big.Int) (Ciphertext, *big.Int, error) { - // generate a nonce: r \in Z**_N - r, err := core.Rand(pk.N) - if err != nil { - return nil, nil, err - } - - // Generate and return the ciphertext - ct, err := pk.encrypt(msg, r) - return ct, r, err -} - -// encrypt produces a ciphertext on input a message and nonce. -func (pk *PublicKey) encrypt(msg, r *big.Int) (Ciphertext, error) { - if msg == nil || r == nil { - return nil, internal.ErrNilArguments - } - - // Ensure msg ∈ Z_N - if err := core.In(msg, pk.N); err != nil { - return nil, err - } - - // Ensure r ∈ Z^*_N: we use the method proved in docs/[EL20] - // ensure r ∈ Z^_N-{0} - if err := core.In(r, pk.N); err != nil { - return nil, err - } - if core.ConstantTimeEq(r, core.Zero) { - return nil, fmt.Errorf("r cannot be 0") - } - - // Compute the ciphertext components: ɑ, β - // ɑ = (N+1)^m (mod N²) - ɑ := new(big.Int).Add(pk.N, core.One) - ɑ.Exp(ɑ, msg, pk.N2) - β := new(big.Int).Exp(r, pk.N, pk.N2) // β = r^N (mod N²) - - // ciphertext = ɑ*β = (N+1)^m * r^N (mod N²) - c, err := core.Mul(ɑ, β, pk.N2) - if err != nil { - // Code coverage note: core.Mul returns error only if the inputs are nil, which can never happen here. - return nil, err - } - return c, nil -} - -// Decrypt is the reverse operation of Encrypt. -func (sk *SecretKey) Decrypt(c Ciphertext) (*big.Int, error) { - if c == nil { - return nil, internal.ErrNilArguments - } - - // Ensure C ∈ Z_N² - if err := core.In(c, sk.N2); err != nil { - return nil, err - } - - // Compute the msg in components - // ɑ ≡ c^{λ(N)} mod N² - ɑ := new(big.Int).Exp(c, sk.Lambda, sk.N2) - - // l = L(ɑ, N) - ell, err := sk.l(ɑ) - if err != nil { - return nil, err - } - - // Compute the msg - // m ≡ lu = L(ɑ)*u = L(c^{λ(N)})*u mod N - m, err := core.Mul(ell, sk.U, sk.N) - if err != nil { - return nil, err - } - return m, nil -} - -// MarshalJSON converts the secret key into json format. -func (sk SecretKey) MarshalJSON() ([]byte, error) { - data := SecretKeyJson{ - sk.N, - sk.Lambda, - sk.Totient, - sk.U, - } - return json.Marshal(data) -} - -// UnmarshalJSON converts the json data into this secret key. -func (sk *SecretKey) UnmarshalJSON(bytes []byte) error { - data := new(SecretKeyJson) - if err := json.Unmarshal(bytes, data); err != nil { - return err - } - if data.N != nil { - sk.N = data.N - sk.N2 = new(big.Int).Mul(data.N, data.N) - } - sk.U = data.U - sk.Totient = data.Totient - sk.Lambda = data.Lambda - return nil -} diff --git a/crypto/paillier/psf.go b/crypto/paillier/psf.go deleted file mode 100644 index e512f18fb..000000000 --- a/crypto/paillier/psf.go +++ /dev/null @@ -1,235 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// -// This file contains proofs that Paillier moduli are square-free: [spec] fig 15 - -package paillier - -import ( - "crypto/elliptic" - "fmt" - "math/big" - - crypto "github.com/sonr-io/sonr/crypto/core" - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -// [spec] 10.2 and ProvePSF, VerifyPSF fig.15 -const PsfProofLength = 13 - -// PsfProofParams contains the inputs to ProvePSF -type PsfProofParams struct { - Curve elliptic.Curve - SecretKey *SecretKey - Pi uint32 - Y *curves.EcPoint -} - -// PsfVerifyParams contains the inputs to VerifyPSF -type PsfVerifyParams struct { - Curve elliptic.Curve - PublicKey *PublicKey - Pi uint32 - Y *curves.EcPoint -} - -// PsfProof is a slice of 13 big.Int's that prove that a Paillier modulus is square-free -type PsfProof []*big.Int - -// Prove that a Paillier modulus is square-free -// [spec] §10.fig 15 -func (p *PsfProofParams) Prove() (PsfProof, error) { - // Verify that params are sane - if p.Curve == nil || - p.SecretKey == nil || - p.Pi == 0 || - p.Y == nil { - return nil, internal.ErrNilArguments - } - - // 1. ell = 13 - // Note this is set above as PsfProofLength - - // 2. M = N^{-1} mod \phi(N) - M, err := crypto.Inv(p.SecretKey.N, p.SecretKey.Totient) - if err != nil { - return nil, err - } - - // 3. [x_1, ..., x_ell] <- GenerateChallenges(g,q,y,Pi,ell) - // NOTE: spec doesn't include N, but it's an oversight--should be part of the - // commitment - x, err := generateChallenges(p.Curve.Params(), p.SecretKey.N, p.Pi, p.Y) - if err != nil { - return nil, err - } - if len(x) != PsfProofLength { - return nil, fmt.Errorf( - "challenges array is not correct length: want=%v got=%v", - PsfProofLength, - len(x), - ) - } - - // 4. For i = [1, ... \ell] - // NOTE: typo in spec: says j = ... but uses subscript i in loop - proof := make([]*big.Int, PsfProofLength) - for i, xj := range x { - // 5. Compute y_i = x_i^M mod N - // NOTE: the pseudocode shows mod phi(N) which is incorrect - // it should be mod N otherwise the reverse in Verify - // will fail. Using phi(N) puts M in the wrong group. - yi, err := crypto.Exp(xj, M, p.SecretKey.N) - if err != nil { - return nil, err - } - - // 6. Set \Pi = [y_1, ..., y_\ell] - // NOTE: typo in spec: says y_t not y_\ell - proof[i] = yi - } - - // 7. return \Pi - return proof, nil -} - -// Verify that a Paillier modulus is square-free -// [spec] §10.fig 15 -func (p PsfProof) Verify(psf *PsfVerifyParams) error { - // Verify that params are sane - if psf == nil || - psf.Curve == nil || - psf.PublicKey == nil || - psf.Pi == 0 || - psf.Y == nil { - return internal.ErrNilArguments - } - - // 1. ell = 13 - // Note this is set above as PsfProofLength - - // 2. t = 1000 - // NOTE not used anywhere - - // 3. if q|N return false - if new(big.Int).Mod(psf.PublicKey.N, psf.Curve.Params().N).Cmp(crypto.Zero) == 0 { - return fmt.Errorf("paillier public key is a multiple of the curve subgroup") - } - - // 4. [x_1, ..., x_ell] <- GenerateChallenges(g,q,y,Pi,ell) - // NOTE: spec doesn't include N, but it's an oversight--should be part of the - // commitment - x, err := generateChallenges(psf.Curve.Params(), psf.PublicKey.N, psf.Pi, psf.Y) - if err != nil { - return err - } - if len(x) != PsfProofLength { - return fmt.Errorf( - "challenges array is not correct length: want=%v got=%v", - PsfProofLength, - len(x), - ) - } - - // 5. for j in [1,...,l] - for j, xj := range x { - // 6. yj^N != x mod N return false - // NOTE: pseudocode uses i when loop uses j - lhs, err := crypto.Exp(p[j], psf.PublicKey.N, psf.PublicKey.N) - if err != nil { - return err - } - if lhs.Cmp(xj) != 0 { - return fmt.Errorf("not equal at %d", j) - } - } - - return nil -} - -// generateChallenges computes `l` deterministic numbers as -// challenges for PsfProof which proves that the Paillier modulus is square free -// [spec] fig.15 GenerateChallenges -func generateChallenges( - params *elliptic.CurveParams, - N *big.Int, - pi uint32, - y *curves.EcPoint, -) ([]*big.Int, error) { - if params == nil || - y == nil || - pi == 0 { - return nil, internal.ErrNilArguments - } - - // 1. Set b = |N| // bit length of N - b := N.BitLen() - - // a modulus that is too small turns this function into an infinite loop - // need at least a byte to guarantee termination - if b < 8 { - return nil, internal.ErrNilArguments - } - - // 2. h = output bit-length of fiat-shamir hash - // See util.fiatShamir which uses sha256 - // So the output bit-length is 256 bits - const h int = 256 - - // 3. Compute s = ⌈b/h⌉ // number of hash outputs required to obtain b bits - // i.e. the number of times we have to call fs-shamir to get the same bits as - // `b`. Compute ceil as ceilVal = (a+b-1) / b - s := int64((b + h - 1) / h) - - // 4. j = 0 - j := int64(0) - - // 5. m = 0 - m := big.NewInt(0) - - x := make([]*big.Int, PsfProofLength) - - Pi := new(big.Int).SetUint64(uint64(pi)) - // 6. while j ≤ l - for j < PsfProofLength { - - bij := big.NewInt(j) - var ej []byte - - // 7. for k = [1,...,s] - for k := int64(1); k <= s; k++ { - bik := big.NewInt(k) - - // 8. Compute e_jk = FS-HASH(g, q, y, p_i, j, k, m) - res, err := crypto.FiatShamir(params.Gx, params.Gy, params.N, y.X, y.Y, Pi, bij, bik, m) - if err != nil { - return nil, err - } - // 9. Set x_j = eJ1 || ... || eJs - // Pseudocode says to concatenate outside this loop - // however, we just concatenate the bytes now instead of storing as temporary - // variables - ej = append(ej, res...) - } - // 10. Truncate ej to b bits - xj := new(big.Int).SetBytes(ej[:b/8]) - - // 11. if x_j < Z_N* i.e. 0 < x_j and x_j < N - if xj.Cmp(crypto.Zero) == 1 && xj.Cmp(N) == -1 { - x[j] = xj - - // 12 j = j + 1 - j++ - // 13 m = 0 - m = big.NewInt(0) - // 14 else - } else { - // 15. Set m = m + 1 - m.Add(m, crypto.One) - } - } - return x, nil -} diff --git a/crypto/paillier/psf_test.go b/crypto/paillier/psf_test.go deleted file mode 100644 index 6974dee44..000000000 --- a/crypto/paillier/psf_test.go +++ /dev/null @@ -1,394 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package paillier - -import ( - "crypto/elliptic" - "encoding/json" - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - crypto "github.com/sonr-io/sonr/crypto/core" - curves2 "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -var testPrimes = []*big.Int{ - internal.B10( - "186141419611617071752010179586510154515933389116254425631491755419216243670159714804545944298892950871169229878325987039840135057969555324774918895952900547869933648175107076399993833724447909579697857041081987997463765989497319509683575289675966710007879762972723174353568113668226442698275449371212397561567", - ), - internal.B10( - "94210786053667323206442523040419729883258172350738703980637961803118626748668924192069593010365236618255120977661397310932923345291377692570649198560048403943687994859423283474169530971418656709749020402756179383990602363122039939937953514870699284906666247063852187255623958659551404494107714695311474384687", - ), - internal.B10( - "130291226847076770981564372061529572170236135412763130013877155698259035960569046218348763182598589633420963942796327547969527085797839549642610021986391589746295634536750785366034581957858065740296991986002552598751827526181747791647357767502200771965093659353354985289411489453223546075843993686648576029043", - ), - internal.B10( - "172938910323633442195852028319756134734590277522945546987913328782597284762767185925315797321999389252040294991952361905020940252121762387957669654615602135429944435719699091344247805645764550860505536884031064967454028383404046221898300153428182409080298694828920944094158777327533157774919783417586902830043", - ), - internal.B10( - "135841191929788643010555393808775051922265083622266098277752143441294911675705272940799534437169053045878247274810449617960047255023823301284034559807472662111224710158898548617194658983006262996831617082584649612602010680423107108651221824216065228161009680618243402116924511141821829055830713600437589058643", - ), - internal.B10( - "179677777376220950493907657233669314916823596507009854134559513388779535023958212632715646194917807302098015450071151245496651913873851032302340489007561121851068326577148680474495447007833318066335149850926605897908761267606415610900931306044455332084757793630487163583451178807470499389106913845684353833379", - ), - internal.B10( - "62649985409697862206708027961094957171873130708493280862148817115812710388878279240372941307490519941098268192630359164091992515623574326498710952492586770923230983753287493884398990474917756375654842939939940915963324175552421981212594421823752854754541693709434365609636589761589816398869727328798680335583", - ), - internal.B10( - "196576931859098680370388202020086631604584490828609819764890020064880575503817891126703473215983239396058738287255240835101797315137072822716923594188151190460588551553676484461393180135097616711975997391550414447010491794087888246885960280296709672609456539741162207414899687167396008233995214434586323322859", - ), - internal.B10( - "271336420864746369701165973306090650688066226258594853124089876839120277465060891854507381090238664515950686049792387028144049076707224579184820539700879884119579186284072404459682082855184644444282438298561112002507411996589407330801765394106772460665497195944412067027079123717579308322520985921886949051399", - ), - internal.B10( - "147653127360336844448178027222853805809444645720500374788954343695331927468524513989671450440433430392339037667457657655958027740671071573403925974795764987870476118984896439440386146680643457835633462311776946902713168513155240275028008685964121441954481847113848701823211862974120297600518927026940189810103", - ), - internal.B10( - "61539010433774119199101441060312213379096965116494840834113311373246794436251480454630309900106802555812462300777026043563820643373439814989443964169335227347638731691284339678436222951965582264570176875078394338903074717434072995072121221264531723385013005031614327462206339323414428493321384497439106152163", - ), - internal.B10( - "311771090987243597109711542316907830756641693311804000593662622484722315782429237915515708860530841821213561483232298821623675096481796856960171671330638042763441430256097782130268494276848432981045602236986861083392706904041234926428759947857376161689191720483868111001987710383245853931937989224732484206639", - ), - internal.B10( - "348545239501897032367950520763624245702184225360238826931782856428685149253861325854706825698843098817604431561258712026020688621010635185480321876001016614912927680387840531641703966894322797491484955817022624047355473480912508041252361257911175397626575812830091471419378132244146077774966527307225203863239", - ), - internal.B10( - "167562983031509383478485987630533113343120902430985961468758712448125734458812918541051012669749885569679178971612428577288632429606851871845164719448590160530844833425628143996971699662729056519326776907622035340086832629206691942750594912221135787534670122007438859975313187460872690748138136170080913902203", - ), - internal.B10( - "151715609132228776595716500435665208768897792993205818803431003524953811539898459230192282642811956896879836518212758893685104146944932088195466999437630114129887975508715417094019351746027667352287673763064246395392591213231796089814648654152625331299642171758052545451706130433176935280325874961374276589763", - ), - internal.B10( - "281712498774102170277967098381151873986368736986748325672760355775943894718315925237789122870763991635031524237638254080973752419302437870447849091185409669906909828874532209010547976564209374430136988588219470076527433259993640332285914706329187116209118972038509278879237122949265824264856530096167843589043", - ), - internal.B10( - "86882427063713590116032012033991745733440719961931885774819345297872782432110706546175706398857226544896860987721577779470479838062106788873559026307646871133570915480684987993282364698928926188640576189281202695899665555602891606955025957497645420156315890379148794822782242384167644977894987285630058930123", - ), - internal.B10( - "83303406464212917441403726886711948278716398972782717472384580707071541544369912289531948826578557956123897261910116726555850408667234850301141318443154703778225305104540324875867615851047711871915209458107086347063530255813116254895432804373554367035028329996279513893337862177371103671113527972705508417219", - ), - internal.B10( - "290829612093510969863838578444630131194824970528125429399090307997156531200557462531776190769158191441614466855963164356672434851525764502180873524299787560160992955274777477308009367164212073773611071813219472273292916120276721541591451163160398750751633065097434700462944540404208636130411713202759646572187", - ), - internal.B10( - "48881643615473281990659967689574873112454227417010573158578046287415357392674453353386274403945930212163960526780980360358370255117866064326375672959460785974850231208253282115124348836379470403659096433419030132737534978624170609788431758477453270578400762995584298785082853409573009591146163658067217132999", - ), - internal.B10( - "47818664065019136841944639898604168570191742429107462510943153778085167306149797958497736138014922106778177497683417470713996340979203175236987691632152128071256018368891463388744514315997309312144264057334961479235114340091423812710466596081259537323405527816634204224641066174554915788023121121924554823463", - ), - internal.B10( - "229695065817346126758526483359337260282925372883465036895664320607569899180246065431164369223444026964554195802821338287119074827091354255558249504915527499047398698041873875019622138440848556549357174461846992529556315682586788137744896985847052668283284231628825924370859640129811142861116994552829398428647", - ), - internal.B10( - "100501115016957347491693508757253443864758446032047524096020585354104983606736759639044367167134409576092528219013168507381959241052976704837620234061351712684500077849808223040972825725745511581504906610633548112115513604053190610668096089811015493012026572475283305559529666099836493252485826156659750294903", - ), - internal.B10( - "164941338210872461448879529698900150056451305424623398039343691654768566536491493438826728710972441042226712374570117138883019423322602098706113298908005378303473844839971995715847918643285222217768344335264383514921181158565529236124115589719970140511822410990649549555047928093673140752570788415674868532299", - ), - internal.B10( - "277037199251333188171108034082127252450960810846571117481542098050121457972964006392527344163695411986229107011168411232117984760439307440561490229321182283823299859836750264962218540927582605520434969388646847458788766216835350519741512353041653865564337457599778511921159510170311560556844284028160928114623", - ), - internal.B10( - "194450633495795999995837828580097111229016136925345956148788562473415774074431957758705067019578300241653926511426134047652491974620284426575921711048247821582093564387999309993254763749991516361193554847964638949731507356038181346481870018202492098453036116472375750355687853028597643560794156133662678349939", - ), - internal.B10( - "351287943170075259292767465687447861777186026969543801283411356809391771346213158326614410370157474105344692424346410925411240089238093158848815209147605381454294661108047095253146499393310219242924552687094316959878415907497273176683394122976929775532753961555304244867490393116346360677109958055297215711587", - ), - internal.B10( - "329970582937843908299463472795994928703202360293919677760100619380642134736439176597341134222679061949935544692834943628667398294307004076774417457697130314341974849843695836050603685013468031012892094273233016929045028941716224648802422408386216033754532303003405690778077639489173685122357063674177077611499", - ), - internal.B10( - "67751546105580063387575764356375682499165422473383503143930633584920975946879807021875353514236996076344028719391905234977223693643926924731304657199486141030504275775023186923364159168130612275534168246529309247449138607249407760246378829338068736888203134857601657561860157938495777271164458736576560502603", - ), - internal.B10( - "276043923868350639738966705196129285523536747369492013710841410915407411458158268634302674024358477700030814139419613881758439643092328709376796555454484423864587139181985503560495790018232370315219082876142282958894264284344738294415199758590186234114829175455336589153989920707778566032047921277945163061363", - ), - internal.B10( - "62028909880050184794454820320289487394141550306616974968340908736543032782344593292214952852576535830823991093496498970213686040280098908204236051130358424961175634703281821899530101130244725435470475135483879784963475148975313832483400747421265545413510460046067002322131902159892876739088034507063542087523", - ), - internal.B10( - "321804071508183671133831207712462079740282619152225438240259877528712344129467977098976100894625335474509551113902455258582802291330071887726188174124352664849954838358973904505681968878957681630941310372231688127901147200937955329324769631743029415035218057960201863908173045670622969475867077447909836936523", - ), - internal.B10( - "52495647838749571441531580865340679598533348873590977282663145916368795913408897399822291638579504238082829052094508345857857144973446573810004060341650816108578548997792700057865473467391946766537119012441105169305106247003867011741811274367120479722991749924616247396514197345075177297436299446651331187067", - ), - internal.B10( - "118753381771703394804894143450628876988609300829627946826004421079000316402854210786451078221445575185505001470635997217855372731401976507648597119694813440063429052266569380936671291883364036649087788968029662592370202444662489071262833666489940296758935970249316300642591963940296755031586580445184253416139", - ), -} - -func TestGenerateChallengesWorks(t *testing.T) { - curves := []elliptic.Curve{btcec.S256(), elliptic.P256()} - for _, curve := range curves { - // dummy secret based on curve - y, _ := curves2.NewScalarBaseMult(curve, big.NewInt(3)) - - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - // Compute N from test primes - skN := new(big.Int).Mul(testPrimes[i], testPrimes[j]) - x, err := generateChallenges(curve.Params(), skN, uint32(i+1), y) - - require.NoError(t, err) - for _, xj := range x { - require.NotNil(t, xj) - require.Greater(t, xj.Cmp(crypto.Zero), 0) - require.Equal(t, xj.Cmp(skN), -1) - } - } - } - } -} - -// tests whether the hash function can still produce valid challenges -// even when the modulus is smaller than the hash output -func TestGenerateChallengesPrimeN(t *testing.T) { - curves := []elliptic.Curve{btcec.S256(), elliptic.P256()} - n := []*big.Int{ - internal.B10("680564733841876926926749214863536724007"), - internal.B10("1234345830644315716128223123383371693999"), - internal.B10( - "358070498390900219760227294443948492156530525739357363711230524749453568134007", - ), - internal.B10( - "409819537231165473932776844223512813127760876374228481246566335070809195677439", - ), - internal.B10( - "336327054820888403283842064345570507895192245801107954728200717775133442039527", - ), - internal.B10( - "353526063197730551176241127281213353808518592628930654494044427064787696719527", - ), - } - - for _, curve := range curves { - // dummy secret based on curve - y, _ := curves2.NewScalarBaseMult(curve, big.NewInt(3)) - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - x, err := generateChallenges(curve.Params(), n[i], uint32(j+1), y) - - require.NoError(t, err) - for _, xj := range x { - require.NotNil(t, xj) - require.Greater(t, xj.Cmp(crypto.Zero), 0) - } - } - } - } -} - -func TestGenerateChallengesNilInputs(t *testing.T) { - y, _ := curves2.NewScalarBaseMult(elliptic.P256(), big.NewInt(1)) - - _, err := generateChallenges(nil, nil, 0, nil) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), nil, 0, nil) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), big.NewInt(0), 0, nil) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), big.NewInt(1), 1, nil) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), big.NewInt(1), 1, y) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), big.NewInt(1), 1, y) - require.Error(t, err) - _, err = generateChallenges(elliptic.P256().Params(), big.NewInt(255), 1, y) - require.NoError(t, err) -} - -func TestPsfProofParams_Prove(t *testing.T) { - // RSA primes for testing - sk, _ := NewSecretKey( - // 75-digit random primes from Wolfram-Alpha - internal.B10( - "110045198697022997120409435651962875820936327127306040565577217116705932648687", - ), - internal.B10( - "95848033199746534486927143950536999279071340697368502822602282152563330640779", - ), - ) - smallSk, _ := NewSecretKey(big.NewInt(13), big.NewInt(11)) - - // Some points for testing - k := internal.B10("270988338908697209412444309907441365656383309727758604622908325428179708750") - Qp256, _ := curves2.NewScalarBaseMult(elliptic.P256(), k) - Qs256, _ := curves2.NewScalarBaseMult(btcec.S256(), k) - pi := uint32(4) - - tests := []struct { - name string - in *PsfProofParams - expectedError error - expectedResultLen int - }{ - // Positive tests - { - "positive: p256, small numbers", - &PsfProofParams{elliptic.P256(), smallSk, 1001, Qp256}, - nil, - PsfProofLength, - }, - { - "positive: p256, large numbers", - &PsfProofParams{elliptic.P256(), sk, pi, Qp256}, - nil, - PsfProofLength, - }, - { - "positive: s256, large numbers", - &PsfProofParams{btcec.S256(), sk, pi, Qs256}, - nil, - PsfProofLength, - }, - - // Nil params - { - "negative: ", - &PsfProofParams{ - btcec.S256(), - sk, - pi, - Qs256, - }, - nil, - PsfProofLength, - }, - { - "negative: proof params are nil", - &PsfProofParams{ - nil, - sk, - pi, - Qs256, - }, - internal.ErrNilArguments, - 0, - }, - { - "negative: SecretKey is nil", - &PsfProofParams{ - btcec.S256(), - nil, - pi, - Qs256, - }, - internal.ErrNilArguments, - 0, - }, - { - "negative: y is nil", - &PsfProofParams{ - btcec.S256(), - sk, - 0, - Qs256, - }, - internal.ErrNilArguments, - 0, - }, - { - "negative: Pi is nil", - &PsfProofParams{ - btcec.S256(), - sk, - pi, - nil, - }, - internal.ErrNilArguments, - 0, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - // test - result, err := test.in.Prove() - - // Verify the results are as expected - require.Equal(t, test.expectedError, err) - require.Len(t, result, test.expectedResultLen) - }) - } -} - -// Test that Range2Proof can be marshaled and unmarshaled correctly -func TestPsfProof_MarshalJSON(t *testing.T) { - // Generate some proof - sk, _ := NewSecretKey( - internal.B10( - "110045198697022997120409435651962875820936327127306040565577217116705932648687", - ), - internal.B10( - "95848033199746534486927143950536999279071340697368502822602282152563330640779", - ), - ) - Q, _ := curves2.NewScalarBaseMult(elliptic.P256(), - internal.B10("270988338908697209412444309907441365656383309727758604622908325428179708750")) - params := &PsfProofParams{ - elliptic.P256(), sk, - 1, - Q, - } - proof, err := params.Prove() - require.NoError(t, err) - require.NotNil(t, proof) - - // Marshal - testJSON, err := json.Marshal(proof) - require.NoError(t, err) - require.NotNil(t, testJSON) - - var unmarshaled PsfProof - err = json.Unmarshal(testJSON, &unmarshaled) - require.NoError(t, err) - - // Test for equality - require.Len(t, ([]*big.Int)(unmarshaled), len(([]*big.Int)(proof))) - for i := range proof { - require.Equal(t, proof[i], unmarshaled[i]) - } -} - -// Tests for Verify -// prove/verify round trip works -// modifying any parameter causes verify to fail -func TestPsfProofWorks(t *testing.T) { - // RSA primes for testing - sk, _ := NewSecretKey( - // 75-digit random primes from Wolfram-Alpha - internal.B10( - "110045198697022997120409435651962875820936327127306040565577217116705932648687", - ), - internal.B10( - "95848033199746534486927143950536999279071340697368502822602282152563330640779", - ), - ) - - // Some points for testing - k := internal.B10("270988338908697209412444309907441365656383309727758604622908325428179708750") - Qp256, _ := curves2.NewScalarBaseMult(elliptic.P256(), k) - pi := uint32(2) - - proveParams := &PsfProofParams{ - Curve: elliptic.P256(), - SecretKey: sk, - Pi: pi, - Y: Qp256, - } - proof, _ := proveParams.Prove() - verifyParams := &PsfVerifyParams{ - Curve: elliptic.P256(), - PublicKey: &sk.PublicKey, - Pi: pi, - Y: Qp256, - } - require.NoError(t, proof.Verify(verifyParams)) -} diff --git a/crypto/password/validator.go b/crypto/password/validator.go deleted file mode 100644 index cbfbe8d3d..000000000 --- a/crypto/password/validator.go +++ /dev/null @@ -1,185 +0,0 @@ -// Package password provides secure password handling and validation -package password - -import ( - "crypto/rand" - "fmt" - "unicode" -) - -// PasswordConfig defines password policy requirements -type PasswordConfig struct { - MinLength int - MaxLength int - RequireUppercase bool - RequireLowercase bool - RequireDigits bool - RequireSpecial bool - MinEntropy float64 -} - -// DefaultPasswordConfig returns secure default password requirements -func DefaultPasswordConfig() *PasswordConfig { - return &PasswordConfig{ - MinLength: 12, - MaxLength: 128, - RequireUppercase: true, - RequireLowercase: true, - RequireDigits: true, - RequireSpecial: true, - MinEntropy: 50.0, // bits - } -} - -// Validator validates passwords against security policies -type Validator struct { - config *PasswordConfig -} - -// NewValidator creates a password validator with the given configuration -func NewValidator(config *PasswordConfig) *Validator { - if config == nil { - config = DefaultPasswordConfig() - } - return &Validator{config: config} -} - -// Validate checks if a password meets security requirements -func (v *Validator) Validate(password []byte) error { - // Check length - if len(password) < v.config.MinLength { - return fmt.Errorf("password must be at least %d characters", v.config.MinLength) - } - if len(password) > v.config.MaxLength { - return fmt.Errorf("password must not exceed %d characters", v.config.MaxLength) - } - - // Check character requirements - var hasUpper, hasLower, hasDigit, hasSpecial bool - for _, ch := range string(password) { - switch { - case unicode.IsUpper(ch): - hasUpper = true - case unicode.IsLower(ch): - hasLower = true - case unicode.IsDigit(ch): - hasDigit = true - case unicode.IsSpace(ch): - // Spaces are allowed but not counted as special - case unicode.IsPunct(ch) || unicode.IsSymbol(ch): - hasSpecial = true - } - } - - if v.config.RequireUppercase && !hasUpper { - return fmt.Errorf("password must contain at least one uppercase letter") - } - if v.config.RequireLowercase && !hasLower { - return fmt.Errorf("password must contain at least one lowercase letter") - } - if v.config.RequireDigits && !hasDigit { - return fmt.Errorf("password must contain at least one digit") - } - if v.config.RequireSpecial && !hasSpecial { - return fmt.Errorf("password must contain at least one special character") - } - - // Check entropy - entropy := v.calculateEntropy(password) - if entropy < v.config.MinEntropy { - return fmt.Errorf("password entropy too low: %.1f bits (minimum: %.1f)", - entropy, v.config.MinEntropy) - } - - return nil -} - -// calculateEntropy estimates password entropy in bits -func (v *Validator) calculateEntropy(password []byte) float64 { - // Count unique characters - charSet := make(map[byte]bool) - for _, b := range password { - charSet[b] = true - } - - // Estimate character pool size - poolSize := 0 - var hasUpper, hasLower, hasDigit, hasSpecial bool - - for ch := range charSet { - r := rune(ch) - switch { - case unicode.IsUpper(r): - hasUpper = true - case unicode.IsLower(r): - hasLower = true - case unicode.IsDigit(r): - hasDigit = true - case unicode.IsPunct(r) || unicode.IsSymbol(r): - hasSpecial = true - } - } - - if hasLower { - poolSize += 26 - } - if hasUpper { - poolSize += 26 - } - if hasDigit { - poolSize += 10 - } - if hasSpecial { - poolSize += 32 // Common special characters - } - - if poolSize == 0 { - return 0 - } - - // Calculate entropy: log2(poolSize^length) - // Simplified: length * log2(poolSize) - bitsPerChar := 0.0 - temp := poolSize - for temp > 0 { - bitsPerChar++ - temp >>= 1 - } - - return float64(len(password)) * bitsPerChar -} - -// GenerateSalt generates a cryptographically secure random salt -func GenerateSalt(size int) ([]byte, error) { - if size < 16 { - return nil, fmt.Errorf("salt size must be at least 16 bytes") - } - - salt := make([]byte, size) - if _, err := rand.Read(salt); err != nil { - return nil, fmt.Errorf("failed to generate salt: %w", err) - } - - return salt, nil -} - -// SecureCompare performs constant-time comparison of two byte slices -func SecureCompare(a, b []byte) bool { - if len(a) != len(b) { - return false - } - - var result byte - for i := 0; i < len(a); i++ { - result |= a[i] ^ b[i] - } - - return result == 0 -} - -// ZeroBytes overwrites a byte slice with zeros -func ZeroBytes(b []byte) { - for i := range b { - b[i] = 0 - } -} diff --git a/crypto/password/validator_test.go b/crypto/password/validator_test.go deleted file mode 100644 index 0b1702525..000000000 --- a/crypto/password/validator_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package password - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestValidator_Validate(t *testing.T) { - validator := NewValidator(DefaultPasswordConfig()) - - testCases := []struct { - name string - password string - wantErr bool - errMsg string - }{ - { - name: "too short", - password: "Short1!", - wantErr: true, - errMsg: "at least 12 characters", - }, - { - name: "too long", - password: string(make([]byte, 129)), - wantErr: true, - errMsg: "not exceed 128 characters", - }, - { - name: "missing uppercase", - password: "longenoughpassword123!", - wantErr: true, - errMsg: "uppercase letter", - }, - { - name: "missing lowercase", - password: "LONGENOUGHPASSWORD123!", - wantErr: true, - errMsg: "lowercase letter", - }, - { - name: "missing digit", - password: "LongEnoughPassword!", - wantErr: true, - errMsg: "one digit", - }, - { - name: "missing special", - password: "LongEnoughPassword123", - wantErr: true, - errMsg: "special character", - }, - { - name: "valid password", - password: "ValidPassword123!", - wantErr: false, - }, - { - name: "complex valid password", - password: "MyS3cur3P@ssw0rd!2024", - wantErr: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := validator.Validate([]byte(tc.password)) - if tc.wantErr { - require.Error(t, err) - assert.Contains(t, err.Error(), tc.errMsg) - } else { - assert.NoError(t, err) - } - }) - } -} - -func TestValidator_CustomConfig(t *testing.T) { - config := &PasswordConfig{ - MinLength: 8, - MaxLength: 64, - RequireUppercase: false, - RequireLowercase: true, - RequireDigits: true, - RequireSpecial: false, - MinEntropy: 30.0, - } - - validator := NewValidator(config) - - // Should pass with custom config - err := validator.Validate([]byte("simple123")) - assert.NoError(t, err) - - // Should fail - too short - err = validator.Validate([]byte("short1")) - assert.Error(t, err) - - // Should fail - no digits - err = validator.Validate([]byte("simplepass")) - assert.Error(t, err) -} - -func TestGenerateSalt(t *testing.T) { - // Test valid salt generation - salt, err := GenerateSalt(32) - require.NoError(t, err) - assert.Len(t, salt, 32) - - // Test different salt each time - salt2, err := GenerateSalt(32) - require.NoError(t, err) - assert.NotEqual(t, salt, salt2) - - // Test minimum size enforcement - _, err = GenerateSalt(8) - assert.Error(t, err) - assert.Contains(t, err.Error(), "at least 16 bytes") -} - -func TestSecureCompare(t *testing.T) { - // Test equal slices - a := []byte("password") - b := []byte("password") - assert.True(t, SecureCompare(a, b)) - - // Test different slices - c := []byte("different") - assert.False(t, SecureCompare(a, c)) - - // Test different lengths - d := []byte("pass") - assert.False(t, SecureCompare(a, d)) - - // Test empty slices - assert.True(t, SecureCompare([]byte{}, []byte{})) -} - -func TestZeroBytes(t *testing.T) { - password := []byte("sensitive") - ZeroBytes(password) - - for _, b := range password { - assert.Equal(t, byte(0), b) - } -} - -func TestCalculateEntropy(t *testing.T) { - validator := NewValidator(nil) - - testCases := []struct { - name string - password string - minEntropy float64 - }{ - { - name: "lowercase only", - password: "abcdefghij", - minEntropy: 40, - }, - { - name: "alphanumeric", - password: "Abc123", - minEntropy: 30, - }, - { - name: "complex", - password: "MyP@ssw0rd!", - minEntropy: 50, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - entropy := validator.calculateEntropy([]byte(tc.password)) - assert.GreaterOrEqual(t, entropy, tc.minEntropy) - }) - } -} - -func BenchmarkValidate(b *testing.B) { - validator := NewValidator(DefaultPasswordConfig()) - password := []byte("ValidPassword123!") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = validator.Validate(password) - } -} - -func BenchmarkGenerateSalt(b *testing.B) { - for i := 0; i < b.N; i++ { - _, _ = GenerateSalt(32) - } -} - -func BenchmarkSecureCompare(b *testing.B) { - a := []byte("password123") - c := []byte("password123") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = SecureCompare(a, c) - } -} diff --git a/crypto/salt/salt.go b/crypto/salt/salt.go deleted file mode 100644 index 9733ad19c..000000000 --- a/crypto/salt/salt.go +++ /dev/null @@ -1,227 +0,0 @@ -// Package salt provides cryptographically secure salt generation and management -// for use in key derivation functions and encryption operations. -package salt - -import ( - "crypto/rand" - "fmt" - "io" -) - -const ( - // DefaultSaltSize defines the recommended salt size (256 bits) - DefaultSaltSize = 32 - // MinSaltSize defines the minimum acceptable salt size (128 bits) - MinSaltSize = 16 - // MaxSaltSize defines the maximum salt size to prevent resource exhaustion - MaxSaltSize = 1024 -) - -// Salt represents a cryptographically secure salt value -type Salt struct { - value []byte -} - -// Generate creates a new cryptographically secure salt of the specified size -func Generate(size int) (*Salt, error) { - if size < MinSaltSize { - return nil, fmt.Errorf("salt size too small: minimum %d bytes required", MinSaltSize) - } - if size > MaxSaltSize { - return nil, fmt.Errorf("salt size too large: maximum %d bytes allowed", MaxSaltSize) - } - - saltBytes := make([]byte, size) - if _, err := io.ReadFull(rand.Reader, saltBytes); err != nil { - return nil, fmt.Errorf("failed to generate random salt: %w", err) - } - - return &Salt{value: saltBytes}, nil -} - -// GenerateDefault creates a new salt with the default recommended size -func GenerateDefault() (*Salt, error) { - return Generate(DefaultSaltSize) -} - -// FromBytes creates a Salt from existing bytes (validates minimum size) -func FromBytes(data []byte) (*Salt, error) { - if len(data) < MinSaltSize { - return nil, fmt.Errorf("salt too small: minimum %d bytes required, got %d", MinSaltSize, len(data)) - } - if len(data) > MaxSaltSize { - return nil, fmt.Errorf("salt too large: maximum %d bytes allowed, got %d", MaxSaltSize, len(data)) - } - - // Copy to prevent external modification - saltBytes := make([]byte, len(data)) - copy(saltBytes, data) - - return &Salt{value: saltBytes}, nil -} - -// Bytes returns a copy of the salt bytes to prevent external modification -func (s *Salt) Bytes() []byte { - if s == nil || s.value == nil { - return nil - } - result := make([]byte, len(s.value)) - copy(result, s.value) - return result -} - -// Size returns the size of the salt in bytes -func (s *Salt) Size() int { - if s == nil || s.value == nil { - return 0 - } - return len(s.value) -} - -// String returns a redacted string representation for logging (does not expose salt value) -func (s *Salt) String() string { - if s == nil || s.value == nil { - return "Salt{}" - } - return fmt.Sprintf("Salt{size=%d}", len(s.value)) -} - -// Equal compares two salts in constant time to prevent timing attacks -func (s *Salt) Equal(other *Salt) bool { - if s == nil || other == nil { - return s == other - } - if len(s.value) != len(other.value) { - return false - } - return constantTimeCompare(s.value, other.value) -} - -// Clear securely zeros the salt value from memory -func (s *Salt) Clear() { - if s != nil && s.value != nil { - for i := range s.value { - s.value[i] = 0 - } - s.value = nil - } -} - -// IsEmpty checks if the salt is nil or has zero length -func (s *Salt) IsEmpty() bool { - return s == nil || s.value == nil || len(s.value) == 0 -} - -// constantTimeCompare performs constant-time comparison of two byte slices -func constantTimeCompare(a, b []byte) bool { - if len(a) != len(b) { - return false - } - - var result byte - for i := 0; i < len(a); i++ { - result |= a[i] ^ b[i] - } - return result == 0 -} - -// SaltStore manages storage and retrieval of salts with metadata -type SaltStore struct { - salts map[string]*Salt -} - -// NewSaltStore creates a new salt store for managing multiple salts -func NewSaltStore() *SaltStore { - return &SaltStore{ - salts: make(map[string]*Salt), - } -} - -// Store saves a salt with the given identifier -func (ss *SaltStore) Store(id string, salt *Salt) error { - if id == "" { - return fmt.Errorf("salt identifier cannot be empty") - } - if salt == nil || salt.IsEmpty() { - return fmt.Errorf("salt cannot be nil or empty") - } - - // Store a copy to prevent external modification - ss.salts[id] = &Salt{ - value: salt.Bytes(), - } - - return nil -} - -// Retrieve gets a salt by its identifier -func (ss *SaltStore) Retrieve(id string) (*Salt, error) { - if id == "" { - return nil, fmt.Errorf("salt identifier cannot be empty") - } - - salt, exists := ss.salts[id] - if !exists { - return nil, fmt.Errorf("salt not found for identifier: %s", id) - } - - // Return a copy to prevent external modification - return &Salt{ - value: salt.Bytes(), - }, nil -} - -// Remove deletes a salt from the store and clears its memory -func (ss *SaltStore) Remove(id string) error { - if id == "" { - return fmt.Errorf("salt identifier cannot be empty") - } - - salt, exists := ss.salts[id] - if !exists { - return fmt.Errorf("salt not found for identifier: %s", id) - } - - // Clear the salt from memory before removal - salt.Clear() - delete(ss.salts, id) - - return nil -} - -// List returns all stored salt identifiers -func (ss *SaltStore) List() []string { - ids := make([]string, 0, len(ss.salts)) - for id := range ss.salts { - ids = append(ids, id) - } - return ids -} - -// Clear removes all salts and clears their memory -func (ss *SaltStore) Clear() { - for id, salt := range ss.salts { - salt.Clear() - delete(ss.salts, id) - } -} - -// Size returns the number of stored salts -func (ss *SaltStore) Size() int { - return len(ss.salts) -} - -// GenerateAndStore creates a new salt and stores it with the given identifier -func (ss *SaltStore) GenerateAndStore(id string, size int) (*Salt, error) { - salt, err := Generate(size) - if err != nil { - return nil, fmt.Errorf("failed to generate salt: %w", err) - } - - if err := ss.Store(id, salt); err != nil { - salt.Clear() // Clean up on failure - return nil, fmt.Errorf("failed to store salt: %w", err) - } - - return salt, nil -} diff --git a/crypto/salt/salt_test.go b/crypto/salt/salt_test.go deleted file mode 100644 index b39d23607..000000000 --- a/crypto/salt/salt_test.go +++ /dev/null @@ -1,421 +0,0 @@ -package salt - -import ( - "bytes" - "fmt" - "testing" -) - -func TestGenerate(t *testing.T) { - tests := []struct { - name string - size int - wantErr bool - }{ - {"minimum size", MinSaltSize, false}, - {"default size", DefaultSaltSize, false}, - {"large size", 512, false}, - {"maximum size", MaxSaltSize, false}, - {"too small", MinSaltSize - 1, true}, - {"too large", MaxSaltSize + 1, true}, - {"zero size", 0, true}, - {"negative size", -1, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - salt, err := Generate(tt.size) - if (err != nil) != tt.wantErr { - t.Errorf("Generate() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if !tt.wantErr { - if salt == nil { - t.Error("Generate() returned nil salt without error") - return - } - if salt.Size() != tt.size { - t.Errorf("Generate() size = %d, want %d", salt.Size(), tt.size) - } - if salt.IsEmpty() { - t.Error("Generate() returned empty salt") - } - - // Test that salt contains random data (not all zeros) - saltBytes := salt.Bytes() - allZeros := true - for _, b := range saltBytes { - if b != 0 { - allZeros = false - break - } - } - if allZeros { - t.Error("Generate() returned all-zero salt (likely not random)") - } - } - }) - } -} - -func TestGenerateDefault(t *testing.T) { - salt, err := GenerateDefault() - if err != nil { - t.Fatalf("GenerateDefault() error = %v", err) - } - - if salt.Size() != DefaultSaltSize { - t.Errorf("GenerateDefault() size = %d, want %d", salt.Size(), DefaultSaltSize) - } -} - -func TestFromBytes(t *testing.T) { - validBytes := make([]byte, DefaultSaltSize) - for i := range validBytes { - validBytes[i] = byte(i) - } - - tests := []struct { - name string - data []byte - wantErr bool - }{ - {"valid default size", validBytes, false}, - {"minimum size", make([]byte, MinSaltSize), false}, - {"large size", make([]byte, 512), false}, - {"too small", make([]byte, MinSaltSize-1), true}, - {"too large", make([]byte, MaxSaltSize+1), true}, - {"empty", []byte{}, true}, - {"nil", nil, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - salt, err := FromBytes(tt.data) - if (err != nil) != tt.wantErr { - t.Errorf("FromBytes() error = %v, wantErr %v", err, tt.wantErr) - return - } - - if !tt.wantErr { - if salt == nil { - t.Error("FromBytes() returned nil salt without error") - return - } - if salt.Size() != len(tt.data) { - t.Errorf("FromBytes() size = %d, want %d", salt.Size(), len(tt.data)) - } - - // Verify data is copied correctly - saltBytes := salt.Bytes() - if !bytes.Equal(saltBytes, tt.data) { - t.Error("FromBytes() data doesn't match input") - } - - // Verify external modification doesn't affect salt - if len(tt.data) > 0 { - originalValue := tt.data[0] - tt.data[0] = ^tt.data[0] // Flip bits - if salt.Bytes()[0] != originalValue { - t.Error("FromBytes() salt was affected by external modification") - } - } - } - }) - } -} - -func TestSaltBytes(t *testing.T) { - salt, err := GenerateDefault() - if err != nil { - t.Fatalf("Failed to generate salt: %v", err) - } - - bytes1 := salt.Bytes() - bytes2 := salt.Bytes() - - // Should return same data - if !bytes.Equal(bytes1, bytes2) { - t.Error("Bytes() returned different data on multiple calls") - } - - // Should be independent copies - if &bytes1[0] == &bytes2[0] { - t.Error("Bytes() returned same underlying array (not a copy)") - } - - // Modifying returned bytes shouldn't affect salt - if len(bytes1) > 0 { - originalValue := bytes1[0] - bytes1[0] = ^bytes1[0] - bytes3 := salt.Bytes() - if bytes3[0] != originalValue { - t.Error("External modification of Bytes() affected salt") - } - } -} - -func TestSaltEqual(t *testing.T) { - salt1, err := Generate(DefaultSaltSize) - if err != nil { - t.Fatalf("Failed to generate salt1: %v", err) - } - - salt2, err := Generate(DefaultSaltSize) - if err != nil { - t.Fatalf("Failed to generate salt2: %v", err) - } - - // Same salt data - salt3, err := FromBytes(salt1.Bytes()) - if err != nil { - t.Fatalf("Failed to create salt3: %v", err) - } - - tests := []struct { - name string - salt1 *Salt - salt2 *Salt - expected bool - }{ - {"same salt", salt1, salt1, true}, - {"equivalent salts", salt1, salt3, true}, - {"different salts", salt1, salt2, false}, - {"nil salts", nil, nil, true}, - {"one nil salt", salt1, nil, false}, - {"nil vs non-nil", nil, salt1, false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := tt.salt1.Equal(tt.salt2) - if result != tt.expected { - t.Errorf("Equal() = %v, want %v", result, tt.expected) - } - }) - } -} - -func TestSaltClear(t *testing.T) { - salt, err := GenerateDefault() - if err != nil { - t.Fatalf("Failed to generate salt: %v", err) - } - - originalSize := salt.Size() - if originalSize == 0 { - t.Fatal("Salt size is zero before clear") - } - - salt.Clear() - - if salt.Size() != 0 { - t.Error("Salt size is not zero after clear") - } - - if !salt.IsEmpty() { - t.Error("Salt is not empty after clear") - } - - bytes := salt.Bytes() - if bytes != nil { - t.Error("Bytes() should return nil after clear") - } -} - -func TestSaltStore(t *testing.T) { - store := NewSaltStore() - - // Test empty store - if store.Size() != 0 { - t.Error("New store should be empty") - } - - // Generate and store salt - salt1, err := GenerateDefault() - if err != nil { - t.Fatalf("Failed to generate salt: %v", err) - } - - err = store.Store("test1", salt1) - if err != nil { - t.Fatalf("Failed to store salt: %v", err) - } - - if store.Size() != 1 { - t.Errorf("Store size = %d, want 1", store.Size()) - } - - // Retrieve salt - retrieved, err := store.Retrieve("test1") - if err != nil { - t.Fatalf("Failed to retrieve salt: %v", err) - } - - if !salt1.Equal(retrieved) { - t.Error("Retrieved salt doesn't match stored salt") - } - - // Test generate and store - salt2, err := store.GenerateAndStore("test2", DefaultSaltSize) - if err != nil { - t.Fatalf("Failed to generate and store salt: %v", err) - } - - if store.Size() != 2 { - t.Errorf("Store size = %d, want 2", store.Size()) - } - - if salt2.Size() != DefaultSaltSize { - t.Errorf("Generated salt size = %d, want %d", salt2.Size(), DefaultSaltSize) - } - - // Test list - ids := store.List() - if len(ids) != 2 { - t.Errorf("List() returned %d ids, want 2", len(ids)) - } - - foundTest1 := false - foundTest2 := false - for _, id := range ids { - if id == "test1" { - foundTest1 = true - } - if id == "test2" { - foundTest2 = true - } - } - if !foundTest1 || !foundTest2 { - t.Error("List() doesn't contain expected IDs") - } - - // Test remove - err = store.Remove("test1") - if err != nil { - t.Fatalf("Failed to remove salt: %v", err) - } - - if store.Size() != 1 { - t.Errorf("Store size = %d, want 1 after removal", store.Size()) - } - - _, err = store.Retrieve("test1") - if err == nil { - t.Error("Should not be able to retrieve removed salt") - } - - // Test clear - store.Clear() - if store.Size() != 0 { - t.Error("Store should be empty after clear") - } -} - -func TestSaltStoreErrors(t *testing.T) { - store := NewSaltStore() - - // Test empty identifier errors - err := store.Store("", nil) - if err == nil { - t.Error("Should error on empty identifier") - } - - _, err = store.Retrieve("") - if err == nil { - t.Error("Should error on empty identifier") - } - - err = store.Remove("") - if err == nil { - t.Error("Should error on empty identifier") - } - - // Test nil salt error - err = store.Store("test", nil) - if err == nil { - t.Error("Should error on nil salt") - } - - // Test empty salt error - emptySalt := &Salt{} - err = store.Store("test", emptySalt) - if err == nil { - t.Error("Should error on empty salt") - } - - // Test retrieve non-existent - _, err = store.Retrieve("nonexistent") - if err == nil { - t.Error("Should error when retrieving non-existent salt") - } - - // Test remove non-existent - err = store.Remove("nonexistent") - if err == nil { - t.Error("Should error when removing non-existent salt") - } -} - -func TestConstantTimeCompare(t *testing.T) { - a := []byte{1, 2, 3, 4, 5} - b := []byte{1, 2, 3, 4, 5} - c := []byte{1, 2, 3, 4, 6} - d := []byte{1, 2, 3, 4} - - tests := []struct { - name string - a, b []byte - expected bool - }{ - {"equal slices", a, b, true}, - {"different content", a, c, false}, - {"different length", a, d, false}, - {"empty slices", []byte{}, []byte{}, true}, - {"one empty", a, []byte{}, false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := constantTimeCompare(tt.a, tt.b) - if result != tt.expected { - t.Errorf("constantTimeCompare() = %v, want %v", result, tt.expected) - } - }) - } -} - -func BenchmarkGenerate(b *testing.B) { - sizes := []int{MinSaltSize, DefaultSaltSize, 512} - - for _, size := range sizes { - b.Run(fmt.Sprintf("%dB", size), func(b *testing.B) { - for i := 0; i < b.N; i++ { - salt, err := Generate(size) - if err != nil { - b.Fatalf("Generate error: %v", err) - } - salt.Clear() // Clean up - } - }) - } -} - -func BenchmarkSaltEqual(b *testing.B) { - salt1, _ := GenerateDefault() - salt2, _ := GenerateDefault() - salt3, _ := FromBytes(salt1.Bytes()) - - b.Run("equal", func(b *testing.B) { - for i := 0; i < b.N; i++ { - salt1.Equal(salt3) - } - }) - - b.Run("different", func(b *testing.B) { - for i := 0; i < b.N; i++ { - salt1.Equal(salt2) - } - }) -} diff --git a/crypto/secure/memory.go b/crypto/secure/memory.go deleted file mode 100644 index d173727ca..000000000 --- a/crypto/secure/memory.go +++ /dev/null @@ -1,325 +0,0 @@ -// Package secure provides utilities for secure memory handling and sensitive data management. -// It includes functions for explicit memory zeroization and secure data lifecycle management. -package secure - -import ( - "crypto/rand" - "fmt" - "runtime" - "sync" -) - -// SecureBytes wraps a byte slice with automatic cleanup functionality -type SecureBytes struct { - data []byte - mu sync.RWMutex - finalized bool -} - -// NewSecureBytes creates a new SecureBytes instance with automatic cleanup -func NewSecureBytes(size int) *SecureBytes { - if size <= 0 { - return &SecureBytes{data: nil} - } - - sb := &SecureBytes{ - data: make([]byte, size), - } - - // Set finalizer for automatic cleanup if Clear() is not called - runtime.SetFinalizer(sb, (*SecureBytes).finalize) - return sb -} - -// FromBytes creates a SecureBytes instance from existing data (copies the data) -func FromBytes(data []byte) *SecureBytes { - if len(data) == 0 { - return &SecureBytes{data: nil} - } - - sb := &SecureBytes{ - data: make([]byte, len(data)), - } - copy(sb.data, data) - - runtime.SetFinalizer(sb, (*SecureBytes).finalize) - return sb -} - -// Bytes returns a copy of the secure data to prevent external modification -func (sb *SecureBytes) Bytes() []byte { - sb.mu.RLock() - defer sb.mu.RUnlock() - - if sb.data == nil { - return nil - } - - result := make([]byte, len(sb.data)) - copy(result, sb.data) - return result -} - -// Size returns the size of the secure data -func (sb *SecureBytes) Size() int { - sb.mu.RLock() - defer sb.mu.RUnlock() - - if sb.data == nil { - return 0 - } - return len(sb.data) -} - -// IsEmpty checks if the secure data is empty or nil -func (sb *SecureBytes) IsEmpty() bool { - sb.mu.RLock() - defer sb.mu.RUnlock() - - return sb.data == nil || len(sb.data) == 0 -} - -// Clear explicitly zeros the memory and removes the finalizer -func (sb *SecureBytes) Clear() { - sb.mu.Lock() - defer sb.mu.Unlock() - - if !sb.finalized && sb.data != nil { - Zeroize(sb.data) - sb.data = nil - sb.finalized = true - runtime.SetFinalizer(sb, nil) // Remove finalizer since we've cleaned up - } -} - -// finalize is called by the garbage collector if Clear() was not called -func (sb *SecureBytes) finalize() { - sb.Clear() -} - -// CopyTo safely copies data to the secure buffer -func (sb *SecureBytes) CopyTo(data []byte) error { - sb.mu.Lock() - defer sb.mu.Unlock() - - if sb.finalized { - return fmt.Errorf("secure bytes has been finalized") - } - - if sb.data == nil { - return fmt.Errorf("secure bytes is nil") - } - - if len(data) > len(sb.data) { - return fmt.Errorf("data size %d exceeds secure buffer size %d", len(data), len(sb.data)) - } - - // Zero existing data first - Zeroize(sb.data) - copy(sb.data, data) - return nil -} - -// Zeroize explicitly zeros out sensitive data from memory using byte slicing -func Zeroize(data []byte) { - if len(data) == 0 { - return - } - - // Explicitly zero each byte to prevent compiler optimizations - for i := range data { - data[i] = 0 - } - - // Force memory barrier to ensure zeroization is not optimized away - runtime.KeepAlive(data) -} - -// ZeroizeString attempts to clear a string reference (limited effectiveness) -// Note: Go strings are immutable, so this only clears the reference, not the underlying data -func ZeroizeString(s *string) { - if s == nil { - return - } - // Simply clear the reference - Go strings are immutable - *s = "" -} - -// SecureString wraps a string with secure cleanup capabilities -type SecureString struct { - value string - mu sync.RWMutex - finalized bool -} - -// NewSecureString creates a new SecureString with automatic cleanup -func NewSecureString(s string) *SecureString { - ss := &SecureString{ - value: s, - } - runtime.SetFinalizer(ss, (*SecureString).finalize) - return ss -} - -// String returns the secure string value -func (ss *SecureString) String() string { - ss.mu.RLock() - defer ss.mu.RUnlock() - - if ss.finalized { - return "" - } - return ss.value -} - -// Clear attempts to zero the string and marks it as finalized -func (ss *SecureString) Clear() { - ss.mu.Lock() - defer ss.mu.Unlock() - - if !ss.finalized { - ZeroizeString(&ss.value) - ss.value = "" - ss.finalized = true - runtime.SetFinalizer(ss, nil) - } -} - -// finalize is called by the garbage collector -func (ss *SecureString) finalize() { - ss.Clear() -} - -// IsEmpty checks if the secure string is empty -func (ss *SecureString) IsEmpty() bool { - ss.mu.RLock() - defer ss.mu.RUnlock() - - return ss.finalized || ss.value == "" -} - -// SecureBuffer provides a reusable buffer for sensitive operations -type SecureBuffer struct { - buffer []byte - mu sync.Mutex -} - -// NewSecureBuffer creates a new secure buffer with the specified capacity -func NewSecureBuffer(capacity int) *SecureBuffer { - if capacity <= 0 { - capacity = 1024 // Default capacity - } - - sb := &SecureBuffer{ - buffer: make([]byte, 0, capacity), - } - runtime.SetFinalizer(sb, (*SecureBuffer).finalize) - return sb -} - -// Write appends data to the secure buffer -func (sb *SecureBuffer) Write(data []byte) error { - sb.mu.Lock() - defer sb.mu.Unlock() - - if len(sb.buffer)+len(data) > cap(sb.buffer) { - return fmt.Errorf("buffer overflow: capacity %d, current size %d, write size %d", - cap(sb.buffer), len(sb.buffer), len(data)) - } - - sb.buffer = append(sb.buffer, data...) - return nil -} - -// Read returns a copy of the buffer contents -func (sb *SecureBuffer) Read() []byte { - sb.mu.Lock() - defer sb.mu.Unlock() - - result := make([]byte, len(sb.buffer)) - copy(result, sb.buffer) - return result -} - -// Reset clears the buffer contents but maintains capacity -func (sb *SecureBuffer) Reset() { - sb.mu.Lock() - defer sb.mu.Unlock() - - if len(sb.buffer) > 0 { - Zeroize(sb.buffer[:cap(sb.buffer)]) // Zero the entire backing array - sb.buffer = sb.buffer[:0] // Reset length to 0 - } -} - -// Clear zeros the buffer and releases memory -func (sb *SecureBuffer) Clear() { - sb.mu.Lock() - defer sb.mu.Unlock() - - if sb.buffer != nil { - Zeroize(sb.buffer[:cap(sb.buffer)]) // Zero entire backing array - sb.buffer = nil - runtime.SetFinalizer(sb, nil) - } -} - -// finalize is called by the garbage collector -func (sb *SecureBuffer) finalize() { - sb.Clear() -} - -// Size returns the current size of data in the buffer -func (sb *SecureBuffer) Size() int { - sb.mu.Lock() - defer sb.mu.Unlock() - - return len(sb.buffer) -} - -// Capacity returns the maximum capacity of the buffer -func (sb *SecureBuffer) Capacity() int { - sb.mu.Lock() - defer sb.mu.Unlock() - - if sb.buffer == nil { - return 0 - } - return cap(sb.buffer) -} - -// ZeroizeMultiple zeros multiple byte slices in a single call -func ZeroizeMultiple(slices ...[]byte) { - for _, slice := range slices { - Zeroize(slice) - } -} - -// SecureCompare performs constant-time comparison of two byte slices -// Returns true if the slices are equal, false otherwise -func SecureCompare(a, b []byte) bool { - if len(a) != len(b) { - return false - } - - var result byte - for i := 0; i < len(a); i++ { - result |= a[i] ^ b[i] - } - - return result == 0 -} - -// SecureRandom fills the provided slice with cryptographically secure random bytes -func SecureRandom(data []byte) error { - if len(data) == 0 { - return nil - } - - // Use Go's crypto/rand for secure random generation - if _, err := rand.Read(data); err != nil { - return fmt.Errorf("failed to generate secure random bytes: %w", err) - } - - return nil -} diff --git a/crypto/secure/memory_test.go b/crypto/secure/memory_test.go deleted file mode 100644 index d2b7e3559..000000000 --- a/crypto/secure/memory_test.go +++ /dev/null @@ -1,523 +0,0 @@ -package secure - -import ( - "bytes" - "fmt" - "runtime" - "testing" - "time" -) - -func TestZeroize(t *testing.T) { - tests := []struct { - name string - data []byte - }{ - {"empty slice", []byte{}}, - {"single byte", []byte{0xFF}}, - {"small slice", []byte{1, 2, 3, 4, 5}}, - {"large slice", make([]byte, 1024)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Fill with non-zero data - for i := range tt.data { - tt.data[i] = byte(i%256 + 1) - } - - // Store original for verification - original := make([]byte, len(tt.data)) - copy(original, tt.data) - - // Zeroize - Zeroize(tt.data) - - // Verify all bytes are zero - for i, b := range tt.data { - if b != 0 { - t.Errorf("Byte at index %d not zeroed: got %d, want 0", i, b) - } - } - - // Verify original data was actually non-zero (for non-empty slices) - if len(original) > 0 { - hasNonZero := false - for _, b := range original { - if b != 0 { - hasNonZero = true - break - } - } - if !hasNonZero { - t.Error("Test data was already all zeros - invalid test") - } - } - }) - } -} - -func TestSecureBytes(t *testing.T) { - t.Run("NewSecureBytes", func(t *testing.T) { - sb := NewSecureBytes(32) - if sb == nil { - t.Fatal("NewSecureBytes returned nil") - } - if sb.Size() != 32 { - t.Errorf("Size() = %d, want 32", sb.Size()) - } - if sb.IsEmpty() { - t.Error("NewSecureBytes should not be empty") - } - sb.Clear() - }) - - t.Run("zero size", func(t *testing.T) { - sb := NewSecureBytes(0) - if sb.Size() != 0 { - t.Errorf("Size() = %d, want 0", sb.Size()) - } - if !sb.IsEmpty() { - t.Error("Zero-size SecureBytes should be empty") - } - }) - - t.Run("FromBytes", func(t *testing.T) { - original := []byte{1, 2, 3, 4, 5} - sb := FromBytes(original) - - if sb.Size() != len(original) { - t.Errorf("Size() = %d, want %d", sb.Size(), len(original)) - } - - retrieved := sb.Bytes() - if !bytes.Equal(retrieved, original) { - t.Error("Retrieved bytes don't match original") - } - - // Verify independence - modifying original shouldn't affect SecureBytes - original[0] = 99 - retrieved2 := sb.Bytes() - if retrieved2[0] == 99 { - t.Error("SecureBytes was affected by external modification") - } - - sb.Clear() - }) - - t.Run("Bytes returns copy", func(t *testing.T) { - sb := NewSecureBytes(16) - - bytes1 := sb.Bytes() - bytes2 := sb.Bytes() - - // Should be equal content - if !bytes.Equal(bytes1, bytes2) { - t.Error("Multiple Bytes() calls returned different content") - } - - // Should be different slices - if len(bytes1) > 0 && &bytes1[0] == &bytes2[0] { - t.Error("Bytes() returned same underlying array") - } - - // Modifying returned slice shouldn't affect SecureBytes - if len(bytes1) > 0 { - bytes1[0] = 0xFF - bytes3 := sb.Bytes() - if bytes3[0] == 0xFF { - t.Error("External modification affected SecureBytes") - } - } - - sb.Clear() - }) - - t.Run("Clear", func(t *testing.T) { - data := []byte{1, 2, 3, 4, 5} - sb := FromBytes(data) - - if sb.IsEmpty() { - t.Error("SecureBytes should not be empty before Clear") - } - - sb.Clear() - - if !sb.IsEmpty() { - t.Error("SecureBytes should be empty after Clear") - } - - if sb.Size() != 0 { - t.Error("Size should be 0 after Clear") - } - - bytes := sb.Bytes() - if bytes != nil { - t.Error("Bytes() should return nil after Clear") - } - }) - - t.Run("CopyTo", func(t *testing.T) { - sb := NewSecureBytes(10) - data := []byte{1, 2, 3, 4, 5} - - err := sb.CopyTo(data) - if err != nil { - t.Fatalf("CopyTo failed: %v", err) - } - - retrieved := sb.Bytes() - if !bytes.Equal(retrieved[:len(data)], data) { - t.Error("CopyTo didn't copy data correctly") - } - - // Test overflow - largeData := make([]byte, 20) - err = sb.CopyTo(largeData) - if err == nil { - t.Error("CopyTo should fail with oversized data") - } - - sb.Clear() - - // Test copy to finalized - err = sb.CopyTo(data) - if err == nil { - t.Error("CopyTo should fail on finalized SecureBytes") - } - }) -} - -func TestSecureString(t *testing.T) { - t.Run("basic operations", func(t *testing.T) { - original := "sensitive data" - ss := NewSecureString(original) - - if ss.String() != original { - t.Error("String() doesn't match original") - } - - if ss.IsEmpty() { - t.Error("SecureString should not be empty") - } - - ss.Clear() - - if !ss.IsEmpty() { - t.Error("SecureString should be empty after Clear") - } - - if ss.String() != "" { - t.Error("String() should return empty string after Clear") - } - }) - - t.Run("empty string", func(t *testing.T) { - ss := NewSecureString("") - if !ss.IsEmpty() { - t.Error("Empty SecureString should report as empty") - } - ss.Clear() - }) -} - -func TestSecureBuffer(t *testing.T) { - t.Run("basic operations", func(t *testing.T) { - sb := NewSecureBuffer(100) - - if sb.Size() != 0 { - t.Error("New buffer should have size 0") - } - - if sb.Capacity() != 100 { - t.Errorf("Capacity() = %d, want 100", sb.Capacity()) - } - - // Write data - data1 := []byte("hello") - err := sb.Write(data1) - if err != nil { - t.Fatalf("Write failed: %v", err) - } - - if sb.Size() != len(data1) { - t.Errorf("Size() = %d, want %d", sb.Size(), len(data1)) - } - - // Write more data - data2 := []byte(" world") - err = sb.Write(data2) - if err != nil { - t.Fatalf("Second write failed: %v", err) - } - - expected := append(data1, data2...) - result := sb.Read() - if !bytes.Equal(result, expected) { - t.Errorf("Read() = %q, want %q", string(result), string(expected)) - } - - sb.Clear() - }) - - t.Run("overflow protection", func(t *testing.T) { - sb := NewSecureBuffer(10) - - // Fill to capacity - data := make([]byte, 10) - err := sb.Write(data) - if err != nil { - t.Fatalf("Write to capacity failed: %v", err) - } - - // Try to overflow - err = sb.Write([]byte{1}) - if err == nil { - t.Error("Write should fail on buffer overflow") - } - - sb.Clear() - }) - - t.Run("reset", func(t *testing.T) { - sb := NewSecureBuffer(50) - - data := []byte("test data") - err := sb.Write(data) - if err != nil { - t.Fatalf("Write failed: %v", err) - } - - if sb.Size() == 0 { - t.Error("Buffer should not be empty before reset") - } - - sb.Reset() - - if sb.Size() != 0 { - t.Error("Buffer should be empty after reset") - } - - if sb.Capacity() != 50 { - t.Error("Capacity should be preserved after reset") - } - - // Should be able to write again - err = sb.Write([]byte("new data")) - if err != nil { - t.Error("Should be able to write after reset") - } - - sb.Clear() - }) -} - -func TestZeroizeMultiple(t *testing.T) { - slice1 := []byte{1, 2, 3} - slice2 := []byte{4, 5, 6} - slice3 := []byte{7, 8, 9} - - ZeroizeMultiple(slice1, slice2, slice3) - - slices := [][]byte{slice1, slice2, slice3} - for i, slice := range slices { - for j, b := range slice { - if b != 0 { - t.Errorf("Slice %d, byte %d not zeroed: got %d", i, j, b) - } - } - } -} - -func TestSecureCompare(t *testing.T) { - tests := []struct { - name string - a, b []byte - expected bool - }{ - {"equal slices", []byte{1, 2, 3}, []byte{1, 2, 3}, true}, - {"different content", []byte{1, 2, 3}, []byte{1, 2, 4}, false}, - {"different length", []byte{1, 2, 3}, []byte{1, 2}, false}, - {"both empty", []byte{}, []byte{}, true}, - {"one empty", []byte{1}, []byte{}, false}, - {"both nil", nil, nil, true}, - {"one nil", []byte{1}, nil, false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := SecureCompare(tt.a, tt.b) - if result != tt.expected { - t.Errorf("SecureCompare() = %v, want %v", result, tt.expected) - } - }) - } -} - -func TestSecureRandom(t *testing.T) { - sizes := []int{0, 1, 16, 32, 1024} - - for _, size := range sizes { - t.Run(fmt.Sprintf("%d bytes", size), func(t *testing.T) { - data := make([]byte, size) - err := SecureRandom(data) - if err != nil { - t.Fatalf("SecureRandom failed: %v", err) - } - - if size == 0 { - return // Nothing to verify for empty slice - } - - // For non-zero sizes, verify we got some randomness - // (Note: there's a tiny chance this could fail with truly random data) - allZeros := true - allSame := true - first := data[0] - - for _, b := range data { - if b != 0 { - allZeros = false - } - if b != first { - allSame = false - } - } - - if size > 1 { - if allZeros { - t.Error("SecureRandom returned all zeros (suspicious)") - } - if allSame { - t.Error("SecureRandom returned all same values (suspicious)") - } - } - }) - } -} - -// Test that finalizers work correctly (this is tricky to test reliably) -func TestFinalizers(t *testing.T) { - t.Run("SecureBytes finalizer", func(t *testing.T) { - // Create a SecureBytes and let it go out of scope - func() { - sb := NewSecureBytes(32) - // Fill with test data - data := make([]byte, 32) - for i := range data { - data[i] = byte(i + 1) - } - sb.CopyTo(data) - // sb goes out of scope here - }() - - // Force garbage collection - runtime.GC() - runtime.GC() - time.Sleep(10 * time.Millisecond) - - // We can't easily verify the finalizer ran, but this tests that - // the finalizer doesn't cause a panic - }) - - t.Run("SecureString finalizer", func(t *testing.T) { - func() { - ss := NewSecureString("test data") - _ = ss.String() - // ss goes out of scope here - }() - - runtime.GC() - runtime.GC() - time.Sleep(10 * time.Millisecond) - }) - - t.Run("SecureBuffer finalizer", func(t *testing.T) { - func() { - sb := NewSecureBuffer(64) - sb.Write([]byte("test data")) - // sb goes out of scope here - }() - - runtime.GC() - runtime.GC() - time.Sleep(10 * time.Millisecond) - }) -} - -func BenchmarkZeroize(b *testing.B) { - sizes := []int{32, 256, 1024, 4096} - - for _, size := range sizes { - b.Run(fmt.Sprintf("%dB", size), func(b *testing.B) { - data := make([]byte, size) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - // Fill with data - for j := range data { - data[j] = byte(j) - } - // Zeroize - Zeroize(data) - } - }) - } -} - -func BenchmarkSecureCompare(b *testing.B) { - sizes := []int{16, 32, 256, 1024} - - for _, size := range sizes { - b.Run(fmt.Sprintf("%dB", size), func(b *testing.B) { - a := make([]byte, size) - b_slice := make([]byte, size) - - // Fill with identical data - for i := range a { - a[i] = byte(i) - b_slice[i] = byte(i) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - SecureCompare(a, b_slice) - } - }) - } -} - -func BenchmarkSecureBytes(b *testing.B) { - b.Run("NewSecureBytes", func(b *testing.B) { - for i := 0; i < b.N; i++ { - sb := NewSecureBytes(32) - sb.Clear() - } - }) - - b.Run("Bytes", func(b *testing.B) { - sb := NewSecureBytes(32) - defer sb.Clear() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - data := sb.Bytes() - _ = data - } - }) - - b.Run("CopyTo", func(b *testing.B) { - sb := NewSecureBytes(32) - defer sb.Clear() - - testData := make([]byte, 16) - for i := range testData { - testData[i] = byte(i) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - sb.CopyTo(testData) - } - }) -} diff --git a/crypto/security_test.go b/crypto/security_test.go deleted file mode 100644 index 9fcf97ab3..000000000 --- a/crypto/security_test.go +++ /dev/null @@ -1,466 +0,0 @@ -// Package crypto provides comprehensive security tests for cryptographic implementations -package crypto - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "fmt" - "math/big" - "sync" - "testing" - "time" - - "github.com/sonr-io/sonr/crypto/argon2" - ecdsaPkg "github.com/sonr-io/sonr/crypto/ecdsa" - "github.com/sonr-io/sonr/crypto/password" - "github.com/sonr-io/sonr/crypto/wasm" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// TestTimingAttackResistance verifies constant-time operations -func TestTimingAttackResistance(t *testing.T) { - // Test Argon2 constant-time comparison - kdf := argon2.New(argon2.LightConfig()) - password := []byte("correct-password") - hash, err := kdf.HashPassword(password) - require.NoError(t, err) - - // Measure timing for correct vs incorrect passwords - correctTimes := make([]time.Duration, 100) - incorrectTimes := make([]time.Duration, 100) - - for i := 0; i < 100; i++ { - // Time correct password - start := time.Now() - _, _ = argon2.VerifyPassword(password, hash) - correctTimes[i] = time.Since(start) - - // Time incorrect password - wrongPassword := []byte("wrong-password-x") - start = time.Now() - _, _ = argon2.VerifyPassword(wrongPassword, hash) - incorrectTimes[i] = time.Since(start) - } - - // Calculate average times - var correctAvg, incorrectAvg time.Duration - for i := 0; i < 100; i++ { - correctAvg += correctTimes[i] - incorrectAvg += incorrectTimes[i] - } - correctAvg /= 100 - incorrectAvg /= 100 - - // Times should be similar (within 20% variance) - diff := correctAvg - incorrectAvg - if diff < 0 { - diff = -diff - } - maxDiff := correctAvg / 5 // 20% threshold - - assert.Less(t, diff, maxDiff, "timing difference suggests non-constant-time comparison") -} - -// TestSignatureMalleabilityAttack tests protection against signature malleability -func TestSignatureMalleabilityAttack(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("transaction data") - hash := sha256.Sum256(message) - - // Create deterministic signature - r, s, err := ecdsaPkg.DeterministicSign(priv, hash[:]) - require.NoError(t, err) - - // Verify original signature - assert.True(t, ecdsa.Verify(&priv.PublicKey, hash[:], r, s)) - - // Create malleable signature (r, -s mod N) - N := priv.Curve.Params().N - sMalleable := new(big.Int).Sub(N, s) - - // Standard ECDSA would accept this, but our canonical check should reject it - assert.False(t, ecdsaPkg.VerifyDeterministic(&priv.PublicKey, hash[:], r, sMalleable), - "malleable signature should be rejected") - - // Canonicalize should fix it - rCanon, sCanon, err := ecdsaPkg.CanonicalizeSignature(r, sMalleable, priv.Curve) - require.NoError(t, err) - assert.Equal(t, s, sCanon, "canonicalized signature should match original") - assert.True(t, ecdsa.Verify(&priv.PublicKey, hash[:], rCanon, sCanon)) -} - -// TestNonceReuseAttack verifies protection against nonce reuse -func TestNonceReuseAttack(t *testing.T) { - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - // Sign same message multiple times with deterministic ECDSA - message := []byte("sensitive data") - hash := sha256.Sum256(message) - - signatures := make([]struct{ r, s *big.Int }, 10) - for i := 0; i < 10; i++ { - r, s, err := ecdsaPkg.DeterministicSign(priv, hash[:]) - require.NoError(t, err) - signatures[i].r = r - signatures[i].s = s - } - - // All signatures should be identical (deterministic) - for i := 1; i < 10; i++ { - assert.Equal(t, signatures[0].r, signatures[i].r, - "deterministic signatures should use same nonce") - assert.Equal(t, signatures[0].s, signatures[i].s, - "deterministic signatures should be identical") - } - - // Different messages should use different nonces - message2 := []byte("different data") - hash2 := sha256.Sum256(message2) - r2, s2, err := ecdsaPkg.DeterministicSign(priv, hash2[:]) - require.NoError(t, err) - - assert.NotEqual(t, signatures[0].r, r2, - "different messages must use different nonces") - assert.NotEqual(t, signatures[0].s, s2, - "different messages must produce different signatures") -} - -// TestPasswordDictionaryAttack tests resistance to dictionary attacks -func TestPasswordDictionaryAttack(t *testing.T) { - commonPasswords := []string{ - "password", "123456", "password123", "admin", "letmein", - "welcome", "monkey", "dragon", "master", "qwerty", - } - - validator := password.NewValidator(password.DefaultPasswordConfig()) - - // All common passwords should be rejected - for _, pwd := range commonPasswords { - err := validator.Validate([]byte(pwd)) - assert.Error(t, err, "common password '%s' should be rejected", pwd) - } - - // Test that Argon2 makes dictionary attacks expensive - kdf := argon2.New(argon2.DefaultConfig()) - - start := time.Now() - for _, pwd := range commonPasswords { - hash, err := kdf.HashPassword([]byte(pwd)) - require.NoError(t, err) - - // Try to crack with dictionary - for _, attempt := range commonPasswords { - _, _ = argon2.VerifyPassword([]byte(attempt), hash) - } - } - elapsed := time.Since(start) - - // Should take significant time (> 1 second for 100 attempts) - assert.Greater(t, elapsed, 1*time.Second, - "Argon2 should make dictionary attacks expensive") -} - -// TestWASMHashCollisionAttack tests resistance to hash collision attacks -func TestWASMHashCollisionAttack(t *testing.T) { - verifier := wasm.NewHashVerifier() - - // Create two different modules - module1 := []byte("wasm module version 1.0") - module2 := []byte("wasm module version 2.0") - - hash1 := verifier.ComputeHash(module1) - hash2 := verifier.ComputeHash(module2) - - // Hashes must be different - assert.NotEqual(t, hash1, hash2, - "different modules must have different hashes") - - // Test collision resistance with similar modules - similarModules := make([][]byte, 100) - hashes := make(map[string]bool) - - for i := 0; i < 100; i++ { - similarModules[i] = []byte(fmt.Sprintf("wasm module version 1.%d", i)) - hash := verifier.ComputeHash(similarModules[i]) - - // Check for collisions - assert.False(t, hashes[hash], - "hash collision detected for module %d", i) - hashes[hash] = true - } -} - -// TestRaceConditionSafety tests thread safety of cryptographic operations -func TestRaceConditionSafety(t *testing.T) { - // Test concurrent Argon2 operations - kdf := argon2.New(argon2.LightConfig()) - password := []byte("test-password") - - var wg sync.WaitGroup - errors := make(chan error, 100) - - for i := 0; i < 100; i++ { - wg.Add(1) - go func() { - defer wg.Done() - - hash, err := kdf.HashPassword(password) - if err != nil { - errors <- err - return - } - - valid, err := argon2.VerifyPassword(password, hash) - if err != nil { - errors <- err - return - } - if !valid { - errors <- fmt.Errorf("password verification failed") - } - }() - } - - wg.Wait() - close(errors) - - // Check for any errors - for err := range errors { - t.Errorf("concurrent operation failed: %v", err) - } - - // Test concurrent ECDSA signing - priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - - message := []byte("concurrent test") - hash := sha256.Sum256(message) - - signatures := make(chan struct{ r, s *big.Int }, 100) - var sigWg sync.WaitGroup - - for i := 0; i < 100; i++ { - sigWg.Add(1) - go func() { - defer sigWg.Done() - - r, s, err := ecdsaPkg.DeterministicSign(priv, hash[:]) - if err == nil { - signatures <- struct{ r, s *big.Int }{r, s} - } - }() - } - - sigWg.Wait() - close(signatures) - - // All signatures should be identical (deterministic) - var firstSig struct{ r, s *big.Int } - count := 0 - for sig := range signatures { - if count == 0 { - firstSig = sig - } else { - assert.Equal(t, firstSig.r, sig.r, - "concurrent signatures should be identical") - assert.Equal(t, firstSig.s, sig.s, - "concurrent signatures should be identical") - } - count++ - } - assert.Equal(t, 100, count, "all concurrent operations should succeed") -} - -// TestMemoryExhaustionAttack tests resistance to memory exhaustion -func TestMemoryExhaustionAttack(t *testing.T) { - // Test with high memory Argon2 config - config := &argon2.Config{ - Time: 1, - Memory: 128 * 1024, // 128MB - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - } - - // Validate config prevents excessive memory use - err := argon2.ValidateConfig(config) - assert.NoError(t, err, "reasonable memory config should be valid") - - // Test with excessive memory request - excessiveConfig := &argon2.Config{ - Time: 1, - Memory: 4 * 1024 * 1024, // 4GB - should be rejected - Parallelism: 4, - SaltLength: 32, - KeyLength: 32, - } - - // This should be caught by reasonable implementations - kdf := argon2.New(excessiveConfig) - - // Attempt derivation with memory limit - password := []byte("test") - salt := make([]byte, 32) - _, _ = rand.Read(salt) - - // Monitor memory usage (simplified test) - start := time.Now() - _ = kdf.DeriveKey(password, salt) - elapsed := time.Since(start) - - // Excessive memory should cause noticeable delay - assert.Less(t, elapsed, 10*time.Second, - "operation should complete in reasonable time") -} - -// TestSaltReuseVulnerability tests that salts are unique -func TestSaltReuseVulnerability(t *testing.T) { - kdf := argon2.New(argon2.DefaultConfig()) - - salts := make(map[string]bool) - - // Generate many salts - for i := 0; i < 1000; i++ { - salt, err := kdf.GenerateSalt() - require.NoError(t, err) - - saltStr := string(salt) - assert.False(t, salts[saltStr], - "salt reuse detected at iteration %d", i) - salts[saltStr] = true - } -} - -// TestWeakRandomnessDetection tests quality of random number generation -func TestWeakRandomnessDetection(t *testing.T) { - // Generate multiple ECDSA keys and check for patterns - keys := make([]*ecdsa.PrivateKey, 100) - - for i := 0; i < 100; i++ { - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - keys[i] = key - } - - // Check that all private keys are unique - seen := make(map[string]bool) - for i, key := range keys { - keyStr := key.D.String() - assert.False(t, seen[keyStr], - "duplicate private key detected at index %d", i) - seen[keyStr] = true - } - - // Check distribution (simplified chi-square test) - // Count leading bits - zeros := 0 - ones := 0 - for _, key := range keys { - if key.D.Bit(0) == 0 { - zeros++ - } else { - ones++ - } - } - - // Should be roughly 50/50 distribution - // For 100 samples, we expect ~50 each, but allow for statistical variance - // Using binomial distribution, 99% confidence interval is approximately ±3 standard deviations - // Standard deviation = sqrt(n*p*(1-p)) = sqrt(100*0.5*0.5) = 5 - // So we allow difference up to 3*5 = 15, but we'll be more lenient with 25 - diff := zeros - ones - if diff < 0 { - diff = -diff - } - assert.Less(t, diff, 25, - "random bit distribution appears biased: %d zeros, %d ones", zeros, ones) -} - -// TestCryptographicAgility tests ability to switch algorithms -func TestCryptographicAgility(t *testing.T) { - // Test different Argon2 configurations - configs := []*argon2.Config{ - argon2.LightConfig(), - argon2.DefaultConfig(), - argon2.HighSecurityConfig(), - } - - password := []byte("test-password") - - for i, config := range configs { - kdf := argon2.New(config) - - hash, err := kdf.HashPassword(password) - require.NoError(t, err, "config %d should work", i) - - // Verify with same config - valid, err := argon2.VerifyPassword(password, hash) - require.NoError(t, err) - assert.True(t, valid, "config %d verification should succeed", i) - } - - // Test different elliptic curves - curves := []elliptic.Curve{ - elliptic.P224(), - elliptic.P256(), - elliptic.P384(), - elliptic.P521(), - } - - message := []byte("test message") - hashMsg := sha256.Sum256(message) - - for _, curve := range curves { - priv, err := ecdsa.GenerateKey(curve, rand.Reader) - require.NoError(t, err) - - r, s, err := ecdsaPkg.DeterministicSign(priv, hashMsg[:]) - require.NoError(t, err) - - valid := ecdsa.Verify(&priv.PublicKey, hashMsg[:], r, s) - assert.True(t, valid, "curve %s should work", curve.Params().Name) - } -} - -// BenchmarkSecurityOperations benchmarks security-critical operations -func BenchmarkSecurityOperations(b *testing.B) { - b.Run("Argon2Default", func(b *testing.B) { - kdf := argon2.New(argon2.DefaultConfig()) - password := []byte("benchmark-password") - salt, _ := kdf.GenerateSalt() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = kdf.DeriveKey(password, salt) - } - }) - - b.Run("ECDSADeterministic", func(b *testing.B) { - priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - hash := sha256.Sum256([]byte("benchmark")) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _, _ = ecdsaPkg.DeterministicSign(priv, hash[:]) - } - }) - - b.Run("WASMHashVerification", func(b *testing.B) { - verifier := wasm.NewHashVerifier() - module := make([]byte, 1024*1024) // 1MB module - rand.Read(module) - hash := verifier.ComputeHash(module) - verifier.AddTrustedHash("bench", hash) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = verifier.VerifyHash("bench", module) - } - }) -} diff --git a/crypto/sharing/README.md b/crypto/sharing/README.md deleted file mode 100755 index 03874fdd4..000000000 --- a/crypto/sharing/README.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Shamir Secret Sharing Scheme - -The code is an implementation of the following papers. - -- -- ~gasarch/TOPICS/secretsharing/feldmanVSS.pdf -- diff --git a/crypto/sharing/ed25519_feldman_test.go b/crypto/sharing/ed25519_feldman_test.go deleted file mode 100644 index c1fed0f98..000000000 --- a/crypto/sharing/ed25519_feldman_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -var testCurve = curves.ED25519() - -func TestEd25519FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, testCurve) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, testCurve) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, testCurve) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split(testCurve.NewScalar(), crand.Reader) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Id: 1, - Value: testCurve.Scalar.New(3).Bytes(), - }, - { - Id: 1, - Value: testCurve.Scalar.New(3).Bytes(), - }, - }...) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Id: 0, - Value: testCurve.Scalar.New(3).Bytes(), - }, - { - Id: 2, - Value: testCurve.Scalar.New(3).Bytes(), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Id: 4, - Value: testCurve.Scalar.New(3).Bytes(), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := testCurve.Scalar.Hash([]byte("test")) - verifiers, shares, err := scheme.Split(secret, crand.Reader) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - err = verifiers.Verify(s) - require.Nil(t, err) - } - secret2, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret2, secret) -} - -func TestEd25519FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, testCurve) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := testCurve.Scalar.Hash([]byte("test")) - verifiers, shares, err := scheme.Split(secret, crand.Reader) - for _, s := range shares { - err = verifiers.Verify(s) - require.Nil(t, err) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/feldman.go b/crypto/sharing/feldman.go deleted file mode 100644 index 3a665f059..000000000 --- a/crypto/sharing/feldman.go +++ /dev/null @@ -1,115 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - "fmt" - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type FeldmanVerifier struct { - Commitments []curves.Point -} - -func (v FeldmanVerifier) Verify(share *ShamirShare) error { - curve := curves.GetCurveByName(v.Commitments[0].CurveName()) - err := share.Validate(curve) - if err != nil { - return err - } - x := curve.Scalar.New(int(share.Id)) - i := curve.Scalar.One() - rhs := v.Commitments[0] - - for j := 1; j < len(v.Commitments); j++ { - i = i.Mul(x) - rhs = rhs.Add(v.Commitments[j].Mul(i)) - } - sc, _ := curve.Scalar.SetBytes(share.Value) - lhs := v.Commitments[0].Generator().Mul(sc) - - if lhs.Equal(rhs) { - return nil - } else { - return fmt.Errorf("not equal") - } -} - -type Feldman struct { - Threshold, Limit uint32 - Curve *curves.Curve -} - -func NewFeldman(threshold, limit uint32, curve *curves.Curve) (*Feldman, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold cannot be less than 2") - } - if limit > 255 { - return nil, fmt.Errorf("cannot exceed 255 shares") - } - if curve == nil { - return nil, fmt.Errorf("invalid curve") - } - return &Feldman{threshold, limit, curve}, nil -} - -func (f Feldman) Split( - secret curves.Scalar, - reader io.Reader, -) (*FeldmanVerifier, []*ShamirShare, error) { - if secret.IsZero() { - return nil, nil, fmt.Errorf("invalid secret") - } - shamir := &Shamir{ - threshold: f.Threshold, - limit: f.Limit, - curve: f.Curve, - } - shares, poly := shamir.getPolyAndShares(secret, reader) - verifier := new(FeldmanVerifier) - verifier.Commitments = make([]curves.Point, f.Threshold) - for i := range verifier.Commitments { - verifier.Commitments[i] = f.Curve.ScalarBaseMult(poly.Coefficients[i]) - } - return verifier, shares, nil -} - -func (f Feldman) LagrangeCoeffs(shares map[uint32]*ShamirShare) (map[uint32]curves.Scalar, error) { - shamir := &Shamir{ - threshold: f.Threshold, - limit: f.Limit, - curve: f.Curve, - } - identities := make([]uint32, 0) - for _, xi := range shares { - identities = append(identities, xi.Id) - } - return shamir.LagrangeCoeffs(identities) -} - -func (f Feldman) Combine(shares ...*ShamirShare) (curves.Scalar, error) { - shamir := &Shamir{ - threshold: f.Threshold, - limit: f.Limit, - curve: f.Curve, - } - return shamir.Combine(shares...) -} - -func (f Feldman) CombinePoints(shares ...*ShamirShare) (curves.Point, error) { - shamir := &Shamir{ - threshold: f.Threshold, - limit: f.Limit, - curve: f.Curve, - } - return shamir.CombinePoints(shares...) -} diff --git a/crypto/sharing/pedersen.go b/crypto/sharing/pedersen.go deleted file mode 100644 index a0757f4a8..000000000 --- a/crypto/sharing/pedersen.go +++ /dev/null @@ -1,154 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - "fmt" - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Pedersen Verifiable Secret Sharing Scheme -type Pedersen struct { - threshold, limit uint32 - curve *curves.Curve - generator curves.Point -} - -type PedersenVerifier struct { - Generator curves.Point - Commitments []curves.Point -} - -func (pv PedersenVerifier) Verify(share, blindShare *ShamirShare) error { - curve := curves.GetCurveByName(pv.Generator.CurveName()) - if err := share.Validate(curve); err != nil { - return err - } - if err := blindShare.Validate(curve); err != nil { - return err - } - - x := curve.Scalar.New(int(share.Id)) - i := curve.Scalar.One() - rhs := pv.Commitments[0] - - for j := 1; j < len(pv.Commitments); j++ { - i = i.Mul(x) - rhs = rhs.Add(pv.Commitments[j].Mul(i)) - } - - sc, _ := curve.Scalar.SetBytes(share.Value) - bsc, _ := curve.Scalar.SetBytes(blindShare.Value) - g := pv.Commitments[0].Generator().Mul(sc) - h := pv.Generator.Mul(bsc) - lhs := g.Add(h) - - if lhs.Equal(rhs) { - return nil - } else { - return fmt.Errorf("not equal") - } -} - -// PedersenResult contains all the data from calling Split -type PedersenResult struct { - Blinding curves.Scalar - BlindingShares, SecretShares []*ShamirShare - FeldmanVerifier *FeldmanVerifier - PedersenVerifier *PedersenVerifier -} - -// NewPedersen creates a new pedersen VSS -func NewPedersen(threshold, limit uint32, generator curves.Point) (*Pedersen, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold cannot be less than 2") - } - if limit > 255 { - return nil, fmt.Errorf("cannot exceed 255 shares") - } - curve := curves.GetCurveByName(generator.CurveName()) - if curve == nil { - return nil, fmt.Errorf("invalid curve") - } - if generator == nil { - return nil, fmt.Errorf("invalid generator") - } - if !generator.IsOnCurve() || generator.IsIdentity() { - return nil, fmt.Errorf("invalid generator") - } - return &Pedersen{threshold, limit, curve, generator}, nil -} - -// Split creates the verifiers, blinding and shares -func (pd Pedersen) Split(secret curves.Scalar, reader io.Reader) (*PedersenResult, error) { - // generate a random blinding factor - blinding := pd.curve.Scalar.Random(reader) - - shamir := Shamir{pd.threshold, pd.limit, pd.curve} - // split the secret into shares - shares, poly := shamir.getPolyAndShares(secret, reader) - - // split the blinding into shares - blindingShares, polyBlinding := shamir.getPolyAndShares(blinding, reader) - - // Generate the verifiable commitments to the polynomial for the shares - blindedverifiers := make([]curves.Point, pd.threshold) - verifiers := make([]curves.Point, pd.threshold) - - // ({p0 * G + b0 * H}, ...,{pt * G + bt * H}) - for i, c := range poly.Coefficients { - s := pd.curve.ScalarBaseMult(c) - b := pd.generator.Mul(polyBlinding.Coefficients[i]) - bv := s.Add(b) - blindedverifiers[i] = bv - verifiers[i] = s - } - verifier1 := &FeldmanVerifier{Commitments: verifiers} - verifier2 := &PedersenVerifier{Commitments: blindedverifiers, Generator: pd.generator} - - return &PedersenResult{ - blinding, blindingShares, shares, verifier1, verifier2, - }, nil -} - -func (pd Pedersen) LagrangeCoeffs( - shares map[uint32]*ShamirShare, -) (map[uint32]curves.Scalar, error) { - shamir := &Shamir{ - threshold: pd.threshold, - limit: pd.limit, - curve: pd.curve, - } - identities := make([]uint32, 0) - for _, xi := range shares { - identities = append(identities, xi.Id) - } - return shamir.LagrangeCoeffs(identities) -} - -func (pd Pedersen) Combine(shares ...*ShamirShare) (curves.Scalar, error) { - shamir := &Shamir{ - threshold: pd.threshold, - limit: pd.limit, - curve: pd.curve, - } - return shamir.Combine(shares...) -} - -func (pd Pedersen) CombinePoints(shares ...*ShamirShare) (curves.Point, error) { - shamir := &Shamir{ - threshold: pd.threshold, - limit: pd.limit, - curve: pd.curve, - } - return shamir.CombinePoints(shares...) -} diff --git a/crypto/sharing/polynomial.go b/crypto/sharing/polynomial.go deleted file mode 100644 index 390f2141e..000000000 --- a/crypto/sharing/polynomial.go +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type Polynomial struct { - Coefficients []curves.Scalar -} - -func (p *Polynomial) Init(intercept curves.Scalar, degree uint32, reader io.Reader) *Polynomial { - p.Coefficients = make([]curves.Scalar, degree) - p.Coefficients[0] = intercept.Clone() - for i := 1; i < int(degree); i++ { - p.Coefficients[i] = intercept.Random(reader) - } - return p -} - -func (p Polynomial) Evaluate(x curves.Scalar) curves.Scalar { - degree := len(p.Coefficients) - 1 - out := p.Coefficients[degree].Clone() - for i := degree - 1; i >= 0; i-- { - out = out.Mul(x).Add(p.Coefficients[i]) - } - return out -} diff --git a/crypto/sharing/polynomial_test.go b/crypto/sharing/polynomial_test.go deleted file mode 100644 index f4efd8d5e..000000000 --- a/crypto/sharing/polynomial_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Copyright Coinbase, Inc. All Rights Reserved. -// -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestNewPoly(t *testing.T) { - curve := curves.BLS12381G1() - secret := curve.NewScalar().Hash([]byte("test")) - - poly := new(Polynomial).Init(secret, 4, crand.Reader) - require.NotNil(t, poly) - - require.Equal(t, poly.Coefficients[0], secret) -} diff --git a/crypto/sharing/shamir.go b/crypto/sharing/shamir.go deleted file mode 100644 index 67a71b747..000000000 --- a/crypto/sharing/shamir.go +++ /dev/null @@ -1,209 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package sharing is an implementation of shamir secret sharing and implements the following papers. -// -// - https://dl.acm.org/doi/pdf/10.1145/359168.359176 -// - https://www.cs.umd.edu/~gasarch/TOPICS/secretsharing/feldmanVSS.pdf -// - https://link.springer.com/content/pdf/10.1007%2F3-540-46766-1_9.pdf -package sharing - -import ( - "encoding/binary" - "fmt" - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type ShamirShare struct { - Id uint32 `json:"identifier"` - Value []byte `json:"value"` -} - -func (ss ShamirShare) Validate(curve *curves.Curve) error { - if ss.Id == 0 { - return fmt.Errorf("invalid identifier") - } - sc, err := curve.Scalar.SetBytes(ss.Value) - if err != nil { - return err - } - if sc.IsZero() { - return fmt.Errorf("invalid share") - } - return nil -} - -func (ss ShamirShare) Bytes() []byte { - var id [4]byte - binary.BigEndian.PutUint32(id[:], ss.Id) - return append(id[:], ss.Value...) -} - -type Shamir struct { - threshold, limit uint32 - curve *curves.Curve -} - -func NewShamir(threshold, limit uint32, curve *curves.Curve) (*Shamir, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold cannot be less than 2") - } - if limit > 255 { - return nil, fmt.Errorf("cannot exceed 255 shares") - } - if curve == nil { - return nil, fmt.Errorf("invalid curve") - } - return &Shamir{threshold, limit, curve}, nil -} - -func (s Shamir) Split(secret curves.Scalar, reader io.Reader) ([]*ShamirShare, error) { - if secret.IsZero() { - return nil, fmt.Errorf("invalid secret") - } - shares, _ := s.getPolyAndShares(secret, reader) - return shares, nil -} - -func (s Shamir) getPolyAndShares( - secret curves.Scalar, - reader io.Reader, -) ([]*ShamirShare, *Polynomial) { - poly := new(Polynomial).Init(secret, s.threshold, reader) - shares := make([]*ShamirShare, s.limit) - for i := range shares { - x := s.curve.Scalar.New(i + 1) - shares[i] = &ShamirShare{ - Id: uint32(i + 1), - Value: poly.Evaluate(x).Bytes(), - } - } - return shares, poly -} - -func (s Shamir) LagrangeCoeffs(identities []uint32) (map[uint32]curves.Scalar, error) { - xs := make(map[uint32]curves.Scalar, len(identities)) - for _, xi := range identities { - xs[xi] = s.curve.Scalar.New(int(xi)) - } - - result := make(map[uint32]curves.Scalar, len(identities)) - for i, xi := range xs { - num := s.curve.Scalar.One() - den := s.curve.Scalar.One() - for j, xj := range xs { - if i == j { - continue - } - - num = num.Mul(xj) - den = den.Mul(xj.Sub(xi)) - } - if den.IsZero() { - return nil, fmt.Errorf("divide by zero") - } - result[i] = num.Div(den) - } - return result, nil -} - -func (s Shamir) Combine(shares ...*ShamirShare) (curves.Scalar, error) { - if len(shares) < int(s.threshold) { - return nil, fmt.Errorf("invalid number of shares") - } - dups := make(map[uint32]bool, len(shares)) - xs := make([]curves.Scalar, len(shares)) - ys := make([]curves.Scalar, len(shares)) - - for i, share := range shares { - err := share.Validate(s.curve) - if err != nil { - return nil, err - } - if share.Id > s.limit { - return nil, fmt.Errorf("invalid share identifier") - } - if _, in := dups[share.Id]; in { - return nil, fmt.Errorf("duplicate share") - } - dups[share.Id] = true - ys[i], _ = s.curve.Scalar.SetBytes(share.Value) - xs[i] = s.curve.Scalar.New(int(share.Id)) - } - return s.interpolate(xs, ys) -} - -func (s Shamir) CombinePoints(shares ...*ShamirShare) (curves.Point, error) { - if len(shares) < int(s.threshold) { - return nil, fmt.Errorf("invalid number of shares") - } - dups := make(map[uint32]bool, len(shares)) - xs := make([]curves.Scalar, len(shares)) - ys := make([]curves.Point, len(shares)) - - for i, share := range shares { - err := share.Validate(s.curve) - if err != nil { - return nil, err - } - if share.Id > s.limit { - return nil, fmt.Errorf("invalid share identifier") - } - if _, in := dups[share.Id]; in { - return nil, fmt.Errorf("duplicate share") - } - dups[share.Id] = true - sc, _ := s.curve.Scalar.SetBytes(share.Value) - ys[i] = s.curve.ScalarBaseMult(sc) - xs[i] = s.curve.Scalar.New(int(share.Id)) - } - return s.interpolatePoint(xs, ys) -} - -func (s Shamir) interpolate(xs, ys []curves.Scalar) (curves.Scalar, error) { - result := s.curve.Scalar.Zero() - for i, xi := range xs { - num := s.curve.Scalar.One() - den := s.curve.Scalar.One() - for j, xj := range xs { - if i == j { - continue - } - num = num.Mul(xj) - den = den.Mul(xj.Sub(xi)) - } - if den.IsZero() { - return nil, fmt.Errorf("divide by zero") - } - result = result.Add(ys[i].Mul(num.Div(den))) - } - return result, nil -} - -func (s Shamir) interpolatePoint(xs []curves.Scalar, ys []curves.Point) (curves.Point, error) { - result := s.curve.NewIdentityPoint() - for i, xi := range xs { - num := s.curve.Scalar.One() - den := s.curve.Scalar.One() - for j, xj := range xs { - if i == j { - continue - } - num = num.Mul(xj) - den = den.Mul(xj.Sub(xi)) - } - if den.IsZero() { - return nil, fmt.Errorf("divide by zero") - } - result = result.Add(ys[i].Mul(num.Div(den))) - } - return result, nil -} diff --git a/crypto/sharing/shamir_test.go b/crypto/sharing/shamir_test.go deleted file mode 100644 index a80eb90eb..000000000 --- a/crypto/sharing/shamir_test.go +++ /dev/null @@ -1,186 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sharing - -import ( - "bytes" - crand "crypto/rand" - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestShamirSplitInvalidArgs(t *testing.T) { - curve := curves.ED25519() - _, err := NewShamir(0, 0, curve) - require.NotNil(t, err) - _, err = NewShamir(3, 2, curve) - require.NotNil(t, err) - _, err = NewShamir(1, 10, curve) - require.NotNil(t, err) - scheme, err := NewShamir(2, 3, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Split(curve.NewScalar(), crand.Reader) - require.NotNil(t, err) -} - -func TestShamirCombineNoShares(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(2, 3, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestShamirCombineDuplicateShare(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(2, 3, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Id: 1, - Value: curve.NewScalar().New(3).Bytes(), - }, - { - Id: 1, - Value: curve.NewScalar().New(3).Bytes(), - }, - }...) - require.NotNil(t, err) -} - -func TestShamirCombineBadIdentifier(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(2, 3, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Id: 0, - Value: curve.NewScalar().New(3).Bytes(), - }, - { - Id: 2, - Value: curve.NewScalar().New(3).Bytes(), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Id: 4, - Value: curve.NewScalar().New(3).Bytes(), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestShamirCombineSingle(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(2, 3, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - - shares, err := scheme.Split(curve.NewScalar().Hash([]byte("test")), crand.Reader) - require.Nil(t, err) - require.NotNil(t, shares) - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, curve.NewScalar().Hash([]byte("test"))) -} - -// Test ComputeL function to compute Lagrange coefficients. -func TestShamirComputeL(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(2, 2, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - secret := curve.Scalar.Hash([]byte("test")) - shares, err := scheme.Split(secret, crand.Reader) - require.Nil(t, err) - require.NotNil(t, shares) - identities := make([]uint32, 0) - for _, xi := range shares { - identities = append(identities, xi.Id) - } - lCoeffs, err := scheme.LagrangeCoeffs(identities) - require.Nil(t, err) - require.NotNil(t, lCoeffs) - - // Checking we can reconstruct the same secret using Lagrange coefficients. - result := curve.NewScalar() - for _, r := range shares { - rc, _ := curve.Scalar.SetBytes(r.Value) - result = result.Add(rc.Mul(lCoeffs[r.Id])) - } - require.Equal(t, result.Bytes(), secret.Bytes()) -} - -func TestShamirAllCombinations(t *testing.T) { - curve := curves.ED25519() - scheme, err := NewShamir(3, 5, curve) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := curve.Scalar.Hash([]byte("test")) - shares, err := scheme.Split(secret, crand.Reader) - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} - -// Ensures that ShamirShare's un/marshal successfully. -func TestMarshalJsonRoundTrip(t *testing.T) { - curve := curves.ED25519() - shares := []ShamirShare{ - {0, curve.Scalar.New(300).Bytes()}, - {2, curve.Scalar.New(300000).Bytes()}, - {20, curve.Scalar.New(12812798).Bytes()}, - {31, curve.Scalar.New(17).Bytes()}, - {57, curve.Scalar.New(5066680).Bytes()}, - {128, curve.Scalar.New(3005).Bytes()}, - {19, curve.Scalar.New(317).Bytes()}, - {7, curve.Scalar.New(323).Bytes()}, - {222, curve.NewScalar().New(-1).Bytes()}, - } - // Run all the tests! - for _, in := range shares { - input, err := json.Marshal(in) - require.NoError(t, err) - require.NotNil(t, input) - - // Unmarshal and test - out := &ShamirShare{} - // out.Value = curve.NewScalar() - err = json.Unmarshal(input, &out) - require.NoError(t, err) - require.Equal(t, in.Id, out.Id) - require.Equal(t, bytes.Compare(in.Value, out.Value), 0) - } -} diff --git a/crypto/sharing/v1/bls12381g1_feldman_test.go b/crypto/sharing/v1/bls12381g1_feldman_test.go deleted file mode 100644 index ef1ca6420..000000000 --- a/crypto/sharing/v1/bls12381g1_feldman_test.go +++ /dev/null @@ -1,177 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -var ( - modulus, _ = new(big.Int).SetString( - "1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", - 16, - ) - field = curves.NewField(modulus) -) - -func TestBls12381G1FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, Bls12381G1()) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, Bls12381G1()) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, Bls12381G1()) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestBls12381G1FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestBls12381G1FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestBls12381G1FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestBls12381G1FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - - verifiers, shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestBls12381G1FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, Bls12381G1()) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - verifiers, shares, err := scheme.Split(secret) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/v1/bls12381g1curve.go b/crypto/sharing/v1/bls12381g1curve.go deleted file mode 100644 index b628c6e5d..000000000 --- a/crypto/sharing/v1/bls12381g1curve.go +++ /dev/null @@ -1,120 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/elliptic" - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - bls12381g1Initonce sync.Once - bls12381g1 Bls12381G1Curve -) - -type Bls12381G1Curve struct { - *elliptic.CurveParams -} - -func bls12381g1InitAll() { - bls12381g1.CurveParams = new(elliptic.CurveParams) - bls12381g1.P, _ = new( - big.Int, - ).SetString("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16) - bls12381g1.N = bls12381.Bls12381FqNew().Params.BiModulus - bls12381g1.B, _ = new( - big.Int, - ).SetString("0bbc3efc5008a26a0e1c8c3fad0059c051ac582950405194dd595f13570725ce8c22631a7918fd8ebaac93d50ce72271", 16) - bls12381g1.Gx, _ = new( - big.Int, - ).SetString("120177419e0bfb75edce6ecc21dbf440f0ae6acdf3d0e747154f95c7143ba1c17817fc679976fff55cb38790fd530c16", 16) - bls12381g1.Gy, _ = new( - big.Int, - ).SetString("0bbc3efc5008a26a0e1c8c3fad0059c051ac582950405194dd595f13570725ce8c22631a7918fd8ebaac93d50ce72271", 16) - bls12381g1.BitSize = 381 - bls12381g1.Name = "Bls12381G1" -} - -func Bls12381G1() *Bls12381G1Curve { - bls12381g1Initonce.Do(bls12381g1InitAll) - return &bls12381g1 -} - -func (curve *Bls12381G1Curve) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *Bls12381G1Curve) IsOnCurve(x, y *big.Int) bool { - _, err := new(bls12381.G1).SetBigInt(x, y) - return err == nil -} - -func (curve *Bls12381G1Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - p1, err1 := new(bls12381.G1).SetBigInt(x1, y1) - p2, err2 := new(bls12381.G1).SetBigInt(x2, y2) - - if err1 != nil || err2 != nil { - return nil, nil - } - return p1.Add(p1, p2).BigInt() -} - -func (curve *Bls12381G1Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p, err := new(bls12381.G1).SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - return p.Double(p).BigInt() -} - -func (curve *Bls12381G1Curve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p, err := new(bls12381.G1).SetBigInt(Bx, By) - if err != nil { - return nil, nil - } - var bb [native.FieldBytes]byte - copy(bb[:], k) - s, err := bls12381.Bls12381FqNew().SetBytes(&bb) - if err != nil { - return nil, nil - } - return p.Mul(p, s).BigInt() -} - -func (curve *Bls12381G1Curve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - p := new(bls12381.G1).Generator() - var bb [native.FieldBytes]byte - copy(bb[:], internal.ReverseScalarBytes(k)) - s, err := bls12381.Bls12381FqNew().SetBytes(&bb) - if err != nil { - return nil, nil - } - return p.Mul(p, s).BigInt() -} - -// Hash an arbitrary byte sequence to a G1 point according to the hash-to-curve standard -func (curve *Bls12381G1Curve) Hash(msg []byte) (*big.Int, *big.Int) { - return new( - bls12381.G1, - ).Hash(native.EllipticPointHasherSha256(), msg, []byte("BLS12381G1_XMD:SHA-256_SSWU_RO_")). - BigInt() -} - -// CompressedBytesFromBigInts takes x and y coordinates and converts them to the BLS compressed point form -func (curve *Bls12381G1Curve) CompressedBytesFromBigInts(x, y *big.Int) ([]byte, error) { - p, err := new(bls12381.G1).SetBigInt(x, y) - if err != nil { - return nil, err - } - out := p.ToCompressed() - return out[:], nil -} diff --git a/crypto/sharing/v1/bls12381g2_feldman_test.go b/crypto/sharing/v1/bls12381g2_feldman_test.go deleted file mode 100755 index 52a3add13..000000000 --- a/crypto/sharing/v1/bls12381g2_feldman_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestBls12381G2FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, Bls12381G2()) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, Bls12381G2()) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, Bls12381G2()) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestBls12381G2FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestBls12381G2FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestBls12381G2FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestBls12381G2FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - - verifiers, shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestBls12381G2FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, Bls12381G2()) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - verifiers, shares, err := scheme.Split(secret) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/v1/bls12381g2curve.go b/crypto/sharing/v1/bls12381g2curve.go deleted file mode 100644 index e0f07802b..000000000 --- a/crypto/sharing/v1/bls12381g2curve.go +++ /dev/null @@ -1,119 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/elliptic" - "math/big" - "sync" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -var ( - bls12381g2Initonce sync.Once - bls12381g2 Bls12381G2Curve -) - -type Bls12381G2Curve struct { - *elliptic.CurveParams -} - -func bls12381g2InitAll() { - bls12381g2.CurveParams = new(elliptic.CurveParams) - bls12381g2.P, _ = new( - big.Int, - ).SetString("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16) - bls12381g2.N = bls12381.Bls12381FqNew().Params.BiModulus - bls12381g2.B, _ = new( - big.Int, - ).SetString("0bbc3efc5008a26a0e1c8c3fad0059c051ac582950405194dd595f13570725ce8c22631a7918fd8ebaac93d50ce72271", 16) - bls12381g2.Gx, _ = new( - big.Int, - ).SetString("120177419e0bfb75edce6ecc21dbf440f0ae6acdf3d0e747154f95c7143ba1c17817fc679976fff55cb38790fd530c16", 16) - bls12381g2.Gy, _ = new( - big.Int, - ).SetString("0bbc3efc5008a26a0e1c8c3fad0059c051ac582950405194dd595f13570725ce8c22631a7918fd8ebaac93d50ce72271", 16) - bls12381g2.BitSize = 381 - bls12381g2.Name = "Bls12381G1" -} - -func Bls12381G2() *Bls12381G1Curve { - bls12381g2Initonce.Do(bls12381g2InitAll) - return &bls12381g1 -} - -func (curve *Bls12381G2Curve) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *Bls12381G2Curve) IsOnCurve(x, y *big.Int) bool { - _, err := new(bls12381.G2).SetBigInt(x, y) - return err == nil -} - -func (curve *Bls12381G2Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - p1, err1 := new(bls12381.G2).SetBigInt(x1, y1) - p2, err2 := new(bls12381.G2).SetBigInt(x2, y2) - - if err1 != nil || err2 != nil { - return nil, nil - } - return p1.Add(p1, p2).BigInt() -} - -func (curve *Bls12381G2Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p, err := new(bls12381.G2).SetBigInt(x1, y1) - if err != nil { - return nil, nil - } - return p.Double(p).BigInt() -} - -func (curve *Bls12381G2Curve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p, err := new(bls12381.G2).SetBigInt(Bx, By) - if err != nil { - return nil, nil - } - var bb [native.FieldBytes]byte - copy(bb[:], k) - s, err := bls12381.Bls12381FqNew().SetBytes(&bb) - if err != nil { - return nil, nil - } - return p.Mul(p, s).BigInt() -} - -func (curve *Bls12381G2Curve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - p := new(bls12381.G2).Generator() - var bb [native.FieldBytes]byte - copy(bb[:], k) - s, err := bls12381.Bls12381FqNew().SetBytes(&bb) - if err != nil { - return nil, nil - } - return p.Mul(p, s).BigInt() -} - -// Hash an arbitrary byte sequence to a G1 point according to the hash-to-curve standard -func (curve *Bls12381G2Curve) Hash(msg []byte) (*big.Int, *big.Int) { - return new( - bls12381.G1, - ).Hash(native.EllipticPointHasherSha256(), msg, []byte("BLS12381G2_XMD:SHA-256_SSWU_RO_")). - BigInt() -} - -// CompressedBytesFromBigInts takes x and y coordinates and converts them to the BLS compressed point form -func (curve *Bls12381G2Curve) CompressedBytesFromBigInts(x, y *big.Int) ([]byte, error) { - p, err := new(bls12381.G2).SetBigInt(x, y) - if err != nil { - return nil, err - } - out := p.ToCompressed() - return out[:], nil -} diff --git a/crypto/sharing/v1/common.go b/crypto/sharing/v1/common.go deleted file mode 100644 index bd88e7ca5..000000000 --- a/crypto/sharing/v1/common.go +++ /dev/null @@ -1,14 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - kryptology "github.com/sonr-io/sonr/crypto/core/curves" -) - -// ShareVerifier is used to verify secret shares from Feldman or Pedersen VSS -type ShareVerifier = kryptology.EcPoint diff --git a/crypto/sharing/v1/ed25519_feldman_test.go b/crypto/sharing/v1/ed25519_feldman_test.go deleted file mode 100755 index d59fb2b1a..000000000 --- a/crypto/sharing/v1/ed25519_feldman_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestEd25519FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, Ed25519()) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, Ed25519()) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, Ed25519()) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestEd25519FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - - verifiers, shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestEd25519FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, Ed25519()) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - verifiers, shares, err := scheme.Split(secret) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/v1/ed25519_pedersen_test.go b/crypto/sharing/v1/ed25519_pedersen_test.go deleted file mode 100644 index 9033e6757..000000000 --- a/crypto/sharing/v1/ed25519_pedersen_test.go +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/sha512" - "math/big" - "testing" - - "filippo.io/edwards25519" - "github.com/stretchr/testify/require" - - core "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - ed25519BasePoint = &core.EcPoint{Curve: Ed25519(), X: Ed25519().Gx, Y: Ed25519().Gy} - testPointEd25519, _ = core.NewScalarBaseMult(Ed25519(), big.NewInt(2222)) -) - -func TestEd25519PedersenSplitInvalidArgs(t *testing.T) { - _, err := NewPedersen(0, 0, nil) - require.NotNil(t, err) - _, err = NewPedersen(3, 2, nil) - require.NotNil(t, err) - _, err = NewPedersen(1, 10, nil) - require.NotNil(t, err) - _, err = NewPedersen(2, 3, nil) - require.NotNil(t, err) - scheme, err := NewPedersen(2, 3, ed25519BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - // test that split doesn't work on secrets bigger than the modulus - _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestEd25519PedersenCombineNoShares(t *testing.T) { - scheme, err := NewPedersen(2, 3, ed25519BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestEd25519PedersenCombineDuplicateShare(t *testing.T) { - scheme, err := NewPedersen(2, 3, ed25519BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestEd25519PedersenCombineBadIdentifier(t *testing.T) { - scheme, err := NewPedersen(2, 3, ed25519BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.Error(t, err) -} - -func TestEd25519PedersenCombineSingle(t *testing.T) { - scheme, err := NewPedersen(2, 3, testPointEd25519) - require.Nil(t, err) - require.NotNil(t, scheme) - - hBytes := sha512.Sum512([]byte("test")) - var arr [32]byte - copy(arr[:], hBytes[:]) - sc, err := edwards25519.NewScalar().SetBytesWithClamping(arr[:]) - require.Nil(t, err) - result, err := scheme.Split(internal.ReverseScalarBytes(sc.Bytes())) - require.Nil(t, err) - require.NotNil(t, result) - for i, s := range result.SecretShares { - ok, err := scheme.Verify(s, result.BlindingShares[i], result.BlindedVerifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(result.SecretShares...) - require.Nil(t, err) - require.Equal(t, internal.ReverseScalarBytes(secret), sc.Bytes()) -} - -func TestEd25519PedersenAllCombinations(t *testing.T) { - scheme, err := NewPedersen(3, 5, testPointEd25519) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - result, err := scheme.Split(secret) - for i, s := range result.SecretShares { - ok, err := scheme.Verify(s, result.BlindingShares[i], result.BlindedVerifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, result) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine( - result.SecretShares[i], - result.SecretShares[j], - result.SecretShares[k], - ) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - - bSecret, err := scheme.Combine( - result.BlindingShares[i], - result.BlindingShares[j], - result.BlindingShares[k], - ) - require.Nil(t, err) - require.NotNil(t, bSecret) - require.Equal(t, bSecret, result.Blinding.Bytes()) - } - } - } -} diff --git a/crypto/sharing/v1/ed25519curve.go b/crypto/sharing/v1/ed25519curve.go deleted file mode 100644 index 4576ba3d7..000000000 --- a/crypto/sharing/v1/ed25519curve.go +++ /dev/null @@ -1,147 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/elliptic" - "math/big" - "sync" - - ed "filippo.io/edwards25519" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -var ( - ed25519Initonce sync.Once - ed25519 Ed25519Curve -) - -type Ed25519Curve struct { - *elliptic.CurveParams -} - -func ed25519InitAll() { - // taken from https://datatracker.ietf.org/doc/html/rfc8032 - ed25519.CurveParams = new(elliptic.CurveParams) - ed25519.P, _ = new( - big.Int, - ).SetString("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED", 16) - ed25519.N, _ = new( - big.Int, - ).SetString("1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED", 16) - ed25519.Gx = new(big.Int) - ed25519.Gy = new(big.Int).SetBytes(ed.NewGeneratorPoint().Bytes()) - ed25519.BitSize = 255 - ed25519.Name = "ed25519" -} - -func Ed25519() *Ed25519Curve { - ed25519Initonce.Do(ed25519InitAll) - return &ed25519 -} - -func (curve *Ed25519Curve) Params() *elliptic.CurveParams { - return curve.CurveParams -} - -func (curve *Ed25519Curve) IsOnCurve(x, y *big.Int) bool { - // ignore the x value since Ed25519 is canonical 32 bytes of y according to RFC 8032 - // Set bytes returns an error if not a valid point - _, err := internal.BigInt2Ed25519Point(y) - return err == nil -} - -func (curve *Ed25519Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - var p1, p2 *ed.Point - var err error - if y1.Cmp(big.NewInt(0)) == 0 { - p1 = ed.NewIdentityPoint() - } else { - p1, err = internal.BigInt2Ed25519Point(y1) - } - if err != nil { - panic(err) - } - if y2.Cmp(big.NewInt(0)) == 0 { - p2 = ed.NewIdentityPoint() - } else { - p2, err = internal.BigInt2Ed25519Point(y2) - } - if err != nil { - panic(err) - } - p1.Add(p1, p2) - return new(big.Int), new(big.Int).SetBytes(p1.Bytes()) -} - -func (curve *Ed25519Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - p, err := internal.BigInt2Ed25519Point(y1) - if err != nil { - panic(err) - } - p1, _ := internal.BigInt2Ed25519Point(y1) - p.Add(p, p1) - return new(big.Int), new(big.Int).SetBytes(p.Bytes()) -} - -func (curve *Ed25519Curve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - p, err := internal.BigInt2Ed25519Point(By) - if err != nil { - panic(err) - } - s, err := internal.BigInt2Ed25519Scalar(new(big.Int).SetBytes(k)) - if err != nil { - var t [64]byte - copy(t[:], internal.ReverseScalarBytes(k)) - s, err = ed.NewScalar().SetUniformBytes(t[:]) - if err != nil { - panic(err) - } - } - p.ScalarMult(s, p) - return new(big.Int), new(big.Int).SetBytes(p.Bytes()) -} - -func (curve *Ed25519Curve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - s, err := internal.BigInt2Ed25519Scalar(new(big.Int).SetBytes(k)) - if err != nil { - var t [64]byte - copy(t[:], internal.ReverseScalarBytes(k)) - s, err = ed.NewScalar().SetUniformBytes(t[:]) - if err != nil { - panic(err) - } - } - p := ed.NewIdentityPoint().ScalarBaseMult(s) - return new(big.Int), new(big.Int).SetBytes(p.Bytes()) -} - -func (curve *Ed25519Curve) Neg(Bx, By *big.Int) (*big.Int, *big.Int) { - var p1 *ed.Point - var err error - if By.Cmp(big.NewInt(0)) == 0 { - p1 = ed.NewIdentityPoint() - } else { - p1, err = internal.BigInt2Ed25519Point(By) - if err != nil { - panic(err) - } - } - p1.Negate(p1) - return new(big.Int), new(big.Int).SetBytes(p1.Bytes()) -} - -func (curve *Ed25519Curve) Hash(msg []byte) (*big.Int, *big.Int) { - data := new(curves.PointEd25519).Hash(msg).ToAffineCompressed() - pt, err := ed.NewIdentityPoint().SetBytes(data) - if err != nil { - panic(err) - } - return new(big.Int), new(big.Int).SetBytes(internal.ReverseScalarBytes(pt.Bytes())) -} diff --git a/crypto/sharing/v1/ed25519curve_test.go b/crypto/sharing/v1/ed25519curve_test.go deleted file mode 100755 index d4b94566e..000000000 --- a/crypto/sharing/v1/ed25519curve_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestEd25519ScalarMult(t *testing.T) { - // These values were caught during testing where this combination - // yields leading zeros in which big.Int chops. - // This test makes sure that this case is correctly handled - y := new( - big.Int, - ).SetBytes([]byte{37, 228, 49, 105, 78, 97, 108, 221, 63, 25, 125, 212, 108, 189, 247, 169, 52, 86, 150, 97, 93, 199, 212, 254, 122, 98, 189, 7, 97, 14, 78, 12}) - x := new(big.Int).SetInt64(4) - curve := Ed25519() - require.True(t, curve.IsOnCurve(nil, y)) - _, newY := curve.ScalarMult(nil, y, x.Bytes()) - require.True(t, curve.IsOnCurve(nil, newY)) -} diff --git a/crypto/sharing/v1/feldman.go b/crypto/sharing/v1/feldman.go deleted file mode 100644 index 0d2059a50..000000000 --- a/crypto/sharing/v1/feldman.go +++ /dev/null @@ -1,107 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/elliptic" - "encoding/binary" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Feldman Verifiable Secret Sharing Scheme -type Feldman struct { - threshold, limit uint32 - curve elliptic.Curve -} - -// FeldmanResult contains all the data from calling Split -type FeldmanResult struct { - SecretShares []*ShamirShare - Verifiers []*ShareVerifier -} - -func NewFeldman(threshold, limit uint32, curve elliptic.Curve) (*Feldman, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold must be at least 2") - } - return &Feldman{ - threshold, limit, curve, - }, nil -} - -func (f Feldman) Split(secret []byte) ([]*ShareVerifier, []*ShamirShare, error) { - field := curves.NewField(f.curve.Params().N) - shamir := Shamir{f.threshold, f.limit, field} - shares, poly, err := shamir.GetSharesAndPolynomial(secret) - if err != nil { - return nil, nil, err - } - // Generate the verifiable commitments to the polynomial for the shares - verifiers := make([]*ShareVerifier, len(poly.Coefficients)) - for i, c := range poly.Coefficients { - v, err := curves.NewScalarBaseMult(f.curve, c.Value) - if err != nil { - return nil, nil, err - } - verifiers[i] = v - } - return verifiers, shares, nil -} - -func (f Feldman) Combine(shares ...*ShamirShare) ([]byte, error) { - field := curves.NewField(f.curve.Params().N) - shamir := Shamir{f.threshold, f.limit, field} - return shamir.Combine(shares...) -} - -// Verify checks a share for validity -func (f Feldman) Verify(share *ShamirShare, verifiers []*ShareVerifier) (bool, error) { - if len(verifiers) < int(f.threshold) { - return false, fmt.Errorf("not enough verifiers to check") - } - field := curves.NewField(f.curve.Params().N) - - xBytes := make([]byte, 4) - binary.BigEndian.PutUint32(xBytes, share.Identifier) - x := field.ElementFromBytes(xBytes) - - i := share.Value.Modulus.One() - - // c_0 - rhs := verifiers[0] - - // Compute the sum of products - // c_0 * c_1^i * c_2^{i^2} * c_3^{i^3} ... c_t^{i_t} - for j := 1; j < len(verifiers); j++ { - // i *= x - i = i.Mul(x) - - c, err := verifiers[j].ScalarMult(i.Value) - if err != nil { - return false, err - } - - // ... * c_j^{i^j} - rhs, err = rhs.Add(c) - if err != nil { - return false, err - } - } - - lhs, err := curves.NewScalarBaseMult(f.curve, share.Value.Value) - if err != nil { - return false, err - } - - // Check if lhs == rhs - return lhs.Equals(rhs), nil -} diff --git a/crypto/sharing/v1/k256_feldman_test.go b/crypto/sharing/v1/k256_feldman_test.go deleted file mode 100755 index 326ae511b..000000000 --- a/crypto/sharing/v1/k256_feldman_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" -) - -func TestK256FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, btcec.S256()) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, btcec.S256()) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, btcec.S256()) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestK256FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestK256FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestK256FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestK256FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - - verifiers, shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestK256FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, btcec.S256()) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - verifiers, shares, err := scheme.Split(secret) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/v1/k256_pedersen_test.go b/crypto/sharing/v1/k256_pedersen_test.go deleted file mode 100644 index 8a12158de..000000000 --- a/crypto/sharing/v1/k256_pedersen_test.go +++ /dev/null @@ -1,201 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "math/big" - "testing" - - "github.com/btcsuite/btcd/btcec/v2" - "github.com/stretchr/testify/require" - - core "github.com/sonr-io/sonr/crypto/core/curves" -) - -var ( - k256BasePoint = &core.EcPoint{Curve: btcec.S256(), X: btcec.S256().Gx, Y: btcec.S256().Gy} - testPointK256, _ = core.NewScalarBaseMult(btcec.S256(), big.NewInt(2222)) -) - -func TestK256PedersenSplitInvalidArgs(t *testing.T) { - _, err := NewPedersen(0, 0, nil) - require.NotNil(t, err) - _, err = NewPedersen(3, 2, nil) - require.NotNil(t, err) - _, err = NewPedersen(1, 10, nil) - require.NotNil(t, err) - _, err = NewPedersen(2, 3, nil) - require.NotNil(t, err) - scheme, err := NewPedersen(2, 3, k256BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - // test that split doesn't work on secrets bigger than the modulus - _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestK256PedersenCombineNoShares(t *testing.T) { - scheme, err := NewPedersen(2, 3, k256BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestK256PedersenCombineDuplicateShare(t *testing.T) { - scheme, err := NewPedersen(2, 3, k256BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestK256PedersenCombineBadIdentifier(t *testing.T) { - scheme, err := NewPedersen(2, 3, k256BasePoint) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.Error(t, err) -} - -func TestK256GeneratorFromHashedBytes(t *testing.T) { - x, y, err := K256GeneratorFromHashedBytes( - []byte("Fair is foul, and foul is fair: Hover through the fog and filthy air."), - ) - require.NoError(t, err) - require.NotNil(t, x) - require.NotNil(t, y) - require.True(t, btcec.S256().IsOnCurve(x, y)) -} - -func TestK256PedersenCombineSingle(t *testing.T) { - scheme, err := NewPedersen(2, 3, testPointK256) - require.Nil(t, err) - require.NotNil(t, scheme) - - result, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, result) - for i, s := range result.SecretShares { - ok, err := scheme.Verify(s, result.BlindingShares[i], result.BlindedVerifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(result.SecretShares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestK256PedersenAllCombinations(t *testing.T) { - scheme, err := NewPedersen(3, 5, testPointK256) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - result, err := scheme.Split(secret) - for i, s := range result.SecretShares { - ok, err := scheme.Verify(s, result.BlindingShares[i], result.BlindedVerifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, result) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine( - result.SecretShares[i], - result.SecretShares[j], - result.SecretShares[k], - ) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - - bSecret, err := scheme.Combine( - result.BlindingShares[i], - result.BlindingShares[j], - result.BlindingShares[k], - ) - require.Nil(t, err) - require.NotNil(t, bSecret) - require.Equal(t, bSecret, result.Blinding.Bytes()) - } - } - } -} diff --git a/crypto/sharing/v1/p256_feldman_test.go b/crypto/sharing/v1/p256_feldman_test.go deleted file mode 100755 index 9175e1b69..000000000 --- a/crypto/sharing/v1/p256_feldman_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "crypto/elliptic" - "math/big" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestP256FeldmanSplitInvalidArgs(t *testing.T) { - _, err := NewFeldman(0, 0, elliptic.P256()) - require.NotNil(t, err) - _, err = NewFeldman(3, 2, elliptic.P256()) - require.NotNil(t, err) - _, err = NewFeldman(1, 10, elliptic.P256()) - require.NotNil(t, err) - scheme, err := NewFeldman(2, 3, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestP256FeldmanCombineNoShares(t *testing.T) { - scheme, err := NewFeldman(2, 3, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestP256FeldmanCombineDuplicateShare(t *testing.T) { - scheme, err := NewFeldman(2, 3, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestP256FeldmanCombineBadIdentifier(t *testing.T) { - scheme, err := NewFeldman(2, 3, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestP256FeldmanCombineSingle(t *testing.T) { - scheme, err := NewFeldman(2, 3, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - - verifiers, shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -func TestP256FeldmanAllCombinations(t *testing.T) { - scheme, err := NewFeldman(3, 5, elliptic.P256()) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - verifiers, shares, err := scheme.Split(secret) - for _, s := range shares { - ok, err := scheme.Verify(s, verifiers) - require.Nil(t, err) - require.True(t, ok) - } - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} diff --git a/crypto/sharing/v1/pedersen.go b/crypto/sharing/v1/pedersen.go deleted file mode 100644 index 5a9c20268..000000000 --- a/crypto/sharing/v1/pedersen.go +++ /dev/null @@ -1,178 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - crand "crypto/rand" - "encoding/binary" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Pedersen Verifiable Secret Sharing Scheme -type Pedersen struct { - threshold, limit uint32 - generator *curves.EcPoint -} - -// PedersenResult contains all the data from calling Split -type PedersenResult struct { - Blinding *big.Int - BlindingShares, SecretShares []*ShamirShare - BlindedVerifiers []*ShareVerifier - Verifiers []*ShareVerifier -} - -// NewPedersen creates a new pedersen VSS -func NewPedersen(threshold, limit uint32, generator *curves.EcPoint) (*Pedersen, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold must be at least 2") - } - - if generator == nil { - return nil, internal.ErrNilArguments - } - if generator.IsIdentity() { - return nil, fmt.Errorf("generator point cannot be at infinity") - } - if !generator.IsOnCurve() { - return nil, fmt.Errorf("generator point must be on the curve") - } - - return &Pedersen{ - threshold, limit, generator, - }, nil -} - -// Split creates the verifiers, blinding and shares -func (pd Pedersen) Split(secret []byte) (*PedersenResult, error) { - // generate a random blinding factor - blinding, err := crand.Int(crand.Reader, pd.generator.Curve.Params().N) - if err != nil { - return nil, err - } - - field := curves.NewField(pd.generator.Curve.Params().N) - shamir := Shamir{pd.threshold, pd.limit, field} - // split the secret into shares - shares, polySecret, err := shamir.GetSharesAndPolynomial(secret) - if err != nil { - return nil, err - } - - // split the blinding into shares - blindingShares, polyBlinding, err := shamir.GetSharesAndPolynomial(blinding.Bytes()) - if err != nil { - return nil, err - } - - // Generate the verifiable commitments to the polynomial for the shares - blindedverifiers := make([]*ShareVerifier, pd.threshold) - verifiers := make([]*ShareVerifier, pd.threshold) - - // ({p0 * G + b0 * H}, ...,{pt * G + bt * H}) - for i, c := range polySecret.Coefficients { - s, err := curves.NewScalarBaseMult(pd.generator.Curve, c.Value) - if err != nil { - return nil, err - } - b, err := pd.generator.ScalarMult(polyBlinding.Coefficients[i].Value) - if err != nil { - return nil, err - } - - bv, err := s.Add(b) - if err != nil { - return nil, err - } - - blindedverifiers[i] = bv - verifiers[i] = s - } - return &PedersenResult{ - blinding, blindingShares, shares, blindedverifiers, verifiers, - }, nil -} - -// Combine recreates the original secret from the shares -func (pd Pedersen) Combine(shares ...*ShamirShare) ([]byte, error) { - field := curves.NewField(pd.generator.Curve.Params().N) - shamir := Shamir{pd.threshold, pd.limit, field} - return shamir.Combine(shares...) -} - -// Verify checks a share for validity -func (pd Pedersen) Verify( - share *ShamirShare, - blinding *ShamirShare, - blindedverifiers []*ShareVerifier, -) (bool, error) { - if len(blindedverifiers) < int(pd.threshold) { - return false, fmt.Errorf("not enough blindedverifiers to check") - } - field := curves.NewField(pd.generator.Curve.Params().N) - - xBytes := make([]byte, 4) - binary.BigEndian.PutUint32(xBytes, share.Identifier) - x := field.ElementFromBytes(xBytes) - - i := share.Value.Modulus.One() - - // c_0 - rhs := blindedverifiers[0] - - // Compute the sum of products - // c_0 * c_1^i * c_2^{i^2} * c_3^{i^3} ... c_t^{i_t} - for j := 1; j < len(blindedverifiers); j++ { - // i *= x - i = i.Mul(x) - - c, err := blindedverifiers[j].ScalarMult(i.Value) - if err != nil { - return false, err - } - - // ... * c_j^{i^j} - rhs, err = rhs.Add(c) - if err != nil { - return false, err - } - } - - lhs, err := curves.NewScalarBaseMult(pd.generator.Curve, share.Value.Value) - if err != nil { - return false, err - } - tmp, err := pd.generator.ScalarMult(blinding.Value.Value) - if err != nil { - return false, err - } - lhs, err = lhs.Add(tmp) - if err != nil { - return false, err - } - - // Check if lhs == rhs - return lhs.Equals(rhs), nil -} - -// K256GeneratorFromHashedBytes computes a generator whose discrete log is unknown -// from a bytes sequence -func K256GeneratorFromHashedBytes(bytes []byte) (x, y *big.Int, err error) { - pt := new(curves.PointK256).Hash(bytes) - p, _ := pt.(*curves.PointK256) - x = p.X().BigInt() - y = p.Y().BigInt() - err = nil - return x, y, err -} diff --git a/crypto/sharing/v1/polynomial.go b/crypto/sharing/v1/polynomial.go deleted file mode 100644 index 09f2326c7..000000000 --- a/crypto/sharing/v1/polynomial.go +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type polynomial struct { - Coefficients []*curves.Element -} - -// newPoly creates a random polynomial of the given degree but with the provided intercept value -func newPoly(intercept *curves.Element, degree uint32) (polynomial, error) { - p := polynomial{ - Coefficients: make([]*curves.Element, degree), - } - - // Intercept is the value to be split - p.Coefficients[0] = intercept - - // random coefficients - for i := uint32(1); i < degree; i++ { - c, err := intercept.Field().RandomElement(nil) - if err != nil { - return p, err - } - p.Coefficients[i] = c - } - - return p, nil -} - -// evaluate returns the value of the polynomial for the given x -func (p polynomial) evaluate(x *curves.Element) *curves.Element { - // Compute the polynomial value using Horner's Method - - degree := len(p.Coefficients) - 1 - result := p.Coefficients[degree].Clone() - for i := degree - 1; i >= 0; i-- { - result = result.Mul(x).Add(p.Coefficients[i]) - } - - return result -} diff --git a/crypto/sharing/v1/polynomial_test.go b/crypto/sharing/v1/polynomial_test.go deleted file mode 100755 index f94dc76ed..000000000 --- a/crypto/sharing/v1/polynomial_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Copyright Coinbase, Inc. All Rights Reserved. -// -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestNewPoly(t *testing.T) { - secret := field.ElementFromBytes([]byte("test")) - - poly, err := newPoly(secret, 4) - require.Nil(t, err) - require.NotNil(t, poly) - - require.Equal(t, poly.Coefficients[0], secret) -} diff --git a/crypto/sharing/v1/shamir.go b/crypto/sharing/v1/shamir.go deleted file mode 100644 index 62de4a928..000000000 --- a/crypto/sharing/v1/shamir.go +++ /dev/null @@ -1,214 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "encoding/binary" - "fmt" - "math/big" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// ShamirShare is the data from splitting a secret -type ShamirShare struct { - // x-coordinate - Identifier uint32 `json:"identifier"` - // y-coordinate - Value *curves.Element `json:"value"` -} - -// NewShamirShare creates a ShamirShare given the Identifier, value, and Field for the value -func NewShamirShare(x uint32, y []byte, f *curves.Field) *ShamirShare { - return &ShamirShare{ - Identifier: x, - Value: f.ElementFromBytes(y), - } -} - -// Bytes returns the representation of the share in bytes with the identifier as the first -// 4 bytes -func (s ShamirShare) Bytes() []byte { - a := make([]byte, 4) - binary.BigEndian.PutUint32(a, s.Identifier) - a = append(a, s.Value.Bytes()...) - return a -} - -// Add returns the sum of two Shamir shares -func (s ShamirShare) Add(other *ShamirShare) *ShamirShare { - if s.Identifier != other.Identifier { - panic("identifiers must match for valid addition") - } - newSecret := s.Value.Add(other.Value) - return NewShamirShare(s.Identifier, newSecret.Bytes(), s.Value.Field()) -} - -// Shamir is the Shamir secret sharing scheme -type Shamir struct { - threshold, limit uint32 - field *curves.Field -} - -// NewShamir creates a Shamir secret sharing scheme -func NewShamir(threshold, limit int, field *curves.Field) (*Shamir, error) { - if limit < threshold { - return nil, fmt.Errorf("limit cannot be less than threshold") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold must be at least 2") - } - return &Shamir{ - uint32(threshold), uint32(limit), field, - }, nil -} - -// Split takes a secret and splits it into multiple shares that requires -// threshold to reconstruct -func (s *Shamir) Split(secret []byte) ([]*ShamirShare, error) { - shares, _, err := s.GetSharesAndPolynomial(secret) - return shares, err -} - -// Combine takes any number of shares and tries to combine them into the original secret -func (s *Shamir) Combine(shares ...*ShamirShare) ([]byte, error) { - if len(shares) < int(s.threshold) { - return nil, fmt.Errorf("not enough shares to combine") - } - - dups := make(map[uint32]bool) - xCoordinates := make([]*curves.Element, s.threshold) - yCoordinates := make([]*curves.Element, s.threshold) - - for i := 0; i < int(s.threshold); i++ { - r := shares[i] - if r.Identifier > s.limit || r.Identifier < 1 { - return nil, fmt.Errorf("invalid share identifier") - } - if _, ok := dups[r.Identifier]; ok { - return nil, fmt.Errorf("duplicate shares cannot be used") - } - - xBytes := make([]byte, 4) - binary.BigEndian.PutUint32(xBytes, r.Identifier) - xCoordinates[i] = s.field.ElementFromBytes(xBytes) - yCoordinates[i] = r.Value - } - - secret, err := s.Interpolate(xCoordinates, yCoordinates) - if err != nil { - return nil, err - } - return secret.Bytes(), nil -} - -// getSharesAndPolynomial returns the shares for the specified secret and the polynomial -// used to create the shares -func (s *Shamir) GetSharesAndPolynomial(secret []byte) ([]*ShamirShare, *polynomial, error) { - if len(secret) == 0 { - return nil, nil, fmt.Errorf("cannot split an empty secret") - } - intSecret := new(big.Int).SetBytes(secret) - if !s.field.IsValid(intSecret) { - return nil, nil, fmt.Errorf("secret is too large") - } - - elemSecret := s.field.NewElement(intSecret) - poly, err := newPoly(elemSecret, s.threshold) - if err != nil { - return nil, nil, fmt.Errorf("failed to generate polynomial: %w", err) - } - - shares := make([]*ShamirShare, s.limit) - for i := uint32(0); i < s.limit; i++ { - x := s.field.NewElement(big.NewInt(int64(i + 1))) - y := poly.evaluate(x) - shares[i] = &ShamirShare{ - Identifier: i + 1, - Value: y, - } - } - return shares, &poly, nil -} - -// interpolate calculates the lagrange interpolation -func (s *Shamir) Interpolate( - xCoordinates, yCoordinates []*curves.Element, -) (*curves.Element, error) { - if len(xCoordinates) < int(s.threshold) || - len(yCoordinates) < int(s.threshold) { - return nil, fmt.Errorf("not enough points") - } - - zero := xCoordinates[0].Field().Zero() - result := yCoordinates[0].Field().Zero() - - for i := 0; i < int(s.threshold); i++ { - basis := xCoordinates[0].Field().One() - for j := 0; j < int(s.threshold); j++ { - if i == j { - continue - } - - // x_m - x_j - denom := xCoordinates[j].Sub(xCoordinates[i]) - if denom.IsEqual(zero) { - return nil, fmt.Errorf("invalid x coordinates") - } - // x_m / x_m - x_j - basis = basis.Mul(xCoordinates[j].Div(denom)) - } - - result = result.Add(yCoordinates[i].Mul(basis)) - } - - return result, nil -} - -// ComputeL is a function that computes all Lagrange coefficients. -// This function is particularly needed in FROST tSchnorr signature. -func (s Shamir) ComputeL(shares ...*ShamirShare) ([]*curves.Element, error) { - if len(shares) < int(s.threshold) { - return nil, fmt.Errorf("not enough shares to compute Lagrange coefficients") - } - dups := make(map[uint32]bool) - xCoordinates := make([]*curves.Element, s.threshold) - for i := 0; i < int(s.threshold); i++ { - r := shares[i] - if r.Identifier > s.limit || r.Identifier < 1 { - return nil, fmt.Errorf("ComputeL: invalid share identifier") - } - if _, ok := dups[r.Identifier]; ok { - return nil, fmt.Errorf("ComputeL: duplicate shares cannot be used") - } - - xBytes := make([]byte, 4) - binary.BigEndian.PutUint32(xBytes, r.Identifier) - xCoordinates[i] = s.field.ElementFromBytes(xBytes) - } - - zero := xCoordinates[0].Field().Zero() - result := make([]*curves.Element, s.threshold) - - for i := 0; i < int(s.threshold); i++ { - basis := xCoordinates[0].Field().One() - for j := 0; j < int(s.threshold); j++ { - if i == j { - continue - } - // x_m - x_j - denom := xCoordinates[j].Sub(xCoordinates[i]) - if denom.IsEqual(zero) { - return nil, fmt.Errorf("invalid x coordinates") - } - // x_m / x_m - x_j - basis = basis.Mul(xCoordinates[j].Div(denom)) - } - result[i] = basis - } - return result, nil -} diff --git a/crypto/sharing/v1/shamir_test.go b/crypto/sharing/v1/shamir_test.go deleted file mode 100644 index 962569fd5..000000000 --- a/crypto/sharing/v1/shamir_test.go +++ /dev/null @@ -1,241 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package v1 - -import ( - "encoding/json" - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestShamirSplitInvalidArgs(t *testing.T) { - _, err := NewShamir(0, 0, field) - require.NotNil(t, err) - _, err = NewShamir(3, 2, field) - require.NotNil(t, err) - _, err = NewShamir(1, 10, field) - require.NotNil(t, err) - scheme, err := NewShamir(2, 3, field) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Split([]byte{}) - require.NotNil(t, err) - _, err = scheme.Split( - []byte{ - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - 0x65, - }, - ) - require.NotNil(t, err) -} - -func TestShamirCombineNoShares(t *testing.T) { - scheme, err := NewShamir(2, 3, field) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine() - require.NotNil(t, err) -} - -func TestShamirCombineDuplicateShare(t *testing.T) { - scheme, err := NewShamir(2, 3, field) - require.Nil(t, err) - require.NotNil(t, scheme) - _, err = scheme.Combine([]*ShamirShare{ - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 1, - Value: field.NewElement(big.NewInt(3)), - }, - }...) - require.NotNil(t, err) -} - -func TestShamirCombineBadIdentifier(t *testing.T) { - scheme, err := NewShamir(2, 3, field) - require.Nil(t, err) - require.NotNil(t, scheme) - shares := []*ShamirShare{ - { - Identifier: 0, - Value: field.NewElement(big.NewInt(3)), - }, - { - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - }, - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) - shares[0] = &ShamirShare{ - Identifier: 4, - Value: field.NewElement(big.NewInt(3)), - } - _, err = scheme.Combine(shares...) - require.NotNil(t, err) -} - -func TestShamirCombineSingle(t *testing.T) { - scheme, err := NewShamir(2, 3, field) - require.Nil(t, err) - require.NotNil(t, scheme) - - shares, err := scheme.Split([]byte("test")) - require.Nil(t, err) - require.NotNil(t, shares) - secret, err := scheme.Combine(shares...) - require.Nil(t, err) - require.Equal(t, secret, []byte("test")) -} - -// Test ComputeL function to compute Lagrange coefficients. -func TestShamirComputeL(t *testing.T) { - scheme, err := NewShamir(2, 2, field) - require.Nil(t, err) - require.NotNil(t, scheme) - secret := []byte("test") - shares, err := scheme.Split(secret) - require.Nil(t, err) - require.NotNil(t, shares) - lCoeffs, err := scheme.ComputeL(shares[0], shares[1]) - require.Nil(t, err) - require.NotNil(t, lCoeffs) - - // Checking we can reconstruct the same secret using Lagrange coefficients. - inputShares := [2]*ShamirShare{shares[0], shares[1]} - yCoordinates := make([]*curves.Element, 2) - for i := 0; i < 2; i++ { - r := inputShares[i] - yCoordinates[i] = r.Value - } - result := yCoordinates[0].Field().Zero() - for i := 0; i < 2; i++ { - result = result.Add(yCoordinates[i].Mul(lCoeffs[i])) - } - require.Equal(t, result.Bytes(), secret) -} - -func TestShamirAllCombinations(t *testing.T) { - scheme, err := NewShamir(3, 5, field) - require.Nil(t, err) - require.NotNil(t, scheme) - - secret := []byte("test") - shares, err := scheme.Split(secret) - require.Nil(t, err) - require.NotNil(t, shares) - // There are 5*4*3 possible combinations - for i := 0; i < 5; i++ { - for j := 0; j < 5; j++ { - if i == j { - continue - } - for k := 0; k < 5; k++ { - if i == k || j == k { - continue - } - - rSecret, err := scheme.Combine(shares[i], shares[j], shares[k]) - require.Nil(t, err) - require.NotNil(t, rSecret) - require.Equal(t, rSecret, secret) - } - } - } -} - -// Ensures that ShamirShare's un/marshal successfully. -func TestMarshalJsonRoundTrip(t *testing.T) { - oneBelowModulus := new(big.Int).Sub(modulus, big.NewInt(1)) - shares := []ShamirShare{ - {0, field.NewElement(big.NewInt(300))}, - {2, field.NewElement(big.NewInt(300000))}, - {20, field.NewElement(big.NewInt(12812798))}, - {31, field.NewElement(big.NewInt(17))}, - {57, field.NewElement(big.NewInt(5066680))}, - {128, field.NewElement(big.NewInt(3005))}, - {19, field.NewElement(big.NewInt(317))}, - {7, field.NewElement(big.NewInt(323))}, - {222, field.NewElement(oneBelowModulus)}, - } - // Run all the tests! - for _, in := range shares { - bytes, err := json.Marshal(in) - require.NoError(t, err) - require.NotNil(t, bytes) - - // Unmarshal and test - out := &ShamirShare{} - err = json.Unmarshal(bytes, &out) - require.NoError(t, err) - require.Equal(t, in.Identifier, out.Identifier) - require.Equal(t, in.Value.Value.Bytes(), out.Value.Value.Bytes()) - } -} - -func TestSharesAdd(t *testing.T) { - finiteField := curves.NewField(big.NewInt(7)) - one := NewShamirShare(0, []byte{0x01}, finiteField) - two := NewShamirShare(0, []byte{0x02}, finiteField) - - // basic addition - sum := one.Add(two) - require.Equal(t, uint32(0), sum.Identifier) - require.Equal(t, []byte{0x03}, sum.Value.Bytes()) - - // addition is performed within the globalField - sum = two.Add(NewShamirShare(0, []byte{0x06}, finiteField)) - require.Equal(t, uint32(0), sum.Identifier) - require.Equal(t, []byte{0x01}, sum.Value.Bytes()) -} - -func TestSharesAdd_errors(t *testing.T) { - finiteField := curves.NewField(big.NewInt(7)) - one := NewShamirShare(0, []byte{0x01}, finiteField) - two := NewShamirShare(1, []byte{0x02}, finiteField) - require.PanicsWithValue(t, "identifiers must match for valid addition", func() { - one.Add(two) - }) -} diff --git a/crypto/signatures/bbs/blind_signature.go b/crypto/signatures/bbs/blind_signature.go deleted file mode 100644 index 5fdbf505f..000000000 --- a/crypto/signatures/bbs/blind_signature.go +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "errors" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/signatures/common" -) - -// BlindSignature is a BBS+ blind signature -// structurally identical to `Signature` but -// is used to help avoid misuse and confusion. -// -// 1 or more message have been hidden by the -// potential signature holder so the signer -// only knows a subset of the messages to be signed -type BlindSignature struct { - a curves.PairingPoint - e, s curves.Scalar -} - -// Init creates an empty signature to a specific curve -// which should be followed by UnmarshalBinary -func (sig *BlindSignature) Init(curve *curves.PairingCurve) *BlindSignature { - sig.a = curve.NewG1IdentityPoint() - sig.e = curve.NewScalar() - sig.s = curve.NewScalar() - return sig -} - -func (sig BlindSignature) MarshalBinary() ([]byte, error) { - out := append(sig.a.ToAffineCompressed(), sig.e.Bytes()...) - out = append(out, sig.s.Bytes()...) - return out, nil -} - -func (sig *BlindSignature) UnmarshalBinary(data []byte) error { - pointLength := len(sig.a.ToAffineCompressed()) - scalarLength := len(sig.s.Bytes()) - expectedLength := pointLength + scalarLength*2 - if len(data) != expectedLength { - return fmt.Errorf("invalid byte sequence") - } - a, err := sig.a.FromAffineCompressed(data[:pointLength]) - if err != nil { - return err - } - e, err := sig.e.SetBytes(data[pointLength:(pointLength + scalarLength)]) - if err != nil { - return err - } - s, err := sig.s.SetBytes(data[(pointLength + scalarLength):]) - if err != nil { - return err - } - var ok bool - sig.a, ok = a.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - sig.e = e - sig.s = s - return nil -} - -func (sig BlindSignature) ToUnblinded(blinder common.SignatureBlinding) *Signature { - return &Signature{ - a: sig.a, - e: sig.e, - s: sig.s.Add(blinder), - } -} diff --git a/crypto/signatures/bbs/blind_signature_context.go b/crypto/signatures/bbs/blind_signature_context.go deleted file mode 100644 index 19d6a772b..000000000 --- a/crypto/signatures/bbs/blind_signature_context.go +++ /dev/null @@ -1,271 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "fmt" - "io" - "sort" - - "github.com/gtank/merlin" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/signatures/common" -) - -// BlindSignatureContext contains the data used for computing -// a blind signature and verifying proof of hidden messages from -// a future signature holder. A potential holder commits to messages -// that the signer will not know during the signing process -// rendering them hidden, but requires the holder to -// prove knowledge of those messages so a malicious party -// doesn't add just random data from anywhere. -type BlindSignatureContext struct { - // The blinded signature commitment - commitment common.Commitment - // The challenge hash for the Fiat-Shamir heuristic - challenge curves.Scalar - // The proofs of hidden messages. - proofs []curves.Scalar -} - -// NewBlindSignatureContext creates the data needed to -// send to a signer to complete a blinded signature -// `msgs` is an index to message map where the index -// corresponds to the index in `generators` -// msgs are hidden from the signer but can also be empty -// if no messages are hidden but a blind signature is still desired -// because the signer should have no knowledge of the signature -func NewBlindSignatureContext( - curve *curves.PairingCurve, - msgs map[int]curves.Scalar, - generators *MessageGenerators, - nonce common.Nonce, - reader io.Reader, -) (*BlindSignatureContext, common.SignatureBlinding, error) { - if curve == nil || generators == nil || nonce == nil || reader == nil { - return nil, nil, internal.ErrNilArguments - } - points := make([]curves.Point, 0) - secrets := make([]curves.Scalar, 0) - - committing := common.NewProofCommittedBuilder(&curves.Curve{ - Scalar: curve.Scalar, - Point: curve.Scalar.Point().(curves.PairingPoint).OtherGroup(), - Name: curve.Name, - }) - - // C = h0^blinding_factor*h_i^m_i..... - for i, m := range msgs { - if i > generators.length || i < 0 { - return nil, nil, fmt.Errorf("invalid index") - } - secrets = append(secrets, m) - pt := generators.Get(i + 1) - points = append(points, pt) - err := committing.CommitRandom(pt, reader) - if err != nil { - return nil, nil, err - } - } - blinding, ok := curve.Scalar.Random(reader).(common.SignatureBlinding) - if !ok { - return nil, nil, fmt.Errorf("unable to create signature blinding") - } - secrets = append(secrets, blinding) - - h0 := generators.Get(0) - points = append(points, h0) - err := committing.CommitRandom(h0, reader) - if err != nil { - return nil, nil, err - } - - // Create a random commitment, compute challenges and response. - // The proof of knowledge consists of a commitment and responses - // Holder and signer engage in a proof of knowledge for `commitment` - commitment := curve.Scalar.Point().(curves.PairingPoint).OtherGroup(). - SumOfProducts(points, secrets) - transcript := merlin.NewTranscript("new blind signature") - transcript.AppendMessage([]byte("random commitment"), committing.GetChallengeContribution()) - transcript.AppendMessage([]byte("blind commitment"), commitment.ToAffineCompressed()) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("blind signature context challenge"), 64) - challenge, err := curve.Scalar.SetBytesWide(okm) - if err != nil { - return nil, nil, err - } - proofs, err := committing.GenerateProof(challenge, secrets) - if err != nil { - return nil, nil, err - } - return &BlindSignatureContext{ - commitment: commitment, - challenge: challenge, - proofs: proofs, - }, blinding, nil -} - -func (bsc *BlindSignatureContext) Init(curve *curves.PairingCurve) *BlindSignatureContext { - bsc.challenge = curve.NewScalar() - bsc.commitment = curve.Scalar.Point().(curves.PairingPoint).OtherGroup() - bsc.proofs = make([]curves.Scalar, 0) - return bsc -} - -// MarshalBinary store the generators as a sequence of bytes -// where each point is compressed. -// Needs (N + 1) * ScalarSize + PointSize -func (bsc BlindSignatureContext) MarshalBinary() ([]byte, error) { - buffer := append(bsc.commitment.ToAffineCompressed(), bsc.challenge.Bytes()...) - for _, p := range bsc.proofs { - buffer = append(buffer, p.Bytes()...) - } - return buffer, nil -} - -func (bsc *BlindSignatureContext) UnmarshalBinary(in []byte) error { - scSize := len(bsc.challenge.Bytes()) - ptSize := len(bsc.commitment.ToAffineCompressed()) - if len(in) < scSize*2+ptSize { - return fmt.Errorf("insufficient number of bytes") - } - - if (len(in)-ptSize)%scSize != 0 { - return fmt.Errorf("invalid byte sequence") - } - commitment, err := bsc.commitment.FromAffineCompressed(in[:ptSize]) - if err != nil { - return err - } - challenge, err := bsc.challenge.SetBytes(in[ptSize:(ptSize + scSize)]) - if err != nil { - return err - } - - nProofs := ((len(in) - ptSize) / scSize) - 1 - proofs := make([]curves.Scalar, nProofs) - for i := 0; i < nProofs; i++ { - proofs[i], err = bsc.challenge.SetBytes(in[(ptSize + (i+1)*scSize):(ptSize + (i+2)*scSize)]) - if err != nil { - return err - } - } - bsc.commitment = commitment - bsc.challenge = challenge - bsc.proofs = proofs - return nil -} - -// Verify validates a proof of hidden messages -func (bsc BlindSignatureContext) Verify( - knownMsgs []int, - generators *MessageGenerators, - nonce common.Nonce, -) error { - known := make(map[int]bool, len(knownMsgs)) - for _, i := range knownMsgs { - if i > generators.length { - return fmt.Errorf("invalid message index") - } - known[i] = true - } - - points := make([]curves.Point, 0) - for i := 0; i < generators.length; i++ { - if _, contains := known[i]; !contains { - points = append(points, generators.Get(i+1)) - } - } - points = append(points, generators.Get(0), bsc.commitment) - scalars := append(bsc.proofs, bsc.challenge.Neg()) - - commitment := points[0].SumOfProducts(points, scalars) - transcript := merlin.NewTranscript("new blind signature") - transcript.AppendMessage([]byte("random commitment"), commitment.ToAffineCompressed()) - transcript.AppendMessage([]byte("blind commitment"), bsc.commitment.ToAffineCompressed()) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("blind signature context challenge"), 64) - challenge, err := bsc.challenge.SetBytesWide(okm) - if err != nil { - return err - } - - if challenge.Cmp(bsc.challenge) != 0 { - return fmt.Errorf("invalid proof") - } - return nil -} - -// ToBlindSignature converts a blind signature where -// msgs are known to the signer -// `msgs` is an index to message map where the index -// corresponds to the index in `generators` -func (bsc BlindSignatureContext) ToBlindSignature( - msgs map[int]curves.Scalar, - sk *SecretKey, - generators *MessageGenerators, - nonce common.Nonce, -) (*BlindSignature, error) { - if sk == nil || generators == nil || nonce == nil { - return nil, internal.ErrNilArguments - } - if sk.value.IsZero() { - return nil, fmt.Errorf("invalid secret key") - } - tv1 := make([]int, 0, len(msgs)) - for i := range msgs { - if i > generators.length { - return nil, fmt.Errorf("not enough message generators") - } - tv1 = append(tv1, i) - } - sort.Ints(tv1) - signingMsgs := make([]curves.Scalar, len(msgs)) - for i, index := range tv1 { - signingMsgs[i] = msgs[index] - } - err := bsc.Verify(tv1, generators, nonce) - if err != nil { - return nil, err - } - - drbg := sha3.NewShake256() - _, _ = drbg.Write(sk.value.Bytes()) - addDeterministicNonceData(generators, signingMsgs, drbg) - // Should yield non-zero values for `e` and `s`, very small likelihood of being zero - e := getNonZeroScalar(sk.value, drbg) - s := getNonZeroScalar(sk.value, drbg) - - exp, err := e.Add(sk.value).Invert() - if err != nil { - return nil, err - } - // B = g1+h_0^s+h_1^m_1... - points := make([]curves.Point, len(msgs)+3) - scalars := make([]curves.Scalar, len(msgs)+3) - points[0] = bsc.commitment - points[1] = bsc.commitment.Generator() - points[2] = generators.Get(0) - scalars[0] = sk.value.One() - scalars[1] = sk.value.One() - scalars[2] = s - i := 3 - for idx, m := range msgs { - points[i] = generators.Get(idx + 1) - scalars[i] = m - i++ - } - b := bsc.commitment.SumOfProducts(points, scalars) - return &BlindSignature{ - a: b.Mul(exp).(curves.PairingPoint), - e: e, - s: s, - }, nil -} diff --git a/crypto/signatures/bbs/blind_signature_context_test.go b/crypto/signatures/bbs/blind_signature_context_test.go deleted file mode 100644 index 60e8c4183..000000000 --- a/crypto/signatures/bbs/blind_signature_context_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - crand "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestBlindSignatureContext(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, pk) - require.NotNil(t, sk) - - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - nonce := curve.Scalar.Random(crand.Reader) - msgs := make(map[int]curves.Scalar, 1) - msgs[0] = curve.Scalar.Hash([]byte("identifier")) - - ctx, blinding, err := NewBlindSignatureContext(curve, msgs, generators, nonce, crand.Reader) - require.NoError(t, err) - require.NotNil(t, blinding) - require.False(t, blinding.IsZero()) - require.NotNil(t, ctx) - require.False(t, ctx.commitment.IsIdentity()) - require.False(t, ctx.challenge.IsZero()) - for _, p := range ctx.proofs { - require.False(t, p.IsZero()) - } - - delete(msgs, 0) - msgs[1] = curve.Scalar.Hash([]byte("firstname")) - msgs[2] = curve.Scalar.Hash([]byte("lastname")) - msgs[3] = curve.Scalar.Hash([]byte("age")) - blindSig, err := ctx.ToBlindSignature(msgs, sk, generators, nonce) - require.NoError(t, err) - require.NotNil(t, blindSig) - require.False(t, blindSig.a.IsIdentity()) - require.False(t, blindSig.e.IsZero()) - require.False(t, blindSig.s.IsZero()) - sig := blindSig.ToUnblinded(blinding) - msgs[0] = curve.Scalar.Hash([]byte("identifier")) - var sigMsgs [4]curves.Scalar - for i := 0; i < 4; i++ { - sigMsgs[i] = msgs[i] - } - err = pk.Verify(sig, generators, sigMsgs[:]) - require.NoError(t, err) -} - -func TestBlindSignatureContextMarshalBinary(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, pk) - require.NotNil(t, sk) - - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - nonce := curve.Scalar.Random(crand.Reader) - msgs := make(map[int]curves.Scalar, 1) - msgs[0] = curve.Scalar.Hash([]byte("identifier")) - - ctx, blinding, err := NewBlindSignatureContext(curve, msgs, generators, nonce, crand.Reader) - require.NoError(t, err) - require.NotNil(t, blinding) - require.False(t, blinding.IsZero()) - require.NotNil(t, ctx) - require.False(t, ctx.commitment.IsIdentity()) - require.False(t, ctx.challenge.IsZero()) - for _, p := range ctx.proofs { - require.False(t, p.IsZero()) - } - - data, err := ctx.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, data) - ctx2 := new(BlindSignatureContext).Init(curve) - err = ctx2.UnmarshalBinary(data) - require.NoError(t, err) - require.Equal(t, ctx.challenge.Cmp(ctx2.challenge), 0) - require.True(t, ctx.commitment.Equal(ctx2.commitment)) - require.Equal(t, len(ctx.proofs), len(ctx2.proofs)) - for i, p := range ctx.proofs { - require.Equal(t, p.Cmp(ctx2.proofs[i]), 0) - } -} diff --git a/crypto/signatures/bbs/message_generators.go b/crypto/signatures/bbs/message_generators.go deleted file mode 100644 index 8723dc447..000000000 --- a/crypto/signatures/bbs/message_generators.go +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "errors" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// MessageGenerators are used to sign a vector of commitments for -// a BBS+ signature. These must be the same generators used by -// sign, verify, prove, and open -// -// These are generated in a deterministic manner. By using -// MessageGenerators in this way, the generators do not need to be -// stored alongside the public key and the same key can be used to sign -// an arbitrary number of messages -// Generators are created by computing -// H_i = H_G1(W || I2OSP(0, 4) || I2OSP(0, 1) || I2OSP(length, 4)) -// where I2OSP means Integer to Octet Stream Primitive and -// I2OSP represents an integer in a statically sized byte array. -// `W` is the BBS+ public key. -// Internally we store the 201 byte state since the only value that changes -// is the index -type MessageGenerators struct { - // Blinding factor generator, stored, so we know what points to return in `Get` - h0 curves.PairingPoint - length int - state [201]byte -} - -// Init set the message generators to the default state -func (msgg *MessageGenerators) Init(w *PublicKey, length int) (*MessageGenerators, error) { - if length < 0 { - return nil, errors.New("length should be nonnegative") - } - msgg.length = length - for i := range msgg.state { - msgg.state[i] = 0 - } - copy(msgg.state[:192], w.value.ToAffineUncompressed()) - msgg.state[197] = byte(length >> 24) - msgg.state[198] = byte(length >> 16) - msgg.state[199] = byte(length >> 8) - msgg.state[200] = byte(length) - var ok bool - msgg.h0, ok = w.value.OtherGroup().Hash(msgg.state[:]).(curves.PairingPoint) - if !ok { - return nil, errors.New("incorrect type conversion") - } - - return msgg, nil -} - -func (msgg MessageGenerators) Get(i int) curves.PairingPoint { - if i <= 0 { - return msgg.h0 - } - if i > msgg.length { - return nil - } - state := msgg.state - state[193] = byte(i >> 24) - state[194] = byte(i >> 16) - state[195] = byte(i >> 8) - state[196] = byte(i) - point, ok := msgg.h0.Hash(msgg.state[:]).(curves.PairingPoint) - if !ok { - return nil - } - return point -} diff --git a/crypto/signatures/bbs/pok_signature.go b/crypto/signatures/bbs/pok_signature.go deleted file mode 100644 index 7009080ee..000000000 --- a/crypto/signatures/bbs/pok_signature.go +++ /dev/null @@ -1,159 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "fmt" - "io" - - "github.com/gtank/merlin" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/signatures/common" -) - -// PokSignature a.k.a. Proof of Knowledge of a Signature -// is used by the prover to convince a verifier -// that they possess a valid signature and -// can selectively disclose a set of signed messages -type PokSignature struct { - // These values correspond to values with the same name - // as section 4.5 in - aPrime, aBar, d curves.PairingPoint - // proof1 for proving signature - // proof2 for selective disclosure - proof1, proof2 *common.ProofCommittedBuilder - // secrets1 for proving signature - // secrets2 for proving relation - // g1 * h1^m1 * h2^m2.... for all disclosed messages - // m_i == d^r3 * h_0^{-s_prime} * h1^-m1 * h2^-m2.... for all undisclosed messages m_i - secrets1, secrets2 []curves.Scalar -} - -// NewPokSignature creates the initial proof data before a Fiat-Shamir calculation -func NewPokSignature(sig *Signature, - generators *MessageGenerators, - msgs []common.ProofMessage, - reader io.Reader, -) (*PokSignature, error) { - if len(msgs) != generators.length { - return nil, fmt.Errorf("mismatch messages and generators") - } - - r1 := getNonZeroScalar(sig.s, reader) - r2 := getNonZeroScalar(sig.s, reader) - r3, err := r1.Invert() - if err != nil { - return nil, err - } - - sigMsgs := make([]curves.Scalar, len(msgs)) - for i, m := range msgs { - sigMsgs[i] = m.GetMessage() - } - - b := computeB(sig.s, sigMsgs, generators) - - aPrime, ok := sig.a.Mul(r1).(curves.PairingPoint) - if !ok { - return nil, fmt.Errorf("invalid point") - } - aBar, ok := b.Mul(r1).Sub(aPrime.Mul(sig.e)).(curves.PairingPoint) - if !ok { - return nil, fmt.Errorf("invalid point") - } - // d = b * r1 + h0 * r2 - d, ok := aPrime.SumOfProducts([]curves.Point{b, generators.h0}, []curves.Scalar{r1, r2}).(curves.PairingPoint) - if !ok { - return nil, fmt.Errorf("invalid point") - } - - // s' = s + r2r3 - sPrime := sig.s.Add(r2.Mul(r3)) - - // For proving relation aBar - d = aPrime * -e + h0 * r2 - curve := curves.Curve{ - Scalar: sig.s.Zero(), - Point: sig.a.Identity(), - } - proof1 := common.NewProofCommittedBuilder(&curve) - // For aPrime * -e - err = proof1.CommitRandom(aPrime, reader) - if err != nil { - return nil, err - } - err = proof1.CommitRandom(generators.h0, reader) - if err != nil { - return nil, err - } - secrets1 := []curves.Scalar{sig.e, r2} - - // For selective disclosure - proof2 := common.NewProofCommittedBuilder(&curve) - // For d * -r3 - err = proof2.CommitRandom(d.Neg(), reader) - if err != nil { - return nil, err - } - // For h0 * s' - err = proof2.CommitRandom(generators.h0, reader) - if err != nil { - return nil, err - } - secrets2 := make([]curves.Scalar, 0, len(msgs)+2) - secrets2 = append(secrets2, r3) - secrets2 = append(secrets2, sPrime) - - for i, m := range msgs { - if m.IsHidden() { - err = proof2.Commit(generators.Get(i+1), m.GetBlinding(reader)) - if err != nil { - return nil, err - } - secrets2 = append(secrets2, m.GetMessage()) - } - } - - return &PokSignature{ - aPrime, - aBar, - d, - proof1, - proof2, - secrets1, - secrets2, - }, nil -} - -// GetChallengeContribution returns the bytes that should be added to -// a sigma protocol transcript for generating the challenge -func (pok *PokSignature) GetChallengeContribution(transcript *merlin.Transcript) { - transcript.AppendMessage([]byte("A'"), pok.aPrime.ToAffineCompressed()) - transcript.AppendMessage([]byte("Abar"), pok.aBar.ToAffineCompressed()) - transcript.AppendMessage([]byte("D"), pok.d.ToAffineCompressed()) - transcript.AppendMessage([]byte("Proof1"), pok.proof1.GetChallengeContribution()) - transcript.AppendMessage([]byte("Proof2"), pok.proof2.GetChallengeContribution()) -} - -// GenerateProof converts the blinding factors and secrets into Schnorr proofs -func (pok *PokSignature) GenerateProof(challenge curves.Scalar) (*PokSignatureProof, error) { - proof1, err := pok.proof1.GenerateProof(challenge, pok.secrets1) - if err != nil { - return nil, err - } - proof2, err := pok.proof2.GenerateProof(challenge, pok.secrets2) - if err != nil { - return nil, err - } - return &PokSignatureProof{ - aPrime: pok.aPrime, - aBar: pok.aBar, - d: pok.d, - proof1: proof1, - proof2: proof2, - }, nil -} diff --git a/crypto/signatures/bbs/pok_signature_proof.go b/crypto/signatures/bbs/pok_signature_proof.go deleted file mode 100644 index cd221fe2e..000000000 --- a/crypto/signatures/bbs/pok_signature_proof.go +++ /dev/null @@ -1,214 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "errors" - "fmt" - - "github.com/gtank/merlin" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/signatures/common" -) - -// PokSignatureProof is the actual proof sent from a prover -// to a verifier that contains a proof of knowledge of a signature -// and the selective disclosure proof -type PokSignatureProof struct { - aPrime, aBar, d curves.PairingPoint - proof1, proof2 []curves.Scalar -} - -// Init creates an empty proof to a specific curve -// which should be followed by UnmarshalBinary -func (pok *PokSignatureProof) Init(curve *curves.PairingCurve) *PokSignatureProof { - pok.aPrime = curve.Scalar.Point().(curves.PairingPoint).OtherGroup() - pok.aBar = pok.aPrime - pok.d = pok.aPrime - pok.proof1 = []curves.Scalar{ - curve.Scalar.Zero(), - curve.Scalar.Zero(), - } - pok.proof2 = make([]curves.Scalar, 0) - return pok -} - -func (pok *PokSignatureProof) MarshalBinary() ([]byte, error) { - data := append(pok.aPrime.ToAffineCompressed(), pok.aBar.ToAffineCompressed()...) - data = append(data, pok.d.ToAffineCompressed()...) - for _, p := range pok.proof1 { - data = append(data, p.Bytes()...) - } - for _, p := range pok.proof2 { - data = append(data, p.Bytes()...) - } - return data, nil -} - -func (pok *PokSignatureProof) UnmarshalBinary(in []byte) error { - scSize := len(pok.proof1[0].Bytes()) - ptSize := len(pok.aPrime.ToAffineCompressed()) - minSize := scSize*4 + ptSize*3 - inSize := len(in) - if inSize < minSize { - return fmt.Errorf("invalid byte sequence") - } - if (inSize-ptSize)%scSize != 0 { - return fmt.Errorf("invalid byte sequence") - } - secretCnt := ((inSize - ptSize*3) / scSize) - 2 - offset := 0 - end := ptSize - - aPrime, err := pok.aPrime.FromAffineCompressed(in[offset:end]) - if err != nil { - return err - } - offset = end - end += ptSize - aBar, err := pok.aBar.FromAffineCompressed(in[offset:end]) - if err != nil { - return err - } - offset = end - end += ptSize - d, err := pok.d.FromAffineCompressed(in[offset:end]) - if err != nil { - return err - } - offset = end - end += scSize - proof1i0, err := pok.proof1[0].SetBytes(in[offset:end]) - if err != nil { - return err - } - offset = end - end += scSize - proof1i1, err := pok.proof1[1].SetBytes(in[offset:end]) - if err != nil { - return err - } - proof2 := make([]curves.Scalar, secretCnt) - for i := 0; i < secretCnt; i++ { - offset = end - end += scSize - proof2[i], err = pok.proof1[0].SetBytes(in[offset:end]) - if err != nil { - return err - } - } - - var ok bool - pok.aPrime, ok = aPrime.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - pok.aBar, ok = aBar.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - pok.d, ok = d.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - pok.proof1[0] = proof1i0 - pok.proof1[1] = proof1i1 - pok.proof2 = proof2 - return nil -} - -// GetChallengeContribution converts the committed values to bytes -// for the Fiat-Shamir challenge -func (pok PokSignatureProof) GetChallengeContribution( - generators *MessageGenerators, - revealedMessages map[int]curves.Scalar, - challenge common.Challenge, - transcript *merlin.Transcript, -) { - transcript.AppendMessage([]byte("A'"), pok.aPrime.ToAffineCompressed()) - transcript.AppendMessage([]byte("Abar"), pok.aBar.ToAffineCompressed()) - transcript.AppendMessage([]byte("D"), pok.d.ToAffineCompressed()) - - proof1Points := []curves.Point{pok.aBar.Sub(pok.d), pok.aPrime, generators.h0} - proof1Scalars := []curves.Scalar{challenge, pok.proof1[0], pok.proof1[1]} - commitmentProof1 := pok.aPrime.SumOfProducts(proof1Points, proof1Scalars) - transcript.AppendMessage([]byte("Proof1"), commitmentProof1.ToAffineCompressed()) - - rPoints := make([]curves.Point, 1, len(revealedMessages)+1) - rScalars := make([]curves.Scalar, 1, len(revealedMessages)+1) - - rPoints[0] = pok.aPrime.Generator() - rScalars[0] = pok.proof1[0].One() - - for idx, msg := range revealedMessages { - rPoints = append(rPoints, generators.Get(idx+1)) - rScalars = append(rScalars, msg) - } - - r := pok.aPrime.SumOfProducts(rPoints, rScalars) - - pts := 3 + generators.length - len(revealedMessages) - proof2Points := make([]curves.Point, 3, pts) - proof2Scalars := make([]curves.Scalar, 3, pts) - - // R * c - proof2Points[0] = r - proof2Scalars[0] = challenge - - // D * -r3Hat - proof2Points[1] = pok.d.Neg() - proof2Scalars[1] = pok.proof2[0] - - // H0 * s'Hat - proof2Points[2] = generators.h0 - proof2Scalars[2] = pok.proof2[1] - - j := 2 - for i := 0; i < generators.length; i++ { - if _, contains := revealedMessages[i]; contains { - continue - } - proof2Points = append(proof2Points, generators.Get(i+1)) - proof2Scalars = append(proof2Scalars, pok.proof2[j]) - j++ - } - commitmentProof2 := r.SumOfProducts(proof2Points, proof2Scalars) - - transcript.AppendMessage([]byte("Proof2"), commitmentProof2.ToAffineCompressed()) -} - -// VerifySigPok only validates the signature proof, -// the selective disclosure proof is checked by -// verifying -// pok.challenge == computedChallenge -func (pok PokSignatureProof) VerifySigPok(pk *PublicKey) bool { - return !pk.value.IsIdentity() && - !pok.aPrime.IsIdentity() && - !pok.aBar.IsIdentity() && - pok.aPrime.MultiPairing(pok.aPrime, pk.value, pok.aBar, pk.value.Generator().Neg().(curves.PairingPoint)). - IsOne() -} - -// Verify checks a signature proof of knowledge and selective disclosure proof -func (pok PokSignatureProof) Verify( - revealedMsgs map[int]curves.Scalar, - pk *PublicKey, - generators *MessageGenerators, - nonce common.Nonce, - challenge common.Challenge, - transcript *merlin.Transcript, -) bool { - pok.GetChallengeContribution(generators, revealedMsgs, challenge, transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - vChallenge, err := pok.proof1[0].SetBytesWide(okm) - if err != nil { - return false - } - return pok.VerifySigPok(pk) && challenge.Cmp(vChallenge) == 0 -} diff --git a/crypto/signatures/bbs/pok_signature_proof_test.go b/crypto/signatures/bbs/pok_signature_proof_test.go deleted file mode 100644 index 0888351d0..000000000 --- a/crypto/signatures/bbs/pok_signature_proof_test.go +++ /dev/null @@ -1,319 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - crand "crypto/rand" - "testing" - - "github.com/gtank/merlin" - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/signatures/common" -) - -func TestPokSignatureProofSomeMessagesRevealed(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, sk) - require.NotNil(t, pk) - require.False(t, sk.value.IsZero()) - require.False(t, pk.value.IsIdentity()) - _, ok := pk.value.(*curves.PointBls12381G2) - require.True(t, ok) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - msgs := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - } - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - require.NotNil(t, sig) - require.False(t, sig.a.IsIdentity()) - require.False(t, sig.e.IsZero()) - require.False(t, sig.s.IsZero()) - - proofMsgs := []common.ProofMessage{ - &common.ProofSpecificMessage{ - Message: msgs[0], - }, - &common.ProofSpecificMessage{ - Message: msgs[1], - }, - &common.RevealedMessage{ - Message: msgs[2], - }, - &common.RevealedMessage{ - Message: msgs[3], - }, - } - - pok, err := NewPokSignature(sig, generators, proofMsgs, crand.Reader) - require.NoError(t, err) - require.NotNil(t, pok) - nonce := curve.Scalar.Random(crand.Reader) - transcript := merlin.NewTranscript("TestPokSignatureProofWorks") - pok.GetChallengeContribution(transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - challenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - - pokSig, err := pok.GenerateProof(challenge) - require.NoError(t, err) - require.NotNil(t, pokSig) - require.True(t, pokSig.VerifySigPok(pk)) - - revealedMsgs := map[int]curves.Scalar{ - 2: msgs[2], - 3: msgs[3], - } - // Manual verify to show how when used in conjunction with other ZKPs - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - pokSig.GetChallengeContribution(generators, revealedMsgs, challenge, transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm = transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - vChallenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - require.Equal(t, challenge.Cmp(vChallenge), 0) - - // Use the all-inclusive method - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - require.True(t, pokSig.Verify(revealedMsgs, pk, generators, nonce, challenge, transcript)) -} - -func TestPokSignatureProofAllMessagesRevealed(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, sk) - require.NotNil(t, pk) - require.False(t, sk.value.IsZero()) - require.False(t, pk.value.IsIdentity()) - _, ok := pk.value.(*curves.PointBls12381G2) - require.True(t, ok) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - msgs := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - } - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - require.NotNil(t, sig) - require.False(t, sig.a.IsIdentity()) - require.False(t, sig.e.IsZero()) - require.False(t, sig.s.IsZero()) - - proofMsgs := []common.ProofMessage{ - &common.RevealedMessage{ - Message: msgs[0], - }, - &common.RevealedMessage{ - Message: msgs[1], - }, - &common.RevealedMessage{ - Message: msgs[2], - }, - &common.RevealedMessage{ - Message: msgs[3], - }, - } - - pok, err := NewPokSignature(sig, generators, proofMsgs, crand.Reader) - require.NoError(t, err) - require.NotNil(t, pok) - nonce := curve.Scalar.Random(crand.Reader) - transcript := merlin.NewTranscript("TestPokSignatureProofWorks") - pok.GetChallengeContribution(transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - challenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - - pokSig, err := pok.GenerateProof(challenge) - require.NoError(t, err) - require.NotNil(t, pokSig) - require.True(t, pokSig.VerifySigPok(pk)) - - revealedMsgs := map[int]curves.Scalar{ - 0: msgs[0], - 1: msgs[1], - 2: msgs[2], - 3: msgs[3], - } - // Manual verify to show how when used in conjunction with other ZKPs - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - pokSig.GetChallengeContribution(generators, revealedMsgs, challenge, transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm = transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - vChallenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - require.Equal(t, challenge.Cmp(vChallenge), 0) - - // Use the all-inclusive method - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - require.True(t, pokSig.Verify(revealedMsgs, pk, generators, nonce, challenge, transcript)) -} - -func TestPokSignatureProofAllMessagesHidden(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, sk) - require.NotNil(t, pk) - require.False(t, sk.value.IsZero()) - require.False(t, pk.value.IsIdentity()) - _, ok := pk.value.(*curves.PointBls12381G2) - require.True(t, ok) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - msgs := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - } - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - require.NotNil(t, sig) - require.False(t, sig.a.IsIdentity()) - require.False(t, sig.e.IsZero()) - require.False(t, sig.s.IsZero()) - - proofMsgs := []common.ProofMessage{ - &common.ProofSpecificMessage{ - Message: msgs[0], - }, - &common.ProofSpecificMessage{ - Message: msgs[1], - }, - &common.ProofSpecificMessage{ - Message: msgs[2], - }, - &common.ProofSpecificMessage{ - Message: msgs[3], - }, - } - - pok, err := NewPokSignature(sig, generators, proofMsgs, crand.Reader) - require.NoError(t, err) - require.NotNil(t, pok) - nonce := curve.Scalar.Random(crand.Reader) - transcript := merlin.NewTranscript("TestPokSignatureProofWorks") - pok.GetChallengeContribution(transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm := transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - challenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - - pokSig, err := pok.GenerateProof(challenge) - require.NoError(t, err) - require.NotNil(t, pokSig) - require.True(t, pokSig.VerifySigPok(pk)) - - revealedMsgs := map[int]curves.Scalar{} - - // Manual verify to show how when used in conjunction with other ZKPs - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - pokSig.GetChallengeContribution(generators, revealedMsgs, challenge, transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - okm = transcript.ExtractBytes([]byte("signature proof of knowledge"), 64) - vChallenge, err := curve.Scalar.SetBytesWide(okm) - require.NoError(t, err) - require.Equal(t, challenge.Cmp(vChallenge), 0) - - // Use the all-inclusive method - transcript = merlin.NewTranscript("TestPokSignatureProofWorks") - require.True(t, pokSig.Verify(revealedMsgs, pk, generators, nonce, challenge, transcript)) -} - -func TestPokSignatureProofMarshalBinary(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - require.NotNil(t, sk) - require.NotNil(t, pk) - require.False(t, sk.value.IsZero()) - require.False(t, pk.value.IsIdentity()) - _, ok := pk.value.(*curves.PointBls12381G2) - require.True(t, ok) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - msgs := []curves.Scalar{ - curve.Scalar.New(2), - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - } - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - require.NotNil(t, sig) - require.False(t, sig.a.IsIdentity()) - require.False(t, sig.e.IsZero()) - require.False(t, sig.s.IsZero()) - - proofMsgs := []common.ProofMessage{ - &common.ProofSpecificMessage{ - Message: msgs[0], - }, - &common.ProofSpecificMessage{ - Message: msgs[1], - }, - &common.RevealedMessage{ - Message: msgs[2], - }, - &common.RevealedMessage{ - Message: msgs[3], - }, - } - - pok, err := NewPokSignature(sig, generators, proofMsgs, crand.Reader) - require.NoError(t, err) - require.NotNil(t, pok) - nonce := curve.Scalar.Random(crand.Reader) - transcript := merlin.NewTranscript("TestPokSignatureProofMarshalBinary") - pok.GetChallengeContribution(transcript) - transcript.AppendMessage([]byte("nonce"), nonce.Bytes()) - challenge, err := curve.Scalar.SetBytesWide( - transcript.ExtractBytes([]byte("signature proof of knowledge"), 64), - ) - require.NoError(t, err) - - pokSig, err := pok.GenerateProof(challenge) - require.NoError(t, err) - require.NotNil(t, pokSig) - - data, err := pokSig.MarshalBinary() - require.NoError(t, err) - require.NotNil(t, data) - pokSig2 := new(PokSignatureProof).Init(curve) - err = pokSig2.UnmarshalBinary(data) - require.NoError(t, err) - require.True(t, pokSig.aPrime.Equal(pokSig2.aPrime)) - require.True(t, pokSig.aBar.Equal(pokSig2.aBar)) - require.True(t, pokSig.d.Equal(pokSig2.d)) - require.Equal(t, len(pokSig.proof1), len(pokSig2.proof1)) - require.Equal(t, len(pokSig.proof2), len(pokSig2.proof2)) - for i, p := range pokSig.proof1 { - require.Equal(t, p.Cmp(pokSig2.proof1[i]), 0) - } - for i, p := range pokSig.proof2 { - require.Equal(t, p.Cmp(pokSig2.proof2[i]), 0) - } -} diff --git a/crypto/signatures/bbs/public_key.go b/crypto/signatures/bbs/public_key.go deleted file mode 100644 index b82b48793..000000000 --- a/crypto/signatures/bbs/public_key.go +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "errors" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// PublicKey is a BBS+ verification key -type PublicKey struct { - value curves.PairingPoint -} - -func (pk *PublicKey) Init(curve *curves.PairingCurve) *PublicKey { - pk.value = curve.NewG2IdentityPoint() - return pk -} - -func (pk PublicKey) MarshalBinary() ([]byte, error) { - return pk.value.ToAffineCompressed(), nil -} - -func (pk *PublicKey) UnmarshalBinary(in []byte) error { - value, err := pk.value.FromAffineCompressed(in) - if err != nil { - return err - } - var ok bool - pk.value, ok = value.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - return nil -} - -// Verify checks a signature where all messages are known to the verifier -func (pk PublicKey) Verify( - signature *Signature, - generators *MessageGenerators, - msgs []curves.Scalar, -) error { - if generators.length < len(msgs) { - return fmt.Errorf("not enough message generators") - } - if len(msgs) < 1 { - return fmt.Errorf("invalid messages") - } - // Identity Point will always return true which is not what we want - if pk.value.IsIdentity() { - return fmt.Errorf("invalid public key") - } - if signature.a.IsIdentity() { - return fmt.Errorf("invalid signature") - } - a, ok := pk.value.Generator().Mul(signature.e).Add(pk.value).(curves.PairingPoint) - if !ok { - return fmt.Errorf("not a valid point") - } - b, ok := computeB(signature.s, msgs, generators).Neg().(curves.PairingPoint) - if !ok { - return fmt.Errorf("not a valid point") - } - - res := a.MultiPairing(signature.a, a, b, pk.value.Generator().(curves.PairingPoint)) - if !res.IsOne() { - return fmt.Errorf("invalid result") - } - - return nil -} diff --git a/crypto/signatures/bbs/secret_key.go b/crypto/signatures/bbs/secret_key.go deleted file mode 100644 index 040238097..000000000 --- a/crypto/signatures/bbs/secret_key.go +++ /dev/null @@ -1,185 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - crand "crypto/rand" - "crypto/sha256" - "errors" - "fmt" - "io" - - "golang.org/x/crypto/hkdf" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// SecretKey is a BBS+ signing key -type SecretKey struct { - value curves.PairingScalar -} - -func NewSecretKey(curve *curves.PairingCurve) (*SecretKey, error) { - // The salt used with generating secret keys - // See section 2.3 from https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04 - const hkdfKeyGenSalt = "BLS-SIG-KEYGEN-SALT-" - const Size = 33 - var ikm [Size]byte - cnt, err := crand.Read(ikm[:32]) - if err != nil { - return nil, err - } - if cnt != Size-1 { - return nil, fmt.Errorf("unable to read sufficient random data") - } - - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04#section-2.3 - h := sha256.New() - n, err := h.Write([]byte(hkdfKeyGenSalt)) - if err != nil { - return nil, err - } - if n != len(hkdfKeyGenSalt) { - return nil, fmt.Errorf("incorrect salt bytes written to be hashed") - } - salt := h.Sum(nil) - - // Leaves key_info parameter as the default empty string - // and just adds parameter I2OSP(L, 2) - kdf := hkdf.New(sha256.New, ikm[:], salt, []byte{0, 48}) - var okm [64]byte - read, err := kdf.Read(okm[:48]) - if err != nil { - return nil, err - } - if read != 48 { - return nil, fmt.Errorf("failed to create secret key") - } - v, err := curve.Scalar.SetBytesWide(okm[:]) - if err != nil { - return nil, err - } - value, ok := v.(curves.PairingScalar) - if !ok { - return nil, fmt.Errorf("invalid scalar") - } - return &SecretKey{ - value: value.SetPoint(curve.PointG2), - }, nil -} - -func NewKeys(curve *curves.PairingCurve) (*PublicKey, *SecretKey, error) { - sk, err := NewSecretKey(curve) - if err != nil { - return nil, nil, err - } - return sk.PublicKey(), sk, nil -} - -func (sk *SecretKey) Init(curve *curves.PairingCurve) *SecretKey { - sk.value = curve.NewScalar() - return sk -} - -func (sk SecretKey) MarshalBinary() ([]byte, error) { - return sk.value.Bytes(), nil -} - -func (sk *SecretKey) UnmarshalBinary(in []byte) error { - value, err := sk.value.SetBytes(in) - if err != nil { - return err - } - var ok bool - sk.value, ok = value.(curves.PairingScalar) - if !ok { - return errors.New("incorrect type conversion") - } - return nil -} - -// Sign generates a new signature where all messages are known to the signer -func (sk *SecretKey) Sign(generators *MessageGenerators, msgs []curves.Scalar) (*Signature, error) { - if generators.length < len(msgs) { - return nil, fmt.Errorf("not enough message generators") - } - if len(msgs) < 1 { - return nil, fmt.Errorf("invalid messages") - } - if sk.value.IsZero() { - return nil, fmt.Errorf("invalid secret key") - } - - drbg := sha3.NewShake256() - _, _ = drbg.Write(sk.value.Bytes()) - addDeterministicNonceData(generators, msgs, drbg) - // Should yield non-zero values for `e` and `s`, very small likelihood of being zero - e := getNonZeroScalar(sk.value, drbg) - s := getNonZeroScalar(sk.value, drbg) - b := computeB(s, msgs, generators) - exp, err := e.Add(sk.value).Invert() - if err != nil { - return nil, err - } - return &Signature{ - a: b.Mul(exp).(curves.PairingPoint), - e: e, - s: s, - }, nil -} - -// PublicKey returns the corresponding public key -func (sk *SecretKey) PublicKey() *PublicKey { - return &PublicKey{ - value: sk.value.Point().Generator().Mul(sk.value).(curves.PairingPoint), - } -} - -// computes g1 + s * h0 + msgs[0] * h[0] + msgs[1] * h[1] ... -func computeB( - s curves.Scalar, - msgs []curves.Scalar, - generators *MessageGenerators, -) curves.PairingPoint { - nMsgs := len(msgs) - points := make([]curves.Point, nMsgs+2) - points[1] = generators.Get(0) - points[0] = points[1].Generator() - - scalars := make([]curves.Scalar, nMsgs+2) - scalars[0] = msgs[0].One() - scalars[1] = s - for i, m := range msgs { - points[i+2] = generators.Get(i + 1) - scalars[i+2] = m - } - pt := points[0].SumOfProducts(points, scalars) - return pt.(curves.PairingPoint) -} - -func addDeterministicNonceData( - generators *MessageGenerators, - msgs []curves.Scalar, - drbg io.Writer, -) { - for i := 0; i <= generators.length; i++ { - _, _ = drbg.Write(generators.Get(i).ToAffineUncompressed()) - } - for _, m := range msgs { - _, _ = drbg.Write(m.Bytes()) - } -} - -func getNonZeroScalar(sc curves.Scalar, reader io.Reader) curves.Scalar { - // Should yield non-zero values for `e` and `s`, very small likelihood of being zero - e := sc.Random(reader) - for e.IsZero() { - e = sc.Random(reader) - } - return e -} diff --git a/crypto/signatures/bbs/signature.go b/crypto/signatures/bbs/signature.go deleted file mode 100644 index c29be6b37..000000000 --- a/crypto/signatures/bbs/signature.go +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package bbs is an implementation of BBS+ signature of https://eprint.iacr.org/2016/663.pdf -package bbs - -import ( - "errors" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Signature is a BBS+ signature -// as described in 4.3 in -// -type Signature struct { - a curves.PairingPoint - e, s curves.Scalar -} - -// Init creates an empty signature to a specific curve -// which should be followed by UnmarshalBinary or Create -func (sig *Signature) Init(curve *curves.PairingCurve) *Signature { - sig.a = curve.NewG1IdentityPoint() - sig.e = curve.NewScalar() - sig.s = curve.NewScalar() - return sig -} - -func (sig Signature) MarshalBinary() ([]byte, error) { - out := append(sig.a.ToAffineCompressed(), sig.e.Bytes()...) - out = append(out, sig.s.Bytes()...) - return out, nil -} - -func (sig *Signature) UnmarshalBinary(data []byte) error { - pointLength := len(sig.a.ToAffineCompressed()) - scalarLength := len(sig.s.Bytes()) - expectedLength := pointLength + scalarLength*2 - if len(data) != expectedLength { - return fmt.Errorf("invalid byte sequence") - } - a, err := sig.a.FromAffineCompressed(data[:pointLength]) - if err != nil { - return err - } - e, err := sig.e.SetBytes(data[pointLength:(pointLength + scalarLength)]) - if err != nil { - return err - } - s, err := sig.s.SetBytes(data[(pointLength + scalarLength):]) - if err != nil { - return err - } - var ok bool - sig.a, ok = a.(curves.PairingPoint) - if !ok { - return errors.New("incorrect type conversion") - } - sig.e = e - sig.s = s - return nil -} diff --git a/crypto/signatures/bbs/signature_test.go b/crypto/signatures/bbs/signature_test.go deleted file mode 100644 index 96d2d3c43..000000000 --- a/crypto/signatures/bbs/signature_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bbs - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestSignatureWorks(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - msgs := []curves.Scalar{ - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - curve.Scalar.New(6), - } - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - err = pk.Verify(sig, generators, msgs) - require.NoError(t, err) -} - -func TestSignatureIncorrectMessages(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - msgs := []curves.Scalar{ - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - curve.Scalar.New(6), - } - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - msgs[0] = curve.Scalar.New(7) - err = pk.Verify(sig, generators, msgs) - require.Error(t, err) -} - -func TestSignatureMarshalBinary(t *testing.T) { - curve := curves.BLS12381(&curves.PointBls12381G2{}) - msgs := []curves.Scalar{ - curve.Scalar.New(3), - curve.Scalar.New(4), - curve.Scalar.New(5), - curve.Scalar.New(6), - } - pk, sk, err := NewKeys(curve) - require.NoError(t, err) - generators, err := new(MessageGenerators).Init(pk, 4) - require.NoError(t, err) - - sig, err := sk.Sign(generators, msgs) - require.NoError(t, err) - - data, err := sig.MarshalBinary() - require.NoError(t, err) - require.Equal(t, 112, len(data)) - sig2 := new(Signature).Init(curve) - err = sig2.UnmarshalBinary(data) - require.NoError(t, err) - require.True(t, sig.a.Equal(sig2.a)) - require.Equal(t, sig.e.Cmp(sig2.e), 0) - require.Equal(t, sig.s.Cmp(sig2.s), 0) -} diff --git a/crypto/signatures/bls/README.md b/crypto/signatures/bls/README.md deleted file mode 100755 index d46edf982..000000000 --- a/crypto/signatures/bls/README.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## BLS Signatures - -An implementation of the Boneh-Lynn-Shacham (BLS) signatures according to the [standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/?include_text=1) -on top of the Barreto-Lynn-Scott (BLS) 12-381 curve. The [BLS12-381 curve](https://github.com/zkcrypto/pairing/tree/master/src/bls12_381#serialization) provides roughly -128-bits of security and BLS is a digital signature with aggregation properties. - -We have implemented all three signature schemes described in the [standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/?include_text=1) -which are designed to handle rogue-key attacks differently. These three are: - -- **Basic** handles rogue key attacks by requiring all signed messages in an aggregate signature be distinct -- **Message Augmentation** handles rogue key attacks by prepending the public key to the message during signing which ensures that all messages are distinct for different public keys. -- **Proof of Possession** handles rogue key attacks by validating public keys in a separate step called a proof of possession. This allows for faster aggregate verification. - -Pairing-friendly curves have two generator-groups 𝔾1, 𝔾2. -Data in 𝔾2 is twice the size of 𝔾1 and operations are slower. -BLS signatures require signatures and public keys to be in opposite groups i.e. signatures in 𝔾1 and public keys in 𝔾2 or -signatures in 𝔾2 and public keys in 𝔾1. This means one of two things: - -- **Short public keys, long signatures**: Signatures are longer and slower to create, verify, and aggregate but public keys are small and fast to aggregate. Used when signing and verification operations not computed as often or for minimizing storage or bandwidth for public keys. -- **Short signatures, long public keys**: Signatures are short and fast to create, verify, and aggregate but public keys are bigger and slower to aggregate. Used when signing and verification operations are computed often or for minimizing storage or bandwidth for signatures. - -This library supports both of these variants for all three signature schemes. The more widely deployed -variant is short public keys, long signatures. We refer to this variant as `UsualBls`. The other variant, -short signatures, long public keys, is named `TinyBls`. -The naming convention follows Sig`SchemeType`[Vt] where **Vt** is short for variant. For example, - -- **Usual Bls Basic -> SigBasic**: Provides all the functions for the Basic signature scheme with signatures in 𝔾2 and public keys in 𝔾1 -- **Tiny Bls Basic -> SigBasicVt**: Provides all the functions for the Basic signature scheme with signatures in 𝔾1 and public keys in 𝔾2 - -One final note, in cryptography, it is considered good practice to use domain separation values to limit attacks to specific contexts. The [standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/?include_text=1) -recommends specific values for each scheme but this library also supports supplying custom domain separation values. For example, there are two functions for creating -a BLS signing instance: - -- **NewSigBasic()** creates a Basic BLS signature using the recommended domain separation value. -- **NewSigBasicWithDst(dst)** creates a Basic BLS signature using the parameter `dst` as the domain separation value such as in the [Eth2.0 Spec](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/validator.md#attestation-aggregation) - -Also implemented is Threshold BLS as described in section 3.2 of [B03](https://www.cc.gatech.edu/~aboldyre/papers/bold.pdf). - -- ThresholdKeygen(parts, threshold int) -> ([]\*SecretKeyShare, error) -- PartialSign(share *SecretKeyShare, msg []byte) -> *PartialSignature -- CombineSigs(*PartialSignature…) -> *Signature - -### Security Considerations - -#### Validating Secret Keys - -Low entropy secret keys are a problem since this means an attacker can more easily guess the value and now can impersonate the key holder. -Secret keys are derived using trusted random number generators (TRNG). If the TRNG produces bad entropy -the secret key will be weak. Secret keys are checked to be non-zero values. A zero value secret key -not only fails the entropy test but also yields a public key that will validate any signature. - -#### Validating Public Keys - -Public keys are ensured to be valid. A valid public key means -it represents a valid, non-identity elliptic curve point in the correct subgroup. -Public keys that are the identity element mean any signature would pass a call to verify. - -#### Validating Signatures - -Generated signatures are ensured to be valid. A valid signature means -it represents a valid, non-identity elliptic curve point in the correct subgroup. -Signatures that are the identity element mean any signature would pass a call to verify. -Verify checks signatures for non-identity elements in the correct subgroup before checking -for a valid signature. - -#### Mitigating Rogue Key Attacks - -A rogue key attacks can only happen to multisignature or aggregated signature. -A rogue key attack is where at least one party produces a valid but malicious public key such that the multisignature requires less than the threshold to verify a signature. -There are two ways to mitigate rogue key attacks: Guarantee all signed messages are unique or validate each public key before use. This library offers both solutions. - -### Comparison to other BLS Implementations and Integrations - -This library has been tested to be compatible with the following implementations -by randomly generating millions of keys and signatures and importing and verifying -between the two libraries. - -1. Ethereum's [py_ecc](https://github.com/ethereum/py_ecc) -2. PhoreProject [Go BLS](https://github.com/phoreproject/bls) -3. Herumi's [BLS](https://github.com/herumi/bls-eth-go-binary) -4. Algorand's [Rust BLS Sig](https://crates.io/crates/bls_sigs_ref) -5. Miracl's [Rust and Go BLS sig](https://github.com/miracl/core) - -The most common and high risk failures that can occur with library implementations -are low entropy secret keys, malformed public keys, and invalid signature generation. - -Low entropy secret keys are a problem since this means an attacker can more easily guess -the value and now can impersonate the key holder. - -Malformed public keys and signatures result in invalid addresses and no ability to withdraw funds. - -To check for these problems, We tested millions of keys/signatures (vs say thousands or hundreds) to prove that - -1. The odds of producing an invalid key/signature is already theoretically low 2-255 -2. The results of running millions of checks shows that nothing bad happened in 10M attempts - -In other words, keys and signatures generated from these libraries can be consumed by this library -and visa-versa. - -Some of the libraries implementations for hash to curve were either out of date -or not compliant with the [IETF Spec](https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/). -This meant that signatures generated by this library would not validate with others and visa-versa. -However, public keys were found to be compatible in all libraries. - -This library is compliant with the latest version (10 as of this writing). diff --git a/crypto/signatures/bls/bls_sig/lib.go b/crypto/signatures/bls/bls_sig/lib.go deleted file mode 100644 index d54675435..000000000 --- a/crypto/signatures/bls/bls_sig/lib.go +++ /dev/null @@ -1,208 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package bls_sig is an implementation of the BLS signature defined in https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -package bls_sig - -import ( - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "fmt" - - "golang.org/x/crypto/hkdf" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/sharing" -) - -// Secret key in Fr -const SecretKeySize = 32 - -// Secret key share with identifier byte in Fr -const SecretKeyShareSize = 33 - -// The salt used with generating secret keys -// See section 2.3 from https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -const hkdfKeyGenSalt = "BLS-SIG-KEYGEN-SALT-" - -// Represents a value mod r where r is the curve order or -// order of the subgroups in G1 and G2 -type SecretKey struct { - value *native.Field -} - -func allRowsUnique(data [][]byte) bool { - seen := make(map[string]bool) - for _, row := range data { - m := string(row) - if _, ok := seen[m]; ok { - return false - } - seen[m] = true - } - return true -} - -func generateRandBytes(count int) ([]byte, error) { - ikm := make([]byte, count) - cnt, err := rand.Read(ikm) - if err != nil { - return nil, err - } - if cnt != count { - return nil, fmt.Errorf("unable to read sufficient random data") - } - return ikm, nil -} - -// Creates a new BLS secret key -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (sk SecretKey) Generate(ikm []byte) (*SecretKey, error) { - if len(ikm) < 32 { - return nil, fmt.Errorf("ikm is too short. Must be at least 32") - } - - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04#section-2.3 - h := sha256.New() - n, err := h.Write([]byte(hkdfKeyGenSalt)) - if err != nil { - return nil, err - } - if n != len(hkdfKeyGenSalt) { - return nil, fmt.Errorf("incorrect salt bytes written to be hashed") - } - salt := h.Sum(nil) - - ikm = append(ikm, 0) - // Leaves key_info parameter as the default empty string - // and just adds parameter I2OSP(L, 2) - var okm [native.WideFieldBytes]byte - kdf := hkdf.New(sha256.New, ikm, salt, []byte{0, 48}) - read, err := kdf.Read(okm[:48]) - copy(okm[:48], internal.ReverseScalarBytes(okm[:48])) - if err != nil { - return nil, err - } - if read != 48 { - return nil, fmt.Errorf("failed to create private key") - } - v := bls12381.Bls12381FqNew().SetBytesWide(&okm) - return &SecretKey{value: v}, nil -} - -// Serialize a secret key to raw bytes -func (sk SecretKey) MarshalBinary() ([]byte, error) { - bytes := sk.value.Bytes() - return internal.ReverseScalarBytes(bytes[:]), nil -} - -// Deserialize a secret key from raw bytes -// Cannot be zero. Must be 32 bytes and cannot be all zeroes. -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-2.3 -func (sk *SecretKey) UnmarshalBinary(data []byte) error { - if len(data) != SecretKeySize { - return fmt.Errorf("secret key must be %d bytes", SecretKeySize) - } - zeros := make([]byte, len(data)) - if subtle.ConstantTimeCompare(data, zeros) == 1 { - return fmt.Errorf("secret key cannot be zero") - } - var bb [native.FieldBytes]byte - copy(bb[:], internal.ReverseScalarBytes(data)) - value, err := bls12381.Bls12381FqNew().SetBytes(&bb) - if err != nil { - return err - } - sk.value = value - return nil -} - -// SecretKeyShare is shamir share of a private key -type SecretKeyShare struct { - identifier byte - value []byte -} - -// Serialize a secret key share to raw bytes -func (sks SecretKeyShare) MarshalBinary() ([]byte, error) { - var blob [SecretKeyShareSize]byte - l := len(sks.value) - copy(blob[:l], sks.value) - blob[l] = sks.identifier - return blob[:], nil -} - -// Deserialize a secret key share from raw bytes -func (sks *SecretKeyShare) UnmarshalBinary(data []byte) error { - if len(data) != SecretKeyShareSize { - return fmt.Errorf("secret key share must be %d bytes", SecretKeyShareSize) - } - - zeros := make([]byte, len(data)) - if subtle.ConstantTimeCompare(data, zeros) == 1 { - return fmt.Errorf("secret key share cannot be zero") - } - l := len(data) - sks.identifier = data[l-1] - sks.value = make([]byte, SecretKeySize) - copy(sks.value, data[:l]) - return nil -} - -// thresholdizeSecretKey splits a composite secret key such that -// `threshold` partial signatures can be combined to form a composite signature -func thresholdizeSecretKey(secretKey *SecretKey, threshold, total uint) ([]*SecretKeyShare, error) { - // Verify our parameters are acceptable. - if secretKey == nil { - return nil, fmt.Errorf("secret key is nil") - } - if threshold > total { - return nil, fmt.Errorf("threshold cannot be greater than the total") - } - if threshold == 0 { - return nil, fmt.Errorf("threshold cannot be zero") - } - if total <= 1 { - return nil, fmt.Errorf("total must be larger than 1") - } - if total > 255 || threshold > 255 { - return nil, fmt.Errorf("cannot have more than 255 shares") - } - - curve := curves.BLS12381G1() - sss, err := sharing.NewShamir(uint32(threshold), uint32(total), curve) - if err != nil { - return nil, err - } - secret, ok := curve.NewScalar().(*curves.ScalarBls12381) - if !ok { - return nil, fmt.Errorf("invalid curve") - } - secret.Value = secretKey.value - shares, err := sss.Split(secret, rand.Reader) - if err != nil { - return nil, err - } - // Verify we got the expected number of shares - if uint(len(shares)) != total { - return nil, fmt.Errorf("%v != %v shares", len(shares), total) - } - - // Package our shares - secrets := make([]*SecretKeyShare, len(shares)) - for i, s := range shares { - // users expect BigEndian - sks := &SecretKeyShare{identifier: byte(s.Id), value: s.Value} - secrets[i] = sks - } - - return secrets, nil -} diff --git a/crypto/signatures/bls/bls_sig/lib_test.go b/crypto/signatures/bls/bls_sig/lib_test.go deleted file mode 100644 index 75e877769..000000000 --- a/crypto/signatures/bls/bls_sig/lib_test.go +++ /dev/null @@ -1,481 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "bytes" - "crypto/rand" - "encoding" - "math/big" - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -func genSecretKey(t *testing.T) *SecretKey { - ikm := make([]byte, 32) - sk, err := new(SecretKey).Generate(ikm) - if err != nil { - t.Errorf("Couldn't generate secret key") - } - return sk -} - -func genRandSecretKey(ikm []byte, t *testing.T) *SecretKey { - sk, err := new(SecretKey).Generate(ikm) - if err != nil { - t.Errorf("Couldn't generate secret key") - } - return sk -} - -func genPublicKeyVt(sk *SecretKey, t *testing.T) *PublicKeyVt { - pk, err := sk.GetPublicKeyVt() - if err != nil { - t.Errorf("Expected GetPublicKeyVt to pass but failed: %v", err) - } - return pk -} - -func genPublicKey(sk *SecretKey, t *testing.T) *PublicKey { - pk, err := sk.GetPublicKey() - if err != nil { - t.Errorf("GetPublicKey failed. Couldn't generate public key: %v", err) - } - return pk -} - -func genSignature(sk *SecretKey, message []byte, t *testing.T) *Signature { - bls := NewSigPop() - - sig, err := bls.Sign(sk, message) - if err != nil { - t.Errorf("createSignature couldn't sign message: %v", err) - } - return sig -} - -func genSignatureVt(sk *SecretKey, message []byte, t *testing.T) *SignatureVt { - bls := NewSigPopVt() - sig, err := bls.Sign(sk, message) - if err != nil { - t.Errorf("createSignatureVt couldn't sign message: %v", err) - } - return sig -} - -func readRand(ikm []byte, t *testing.T) { - n, err := rand.Read(ikm) - if err != nil || n < len(ikm) { - t.Errorf("Not enough data was read or an error occurred") - } -} - -func assertSecretKeyGen(seed, expected []byte, t *testing.T) { - sk, err := new(SecretKey).Generate(seed) - if err != nil { - t.Errorf("Expected Generate to succeed but failed") - } - actual, _ := sk.MarshalBinary() - if len(actual) != len(expected) { - t.Errorf("Length of Generate output is incorrect. Expected 32, found: %v\n", len(actual)) - } - if !bytes.Equal(actual[:], expected) { - t.Errorf("SecretKey was not as expected") - } -} - -func marshalStruct(value encoding.BinaryMarshaler, t *testing.T) []byte { - out, err := value.MarshalBinary() - if err != nil { - t.Errorf("MarshalBinary failed: %v", err) - } - return out -} - -func TestSecretKeyZeroBytes(t *testing.T) { - seed := []byte{} - _, err := new(SecretKey).Generate(seed) - if err == nil { - t.Errorf("Expected Generate to fail but succeeded") - } -} - -func TestMarshalLeadingZeroes(t *testing.T) { - tests := []struct { - name string - in []byte - }{ - { - "no leading zeroes", - []byte{ - 74, - 53, - 59, - 227, - 218, - 192, - 145, - 160, - 167, - 230, - 64, - 98, - 3, - 114, - 245, - 225, - 226, - 228, - 64, - 23, - 23, - 193, - 231, - 156, - 172, - 111, - 251, - 168, - 246, - 144, - 86, - 4, - }, - }, - { - "one leading zero byte", - []byte{ - 0o0, - 53, - 59, - 227, - 218, - 192, - 145, - 160, - 167, - 230, - 64, - 98, - 3, - 114, - 245, - 225, - 226, - 228, - 64, - 23, - 23, - 193, - 231, - 156, - 172, - 111, - 251, - 168, - 246, - 144, - 86, - 4, - }, - }, - { - "two leading zeroes", - []byte{ - 0o0, - 0o0, - 59, - 227, - 218, - 192, - 145, - 160, - 167, - 230, - 64, - 98, - 3, - 114, - 245, - 225, - 226, - 228, - 64, - 23, - 23, - 193, - 231, - 156, - 172, - 111, - 251, - 168, - 246, - 144, - 86, - 4, - }, - }, - } - // Run all the tests! - ss := bls12381.Bls12381FqNew() - for _, test := range tests { - // Marshal - var k big.Int - k.SetBytes(test.in) - ss.SetBigInt(&k) - bytes, err := SecretKey{ss}.MarshalBinary() - if err != nil { - t.Errorf("%v", err) - continue - } - - // Test that marshal produces a values of the exected len - t.Run(test.name, func(t *testing.T) { - if len(bytes) != SecretKeySize { - t.Errorf("expected len=%v got len=%v", SecretKeySize, len(bytes)) - } - }) - - // Test that we can also unmarhsal correctly - t.Run(test.name, func(t *testing.T) { - var actual SecretKey - err := actual.UnmarshalBinary(bytes) - // Test for error - if err != nil { - t.Errorf("%v", err) - return - } - - // Test for correctness - if actual.value.Cmp(ss) != 0 { - t.Errorf("unmarshaled doens't match original value") - } - }) - } -} - -func TestSecretKey32Bytes(t *testing.T) { - seed := make([]byte, 32) - expected := []byte{ - 77, - 18, - 154, - 25, - 223, - 134, - 160, - 245, - 52, - 91, - 173, - 76, - 198, - 242, - 73, - 236, - 42, - 129, - 156, - 204, - 51, - 134, - 137, - 91, - 235, - 79, - 125, - 152, - 179, - 219, - 98, - 53, - } - assertSecretKeyGen(seed, expected, t) -} - -func TestSecretKey128Bytes(t *testing.T) { - seed := make([]byte, 128) - expected := []byte{ - 97, - 207, - 109, - 96, - 94, - 90, - 233, - 215, - 221, - 207, - 240, - 139, - 24, - 209, - 152, - 170, - 73, - 209, - 151, - 241, - 148, - 176, - 173, - 92, - 101, - 48, - 39, - 175, - 201, - 219, - 146, - 168, - } - assertSecretKeyGen(seed, expected, t) -} - -func TestRandomSecretKey(t *testing.T) { - seed := make([]byte, 48) - _, _ = rand.Read(seed) - _, err := new(SecretKey).Generate(seed) - if err != nil { - t.Errorf("Expected Generate to succeed but failed") - } -} - -func TestSecretKeyToBytes(t *testing.T) { - sk := genSecretKey(t) - skBytes := marshalStruct(sk, t) - sk1 := new(SecretKey) - err := sk1.UnmarshalBinary(skBytes) - if err != nil { - t.Errorf("Expected UnmarshalBinary to pass but failed: %v", err) - } - out := sk1.value.Bytes() - for i, b := range internal.ReverseScalarBytes(out[:]) { - if skBytes[i] != b { - t.Errorf( - "Expected secret keys to be equal but are different at offset %d: %v != %v", - i, - skBytes[i], - b, - ) - } - } - sk2 := new(SecretKey) - err = sk2.UnmarshalBinary(skBytes) - if err != nil { - t.Errorf("Expected FromBytes to succeed but failed.") - } - if !bytes.Equal(marshalStruct(sk2, t), skBytes) { - t.Errorf("Expected secret keys to be equal but are different") - } -} - -// Verifies that the thresholdize creates the expected number -// of shares -func TestThresholdizeSecretKeyCountsCorrect(t *testing.T) { - sk := &SecretKey{value: bls12381.Bls12381FqNew().SetBigInt(big.NewInt(248631463258962596))} - tests := []struct { - key *SecretKey - t, n uint - expectedError bool - }{ - // bad cases - {sk, 1, 1, true}, // n == 1 - {sk, 1, 5, true}, // t == 1 - {nil, 3, 5, true}, // sk nil - {sk, 101, 100, true}, // t> n - {sk, 0, 10, true}, // t == 0 - {sk, 10, 256, true}, // n > 256 - - // good cases - {sk, 10, 10, false}, // t == n - {sk, 2, 10, false}, // boundary case for t - {sk, 9, 10, false}, // boundary case for t - {sk, 10, 255, false}, // boundary case for n - {sk, 254, 255, false}, // boundary case for t,n - {sk, 100, 200, false}, // arbitrary t,n values - {sk, 10, 20, false}, // arbitrary t,n values - {sk, 15, 200, false}, // arbitrary t,n values - {sk, 254, 255, false}, // boundary case - {sk, 255, 255, false}, // boundary case - } - - // Run all the tests! - for i, test := range tests { - shares, err := thresholdizeSecretKey(test.key, test.t, test.n) - - // Check for errors - if test.expectedError && err == nil { - t.Errorf( - "%d - expected an error but received nil. t=%v, n=%v, sk=%v", - i, - test.t, - test.n, - sk, - ) - } - - // Check for errors - if !test.expectedError && err != nil { - t.Errorf( - "%d - received unexpected error %v. t=%v, n=%v, sk=%v", - i, - err, - test.t, - test.n, - sk, - ) - } - - // Check the share count == n - if !test.expectedError && test.n != uint(len(shares)) { - t.Errorf("%d - expected len(shares) = %v != %v (n)", i, len(shares), test.n) - } - } -} - -func TestSecretKeyShareUnmarshalBinary(t *testing.T) { - sk := genSecretKey(t) - sks, err := thresholdizeSecretKey(sk, 3, 5) - if err != nil { - t.Errorf("Expected thresholdizeSecretKey to pass but failed.") - } - - for i, sh := range sks { - b1, err := sh.MarshalBinary() - if err != nil { - t.Errorf("%d - expected MarshalBinary to pass but failed. sh=%v", i, sh) - } - - // UnmarshalBinary b1 to new SecretKeyShare - sh1 := new(SecretKeyShare) - err = sh1.UnmarshalBinary(b1) - if err != nil { - t.Errorf("%d - expected UnmarshalBinary to pass but failed. sh=%v", i, sh) - } - - // zero bytes slice with length equal to SecretKeySize - zeros := make([]byte, SecretKeySize) - b2, err := sh1.MarshalBinary() - if err != nil { - t.Errorf("%d - expected MarshalBinary to pass but failed. sh1=%v", i, sh1) - } - - // Check if []bytes from UnmarshalBinary != zeros && Initial bytes(b1) == Final bytes(b2) - if bytes.Equal(zeros, b2) && !bytes.Equal(b1, b2) { - t.Errorf( - "%d - expected UnmarshalBinary to give non zeros value but failed. sh1=%v, sh=%v", - i, - sh1, - sh, - ) - } - } -} diff --git a/crypto/signatures/bls/bls_sig/tiny_bls.go b/crypto/signatures/bls/bls_sig/tiny_bls.go deleted file mode 100755 index ff279710e..000000000 --- a/crypto/signatures/bls/bls_sig/tiny_bls.go +++ /dev/null @@ -1,484 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "fmt" -) - -const ( - // Domain separation tag for basic signatures - // according to section 4.2.1 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignatureBasicVtDst = "BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_" - // Domain separation tag for basic signatures - // according to section 4.2.2 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignatureAugVtDst = "BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_" - // Domain separation tag for proof of possession signatures - // according to section 4.2.3 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignaturePopVtDst = "BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_POP_" - // Domain separation tag for proof of possession proofs - // according to section 4.2.3 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsPopProofVtDst = "BLS_POP_BLS12381G1_XMD:SHA-256_SSWU_RO_POP_" -) - -type BlsSchemeVt interface { - Keygen() (*PublicKeyVt, *SecretKey, error) - KeygenWithSeed(ikm []byte) (*PublicKeyVt, *SecretKey, error) - Sign(sk *SecretKey, msg []byte) (*SignatureVt, error) - Verify(pk *PublicKeyVt, msg []byte, sig *SignatureVt) bool - AggregateVerify(pks []*PublicKeyVt, msgs [][]byte, sigs []*SignatureVt) bool -} - -// generateKeysVt creates 32 bytes of random data to be fed to -// generateKeysWithSeedVt -func generateKeysVt() (*PublicKeyVt, *SecretKey, error) { - ikm, err := generateRandBytes(32) - if err != nil { - return nil, nil, err - } - return generateKeysWithSeedVt(ikm) -} - -// generateKeysWithSeedVt generates a BLS key pair given input key material (ikm) -func generateKeysWithSeedVt(ikm []byte) (*PublicKeyVt, *SecretKey, error) { - sk, err := new(SecretKey).Generate(ikm) - if err != nil { - return nil, nil, err - } - pk, err := sk.GetPublicKeyVt() - if err != nil { - return nil, nil, err - } - return pk, sk, nil -} - -// thresholdGenerateKeys will generate random secret key shares and the corresponding public key -func thresholdGenerateKeysVt(threshold, total uint) (*PublicKeyVt, []*SecretKeyShare, error) { - pk, sk, err := generateKeysVt() - if err != nil { - return nil, nil, err - } - shares, err := thresholdizeSecretKey(sk, threshold, total) - if err != nil { - return nil, nil, err - } - return pk, shares, nil -} - -// thresholdGenerateKeysWithSeed will generate random secret key shares and the corresponding public key -// using the corresponding seed `ikm` -func thresholdGenerateKeysWithSeedVt( - ikm []byte, - threshold, total uint, -) (*PublicKeyVt, []*SecretKeyShare, error) { - pk, sk, err := generateKeysWithSeedVt(ikm) - if err != nil { - return nil, nil, err - } - shares, err := thresholdizeSecretKey(sk, threshold, total) - if err != nil { - return nil, nil, err - } - return pk, shares, nil -} - -// SigBasicVt is minimal-pubkey-size scheme that doesn't support FastAggregateVerification. -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.1 -type SigBasicVt struct { - dst string -} - -// Creates a new BLS basic signature scheme with the standard domain separation tag used for signatures. -func NewSigBasicVt() *SigBasicVt { - return &SigBasicVt{dst: blsSignatureBasicVtDst} -} - -// Creates a new BLS basic signature scheme with a custom domain separation tag used for signatures. -func NewSigBasicVtWithDst(signDst string) *SigBasicVt { - return &SigBasicVt{dst: signDst} -} - -// Creates a new BLS key pair -func (b SigBasicVt) Keygen() (*PublicKeyVt, *SecretKey, error) { - return generateKeysVt() -} - -// Creates a new BLS key pair -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigBasicVt) KeygenWithSeed(ikm []byte) (*PublicKeyVt, *SecretKey, error) { - return generateKeysWithSeedVt(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigBasicVt) ThresholdKeygen( - threshold, total uint, -) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysVt(threshold, total) -} - -// ThresholdKeygenWithSeed generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures from input key material (ikm) -func (b SigBasicVt) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeedVt(ikm, threshold, total) -} - -// Computes a signature in G1 from sk, a secret key, and a message -func (b SigBasicVt) Sign(sk *SecretKey, msg []byte) (*SignatureVt, error) { - return sk.createSignatureVt(msg, b.dst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigBasicVt) PartialSign(sks *SecretKeyShare, msg []byte) (*PartialSignatureVt, error) { - return sks.partialSignVt(msg, b.dst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigBasicVt) CombineSignatures(sigs ...*PartialSignatureVt) (*SignatureVt, error) { - return combineSigsVt(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -func (b SigBasicVt) Verify(pk *PublicKeyVt, msg []byte, sig *SignatureVt) (bool, error) { - return pk.verifySignatureVt(msg, sig, b.dst) -} - -// The AggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// Each message must be different or this will return false. -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigBasicVt) AggregateVerify( - pks []*PublicKeyVt, - msgs [][]byte, - sigs []*SignatureVt, -) (bool, error) { - if !allRowsUnique(msgs) { - return false, fmt.Errorf("all messages must be distinct") - } - asig, err := aggregateSignaturesVt(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, msgs, b.dst) -} - -// SigAugVt is minimal-signature-size scheme that doesn't support FastAggregateVerification. -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.2 -type SigAugVt struct { - dst string -} - -// Creates a new BLS message augmentation signature scheme with the standard domain separation tag used for signatures. -func NewSigAugVt() *SigAugVt { - return &SigAugVt{dst: blsSignatureAugVtDst} -} - -// Creates a new BLS message augmentation signature scheme with a custom domain separation tag used for signatures. -func NewSigAugVtWithDst(signDst string) *SigAugVt { - return &SigAugVt{dst: signDst} -} - -// Creates a new BLS key pair -func (b SigAugVt) Keygen() (*PublicKeyVt, *SecretKey, error) { - return generateKeysVt() -} - -// Creates a new BLS secret key -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigAugVt) KeygenWithSeed(ikm []byte) (*PublicKeyVt, *SecretKey, error) { - return generateKeysWithSeedVt(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigAugVt) ThresholdKeygen(threshold, total uint) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysVt(threshold, total) -} - -// ThresholdKeygenWithSeed generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigAugVt) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeedVt(ikm, threshold, total) -} - -// Computes a signature in G1 from sk, a secret key, and a message -// See section 3.2.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02 -func (b SigAugVt) Sign(sk *SecretKey, msg []byte) (*SignatureVt, error) { - pk, err := sk.GetPublicKeyVt() - if err != nil { - return nil, err - } - bytes, err := pk.MarshalBinary() - if err != nil { - return nil, fmt.Errorf("MarshalBinary failed") - } - bytes = append(bytes, msg...) - return sk.createSignatureVt(bytes, b.dst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigAugVt) PartialSign( - sks *SecretKeyShare, - pk *PublicKeyVt, - msg []byte, -) (*PartialSignatureVt, error) { - if len(msg) == 0 { - return nil, fmt.Errorf("message cannot be empty or nil") - } - bytes, err := pk.MarshalBinary() - if err != nil { - return nil, fmt.Errorf("MarshalBinary failed") - } - bytes = append(bytes, msg...) - return sks.partialSignVt(bytes, b.dst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigAugVt) CombineSignatures(sigs ...*PartialSignatureVt) (*SignatureVt, error) { - return combineSigsVt(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -// See section 3.2.2 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigAugVt) Verify(pk *PublicKeyVt, msg []byte, sig *SignatureVt) (bool, error) { - bytes, err := pk.MarshalBinary() - if err != nil { - return false, err - } - bytes = append(bytes, msg...) - return pk.verifySignatureVt(bytes, sig, b.dst) -} - -// The aggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// See section 3.2.3 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigAugVt) AggregateVerify( - pks []*PublicKeyVt, - msgs [][]byte, - sigs []*SignatureVt, -) (bool, error) { - if len(pks) != len(msgs) { - return false, fmt.Errorf( - "the number of public keys does not match the number of messages: %v != %v", - len(pks), - len(msgs), - ) - } - data := make([][]byte, len(msgs)) - for i, msg := range msgs { - bytes, err := pks[i].MarshalBinary() - if err != nil { - return false, err - } - data[i] = append(bytes, msg...) - } - asig, err := aggregateSignaturesVt(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, data, b.dst) -} - -// SigEth2Vt supports signatures on Eth2. -// Internally is an alias for SigPopVt -type SigEth2Vt = SigPopVt - -// NewSigEth2Vt Creates a new BLS ETH2 signature scheme with the standard domain separation tag used for signatures. -func NewSigEth2Vt() *SigEth2Vt { - return NewSigPopVt() -} - -// SigPopVt is minimal-signature-size scheme that supports FastAggregateVerification -// and requires using proofs of possession to mitigate rogue-key attacks -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.3 -type SigPopVt struct { - sigDst string - popDst string -} - -// Creates a new BLS proof of possession signature scheme with the standard domain separation tag used for signatures. -func NewSigPopVt() *SigPopVt { - return &SigPopVt{sigDst: blsSignaturePopVtDst, popDst: blsPopProofVtDst} -} - -// Creates a new BLS message proof of possession signature scheme with a custom domain separation tag used for signatures. -func NewSigPopVtWithDst(signDst, popDst string) (*SigPopVt, error) { - if signDst == popDst { - return nil, fmt.Errorf("domain separation tags cannot be equal") - } - return &SigPopVt{sigDst: signDst, popDst: popDst}, nil -} - -// Creates a new BLS key pair -func (b SigPopVt) Keygen() (*PublicKeyVt, *SecretKey, error) { - return generateKeysVt() -} - -// Creates a new BLS secret key -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigPopVt) KeygenWithSeed(ikm []byte) (*PublicKeyVt, *SecretKey, error) { - return generateKeysWithSeedVt(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigPopVt) ThresholdKeygen(threshold, total uint) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysVt(threshold, total) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigPopVt) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKeyVt, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeedVt(ikm, threshold, total) -} - -// Computes a signature in G1 from sk, a secret key, and a message -// See section 2.6 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) Sign(sk *SecretKey, msg []byte) (*SignatureVt, error) { - return sk.createSignatureVt(msg, b.sigDst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigPopVt) PartialSign(sks *SecretKeyShare, msg []byte) (*PartialSignatureVt, error) { - return sks.partialSignVt(msg, b.sigDst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigPopVt) CombineSignatures(sigs ...*PartialSignatureVt) (*SignatureVt, error) { - return combineSigsVt(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -// See section 2.7 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) Verify(pk *PublicKeyVt, msg []byte, sig *SignatureVt) (bool, error) { - return pk.verifySignatureVt(msg, sig, b.sigDst) -} - -// The aggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// Each message must be different or this will return false. -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02 -func (b SigPopVt) AggregateVerify( - pks []*PublicKeyVt, - msgs [][]byte, - sigs []*SignatureVt, -) (bool, error) { - if !allRowsUnique(msgs) { - return false, fmt.Errorf("all messages must be distinct") - } - asig, err := aggregateSignaturesVt(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, msgs, b.sigDst) -} - -// Combine many signatures together to form a Multisignature. -// Multisignatures can be created when multiple signers jointly -// generate signatures over the same message. -func (b SigPopVt) AggregateSignatures(sigs ...*SignatureVt) (*MultiSignatureVt, error) { - g1, err := aggregateSignaturesVt(sigs...) - if err != nil { - return nil, err - } - return &MultiSignatureVt{value: g1.value}, nil -} - -// Combine many public keys together to form a Multipublickey. -// Multipublickeys are used to verify multisignatures. -func (b SigPopVt) AggregatePublicKeys(pks ...*PublicKeyVt) (*MultiPublicKeyVt, error) { - g2, err := aggregatePublicKeysVt(pks...) - if err != nil { - return nil, err - } - return &MultiPublicKeyVt{value: g2.value}, nil -} - -// Checks that a multisignature is valid for the message under the multi public key -// Similar to FastAggregateVerify except the keys and signatures have already been -// combined. See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02 -func (b SigPopVt) VerifyMultiSignature( - pk *MultiPublicKeyVt, - msg []byte, - sig *MultiSignatureVt, -) (bool, error) { - s := &SignatureVt{value: sig.value} - p := &PublicKeyVt{value: pk.value} - return p.verifySignatureVt(msg, s, b.sigDst) -} - -// FastAggregateVerify verifies an aggregated signature over the same message under the given public keys. -// See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) FastAggregateVerify( - pks []*PublicKeyVt, - msg []byte, - asig *SignatureVt, -) (bool, error) { - apk, err := aggregatePublicKeysVt(pks...) - if err != nil { - return false, err - } - return apk.verifySignatureVt(msg, asig, b.sigDst) -} - -// FastAggregateVerifyConstituent verifies a list of signature over the same message under the given public keys. -// See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) FastAggregateVerifyConstituent( - pks []*PublicKeyVt, - msg []byte, - sigs []*SignatureVt, -) (bool, error) { - asig, err := aggregateSignaturesVt(sigs...) - if err != nil { - return false, err - } - return b.FastAggregateVerify(pks, msg, asig) -} - -// Create a proof of possession for the corresponding public key. -// A proof of possession must be created for each public key to be used -// in FastAggregateVerify or a Multipublickey to avoid rogue key attacks. -// See section 3.3.2 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) PopProve(sk *SecretKey) (*ProofOfPossessionVt, error) { - return sk.createProofOfPossessionVt(b.popDst) -} - -// verify a proof of possession for the corresponding public key is valid. -// A proof of possession must be created for each public key to be used -// in FastAggregateVerify or a Multipublickey to avoid rogue key attacks. -// See section 3.3.3 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPopVt) PopVerify(pk *PublicKeyVt, pop1 *ProofOfPossessionVt) (bool, error) { - return pop1.verify(pk, b.popDst) -} diff --git a/crypto/signatures/bls/bls_sig/tiny_bls_sig.go b/crypto/signatures/bls/bls_sig/tiny_bls_sig.go deleted file mode 100644 index bc83b6e80..000000000 --- a/crypto/signatures/bls/bls_sig/tiny_bls_sig.go +++ /dev/null @@ -1,516 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Implement BLS signatures on the BLS12-381 curve -// according to https://crypto.standford.edu/~dabo/pubs/papers/BLSmultisig.html -// and https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -// this file implements signatures in G1 and public keys in G2. -// Public Keys and Signatures can be aggregated but the consumer -// must use proofs of possession to defend against rogue-key attacks. - -const ( - // Public key size in G2 - PublicKeyVtSize = 96 - // Signature size in G1 - SignatureVtSize = 48 - // Proof of Possession in G1 - ProofOfPossessionVtSize = 48 -) - -// Represents a public key in G2 -type PublicKeyVt struct { - value bls12381.G2 -} - -// Serialize a public key to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pk *PublicKeyVt) MarshalBinary() ([]byte, error) { - out := pk.value.ToCompressed() - return out[:], nil -} - -// Deserialize a public key from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the public key -// otherwise it will return an error -func (pk *PublicKeyVt) UnmarshalBinary(data []byte) error { - if len(data) != PublicKeyVtSize { - return fmt.Errorf("public key must be %d bytes", PublicKeySize) - } - var blob [PublicKeyVtSize]byte - copy(blob[:], data) - p2, err := new(bls12381.G2).FromCompressed(&blob) - if err != nil { - return err - } - if p2.IsIdentity() == 1 { - return fmt.Errorf("public keys cannot be zero") - } - pk.value = *p2 - return nil -} - -// Represents a BLS signature in G1 -type SignatureVt struct { - value bls12381.G1 -} - -// Serialize a signature to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (sig *SignatureVt) MarshalBinary() ([]byte, error) { - out := sig.value.ToCompressed() - return out[:], nil -} - -func (sig *SignatureVt) verify(pk *PublicKeyVt, message []byte, signDstVt string) (bool, error) { - return pk.verifySignatureVt(message, sig, signDstVt) -} - -// The AggregateVerify algorithm checks an aggregated signature over -// several (PK, message) pairs. -// The Signature is the output of aggregateSignaturesVt -// Each message must be different or this will return false. -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (sig *SignatureVt) aggregateVerify( - pks []*PublicKeyVt, - msgs [][]byte, - signDstVt string, -) (bool, error) { - return sig.coreAggregateVerify(pks, msgs, signDstVt) -} - -func (sig *SignatureVt) coreAggregateVerify( - pks []*PublicKeyVt, - msgs [][]byte, - signDstVt string, -) (bool, error) { - if len(pks) < 1 { - return false, fmt.Errorf("at least one key is required") - } - if len(msgs) < 1 { - return false, fmt.Errorf("at least one message is required") - } - if len(pks) != len(msgs) { - return false, fmt.Errorf( - "the number of public keys does not match the number of messages: %v != %v", - len(pks), - len(msgs), - ) - } - if sig.value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("signature is not in the correct subgroup") - } - - engine := new(bls12381.Engine) - dst := []byte(signDstVt) - // e(H(m_1), pk_1)*...*e(H(m_N), pk_N) == e(s, g2) - // However, we use only one miller loop - // by doing the equivalent of - // e(H(m_1), pk_1)*...*e(H(m_N), pk_N) * e(s^-1, g2) == 1 - for i, pk := range pks { - if pk == nil { - return false, fmt.Errorf("public key at %d is nil", i) - } - if pk.value.IsIdentity() == 1 || pk.value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("public key at %d is not in the correct subgroup", i) - } - p1 := new(bls12381.G1).Hash(native.EllipticPointHasherSha256(), msgs[i], dst) - engine.AddPair(p1, &pk.value) - } - engine.AddPairInvG2(&sig.value, new(bls12381.G2).Generator()) - return engine.Check(), nil -} - -// Deserialize a signature from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (sig *SignatureVt) UnmarshalBinary(data []byte) error { - if len(data) != SignatureVtSize { - return fmt.Errorf("signature must be %d bytes", SignatureSize) - } - var blob [SignatureVtSize]byte - copy(blob[:], data) - p1, err := new(bls12381.G1).FromCompressed(&blob) - if err != nil { - return err - } - if p1.IsIdentity() == 1 { - return fmt.Errorf("signatures cannot be zero") - } - sig.value = *p1 - return nil -} - -// Get the corresponding public key from a secret key -// Verifies the public key is in the correct subgroup -func (sk *SecretKey) GetPublicKeyVt() (*PublicKeyVt, error) { - result := new(bls12381.G2).Mul(new(bls12381.G2).Generator(), sk.value) - if result.InCorrectSubgroup() == 0 || result.IsIdentity() == 1 { - return nil, fmt.Errorf("point is not in correct subgroup") - } - return &PublicKeyVt{value: *result}, nil -} - -// Compute a signature from a secret key and message -// This signature is deterministic which protects against -// attacks arising from signing with bad randomness like -// the nonce reuse attack on ECDSA. `message` is -// hashed to a point in G1 as described in to -// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/?include_text=1 -// See Section 2.6 in https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -// nil message is not permitted but empty slice is allowed -func (sk *SecretKey) createSignatureVt(message []byte, dstVt string) (*SignatureVt, error) { - if message == nil { - return nil, fmt.Errorf("message cannot be nil") - } - if sk.value.IsZero() == 1 { - return nil, fmt.Errorf("invalid secret key") - } - p1 := new(bls12381.G1).Hash(native.EllipticPointHasherSha256(), message, []byte(dstVt)) - result := new(bls12381.G1).Mul(p1, sk.value) - if result.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("point is not in correct subgroup") - } - return &SignatureVt{value: *result}, nil -} - -// Verify a signature is valid for the message under this public key. -// See Section 2.7 in https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (pk PublicKeyVt) verifySignatureVt( - message []byte, - signature *SignatureVt, - dstVt string, -) (bool, error) { - if signature == nil || message == nil || pk.value.IsIdentity() == 1 { - return false, fmt.Errorf("signature and message and public key cannot be nil or zero") - } - if signature.value.IsIdentity() == 1 || signature.value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("signature is not in the correct subgroup") - } - engine := new(bls12381.Engine) - - p1 := new(bls12381.G1).Hash(native.EllipticPointHasherSha256(), message, []byte(dstVt)) - // e(H(m), pk) == e(s, g2) - // However, we can reduce the number of miller loops - // by doing the equivalent of - // e(H(m)^-1, pk) * e(s, g2) == 1 - engine.AddPairInvG1(p1, &pk.value) - engine.AddPair(&signature.value, new(bls12381.G2).Generator()) - return engine.Check(), nil -} - -// Combine public keys into one aggregated key -func aggregatePublicKeysVt(pks ...*PublicKeyVt) (*PublicKeyVt, error) { - if len(pks) < 1 { - return nil, fmt.Errorf("at least one public key is required") - } - result := new(bls12381.G2).Identity() - for i, k := range pks { - if k == nil { - return nil, fmt.Errorf("key at %d is nil, keys cannot be nil", i) - } - if k.value.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("key at %d is not in the correct subgroup", i) - } - result.Add(result, &k.value) - } - return &PublicKeyVt{value: *result}, nil -} - -// Combine signatures into one aggregated signature -func aggregateSignaturesVt(sigs ...*SignatureVt) (*SignatureVt, error) { - if len(sigs) < 1 { - return nil, fmt.Errorf("at least one signature is required") - } - result := new(bls12381.G1).Identity() - for i, s := range sigs { - if s == nil { - return nil, fmt.Errorf("signature at %d is nil, signature cannot be nil", i) - } - if s.value.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("signature at %d is not in the correct subgroup", i) - } - result.Add(result, &s.value) - } - return &SignatureVt{value: *result}, nil -} - -// A proof of possession scheme uses a separate public key validation -// step, called a proof of possession, to defend against rogue key -// attacks. This enables an optimization to aggregate signature -// verification for the case that all signatures are on the same -// message. -type ProofOfPossessionVt struct { - value bls12381.G1 -} - -// Generates a proof-of-possession (PoP) for this secret key. The PoP signature should be verified before -// before accepting any aggregate signatures related to the corresponding pubkey. -func (sk *SecretKey) createProofOfPossessionVt(popDstVt string) (*ProofOfPossessionVt, error) { - pk, err := sk.GetPublicKeyVt() - if err != nil { - return nil, err - } - msg, err := pk.MarshalBinary() - if err != nil { - return nil, err - } - sig, err := sk.createSignatureVt(msg, popDstVt) - if err != nil { - return nil, err - } - return &ProofOfPossessionVt{value: sig.value}, nil -} - -// Serialize a proof of possession to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pop *ProofOfPossessionVt) MarshalBinary() ([]byte, error) { - out := pop.value.ToCompressed() - return out[:], nil -} - -// Deserialize a proof of possession from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (pop *ProofOfPossessionVt) UnmarshalBinary(data []byte) error { - p1 := new(SignatureVt) - err := p1.UnmarshalBinary(data) - if err != nil { - return err - } - pop.value = p1.value - return nil -} - -// Verifies that PoP is valid for this pubkey. In order to prevent rogue key attacks, a PoP must be validated -// for each pubkey in an aggregated signature. -func (pop *ProofOfPossessionVt) verify(pk *PublicKeyVt, popDstVt string) (bool, error) { - if pk == nil { - return false, fmt.Errorf("public key cannot be nil") - } - msg, err := pk.MarshalBinary() - if err != nil { - return false, err - } - return pk.verifySignatureVt(msg, &SignatureVt{value: pop.value}, popDstVt) -} - -// Represents an MultiSignature in G1. A multisignature is used when multiple signatures -// are calculated over the same message vs an aggregate signature where each message signed -// is a unique. -type MultiSignatureVt struct { - value bls12381.G1 -} - -// Serialize a multi-signature to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (sig *MultiSignatureVt) MarshalBinary() ([]byte, error) { - out := sig.value.ToCompressed() - return out[:], nil -} - -// Check a multisignature is valid for a multipublickey and a message -func (sig *MultiSignatureVt) verify( - pk *MultiPublicKeyVt, - message []byte, - signDstVt string, -) (bool, error) { - if pk == nil { - return false, fmt.Errorf("public key cannot be nil") - } - p := &PublicKeyVt{value: pk.value} - return p.verifySignatureVt(message, &SignatureVt{value: sig.value}, signDstVt) -} - -// Deserialize a signature from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (sig *MultiSignatureVt) UnmarshalBinary(data []byte) error { - if len(data) != SignatureVtSize { - return fmt.Errorf("multi signature must be %v bytes", SignatureSize) - } - s1 := new(SignatureVt) - err := s1.UnmarshalBinary(data) - if err != nil { - return err - } - sig.value = s1.value - return nil -} - -// Represents accumulated multiple Public Keys in G2 for verifying a multisignature -type MultiPublicKeyVt struct { - value bls12381.G2 -} - -// Serialize a public key to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pk *MultiPublicKeyVt) MarshalBinary() ([]byte, error) { - out := pk.value.ToCompressed() - return out[:], nil -} - -// Deserialize a public key from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the public key -// otherwise it will return an error -func (pk *MultiPublicKeyVt) UnmarshalBinary(data []byte) error { - if len(data) != PublicKeyVtSize { - return fmt.Errorf("multi public key must be %v bytes", PublicKeySize) - } - p2 := new(PublicKeyVt) - err := p2.UnmarshalBinary(data) - if err != nil { - return err - } - pk.value = p2.value - return nil -} - -// Check a multisignature is valid for a multipublickey and a message -func (pk *MultiPublicKeyVt) verify( - message []byte, - sig *MultiSignatureVt, - signDstVt string, -) (bool, error) { - return sig.verify(pk, message, signDstVt) -} - -// PartialSignatureVt represents threshold Gap Diffie-Hellman BLS signature -// that can be combined with other partials to yield a completed BLS signature -// See section 3.2 in -type PartialSignatureVt struct { - identifier byte - signature bls12381.G1 -} - -// partialSignVt creates a partial signature that can be combined with other partial signatures -// to yield a complete signature -func (sks *SecretKeyShare) partialSignVt( - message []byte, - signDst string, -) (*PartialSignatureVt, error) { - if len(message) == 0 { - return nil, fmt.Errorf("message cannot be empty or nil") - } - p1 := new(bls12381.G1).Hash(native.EllipticPointHasherSha256(), message, []byte(signDst)) - - var blob [SecretKeySize]byte - copy(blob[:], internal.ReverseScalarBytes(sks.value)) - s, err := bls12381.Bls12381FqNew().SetBytes(&blob) - if err != nil { - return nil, err - } - result := new(bls12381.G1).Mul(p1, s) - if result.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("point is not on correct subgroup") - } - return &PartialSignatureVt{identifier: sks.identifier, signature: *result}, nil -} - -// combineSigsVt gathers partial signatures and yields a complete signature -func combineSigsVt(partials []*PartialSignatureVt) (*SignatureVt, error) { - if len(partials) < 2 { - return nil, fmt.Errorf("must have at least 2 partial signatures") - } - if len(partials) > 255 { - return nil, fmt.Errorf("unsupported to combine more than 255 signatures") - } - - xVars, yVars, err := splitXYVt(partials) - if err != nil { - return nil, err - } - - sTmp := new(bls12381.G1).Identity() - sig := new(bls12381.G1).Identity() - - // Lagrange interpolation - basis := bls12381.Bls12381FqNew() - for i, xi := range xVars { - basis.SetOne() - - for j, xj := range xVars { - if i == j { - continue - } - - num := bls12381.Bls12381FqNew().Neg(xj) // x - x_m - den := bls12381.Bls12381FqNew().Sub(xi, xj) // x_j - x_m - _, wasInverted := den.Invert(den) - // wasInverted == false if den == 0 - if !wasInverted { - return nil, fmt.Errorf("signatures cannot be recombined") - } - basis.Mul(basis, num.Mul(num, den)) - } - sTmp.Mul(yVars[i], basis) - sig.Add(sig, sTmp) - } - if sig.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("signature is not in the correct subgroup") - } - - return &SignatureVt{value: *sig}, nil -} - -// Ensure no duplicates x values and convert x values to field elements -func splitXYVt(partials []*PartialSignatureVt) ([]*native.Field, []*bls12381.G1, error) { - x := make([]*native.Field, len(partials)) - y := make([]*bls12381.G1, len(partials)) - - dup := make(map[byte]bool) - - for i, sp := range partials { - if sp == nil { - return nil, nil, fmt.Errorf("partial signature cannot be nil") - } - if _, exists := dup[sp.identifier]; exists { - return nil, nil, fmt.Errorf("duplicate signature included") - } - if sp.signature.InCorrectSubgroup() == 0 { - return nil, nil, fmt.Errorf("signature is not in the correct subgroup") - } - dup[sp.identifier] = true - x[i] = bls12381.Bls12381FqNew().SetUint64(uint64(sp.identifier)) - y[i] = &sp.signature - } - return x, y, nil -} diff --git a/crypto/signatures/bls/bls_sig/tiny_bls_sig_aug_test.go b/crypto/signatures/bls/bls_sig/tiny_bls_sig_aug_test.go deleted file mode 100644 index 3f5ed17ec..000000000 --- a/crypto/signatures/bls/bls_sig/tiny_bls_sig_aug_test.go +++ /dev/null @@ -1,389 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -func generateAugSignatureG1(sk *SecretKey, msg []byte, t *testing.T) *SignatureVt { - bls := NewSigAugVt() - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Aug Sign failed") - } - return sig -} - -func generateAugAggregateDataG1(t *testing.T) ([]*PublicKeyVt, []*SignatureVt, [][]byte) { - msgs := make([][]byte, numAggregateG1) - pks := make([]*PublicKeyVt, numAggregateG1) - sigs := make([]*SignatureVt, numAggregateG1) - ikm := make([]byte, 32) - bls := NewSigAugVt() - - for i := 0; i < numAggregateG1; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - msg := make([]byte, 20) - readRand(msg, t) - sig := generateAugSignatureG1(sk, msg, t) - msgs[i] = msg - sigs[i] = sig - pks[i] = pk - } - return pks, sigs, msgs -} - -func TestAugKeyGenG1Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAugVt() - _, _, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } -} - -func TestAugKeyGenG1Fail(t *testing.T) { - ikm := make([]byte, 10) - readRand(ikm, t) - bls := NewSigAugVt() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Aug KeyGen succeeded when it should've failed") - } -} - -func TestAugCustomDstG1(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAugVtWithDst("BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_TEST") - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug Custom Dst KeyGen failed") - } - - readRand(ikm, t) - sig, err := bls.Sign(sk, ikm) - if err != nil { - t.Errorf("Aug Custom Dst Sign failed") - } - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Aug Custom Dst Verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Aug Custom Dst Verify succeeded when it should've failed.") - } -} - -func TestAugSigningG1(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAugVt() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - readRand(ikm, t) - sig := generateAugSignatureG1(sk, ikm, t) - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Aug Verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Aug Verify succeeded when it should've failed.") - } -} - -func TestAugAggregateVerifyG1Works(t *testing.T) { - pks, sigs, msgs := generateAugAggregateDataG1(t) - bls := NewSigAugVt() - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug AggregateVerify failed") - } -} - -func TestAugAggregateVerifyG1BadPks(t *testing.T) { - bls := NewSigAugVt() - pks, sigs, msgs := generateAugAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug AggregateVerify failed") - } - - pks[0] = pks[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug AggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - pkValue := new(bls12381.G2).Identity() - pks[0] = &PublicKeyVt{value: *pkValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug AggregateVerify succeeded with zero byte public key it should've failed") - } - - // Try with base generator - pkValue.Generator() - pks[0] = &PublicKeyVt{value: *pkValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Aug aggregateVerify succeeded with the base generator public key it should've failed", - ) - } -} - -func TestAugAggregateVerifyG1BadSigs(t *testing.T) { - bls := NewSigAugVt() - pks, sigs, msgs := generateAugAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug aggregateVerify failed") - } - - sigs[0] = sigs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } - - // Try a zero signature to make sure it doesn't crash - sigValue := new(bls12381.G1).Identity() - sigs[0] = &SignatureVt{value: *sigValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded with zero byte signature it should've failed") - } - - // Try with base generator - sigValue.Generator() - sigs[0] = &SignatureVt{value: *sigValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Aug aggregateVerify succeeded with the base generator signature it should've failed", - ) - } -} - -func TestAugAggregateVerifyG1BadMsgs(t *testing.T) { - bls := NewSigAugVt() - pks, sigs, msgs := generateAugAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug aggregateVerify failed") - } - - // Test len(pks) != len(msgs) - if res, _ := bls.AggregateVerify(pks, msgs[0:8], sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } - - msgs[0] = msgs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } -} - -func TestAugAggregateVerifyG1DupMsg(t *testing.T) { - bls := NewSigAugVt() - - // Only two messages but repeated - messages := make([][]byte, numAggregateG1) - messages[0] = []byte("Yes") - messages[1] = []byte("No") - for i := 2; i < numAggregateG1; i++ { - messages[i] = messages[i%2] - } - - pks := make([]*PublicKeyVt, numAggregateG1) - sigs := make([]*SignatureVt, numAggregateG1) - - ikm := make([]byte, 32) - for i := 0; i < numAggregateG1; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - sig := generateAugSignatureG1(sk, messages[i], t) - pks[i] = pk - sigs[i] = sig - } - - if res, _ := bls.AggregateVerify(pks, messages, sigs); !res { - t.Errorf("Aug aggregateVerify failed for duplicate messages") - } -} - -func TestBlsAugG1KeyGen(t *testing.T) { - bls := NewSigAugVt() - _, _, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } -} - -func TestAugVtThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigAugVt() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(1, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestAugVtThresholdKeygen(t *testing.T) { - bls := NewSigAugVt() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestAugPartialSignVt(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigAugVt() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], pk, msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], pk, msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures failed: %v", err) - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestAugVtPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigAugVt() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignatureVt, total) - sigs2 := make([]*PartialSignatureVt, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], pk1, msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], pk2, msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} - -func TestEmptyMessageAugPartialSignVt(t *testing.T) { - bls := NewSigAugVt() - pk, sks, err := bls.ThresholdKeygen(5, 6) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - - // Sign an empty message - _, err = bls.PartialSign(sks[0], pk, []byte{}) - if err == nil { - t.Errorf("Expected partial sign to fail on empty message") - } -} - -func TestNilMessageAugPartialSignVt(t *testing.T) { - bls := NewSigAugVt() - pk, sks, err := bls.ThresholdKeygen(5, 6) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - - // Sign nil message - _, err = bls.PartialSign(sks[0], pk, nil) - if err == nil { - t.Errorf("Expected partial signing to fail on nil message") - } -} diff --git a/crypto/signatures/bls/bls_sig/tiny_bls_sig_basic_test.go b/crypto/signatures/bls/bls_sig/tiny_bls_sig_basic_test.go deleted file mode 100644 index a0c0494e7..000000000 --- a/crypto/signatures/bls/bls_sig/tiny_bls_sig_basic_test.go +++ /dev/null @@ -1,385 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -func generateBasicSignatureG1(sk *SecretKey, msg []byte, t *testing.T) *SignatureVt { - bls := NewSigBasicVt() - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Basic Sign failed") - } - return sig -} - -func generateBasicAggregateDataG1(t *testing.T) ([]*PublicKeyVt, []*SignatureVt, [][]byte) { - msgs := make([][]byte, numAggregateG1) - pks := make([]*PublicKeyVt, numAggregateG1) - sigs := make([]*SignatureVt, numAggregateG1) - ikm := make([]byte, 32) - bls := NewSigBasicVt() - - for i := 0; i < numAggregateG1; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } - msg := make([]byte, 20) - readRand(msg, t) - sig := generateBasicSignatureG1(sk, msg, t) - msgs[i] = msg - sigs[i] = sig - pks[i] = pk - } - return pks, sigs, msgs -} - -func TestBasicKeyGenG1Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasicVt() - _, _, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } -} - -func TestBasicKeyGenG1Fail(t *testing.T) { - ikm := make([]byte, 10) - readRand(ikm, t) - bls := NewSigBasicVt() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Basic KeyGen succeeded when it should've failed") - } -} - -func TestBasicCustomDstG1(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasicVtWithDst("BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_TEST") - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic Custom Dst KeyGen failed") - } - - readRand(ikm, t) - sig, err := bls.Sign(sk, ikm) - if err != nil { - t.Errorf("Basic Custom Dst Sign failed") - } - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Basic Custon Dst Verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Basic Custom Dst Verify succeeded when it should've failed.") - } -} - -func TestBasicSigningG1(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasicVt() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - readRand(ikm, t) - sig := generateBasicSignatureG1(sk, ikm, t) - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Basic Verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Basic Verify succeeded when it should've failed.") - } -} - -func TestBasicSigningEmptyMessage(t *testing.T) { - bls := NewSigBasicVt() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - // Sign an empty message - _, err = bls.Sign(sk, []byte{}) - if err != nil { - t.Errorf("Expected signing message to succeed: %v", err) - } -} - -func TestBasicSigningNilMessage(t *testing.T) { - bls := NewSigBasicVt() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - // Sign nil message - _, err = bls.Sign(sk, nil) - if err == nil { - t.Errorf("Expected signing empty message to fail") - } -} - -func TestBasicAggregateVerifyG1Works(t *testing.T) { - pks, sigs, msgs := generateBasicAggregateDataG1(t) - bls := NewSigBasicVt() - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic AggregateVerify failed") - } -} - -func TestBasicAggregateVerifyG1BadPks(t *testing.T) { - bls := NewSigBasicVt() - pks, sigs, msgs := generateBasicAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic aggregateVerify failed") - } - - pks[0] = pks[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - pkValue := new(bls12381.G2).Identity() - pks[0] = &PublicKeyVt{value: *pkValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded with zero byte public key it should've failed") - } - - // Try with base generator - pkValue.Generator() - pks[0] = &PublicKeyVt{value: *pkValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Basic aggregateVerify succeeded with the base generator public key it should've failed", - ) - } -} - -func TestBasicAggregateVerifyG1BadSigs(t *testing.T) { - bls := NewSigBasicVt() - pks, sigs, msgs := generateBasicAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic aggregateVerify failed") - } - - sigs[0] = sigs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - g1 := new(bls12381.G1).Identity() - sigValue := g1.Identity() - sigs[0] = &SignatureVt{value: *sigValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded with zero byte signature it should've failed") - } - - // Try with base generator - sigValue = g1.Generator() - sigs[0] = &SignatureVt{value: *sigValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Basic aggregateVerify succeeded with the base generator signature it should've failed", - ) - } -} - -func TestBasicAggregateVerifyG1BadMsgs(t *testing.T) { - bls := NewSigBasicVt() - pks, sigs, msgs := generateBasicAggregateDataG1(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic aggregateVerify failed") - } - - msgs[0] = msgs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded when it should've failed") - } -} - -func TestBasicVtThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigBasicVt() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(0, 1) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestBasicVtThresholdKeygen(t *testing.T) { - bls := NewSigBasicVt() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("Keygen failed: %v", err) - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestBasicPartialSignVt(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigBasicVt() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures succeeded when it should've failed") - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestBasicVtPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigBasicVt() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignatureVt, total) - sigs2 := make([]*PartialSignatureVt, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} - -func TestIdentityPublicKeyVt(t *testing.T) { - bls := NewSigBasicVt() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } - msg := []byte{0, 0, 0, 0} - sig, _ := bls.Sign(sk, msg) - pk := PublicKeyVt{value: *new(bls12381.G2).Identity()} - if res, _ := bls.Verify(&pk, msg, sig); res { - t.Errorf("Verify succeeded when the public key is the identity.") - } -} - -func TestThresholdSignTooHighAndLowVt(t *testing.T) { - bls := NewSigBasicVt() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - msg := make([]byte, 10) - - ps, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - - _, err = bls.CombineSignatures(ps) - if err == nil { - t.Errorf("CombinSignatures succeeded when it should've failed") - } - - pss := make([]*PartialSignatureVt, 256) - - _, err = bls.CombineSignatures(pss...) - if err == nil { - t.Errorf("CombinSignatures succeeded when it should've failed") - } -} diff --git a/crypto/signatures/bls/bls_sig/tiny_bls_sig_pop_test.go b/crypto/signatures/bls/bls_sig/tiny_bls_sig_pop_test.go deleted file mode 100644 index 4970d0699..000000000 --- a/crypto/signatures/bls/bls_sig/tiny_bls_sig_pop_test.go +++ /dev/null @@ -1,962 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "bytes" - "math/big" - "math/rand" - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -const numAggregateG1 = 10 - -func TestGetPublicKeyG2(t *testing.T) { - sk := genSecretKey(t) - pk := genPublicKeyVt(sk, t) - actual := marshalStruct(pk, t) - expected := []byte{ - 175, - 76, - 33, - 103, - 184, - 172, - 12, - 111, - 24, - 87, - 84, - 61, - 243, - 82, - 99, - 76, - 131, - 95, - 171, - 237, - 145, - 143, - 7, - 93, - 205, - 148, - 104, - 29, - 153, - 103, - 187, - 206, - 112, - 223, - 252, - 198, - 102, - 41, - 38, - 244, - 228, - 223, - 102, - 16, - 216, - 152, - 231, - 250, - 7, - 111, - 90, - 98, - 194, - 244, - 101, - 251, - 69, - 130, - 11, - 209, - 41, - 210, - 133, - 105, - 217, - 179, - 190, - 1, - 6, - 155, - 135, - 2, - 168, - 249, - 253, - 41, - 59, - 87, - 8, - 49, - 231, - 198, - 142, - 30, - 186, - 44, - 175, - 17, - 198, - 63, - 210, - 176, - 237, - 171, - 11, - 127, - } - if !bytes.Equal(actual, expected) { - t.Errorf("Expected GetPublicKeyVt to pass but failed.") - } -} - -func testSignG1(message []byte, t *testing.T) { - sk := genSecretKey(t) - sig := genSignatureVt(sk, message, t) - pk := genPublicKeyVt(sk, t) - - bls := NewSigPopVt() - - if res, _ := bls.Verify(pk, message, sig); !res { - t.Errorf("createSignatureVt failed when it should've passed.") - } -} - -func TestSignG1EmptyNilMessage(t *testing.T) { - sk := genSecretKey(t) - bls := NewSigPopVt() - sig, _ := bls.Sign(sk, nil) - pk := genPublicKeyVt(sk, t) - - if res, _ := bls.Verify(pk, nil, sig); res { - t.Errorf("createSignature succeeded when it should've failed") - } - - message := []byte{} - sig = genSignatureVt(sk, message, t) - - if res, err := bls.Verify(pk, message, sig); !res { - t.Errorf("create and verify failed on empty message: %v", err) - } -} - -func TestSignG1OneByteMessage(t *testing.T) { - message := []byte{1} - testSignG1(message, t) -} - -func TestSignG1LargeMessage(t *testing.T) { - message := make([]byte, 1048576) - testSignG1(message, t) -} - -func TestSignG1RandomMessage(t *testing.T) { - message := make([]byte, 65537) - readRand(message, t) - testSignG1(message, t) -} - -func TestSignG1BadMessage(t *testing.T) { - message := make([]byte, 1024) - sk := genSecretKey(t) - sig := genSignatureVt(sk, message, t) - pk := genPublicKeyVt(sk, t) - message = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} - - bls := NewSigPopVt() - - if res, _ := bls.Verify(pk, message, sig); res { - t.Errorf("Expected signature to not verify") - } -} - -func TestBadConversionsG1(t *testing.T) { - sk := genSecretKey(t) - message := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} - sig := genSignatureVt(sk, message, t) - pk := genPublicKeyVt(sk, t) - - bls := NewSigPopVt() - - if res, _ := bls.Verify(pk, message, sig); !res { - t.Errorf("Signature should be valid") - } - if res, _ := sig.verify(pk, message, blsSignaturePopVtDst); !res { - t.Errorf("Signature should be valid") - } - - // Convert public key to signature in G2 - sig2 := new(Signature) - err := sig2.UnmarshalBinary(marshalStruct(pk, t)) - if err != nil { - t.Errorf("Should be able to convert to signature in G2") - } - pk2 := new(PublicKey) - err = pk2.UnmarshalBinary(marshalStruct(sig, t)) - if err != nil { - t.Errorf("Should be able to convert to public key in G1") - } - - res, _ := pk2.verifySignature(message, sig2, blsSignaturePopVtDst) - if res { - t.Errorf("The signature shouldn't verify") - } -} - -func TestAggregatePublicKeysG2(t *testing.T) { - pks := []*PublicKeyVt{} - ikm := make([]byte, 32) - for i := 0; i < 20; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - pk := genPublicKeyVt(sk, t) - pks = append(pks, pk) - } - apk1, err := aggregatePublicKeysVt(pks...) - if err != nil { - t.Errorf("%v", err) - } - rng := rand.New(rand.NewSource(1234567890)) - rng.Shuffle(len(pks), func(i, j int) { pks[i], pks[j] = pks[j], pks[i] }) - apk2, err := aggregatePublicKeysVt(pks...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(apk1, t), marshalStruct(apk2, t)) { - t.Errorf("Aggregated public keys should be equal") - } - rand.Shuffle(len(pks), func(i, j int) { pks[i], pks[j] = pks[j], pks[i] }) - apk1, err = aggregatePublicKeysVt(pks...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(apk1, t), marshalStruct(apk2, t)) { - t.Errorf("Aggregated public keys should be equal") - } -} - -func TestAggregateSignaturesG1(t *testing.T) { - sigs := []*SignatureVt{} - ikm := make([]byte, 32) - for i := 0; i < 20; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - sig := genSignatureVt(sk, ikm, t) - sigs = append(sigs, sig) - } - asig1, err := aggregateSignaturesVt(sigs...) - if err != nil { - t.Errorf("%v", err) - } - rng2 := rand.New(rand.NewSource(1234567890)) - rng2.Shuffle(len(sigs), func(i, j int) { sigs[i], sigs[j] = sigs[j], sigs[i] }) - asig2, err := aggregateSignaturesVt(sigs...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(asig1, t), marshalStruct(asig2, t)) { - t.Errorf("Aggregated signatures should be equal") - } - rand.Shuffle(len(sigs), func(i, j int) { sigs[i], sigs[j] = sigs[j], sigs[i] }) - asig1, err = aggregateSignaturesVt(sigs...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(asig1, t), marshalStruct(asig2, t)) { - t.Errorf("Aggregated signatures should be equal") - } -} - -func initAggregatedTestValuesG1(messages [][]byte, t *testing.T) ([]*PublicKeyVt, []*SignatureVt) { - pks := []*PublicKeyVt{} - sigs := []*SignatureVt{} - ikm := make([]byte, 32) - for i := 0; i < numAggregateG1; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - sig := genSignatureVt(sk, messages[i%len(messages)], t) - sigs = append(sigs, sig) - pk := genPublicKeyVt(sk, t) - pks = append(pks, pk) - } - return pks, sigs -} - -func TestAggregatedFunctionalityG1(t *testing.T) { - message := make([]byte, 20) - messages := make([][]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG1(messages, t) - - bls := NewSigPopVt() - asig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - if res, _ := bls.VerifyMultiSignature(apk, message, asig); !res { - t.Errorf("Should verify aggregated signatures with same message") - } - if res, _ := asig.verify(apk, message, blsSignaturePopVtDst); !res { - t.Errorf("MultiSignature.verify failed.") - } - if res, _ := apk.verify(message, asig, blsSignaturePopVtDst); !res { - t.Errorf("MultiPublicKey.verify failed.") - } -} - -func TestBadAggregatedFunctionalityG1(t *testing.T) { - message := make([]byte, 20) - messages := make([][]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG1(messages, t) - - bls := NewSigPopVt() - - apk, err := bls.AggregatePublicKeys(pks[2:]...) - if err != nil { - t.Errorf("%v", err) - } - asig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - - if res, _ := bls.VerifyMultiSignature(apk, message, asig); res { - t.Errorf( - "Should not verify aggregated signatures with same message when some public keys are missing", - ) - } - - apk, err = bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - asig, err = bls.AggregateSignatures(sigs[2:]...) - if err != nil { - t.Errorf("%v", err) - } - if res, _ := bls.VerifyMultiSignature(apk, message, asig); res { - t.Errorf( - "Should not verify aggregated signatures with same message when some signatures are missing", - ) - } - - asig, err = bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - - badmsg := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} - if res, _ := bls.VerifyMultiSignature(apk, badmsg, asig); res { - t.Errorf("Should not verify aggregated signature with bad message") - } -} - -func TestAggregateVerifyG1Pass(t *testing.T) { - messages := make([][]byte, numAggregateG1) - for i := 0; i < numAggregateG1; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - if res, _ := bls.AggregateVerify(pks, messages, sigs); !res { - t.Errorf("Expected aggregateVerify to pass but failed") - } -} - -func TestAggregateVerifyG1MsgSigCntMismatch(t *testing.T) { - messages := make([][]byte, 8) - for i := 0; i < 8; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - if res, _ := bls.AggregateVerify(pks, messages, sigs); res { - t.Errorf("Expected AggregateVerifyG1 to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG1FailDupMsg(t *testing.T) { - messages := make([][]byte, 10) - for i := 0; i < 9; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - // Duplicate message - messages[9] = messages[0] - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - if res, _ := bls.AggregateVerify(pks, messages, sigs); res { - t.Errorf("Expected aggregateVerify to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG1FailIncorrectMsg(t *testing.T) { - messages := make([][]byte, 10) - for i := 0; i < 9; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - // Duplicate message - messages[9] = messages[0] - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - if res, _ := bls.AggregateVerify(pks[2:], messages[2:], sigs); res { - t.Errorf("Expected aggregateVerify to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG1OneMsg(t *testing.T) { - messages := make([][]byte, 1) - messages[0] = make([]byte, 20) - sk := genSecretKey(t) - sig := genSignatureVt(sk, messages[0], t) - pk := genPublicKeyVt(sk, t) - bls := NewSigPopVt() - // Should be the same as verifySignatureVt - if res, _ := bls.AggregateVerify([]*PublicKeyVt{pk}, messages, []*SignatureVt{sig}); !res { - t.Errorf("Expected AggregateVerifyG1OneMsg to pass but failed") - } -} - -func TestVerifyG1Mutability(t *testing.T) { - // verify should not change any inputs - ikm := make([]byte, 32) - ikm_copy := make([]byte, 32) - readRand(ikm, t) - copy(ikm_copy, ikm) - bls := NewSigPopVt() - pk, sk, err := bls.KeygenWithSeed(ikm) - - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPopVt.KeygenWithSeed modifies ikm") - } - if err != nil { - t.Errorf("Expected KeygenWithSeed to succeed but failed.") - } - sig, err := bls.Sign(sk, ikm) - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPopVt.Sign modifies message") - } - if err != nil { - t.Errorf("SigPopVt.KeygenWithSeed to succeed but failed.") - } - sigCopy := marshalStruct(sig, t) - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Expected verify to succeed but failed.") - } - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPopVt.verify modifies message") - } - if !bytes.Equal(sigCopy, marshalStruct(sig, t)) { - t.Errorf("SigPopVt.verify modifies signature") - } -} - -func TestPublicKeyG2FromBadBytes(t *testing.T) { - pk := make([]byte, 32) - err := new(PublicKeyVt).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG2FromBytes to fail but passed") - } - // All zeros - pk = make([]byte, PublicKeyVtSize) - // See https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization - // 1 << 7 == compressed - // 1 << 6 == infinity or zero - pk[0] = 0xc0 - err = new(PublicKeyVt).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG2FromBytes to fail but passed") - } - sk := genSecretKey(t) - pk1, err := sk.GetPublicKeyVt() - if err != nil { - t.Errorf("Expected GetPublicKeyVt to pass but failed.") - } - out := marshalStruct(pk1, t) - out[3] += 1 - err = new(PublicKeyVt).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG2FromBytes to fail but passed") - } -} - -func TestSignatureG1FromBadBytes(t *testing.T) { - sig := make([]byte, 32) - err := new(SignatureVt).UnmarshalBinary(sig) - if err == nil { - t.Errorf("Expected SignatureG1FromBytes to fail but passed") - } - // All zeros - sig = make([]byte, SignatureVtSize) - // See https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization - // 1 << 7 == compressed - // 1 << 6 == infinity or zero - sig[0] = 0xc0 - err = new(SignatureVt).UnmarshalBinary(sig) - if err == nil { - t.Errorf("Expected SignatureG1FromBytes to fail but passed") - } -} - -func TestBadSecretKeyG1(t *testing.T) { - sk := &SecretKey{value: bls12381.Bls12381FqNew()} - pk, err := sk.GetPublicKeyVt() - if err == nil { - t.Errorf("Expected GetPublicKeyVt to fail with 0 byte secret key but passed: %v", pk) - } - _ = sk.UnmarshalBinary(sk.value.Params.BiModulus.Bytes()) - pk, err = sk.GetPublicKeyVt() - if err == nil { - t.Errorf("Expected GetPublicKeyVt to fail with secret key with Q but passed: %v", pk) - } - - err = sk.UnmarshalBinary([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}) - if err == nil { - t.Errorf("Expected SecretKeyFromBytes to fail with not enough bytes but passed: %v", pk) - } - - err = sk.UnmarshalBinary(make([]byte, 32)) - if err == nil { - t.Errorf("Expected SecretKeyFromBytes to fail but passed: %v", pk) - } -} - -func TestProofOfPossessionG1Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigPopVt() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Key gen failed but should've succeeded") - } - pop, err := bls.PopProve(sk) - if err != nil { - t.Errorf("PopProve failed but should've succeeded") - } - if res, _ := bls.PopVerify(pk, pop); !res { - t.Errorf("PopVerify failed but should've succeeded") - } -} - -func TestProofOfPossessionG1FromBadKey(t *testing.T) { - ikm := make([]byte, 32) - value := new(big.Int) - value.SetBytes(ikm) - sk := SecretKey{value: bls12381.Bls12381FqNew().SetBigInt(value)} - _, err := sk.createProofOfPossessionVt(blsSignaturePopVtDst) - if err == nil { - t.Errorf("createProofOfPossessionVt should've failed but succeeded.") - } -} - -func TestProofOfPossessionG1BytesWorks(t *testing.T) { - sk := genSecretKey(t) - pop, err := sk.createProofOfPossessionVt(blsSignaturePopVtDst) - if err != nil { - t.Errorf("CreateProofOfPossesionG1 failed but shouldn've succeeded.") - } - out := marshalStruct(pop, t) - if len(out) != ProofOfPossessionVtSize { - t.Errorf( - "ProofOfPossessionBytes incorrect size: expected %v, got %v", - ProofOfPossessionVtSize, - len(out), - ) - } - pop2 := new(ProofOfPossessionVt) - err = pop2.UnmarshalBinary(out) - if err != nil { - t.Errorf("ProofOfPossessionVt.UnmarshalBinary failed: %v", err) - } - out2 := marshalStruct(pop2, t) - if !bytes.Equal(out, out2) { - t.Errorf("ProofOfPossessionVt.UnmarshalBinary failed, not equal when deserialized") - } -} - -func TestProofOfPossessionG1BadBytes(t *testing.T) { - zeros := make([]byte, ProofOfPossessionVtSize) - temp := new(ProofOfPossessionVt) - err := temp.UnmarshalBinary(zeros) - if err == nil { - t.Errorf("ProofOfPossessionVt.UnmarshalBinary shouldn've failed but succeeded.") - } -} - -func TestProofOfPossessionG1Fails(t *testing.T) { - sk := genSecretKey(t) - pop, err := sk.createProofOfPossessionVt(blsSignaturePopVtDst) - if err != nil { - t.Errorf("Expected createProofOfPossessionVt to succeed but failed.") - } - - ikm := make([]byte, 32) - readRand(ikm, t) - sk = genRandSecretKey(ikm, t) - bad, err := sk.GetPublicKeyVt() - if err != nil { - t.Errorf("Expected PublicKeyG2FromBytes to succeed but failed: %v", err) - } - if res, _ := pop.verify(bad, blsSignaturePopVtDst); res { - t.Errorf("Expected ProofOfPossession verify to fail but succeeded.") - } -} - -func TestMultiSigG1Bytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - _, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - msig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - msigBytes := marshalStruct(msig, t) - if len(msigBytes) != SignatureVtSize { - t.Errorf( - "Invalid multi-sig length. Expected %d bytes, found %d", - SignatureVtSize, - len(msigBytes), - ) - } - msig2 := new(MultiSignatureVt) - err = msig2.UnmarshalBinary(msigBytes) - if err != nil { - t.Errorf("MultiSignatureG1FromBytes failed with %v", err) - } - msigBytes2 := marshalStruct(msig2, t) - - if !bytes.Equal(msigBytes, msigBytes2) { - t.Errorf("Bytes methods not equal.") - } -} - -func TestMultiSigG1BadBytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - _, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - msig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - msigBytes := marshalStruct(msig, t) - if len(msigBytes) != SignatureVtSize { - t.Errorf( - "Invalid multi-sig length. Expected %d bytes, found %d", - SignatureSize, - len(msigBytes), - ) - } - msigBytes[0] = 0 - temp := new(MultiSignatureVt) - err = temp.UnmarshalBinary(msigBytes) - if err == nil { - t.Errorf("MultiSignatureG1FromBytes should've failed but succeeded") - } - msigBytes = make([]byte, SignatureVtSize) - err = temp.UnmarshalBinary(msigBytes) - if err == nil { - t.Errorf("MultiSignatureG1FromBytes should've failed but succeeded") - } -} - -func TestMultiPubkeyG2Bytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - pks, _ := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - apkBytes := marshalStruct(apk, t) - if len(apkBytes) != PublicKeyVtSize { - t.Errorf("MultiPublicKeyVt has an incorrect size") - } - apk2 := new(MultiPublicKeyVt) - err = apk2.UnmarshalBinary(apkBytes) - if err != nil { - t.Errorf("MultiPublicKeyVt.UnmarshalBinary failed with %v", err) - } - apk2Bytes := marshalStruct(apk2, t) - if !bytes.Equal(apkBytes, apk2Bytes) { - t.Errorf("Bytes methods not equal.") - } -} - -func TestMultiPubkeyG2BadBytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - pks, _ := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - apkBytes := marshalStruct(apk, t) - if len(apkBytes) != PublicKeyVtSize { - t.Errorf("MultiPublicKeyVt has an incorrect size") - } - apkBytes[0] = 0 - temp := new(MultiPublicKeyVt) - err = temp.UnmarshalBinary(apkBytes) - if err == nil { - t.Errorf("MultiPublicKeyVt.UnmarshalBinary should've failed but succeeded") - } - apkBytes = make([]byte, PublicKeyVtSize) - err = temp.UnmarshalBinary(apkBytes) - if err == nil { - t.Errorf("MultiPublicKeyVt.UnmarshalBinary should've failed but succeeded") - } -} - -func TestFastAggregateVerifyConstituentG1Works(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - - if res, _ := bls.FastAggregateVerifyConstituent(pks, message, sigs); !res { - t.Errorf("FastAggregateVerify failed.") - } -} - -func TestFastAggregateVerifyG1Works(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG1(messages, t) - asig, _ := aggregateSignaturesVt(sigs...) - bls := NewSigPopVt() - - if res, _ := bls.FastAggregateVerify(pks, message, asig); !res { - t.Errorf("FastAggregateVerify failed.") - } -} - -func TestFastAggregateVerifyG1Fails(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG1(messages, t) - bls := NewSigPopVt() - message[0] = 1 - if res, _ := bls.FastAggregateVerifyConstituent(pks, message, sigs); res { - t.Errorf("FastAggregateVerify verified when it should've failed.") - } -} - -func TestCustomPopDstG1Works(t *testing.T) { - bls, _ := NewSigPopVtWithDst("BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_POP_TEST", - "BLS_POP_BLS12381G1_XMD:SHA-256_SSWU_RO_POP_TEST") - msg := make([]byte, 20) - ikm := make([]byte, 32) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Couldn't create custom dst keys: %v", err) - } - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Couldn't sign with custom dst: %v", err) - } - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("verify fails with custom dst") - } - - pks := make([]*PublicKeyVt, 10) - sigs := make([]*SignatureVt, 10) - pks[0] = pk - sigs[0] = sig - for i := 1; i < 10; i++ { - readRand(ikm, t) - pkt, skt, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Couldn't create custom dst keys: %v", err) - } - sigt, err := bls.Sign(skt, msg) - if err != nil { - t.Errorf("Couldn't sign with custom dst: %v", err) - } - pks[i] = pkt - sigs[i] = sigt - } - - if res, _ := bls.FastAggregateVerifyConstituent(pks, msg, sigs); !res { - t.Errorf("FastAggregateVerify failed with custom dst") - } - - pop, err := bls.PopProve(sk) - if err != nil { - t.Errorf("PopProve failed with custom dst") - } - - if res, _ := bls.PopVerify(pk, pop); !res { - t.Errorf("PopVerify failed with custom dst") - } -} - -func TestBlsPopG1KeyGenWithSeed(t *testing.T) { - ikm := []byte("Not enough bytes") - bls := NewSigPopVt() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Expected KeygenWithSeed to fail but succeeded") - } -} - -func TestBlsPopG1KeyGen(t *testing.T) { - bls := NewSigPopVt() - _, _, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } -} - -func TestPopVtThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigPopVt() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(1, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestPopVtThresholdKeygen(t *testing.T) { - bls := NewSigPopVt() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestPopPartialSignVt(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigPopVt() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures succeeded when it should've failed") - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestPopVtPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigPopVt() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignatureVt, total) - sigs2 := make([]*PartialSignatureVt, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} diff --git a/crypto/signatures/bls/bls_sig/usual_bls.go b/crypto/signatures/bls/bls_sig/usual_bls.go deleted file mode 100755 index f35193e44..000000000 --- a/crypto/signatures/bls/bls_sig/usual_bls.go +++ /dev/null @@ -1,478 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "fmt" -) - -const ( - // Domain separation tag for basic signatures - // according to section 4.2.1 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignatureBasicDst = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_" - // Domain separation tag for basic signatures - // according to section 4.2.2 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignatureAugDst = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_" - // Domain separation tag for proof of possession signatures - // according to section 4.2.3 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsSignaturePopDst = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_" - // Domain separation tag for proof of possession proofs - // according to section 4.2.3 in - // https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 - blsPopProofDst = "BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_" -) - -type BlsScheme interface { - Keygen() (*PublicKey, *SecretKey, error) - KeygenWithSeed(ikm []byte) (*PublicKey, *SecretKey, error) - Sign(sk *SecretKey, msg []byte) (*Signature, error) - Verify(pk *PublicKey, msg []byte, sig *Signature) bool - AggregateVerify(pks []*PublicKey, msgs [][]byte, sigs []*Signature) bool -} - -// generateKeys creates 32 bytes of random data to be fed to -// generateKeysWithSeed -func generateKeys() (*PublicKey, *SecretKey, error) { - ikm, err := generateRandBytes(32) - if err != nil { - return nil, nil, err - } - return generateKeysWithSeed(ikm) -} - -// generateKeysWithSeed generates a BLS key pair given input key material (ikm) -func generateKeysWithSeed(ikm []byte) (*PublicKey, *SecretKey, error) { - sk, err := new(SecretKey).Generate(ikm) - if err != nil { - return nil, nil, err - } - pk, err := sk.GetPublicKey() - if err != nil { - return nil, nil, err - } - return pk, sk, nil -} - -// thresholdGenerateKeys will generate random secret key shares and the corresponding public key -func thresholdGenerateKeys(threshold, total uint) (*PublicKey, []*SecretKeyShare, error) { - pk, sk, err := generateKeys() - if err != nil { - return nil, nil, err - } - shares, err := thresholdizeSecretKey(sk, threshold, total) - if err != nil { - return nil, nil, err - } - return pk, shares, nil -} - -// thresholdGenerateKeysWithSeed will generate random secret key shares and the corresponding public key -// using the corresponding seed `ikm` -func thresholdGenerateKeysWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKey, []*SecretKeyShare, error) { - pk, sk, err := generateKeysWithSeed(ikm) - if err != nil { - return nil, nil, err - } - shares, err := thresholdizeSecretKey(sk, threshold, total) - if err != nil { - return nil, nil, err - } - return pk, shares, nil -} - -// SigBasic is minimal-pubkey-size scheme that doesn't support FastAggregateVerificiation. -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.1 -type SigBasic struct { - dst string -} - -// Creates a new BLS basic signature scheme with the standard domain separation tag used for signatures. -func NewSigBasic() *SigBasic { - return &SigBasic{dst: blsSignatureBasicDst} -} - -// Creates a new BLS basic signature scheme with a custom domain separation tag used for signatures. -func NewSigBasicWithDst(signDst string) *SigBasic { - return &SigBasic{dst: signDst} -} - -// Creates a new BLS key pair -func (b SigBasic) Keygen() (*PublicKey, *SecretKey, error) { - return generateKeys() -} - -// Creates a new BLS key pair -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigBasic) KeygenWithSeed(ikm []byte) (*PublicKey, *SecretKey, error) { - return generateKeysWithSeed(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigBasic) ThresholdKeygen(threshold, total uint) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeys(threshold, total) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigBasic) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeed(ikm, threshold, total) -} - -// Computes a signature in G2 from sk, a secret key, and a message -func (b SigBasic) Sign(sk *SecretKey, msg []byte) (*Signature, error) { - return sk.createSignature(msg, b.dst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigBasic) PartialSign(sks *SecretKeyShare, msg []byte) (*PartialSignature, error) { - return sks.partialSign(msg, b.dst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigBasic) CombineSignatures(sigs ...*PartialSignature) (*Signature, error) { - return combineSigs(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -func (b SigBasic) Verify(pk *PublicKey, msg []byte, sig *Signature) (bool, error) { - return pk.verifySignature(msg, sig, b.dst) -} - -// The AggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// Each message must be different or this will return false. -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigBasic) AggregateVerify( - pks []*PublicKey, - msgs [][]byte, - sigs []*Signature, -) (bool, error) { - if !allRowsUnique(msgs) { - return false, fmt.Errorf("all messages must be distinct") - } - asig, err := aggregateSignatures(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, msgs, b.dst) -} - -// SigAug is minimal-pubkey-size scheme that doesn't support FastAggregateVerificiation. -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.2 -type SigAug struct { - dst string -} - -// Creates a new BLS message augmentation signature scheme with the standard domain separation tag used for signatures. -func NewSigAug() *SigAug { - return &SigAug{dst: blsSignatureAugDst} -} - -// Creates a new BLS message augmentation signature scheme with a custom domain separation tag used for signatures. -func NewSigAugWithDst(signDst string) *SigAug { - return &SigAug{dst: signDst} -} - -// Creates a new BLS key pair -func (b SigAug) Keygen() (*PublicKey, *SecretKey, error) { - return generateKeys() -} - -// Creates a new BLS secret key -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigAug) KeygenWithSeed(ikm []byte) (*PublicKey, *SecretKey, error) { - return generateKeysWithSeed(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigAug) ThresholdKeygen(threshold, total uint) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeys(threshold, total) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigAug) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeed(ikm, threshold, total) -} - -// Computes a signature in G1 from sk, a secret key, and a message -// See section 3.2.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigAug) Sign(sk *SecretKey, msg []byte) (*Signature, error) { - if len(msg) == 0 { - return nil, fmt.Errorf("message cannot be empty or nil") - } - - pk, err := sk.GetPublicKey() - if err != nil { - return nil, err - } - bytes, err := pk.MarshalBinary() - if err != nil { - return nil, fmt.Errorf("MarshalBinary failed") - } - bytes = append(bytes, msg...) - return sk.createSignature(bytes, b.dst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigAug) PartialSign( - sks *SecretKeyShare, - pk *PublicKey, - msg []byte, -) (*PartialSignature, error) { - if len(msg) == 0 { - return nil, fmt.Errorf("message cannot be empty or nil") - } - - bytes, err := pk.MarshalBinary() - if err != nil { - return nil, fmt.Errorf("MarshalBinary failed") - } - bytes = append(bytes, msg...) - return sks.partialSign(bytes, b.dst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigAug) CombineSignatures(sigs ...*PartialSignature) (*Signature, error) { - return combineSigs(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -// See section 3.2.2 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigAug) Verify(pk *PublicKey, msg []byte, sig *Signature) (bool, error) { - bytes, err := pk.MarshalBinary() - if err != nil { - return false, err - } - bytes = append(bytes, msg...) - return pk.verifySignature(bytes, sig, b.dst) -} - -// The AggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// See section 3.2.3 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigAug) AggregateVerify(pks []*PublicKey, msgs [][]byte, sigs []*Signature) (bool, error) { - if len(pks) != len(msgs) { - return false, fmt.Errorf( - "the number of public keys does not match the number of messages: %v != %v", - len(pks), - len(msgs), - ) - } - data := make([][]byte, len(msgs)) - for i, msg := range msgs { - bytes, err := pks[i].MarshalBinary() - if err != nil { - return false, err - } - data[i] = append(bytes, msg...) - } - asig, err := aggregateSignatures(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, data, b.dst) -} - -// SigEth2 supports signatures on Eth2. -// Internally is an alias for SigPop -type SigEth2 = SigPop - -// NewSigEth2 Creates a new BLS ETH2 signature scheme with the standard domain separation tag used for signatures. -func NewSigEth2() *SigEth2 { - return NewSigPop() -} - -// SigPop is minimal-pubkey-size scheme that supports FastAggregateVerification -// and requires using proofs of possession to mitigate rogue-key attacks -// see: https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03#section-4.2.3 -type SigPop struct { - sigDst string - popDst string -} - -// Creates a new BLS proof of possession signature scheme with the standard domain separation tag used for signatures. -func NewSigPop() *SigPop { - return &SigPop{sigDst: blsSignaturePopDst, popDst: blsPopProofDst} -} - -// Creates a new BLS message proof of possession signature scheme with a custom domain separation tag used for signatures. -func NewSigPopWithDst(signDst, popDst string) (*SigPop, error) { - if signDst == popDst { - return nil, fmt.Errorf("domain separation tags cannot be equal") - } - return &SigPop{sigDst: signDst, popDst: popDst}, nil -} - -// Creates a new BLS key pair -func (b SigPop) Keygen() (*PublicKey, *SecretKey, error) { - return generateKeys() -} - -// Creates a new BLS secret key -// Input key material (ikm) MUST be at least 32 bytes long, -// but it MAY be longer. -func (b SigPop) KeygenWithSeed(ikm []byte) (*PublicKey, *SecretKey, error) { - return generateKeysWithSeed(ikm) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigPop) ThresholdKeygen(threshold, total uint) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeys(threshold, total) -} - -// ThresholdKeyGen generates a public key and `total` secret key shares such that -// `threshold` of them can be combined in signatures -func (b SigPop) ThresholdKeygenWithSeed( - ikm []byte, - threshold, total uint, -) (*PublicKey, []*SecretKeyShare, error) { - return thresholdGenerateKeysWithSeed(ikm, threshold, total) -} - -// Computes a signature in G2 from sk, a secret key, and a message -// See section 2.6 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) Sign(sk *SecretKey, msg []byte) (*Signature, error) { - return sk.createSignature(msg, b.sigDst) -} - -// Compute a partial signature in G2 that can be combined with other partial signature -func (b SigPop) PartialSign(sks *SecretKeyShare, msg []byte) (*PartialSignature, error) { - return sks.partialSign(msg, b.sigDst) -} - -// CombineSignatures takes partial signatures to yield a completed signature -func (b SigPop) CombineSignatures(sigs ...*PartialSignature) (*Signature, error) { - return combineSigs(sigs) -} - -// Checks that a signature is valid for the message under the public key pk -// See section 2.7 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) Verify(pk *PublicKey, msg []byte, sig *Signature) (bool, error) { - return pk.verifySignature(msg, sig, b.sigDst) -} - -// The aggregateVerify algorithm checks an aggregated signature over -// several (PK, message, signature) pairs. -// Each message must be different or this will return false. -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) AggregateVerify(pks []*PublicKey, msgs [][]byte, sigs []*Signature) (bool, error) { - if !allRowsUnique(msgs) { - return false, fmt.Errorf("all messages must be distinct") - } - asig, err := aggregateSignatures(sigs...) - if err != nil { - return false, err - } - return asig.aggregateVerify(pks, msgs, b.sigDst) -} - -// Combine many signatures together to form a Multisignature. -// Multisignatures can be created when multiple signers jointly -// generate signatures over the same message. -func (b SigPop) AggregateSignatures(sigs ...*Signature) (*MultiSignature, error) { - g1, err := aggregateSignatures(sigs...) - if err != nil { - return nil, err - } - return &MultiSignature{value: g1.Value}, nil -} - -// Combine many public keys together to form a Multipublickey. -// Multipublickeys are used to verify multisignatures. -func (b SigPop) AggregatePublicKeys(pks ...*PublicKey) (*MultiPublicKey, error) { - g2, err := aggregatePublicKeys(pks...) - if err != nil { - return nil, err - } - return &MultiPublicKey{value: g2.value}, nil -} - -// Checks that a multisignature is valid for the message under the multi public key -// Similar to FastAggregateVerify except the keys and signatures have already been -// combined. See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) VerifyMultiSignature( - pk *MultiPublicKey, - msg []byte, - sig *MultiSignature, -) (bool, error) { - s := &Signature{Value: sig.value} - p := &PublicKey{value: pk.value} - return p.verifySignature(msg, s, b.sigDst) -} - -// FastAggregateVerify verifies an aggregated signature against the specified message and set of public keys. -// See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) FastAggregateVerify(pks []*PublicKey, msg []byte, asig *Signature) (bool, error) { - apk, err := aggregatePublicKeys(pks...) - if err != nil { - return false, err - } - return apk.verifySignature(msg, asig, b.sigDst) -} - -// FastAggregateVerifyConstituent aggregates all constituent signatures and the verifies -// them against the specified message and public keys -// See section 3.3.4 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) FastAggregateVerifyConstituent( - pks []*PublicKey, - msg []byte, - sigs []*Signature, -) (bool, error) { - // Aggregate the constituent signatures - asig, err := aggregateSignatures(sigs...) - if err != nil { - return false, err - } - // And verify - return b.FastAggregateVerify(pks, msg, asig) -} - -// Create a proof of possession for the corresponding public key. -// A proof of possession must be created for each public key to be used -// in FastAggregateVerify or a Multipublickey to avoid rogue key attacks. -// See section 3.3.2 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) PopProve(sk *SecretKey) (*ProofOfPossession, error) { - return sk.createProofOfPossession(b.popDst) -} - -// verify a proof of possession for the corresponding public key is valid. -// A proof of possession must be created for each public key to be used -// in FastAggregateVerify or a Multipublickey to avoid rogue key attacks. -// See section 3.3.3 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (b SigPop) PopVerify(pk *PublicKey, pop2 *ProofOfPossession) (bool, error) { - return pop2.verify(pk, b.popDst) -} diff --git a/crypto/signatures/bls/bls_sig/usual_bls_sig.go b/crypto/signatures/bls/bls_sig/usual_bls_sig.go deleted file mode 100644 index 094c1ae28..000000000 --- a/crypto/signatures/bls/bls_sig/usual_bls_sig.go +++ /dev/null @@ -1,507 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves/native" - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Implement BLS signatures on the BLS12-381 curve -// according to https://crypto.standford.edu/~dabo/pubs/papers/BLSmultisig.html -// and https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -// this file implements signatures in G2 and public keys in G1. -// Public Keys and Signatures can be aggregated but the consumer -// must use proofs of possession to defend against rogue-key attacks. - -const ( - // Public key size in G1 - PublicKeySize = 48 - // Signature size in G2 - SignatureSize = 96 - // Proof of Possession in G2 - ProofOfPossessionSize = 96 -) - -// Represents a public key in G1 -type PublicKey struct { - value bls12381.G1 -} - -// Serialize a public key to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pk PublicKey) MarshalBinary() ([]byte, error) { - out := pk.value.ToCompressed() - return out[:], nil -} - -// Deserialize a public key from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the public key -// otherwise it will return an error -func (pk *PublicKey) UnmarshalBinary(data []byte) error { - if len(data) != PublicKeySize { - return fmt.Errorf("public key must be %d bytes", PublicKeySize) - } - var blob [PublicKeySize]byte - copy(blob[:], data) - p1, err := new(bls12381.G1).FromCompressed(&blob) - if err != nil { - return err - } - if p1.IsIdentity() == 1 { - return fmt.Errorf("public keys cannot be zero") - } - pk.value = *p1 - return nil -} - -// Represents a BLS signature in G2 -type Signature struct { - Value bls12381.G2 -} - -// Serialize a signature to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (sig Signature) MarshalBinary() ([]byte, error) { - out := sig.Value.ToCompressed() - return out[:], nil -} - -func (sig Signature) verify(pk *PublicKey, message []byte, signDst string) (bool, error) { - return pk.verifySignature(message, &sig, signDst) -} - -// The AggregateVerify algorithm checks an aggregated signature over -// several (PK, message) pairs. -// The Signature is the output of aggregateSignatures -// Each message must be different or this will return false -// See section 3.1.1 from -// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (sig Signature) aggregateVerify( - pks []*PublicKey, - msgs [][]byte, - signDst string, -) (bool, error) { - return sig.coreAggregateVerify(pks, msgs, signDst) -} - -func (sig Signature) coreAggregateVerify( - pks []*PublicKey, - msgs [][]byte, - signDst string, -) (bool, error) { - if len(pks) < 1 { - return false, fmt.Errorf("at least one key is required") - } - if len(msgs) < 1 { - return false, fmt.Errorf("at least one message is required") - } - if len(pks) != len(msgs) { - return false, fmt.Errorf( - "the number of public keys does not match the number of messages: %v != %v", - len(pks), - len(msgs), - ) - } - if sig.Value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("signature is not in the correct subgroup") - } - - dst := []byte(signDst) - engine := new(bls12381.Engine) - // e(pk_1, H(m_1))*...*e(pk_N, H(m_N)) == e(g1, s) - // However, we use only one miller loop - // by doing the equivalent of - // e(pk_1, H(m_1))*...*e(pk_N, H(m_N)) * e(g1^-1, s) == 1 - for i, pk := range pks { - if pk == nil { - return false, fmt.Errorf("public key at %d is nil", i) - } - if pk.value.IsIdentity() == 1 || pk.value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("public key at %d is not in the correct subgroup", i) - } - p2 := new(bls12381.G2).Hash(native.EllipticPointHasherSha256(), msgs[i], dst) - engine.AddPair(&pk.value, p2) - } - engine.AddPairInvG1(new(bls12381.G1).Generator(), &sig.Value) - return engine.Check(), nil -} - -// Deserialize a signature from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (sig *Signature) UnmarshalBinary(data []byte) error { - if len(data) != SignatureSize { - return fmt.Errorf("signature must be %d bytes", SignatureSize) - } - var blob [SignatureSize]byte - copy(blob[:], data) - p2, err := new(bls12381.G2).FromCompressed(&blob) - if err != nil { - return err - } - if p2.IsIdentity() == 1 { - return fmt.Errorf("signatures cannot be zero") - } - sig.Value = *p2 - return nil -} - -// Get the corresponding public key from a secret key -// Verifies the public key is in the correct subgroup -func (sk SecretKey) GetPublicKey() (*PublicKey, error) { - result := new(bls12381.G1).Generator() - result.Mul(result, sk.value) - if result.InCorrectSubgroup() == 0 || result.IsIdentity() == 1 { - return nil, fmt.Errorf("point is not in correct subgroup") - } - return &PublicKey{value: *result}, nil -} - -// Compute a signature from a secret key and message -// This signature is deterministic which protects against -// attacks arising from signing with bad randomness like -// the nonce reuse attack on ECDSA. `message` is -// hashed to a point in G2 as described in to -// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/?include_text=1 -// See Section 2.6 in https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -// nil message is not permitted but empty slice is allowed -func (sk SecretKey) createSignature(message []byte, dst string) (*Signature, error) { - if message == nil { - return nil, fmt.Errorf("message cannot be nil") - } - if sk.value.IsZero() == 1 { - return nil, fmt.Errorf("invalid secret key") - } - p2 := new(bls12381.G2).Hash(native.EllipticPointHasherSha256(), message, []byte(dst)) - result := new(bls12381.G2).Mul(p2, sk.value) - if result.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("point is not on correct subgroup") - } - return &Signature{Value: *result}, nil -} - -// Verify a signature is valid for the message under this public key. -// See Section 2.7 in https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-03 -func (pk PublicKey) verifySignature( - message []byte, - signature *Signature, - dst string, -) (bool, error) { - if signature == nil || message == nil || pk.value.IsIdentity() == 1 { - return false, fmt.Errorf("signature and message and public key cannot be nil or zero") - } - if signature.Value.IsIdentity() == 1 || signature.Value.InCorrectSubgroup() == 0 { - return false, fmt.Errorf("signature is not in the correct subgroup") - } - engine := new(bls12381.Engine) - - p2 := new(bls12381.G2).Hash(native.EllipticPointHasherSha256(), message, []byte(dst)) - // e(pk, H(m)) == e(g1, s) - // However, we can reduce the number of miller loops - // by doing the equivalent of - // e(pk^-1, H(m)) * e(g1, s) == 1 - engine.AddPair(&pk.value, p2) - engine.AddPairInvG1(new(bls12381.G1).Generator(), &signature.Value) - return engine.Check(), nil -} - -// Combine public keys into one aggregated key -func aggregatePublicKeys(pks ...*PublicKey) (*PublicKey, error) { - if len(pks) < 1 { - return nil, fmt.Errorf("at least one public key is required") - } - result := new(bls12381.G1).Identity() - for i, k := range pks { - if k == nil { - return nil, fmt.Errorf("key at %d is nil, keys cannot be nil", i) - } - if k.value.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("key at %d is not in the correct subgroup", i) - } - result.Add(result, &k.value) - } - return &PublicKey{value: *result}, nil -} - -// Combine signatures into one aggregated signature -func aggregateSignatures(sigs ...*Signature) (*Signature, error) { - if len(sigs) < 1 { - return nil, fmt.Errorf("at least one signature is required") - } - result := new(bls12381.G2).Identity() - for i, s := range sigs { - if s == nil { - return nil, fmt.Errorf("signature at %d is nil, signature cannot be nil", i) - } - if s.Value.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("signature at %d is not in the correct subgroup", i) - } - result.Add(result, &s.Value) - } - return &Signature{Value: *result}, nil -} - -// A proof of possession scheme uses a separate public key validation -// step, called a proof of possession, to defend against rogue key -// attacks. This enables an optimization to aggregate signature -// verification for the case that all signatures are on the same -// message. -type ProofOfPossession struct { - value bls12381.G2 -} - -// Generates a proof-of-possession (PoP) for this secret key. The PoP signature should be verified before -// before accepting any aggregate signatures related to the corresponding pubkey. -func (sk SecretKey) createProofOfPossession(popDst string) (*ProofOfPossession, error) { - pk, err := sk.GetPublicKey() - if err != nil { - return nil, err - } - msg, err := pk.MarshalBinary() - if err != nil { - return nil, err - } - sig, err := sk.createSignature(msg, popDst) - if err != nil { - return nil, err - } - return &ProofOfPossession{value: sig.Value}, nil -} - -// Serialize a proof of possession to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pop ProofOfPossession) MarshalBinary() ([]byte, error) { - out := pop.value.ToCompressed() - return out[:], nil -} - -// Deserialize a proof of possession from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (pop *ProofOfPossession) UnmarshalBinary(data []byte) error { - p2 := new(Signature) - err := p2.UnmarshalBinary(data) - if err != nil { - return err - } - pop.value = p2.Value - return nil -} - -// Verifies that PoP is valid for this pubkey. In order to prevent rogue key attacks, a PoP must be validated -// for each pubkey in an aggregated signature. -func (pop ProofOfPossession) verify(pk *PublicKey, popDst string) (bool, error) { - if pk == nil { - return false, fmt.Errorf("public key cannot be nil") - } - msg, err := pk.MarshalBinary() - if err != nil { - return false, err - } - return pk.verifySignature(msg, &Signature{Value: pop.value}, popDst) -} - -// Represents an MultiSignature in G2. A multisignature is used when multiple signatures -// are calculated over the same message vs an aggregate signature where each message signed -// is a unique. -type MultiSignature struct { - value bls12381.G2 -} - -// Serialize a multi-signature to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (sig MultiSignature) MarshalBinary() ([]byte, error) { - out := sig.value.ToCompressed() - return out[:], nil -} - -// Check a multisignature is valid for a multipublickey and a message -func (sig MultiSignature) verify(pk *MultiPublicKey, message []byte, signDst string) (bool, error) { - if pk == nil { - return false, fmt.Errorf("public key cannot be nil") - } - p := PublicKey{value: pk.value} - return p.verifySignature(message, &Signature{Value: sig.value}, signDst) -} - -// Deserialize a signature from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the Signature -// otherwise it will return an error -func (sig *MultiSignature) UnmarshalBinary(data []byte) error { - if len(data) != SignatureSize { - return fmt.Errorf("multi signature must be %v bytes", SignatureSize) - } - s2 := new(Signature) - err := s2.UnmarshalBinary(data) - if err != nil { - return err - } - sig.value = s2.Value - return nil -} - -// Represents accumulated multiple Public Keys in G1 for verifying a multisignature -type MultiPublicKey struct { - value bls12381.G1 -} - -// Serialize a public key to a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -func (pk MultiPublicKey) MarshalBinary() ([]byte, error) { - out := pk.value.ToCompressed() - return out[:], nil -} - -// Deserialize a public key from a byte array in compressed form. -// See -// https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization -// https://docs.rs/bls12_381/0.1.1/bls12_381/notes/serialization/index.html -// If successful, it will assign the public key -// otherwise it will return an error -func (pk *MultiPublicKey) UnmarshalBinary(data []byte) error { - if len(data) != PublicKeySize { - return fmt.Errorf("multi public key must be %v bytes", PublicKeySize) - } - p1 := new(PublicKey) - err := p1.UnmarshalBinary(data) - if err != nil { - return err - } - pk.value = p1.value - return nil -} - -// Check a multisignature is valid for a multipublickey and a message -func (pk MultiPublicKey) verify(message []byte, sig *MultiSignature, signDst string) (bool, error) { - return sig.verify(&pk, message, signDst) -} - -// PartialSignature represents threshold Gap Diffie-Hellman BLS signature -// that can be combined with other partials to yield a completed BLS signature -// See section 3.2 in -type PartialSignature struct { - Identifier byte - Signature bls12381.G2 -} - -// partialSign creates a partial signature that can be combined with other partial signatures -// to yield a complete signature -func (sks SecretKeyShare) partialSign(message []byte, signDst string) (*PartialSignature, error) { - if len(message) == 0 { - return nil, fmt.Errorf("message cannot be empty or nil") - } - p2 := new(bls12381.G2).Hash(native.EllipticPointHasherSha256(), message, []byte(signDst)) - - var blob [SecretKeySize]byte - copy(blob[:], internal.ReverseScalarBytes(sks.value)) - s, err := bls12381.Bls12381FqNew().SetBytes(&blob) - if err != nil { - return nil, err - } - result := new(bls12381.G2).Mul(p2, s) - if result.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("point is not on correct subgroup") - } - return &PartialSignature{Identifier: sks.identifier, Signature: *result}, nil -} - -// combineSigs gathers partial signatures and yields a complete signature -func combineSigs(partials []*PartialSignature) (*Signature, error) { - if len(partials) < 2 { - return nil, fmt.Errorf("must have at least 2 partial signatures") - } - if len(partials) > 255 { - return nil, fmt.Errorf("unsupported to combine more than 255 signatures") - } - - // Don't know the actual values so put the minimum - xVars, yVars, err := splitXY(partials) - if err != nil { - return nil, err - } - - sTmp := new(bls12381.G2).Identity() - sig := new(bls12381.G2).Identity() - - // Lagrange interpolation - basis := bls12381.Bls12381FqNew().SetOne() - for i, xi := range xVars { - basis.SetOne() - - for j, xj := range xVars { - if i == j { - continue - } - - num := bls12381.Bls12381FqNew().Neg(xj) // - x_m - den := bls12381.Bls12381FqNew().Sub(xi, xj) // x_j - x_m - _, wasInverted := den.Invert(den) - // wasInverted == false if den == 0 - if !wasInverted { - return nil, fmt.Errorf("signatures cannot be recombined") - } - basis.Mul(basis, num.Mul(num, den)) - } - sTmp.Mul(yVars[i], basis) - sig.Add(sig, sTmp) - } - if sig.InCorrectSubgroup() == 0 { - return nil, fmt.Errorf("signature is not in the correct subgroup") - } - - return &Signature{Value: *sig}, nil -} - -// Ensure no duplicates x values and convert x values to field elements -func splitXY(partials []*PartialSignature) ([]*native.Field, []*bls12381.G2, error) { - x := make([]*native.Field, len(partials)) - y := make([]*bls12381.G2, len(partials)) - - dup := make(map[byte]bool) - - for i, sp := range partials { - if sp == nil { - return nil, nil, fmt.Errorf("partial signature cannot be nil") - } - if _, exists := dup[sp.Identifier]; exists { - return nil, nil, fmt.Errorf("duplicate signature included") - } - if sp.Signature.InCorrectSubgroup() == 0 { - return nil, nil, fmt.Errorf("signature is not in the correct subgroup") - } - dup[sp.Identifier] = true - x[i] = bls12381.Bls12381FqNew().SetUint64(uint64(sp.Identifier)) - y[i] = &sp.Signature - } - return x, y, nil -} diff --git a/crypto/signatures/bls/bls_sig/usual_bls_sig_aug_test.go b/crypto/signatures/bls/bls_sig/usual_bls_sig_aug_test.go deleted file mode 100644 index 0c55d57d5..000000000 --- a/crypto/signatures/bls/bls_sig/usual_bls_sig_aug_test.go +++ /dev/null @@ -1,417 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -func generateAugSignatureG2(sk *SecretKey, msg []byte, t *testing.T) *Signature { - bls := NewSigAug() - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Aug Sign failed") - } - return sig -} - -func generateAugAggregateDataG2(t *testing.T) ([]*PublicKey, []*Signature, [][]byte) { - msgs := make([][]byte, numAggregateG2) - pks := make([]*PublicKey, numAggregateG2) - sigs := make([]*Signature, numAggregateG2) - ikm := make([]byte, 32) - bls := NewSigAug() - - for i := 0; i < numAggregateG2; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - msg := make([]byte, 20) - readRand(msg, t) - sig := generateAugSignatureG2(sk, msg, t) - msgs[i] = msg - sigs[i] = sig - pks[i] = pk - } - return pks, sigs, msgs -} - -func TestAugKeyGenG2Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAug() - _, _, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } -} - -func TestAugKeyGenG2Fail(t *testing.T) { - ikm := make([]byte, 10) - readRand(ikm, t) - bls := NewSigAug() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Aug KeyGen succeeded when it should've failed") - } -} - -func TestAugCustomDstG2(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAugWithDst("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_TEST") - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug Custom Dst KeyGen failed") - } - - readRand(ikm, t) - sig, err := bls.Sign(sk, ikm) - if err != nil { - t.Errorf("Aug Custom Dst Sign failed") - } - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Aug Custon Dst Verify failed") - } - - ikm[0] = 0 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Aug Custom Dst Verify succeeded when it should've failed.") - } -} - -func TestAugSigningG2(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigAug() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - readRand(ikm, t) - sig := generateAugSignatureG2(sk, ikm, t) - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Aug Verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Aug Verify succeeded when it should've failed.") - } -} - -func TestAugSignEmptyMessage(t *testing.T) { - bls := NewSigAug() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - // Sign a nil message - _, err = bls.Sign(sk, nil) - if err == nil { - t.Errorf("Expected sign of nil message to fail") - } -} - -func TestAugSignNilMessage(t *testing.T) { - bls := NewSigAug() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - // Sign an empty message - _, err = bls.Sign(sk, []byte{}) - if err == nil { - t.Errorf("Expected sign of empty message to fail") - } -} - -func TestAugAggregateVerifyG2Works(t *testing.T) { - pks, sigs, msgs := generateAugAggregateDataG2(t) - bls := NewSigAug() - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug AggregateVerify failed") - } -} - -func TestAugAggregateVerifyG2BadPks(t *testing.T) { - bls := NewSigAug() - pks, sigs, msgs := generateAugAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug AggregateVerify failed") - } - - pks[0] = pks[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug AggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - pkValue := new(bls12381.G1).Identity() - pks[0] = &PublicKey{value: *pkValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug AggregateVerify succeeded with zero byte public key it should've failed") - } - - // Try with base generator - pkValue.Generator() - pks[0] = &PublicKey{value: *pkValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Aug aggregateVerify succeeded with the base generator public key it should've failed", - ) - } -} - -func TestAugAggregateVerifyG2BadSigs(t *testing.T) { - bls := NewSigAug() - pks, sigs, msgs := generateAugAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug aggregateVerify failed") - } - - sigs[0] = sigs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - sigValue := new(bls12381.G2).Identity() - sigs[0] = &Signature{Value: *sigValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded with zero byte signature it should've failed") - } - - // Try with base generator - sigValue.Generator() - sigs[0] = &Signature{Value: *sigValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Aug aggregateVerify succeeded with the base generator signature it should've failed", - ) - } -} - -func TestAugAggregateVerifyG2BadMsgs(t *testing.T) { - bls := NewSigAug() - pks, sigs, msgs := generateAugAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Aug aggregateVerify failed") - } - - // Test len(pks) != len(msgs) - if res, _ := bls.AggregateVerify(pks, msgs[0:8], sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } - - msgs[0] = msgs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Aug aggregateVerify succeeded when it should've failed") - } -} - -func TestAugAggregateVerifyG2DupMsg(t *testing.T) { - bls := NewSigAug() - - // Only two messages but repeated - messages := make([][]byte, numAggregateG2) - messages[0] = []byte("Yes") - messages[1] = []byte("No") - for i := 2; i < numAggregateG2; i++ { - messages[i] = messages[i%2] - } - - pks := make([]*PublicKey, numAggregateG2) - sigs := make([]*Signature, numAggregateG2) - - ikm := make([]byte, 32) - for i := 0; i < numAggregateG2; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Aug KeyGen failed") - } - - sig := generateAugSignatureG2(sk, messages[i], t) - pks[i] = pk - sigs[i] = sig - } - - if res, _ := bls.AggregateVerify(pks, messages, sigs); !res { - t.Errorf("Aug aggregateVerify failed for duplicate messages") - } -} - -func TestBlsAugG2KeyGen(t *testing.T) { - bls := NewSigAug() - _, _, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } -} - -func TestAugThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigAug() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(1, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestAugThresholdKeygen(t *testing.T) { - bls := NewSigAug() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestAugPartialSign(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigAug() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], pk, msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], pk, msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures succeeded when it should've failed") - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestAugPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigAug() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignature, total) - sigs2 := make([]*PartialSignature, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], pk1, msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], pk2, msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} - -func TestAugPartialSignEmptyMessage(t *testing.T) { - bls := NewSigAug() - pk, sks, err := bls.ThresholdKeygen(2, 2) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - - // Test signing an empty message - _, err = bls.PartialSign(sks[0], pk, []byte{}) - if err == nil { - t.Errorf("Expected partial sign of empty message to fail") - } -} - -func TestAugPartialSignNilMessage(t *testing.T) { - bls := NewSigAug() - pk, sks, err := bls.ThresholdKeygen(7, 7) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - - // Test signing a nil message - _, err = bls.PartialSign(sks[0], pk, nil) - if err == nil { - t.Errorf("Expected partial sign of nil message to fail") - } -} diff --git a/crypto/signatures/bls/bls_sig/usual_bls_sig_basic_test.go b/crypto/signatures/bls/bls_sig/usual_bls_sig_basic_test.go deleted file mode 100644 index 91c332d3e..000000000 --- a/crypto/signatures/bls/bls_sig/usual_bls_sig_basic_test.go +++ /dev/null @@ -1,417 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -func generateBasicSignatureG2(sk *SecretKey, msg []byte, t *testing.T) *Signature { - bls := NewSigBasic() - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Basic Sign failed") - } - return sig -} - -func generateBasicAggregateDataG2(t *testing.T) ([]*PublicKey, []*Signature, [][]byte) { - msgs := make([][]byte, numAggregateG2) - pks := make([]*PublicKey, numAggregateG2) - sigs := make([]*Signature, numAggregateG2) - ikm := make([]byte, 32) - bls := NewSigBasic() - - for i := 0; i < numAggregateG2; i++ { - readRand(ikm, t) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } - msg := make([]byte, 20) - readRand(msg, t) - sig := generateBasicSignatureG2(sk, msg, t) - msgs[i] = msg - sigs[i] = sig - pks[i] = pk - } - return pks, sigs, msgs -} - -func TestBasicKeyGenG2Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasic() - _, _, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } -} - -func TestBasicKeyGenG2Fail(t *testing.T) { - ikm := make([]byte, 10) - readRand(ikm, t) - bls := NewSigBasic() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Basic KeyGen succeeded when it should've failed") - } -} - -func TestBasicCustomDstG2(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasicWithDst("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_TEST") - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic Custom Dst KeyGen failed") - } - - readRand(ikm, t) - sig, err := bls.Sign(sk, ikm) - if err != nil { - t.Errorf("Basic Custom Dst Sign failed") - } - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Basic Custon Dst verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Basic Custom Dst verify succeeded when it should've failed.") - } -} - -func TestBasicSigningG2(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigBasic() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - readRand(ikm, t) - sig := generateBasicSignatureG2(sk, ikm, t) - - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Basic verify failed") - } - - ikm[0] += 1 - if res, _ := bls.Verify(pk, ikm, sig); res { - t.Errorf("Basic verify succeeded when it should've failed.") - } -} - -func TestBasicSigningG2EmptyMessage(t *testing.T) { - // So basic - bls := NewSigBasic() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - // Sign an empty message - _, err = bls.Sign(sk, []byte{}) - if err != nil { - t.Errorf("Expected signing empty message to succeed: %v", err) - } -} - -func TestBasicSigningG2NilMessage(t *testing.T) { - // So basic - bls := NewSigBasic() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Basic KeyGen failed") - } - - // Sign an empty message - _, err = bls.Sign(sk, nil) - if err == nil { - t.Errorf("Expected signing nil message to fail") - } -} - -func TestBasicAggregateVerifyG2Works(t *testing.T) { - pks, sigs, msgs := generateBasicAggregateDataG2(t) - bls := NewSigBasic() - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic AggregateVerify failed") - } -} - -func TestBasicAggregateVerifyG2BadPks(t *testing.T) { - bls := NewSigBasic() - pks, sigs, msgs := generateBasicAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic AggregateVerify failed") - } - - pks[0] = pks[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic AggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - pkValue := new(bls12381.G1).Identity() - pks[0] = &PublicKey{value: *pkValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic AggregateVerify succeeded with zero byte public key it should've failed") - } - - // Try with base generator - pkValue.Generator() - pks[0] = &PublicKey{value: *pkValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Basic aggregateVerify succeeded with the base generator public key it should've failed", - ) - } -} - -func TestBasicAggregateVerifyG2BadSigs(t *testing.T) { - bls := NewSigBasic() - pks, sigs, msgs := generateBasicAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic aggregateVerify failed") - } - - sigs[0] = sigs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded when it should've failed") - } - - // Try a zero key to make sure it doesn't crash - sigValue := new(bls12381.G2).Identity() - sigs[0] = &Signature{Value: *sigValue} - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded with zero byte signature it should've failed") - } - - // Try with base generator - sigValue.Generator() - sigs[0] = &Signature{Value: *sigValue} - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf( - "Basic aggregateVerify succeeded with the base generator signature it should've failed", - ) - } -} - -func TestBasicAggregateVerifyG2BadMsgs(t *testing.T) { - bls := NewSigBasic() - pks, sigs, msgs := generateBasicAggregateDataG2(t) - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); !res { - t.Errorf("Basic aggregateVerify failed") - } - - msgs[0] = msgs[1] - - if res, _ := bls.AggregateVerify(pks, msgs, sigs); res { - t.Errorf("Basic aggregateVerify succeeded when it should've failed") - } -} - -func TestBasicThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigBasic() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(1, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestBasicThresholdKeygen(t *testing.T) { - bls := NewSigBasic() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestBasicPartialSign(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigBasic() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures succeeded when it should've failed") - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that duplicate partial signatures cannot be used to create a complete one -func TestBasicPartialDuplicateShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigBasic() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignature, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining duplicates from group 1 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[0], sigs1[1], sigs1[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded") - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf("CombineSignatures worked with duplicate partial signatures") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestBasicPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigBasic() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignature, total) - sigs2 := make([]*PartialSignature, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} - -func TestIdentityPublicKey(t *testing.T) { - bls := NewSigBasic() - _, sk, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } - msg := []byte{0, 0, 0, 0} - sig, _ := bls.Sign(sk, msg) - pk := PublicKey{value: *new(bls12381.G1).Identity()} - if res, _ := bls.Verify(&pk, msg, sig); res { - t.Errorf("Verify succeeded when the public key is the identity.") - } -} - -func TestThresholdSignTooHighAndLow(t *testing.T) { - bls := NewSigBasic() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - msg := make([]byte, 10) - - ps, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - - _, err = bls.CombineSignatures(ps) - if err == nil { - t.Errorf("CombinSignatures succeeded when it should've failed") - } - - pss := make([]*PartialSignature, 256) - - _, err = bls.CombineSignatures(pss...) - if err == nil { - t.Errorf("CombinSignatures succeeded when it should've failed") - } -} diff --git a/crypto/signatures/bls/bls_sig/usual_bls_sig_pop_test.go b/crypto/signatures/bls/bls_sig/usual_bls_sig_pop_test.go deleted file mode 100644 index d5230ce47..000000000 --- a/crypto/signatures/bls/bls_sig/usual_bls_sig_pop_test.go +++ /dev/null @@ -1,936 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package bls_sig - -import ( - "bytes" - "math/big" - "math/rand" - "testing" - - "github.com/sonr-io/sonr/crypto/core/curves/native/bls12381" -) - -const numAggregateG2 = 10 - -func TestGetPublicKeyG1(t *testing.T) { - sk := genSecretKey(t) - pk := genPublicKey(sk, t) - actual := marshalStruct(pk, t) - expected := []byte{ - 166, - 149, - 173, - 50, - 93, - 252, - 126, - 17, - 145, - 251, - 201, - 241, - 134, - 245, - 142, - 255, - 66, - 166, - 52, - 2, - 151, - 49, - 177, - 131, - 128, - 255, - 137, - 191, - 66, - 196, - 100, - 164, - 44, - 184, - 202, - 85, - 178, - 0, - 240, - 81, - 245, - 127, - 30, - 24, - 147, - 198, - 135, - 89, - } - if !bytes.Equal(actual, expected) { - t.Errorf("Expected GetPublicKey to pass but failed.") - } -} - -func testSignG2(message []byte, t *testing.T) { - sk := genSecretKey(t) - sig := genSignature(sk, message, t) - pk := genPublicKey(sk, t) - - bls := NewSigPop() - - if res, err := bls.Verify(pk, message, sig); !res { - t.Errorf("createSignature failed when it should've passed: %v", err) - } -} - -func TestSignG2EmptyMessage(t *testing.T) { - bls := NewSigPop() - sk := genSecretKey(t) - sig, _ := bls.Sign(sk, nil) - pk := genPublicKey(sk, t) - - if res, _ := bls.Verify(pk, nil, sig); res { - t.Errorf("createSignature succeeded when it should've failed") - } - - message := []byte{} - sig = genSignature(sk, message, t) - - if res, err := bls.Verify(pk, message, sig); !res { - t.Errorf("create and verify failed on empty message: %v", err) - } -} - -func TestSignG2OneByteMessage(t *testing.T) { - message := []byte{1} - testSignG2(message, t) -} - -func TestSignG2LargeMessage(t *testing.T) { - message := make([]byte, 1048576) - testSignG2(message, t) -} - -func TestSignG2RandomMessage(t *testing.T) { - message := make([]byte, 65537) - readRand(message, t) - testSignG2(message, t) -} - -func TestSignG2BadMessage(t *testing.T) { - message := make([]byte, 1024) - sk := genSecretKey(t) - sig := genSignature(sk, message, t) - pk := genPublicKey(sk, t) - message = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} - - bls := NewSigPop() - - if res, _ := bls.Verify(pk, message, sig); res { - t.Errorf("Expected signature to not verify") - } -} - -func TestBadConversionsG2(t *testing.T) { - sk := genSecretKey(t) - message := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} - sig := genSignature(sk, message, t) - pk := genPublicKey(sk, t) - - bls := NewSigPop() - - if res, _ := bls.Verify(pk, message, sig); !res { - t.Errorf("Signature should be valid") - } - if res, _ := sig.verify(pk, message, blsSignaturePopDst); !res { - t.Errorf("Signature should be valid") - } - - // Convert public key to signature in G2 - sig2 := new(SignatureVt) - err := sig2.UnmarshalBinary(marshalStruct(pk, t)) - if err != nil { - t.Errorf("Should be able to convert to signature in G2") - } - pk2 := new(PublicKeyVt) - err = pk2.UnmarshalBinary(marshalStruct(sig, t)) - if err != nil { - t.Errorf("Should be able to convert to public key in G1") - } - - if res, _ := pk2.verifySignatureVt(message, sig2, blsSignaturePopDst); res { - t.Errorf("The signature shouldn't verify") - } -} - -func TestAggregatePublicKeysG1(t *testing.T) { - pks := []*PublicKey{} - ikm := make([]byte, 32) - for i := 0; i < 20; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - pk := genPublicKey(sk, t) - pks = append(pks, pk) - } - apk1, err := aggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - rng := rand.New(rand.NewSource(1234567890)) - rng.Shuffle(len(pks), func(i, j int) { pks[i], pks[j] = pks[j], pks[i] }) - apk2, err := aggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(apk1, t), marshalStruct(apk2, t)) { - t.Errorf("Aggregated public keys should be equal") - } - rand.Shuffle(len(pks), func(i, j int) { pks[i], pks[j] = pks[j], pks[i] }) - apk1, err = aggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(apk1, t), marshalStruct(apk2, t)) { - t.Errorf("Aggregated public keys should be equal") - } -} - -func TestAggregateSignaturesG2(t *testing.T) { - var sigs []*Signature - ikm := make([]byte, 32) - for i := 0; i < 20; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - sig := genSignature(sk, ikm, t) - sigs = append(sigs, sig) - } - asig1, err := aggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - rng2 := rand.New(rand.NewSource(1234567890)) - rng2.Shuffle(len(sigs), func(i, j int) { sigs[i], sigs[j] = sigs[j], sigs[i] }) - asig2, err := aggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(asig1, t), marshalStruct(asig2, t)) { - t.Errorf("Aggregated signatures should be equal") - } - rand.Shuffle(len(sigs), func(i, j int) { sigs[i], sigs[j] = sigs[j], sigs[i] }) - asig1, err = aggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - if !bytes.Equal(marshalStruct(asig1, t), marshalStruct(asig2, t)) { - t.Errorf("Aggregated signatures should be equal") - } -} - -func initAggregatedTestValuesG2(messages [][]byte, t *testing.T) ([]*PublicKey, []*Signature) { - pks := []*PublicKey{} - sigs := []*Signature{} - ikm := make([]byte, 32) - for i := 0; i < numAggregateG2; i++ { - readRand(ikm, t) - sk := genRandSecretKey(ikm, t) - sig := genSignature(sk, messages[i%len(messages)], t) - sigs = append(sigs, sig) - pk := genPublicKey(sk, t) - pks = append(pks, pk) - } - return pks, sigs -} - -func TestAggregatedFunctionalityG2(t *testing.T) { - message := make([]byte, 20) - messages := make([][]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG2(messages, t) - - bls := NewSigPop() - asig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - if res, _ := bls.VerifyMultiSignature(apk, message, asig); !res { - t.Errorf("Should verify aggregated signatures with same message") - } - if res, _ := asig.verify(apk, message, blsSignaturePopDst); !res { - t.Errorf("MultiSignature.verify failed.") - } - if res, _ := apk.verify(message, asig, blsSignaturePopDst); !res { - t.Errorf("MultiPublicKey.verify failed.") - } -} - -func TestBadAggregatedFunctionalityG2(t *testing.T) { - message := make([]byte, 20) - messages := make([][]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG2(messages, t) - - bls := NewSigPop() - - apk, err := bls.AggregatePublicKeys(pks[2:]...) - if err != nil { - t.Errorf("%v", err) - } - asig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - - if res, _ := bls.VerifyMultiSignature(apk, message, asig); res { - t.Errorf( - "Should not verify aggregated signatures with same message when some public keys are missing", - ) - } - - apk, err = bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - asig, err = bls.AggregateSignatures(sigs[2:]...) - if err != nil { - t.Errorf("%v", err) - } - if res, _ := bls.VerifyMultiSignature(apk, message, asig); res { - t.Errorf( - "Should not verify aggregated signatures with same message when some signatures are missing", - ) - } - - asig, err = bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - - badmsg := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} - if res, _ := bls.VerifyMultiSignature(apk, badmsg, asig); res { - t.Errorf("Should not verify aggregated signature with bad message") - } -} - -func TestAggregateVerifyG2Pass(t *testing.T) { - messages := make([][]byte, numAggregateG2) - for i := 0; i < numAggregateG2; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - if res, _ := bls.AggregateVerify(pks, messages, sigs); !res { - t.Errorf("Expected aggregateVerify to pass but failed") - } -} - -func TestAggregateVerifyG2MsgSigCntMismatch(t *testing.T) { - messages := make([][]byte, 8) - for i := 0; i < 8; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - if res, _ := bls.AggregateVerify(pks, messages, sigs); res { - t.Errorf("Expected AggregateVerifyG2 to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG2FailDupMsg(t *testing.T) { - messages := make([][]byte, 10) - for i := 0; i < 9; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - // Duplicate message - messages[9] = messages[0] - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - if res, _ := bls.AggregateVerify(pks, messages, sigs); res { - t.Errorf("Expected aggregateVerify to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG2FailIncorrectMsg(t *testing.T) { - messages := make([][]byte, 10) - for i := 0; i < 9; i++ { - message := make([]byte, 20) - readRand(message, t) - messages[i] = message - } - // Duplicate message - messages[9] = messages[0] - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - if res, _ := bls.AggregateVerify(pks[2:], messages[2:], sigs); res { - t.Errorf("Expected aggregateVerify to fail with duplicate message but passed") - } -} - -func TestAggregateVerifyG2OneMsg(t *testing.T) { - messages := make([][]byte, 1) - messages[0] = make([]byte, 20) - sk := genSecretKey(t) - sig := genSignature(sk, messages[0], t) - pk := genPublicKey(sk, t) - bls := NewSigPop() - // Should be the same as verifySignature - if res, _ := bls.AggregateVerify([]*PublicKey{pk}, messages, []*Signature{sig}); !res { - t.Errorf("Expected AggregateVerifyG2OneMsg to pass but failed") - } -} - -func TestVerifyG2Mutability(t *testing.T) { - // verify should not change any inputs - ikm := make([]byte, 32) - ikm_copy := make([]byte, 32) - readRand(ikm, t) - copy(ikm_copy, ikm) - bls := NewSigPop() - pk, sk, err := bls.KeygenWithSeed(ikm) - - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPop.KeygenWithSeed modifies ikm") - } - if err != nil { - t.Errorf("Expected KeygenWithSeed to succeed but failed.") - } - sig, err := bls.Sign(sk, ikm) - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPop.Sign modifies message") - } - if err != nil { - t.Errorf("SigPop.KeygenWithSeed to succeed but failed.") - } - sigCopy := marshalStruct(sig, t) - if res, _ := bls.Verify(pk, ikm, sig); !res { - t.Errorf("Expected verify to succeed but failed.") - } - if !bytes.Equal(ikm, ikm_copy) { - t.Errorf("SigPop.verify modifies message") - } - if !bytes.Equal(sigCopy, marshalStruct(sig, t)) { - t.Errorf("SigPop.verify modifies signature") - } -} - -func TestPublicKeyG1FromBadBytes(t *testing.T) { - pk := make([]byte, 32) - err := new(PublicKey).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG1FromBytes to fail but passed") - } - // All zeros - pk = make([]byte, PublicKeySize) - // See https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization - // 1 << 7 == compressed - // 1 << 6 == infinity or zero - pk[0] = 0xc0 - err = new(PublicKey).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG1FromBytes to fail but passed") - } - sk := genSecretKey(t) - pk1, err := sk.GetPublicKey() - if err != nil { - t.Errorf("Expected GetPublicKey to pass but failed.") - } - out := marshalStruct(pk1, t) - out[3] += 1 - err = new(PublicKey).UnmarshalBinary(pk) - if err == nil { - t.Errorf("Expected PublicKeyG1FromBytes to fail but passed") - } -} - -func TestSignatureG2FromBadBytes(t *testing.T) { - sig := make([]byte, 32) - err := new(Signature).UnmarshalBinary(sig) - if err == nil { - t.Errorf("Expected SignatureG2FromBytes to fail but passed") - } - // All zeros - sig = make([]byte, SignatureSize) - // See https://github.com/zcash/librustzcash/blob/master/pairing/src/bls12_381/README.md#serialization - // 1 << 7 == compressed - // 1 << 6 == infinity or zero - sig[0] = 0xc0 - err = new(Signature).UnmarshalBinary(sig) - if err == nil { - t.Errorf("Expected SignatureG2FromBytes to fail but passed") - } -} - -func TestBadSecretKeyG2(t *testing.T) { - sk := &SecretKey{value: bls12381.Bls12381FqNew()} - pk, err := sk.GetPublicKey() - if err == nil { - t.Errorf("Expected GetPublicKey to fail with 0 byte secret key but passed: %v", pk) - } - _ = sk.UnmarshalBinary(sk.value.Params.BiModulus.Bytes()) - pk, err = sk.GetPublicKey() - if err == nil { - t.Errorf("Expected GetPublicKey to fail with secret key with Q but passed: %v", pk) - } - - err = sk.UnmarshalBinary([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}) - if err == nil { - t.Errorf("Expected SecretKeyFromBytes to fail with not enough bytes but passed: %v", pk) - } - - err = sk.UnmarshalBinary(make([]byte, 32)) - if err == nil { - t.Errorf("Expected SecretKeyFromBytes to fail with all zeros but passed: %v", pk) - } -} - -func TestProofOfPossessionG2Works(t *testing.T) { - ikm := make([]byte, 32) - readRand(ikm, t) - bls := NewSigPop() - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Key gen failed but should've succeeded") - } - pop, err := bls.PopProve(sk) - if err != nil { - t.Errorf("PopProve failed but should've succeeded") - } - if res, _ := bls.PopVerify(pk, pop); !res { - t.Errorf("PopVerify failed but should've succeeded") - } -} - -func TestProofOfPossessionG2FromBadKey(t *testing.T) { - ikm := make([]byte, 32) - value := new(big.Int) - value.SetBytes(ikm) - sk := SecretKey{value: bls12381.Bls12381FqNew().SetBigInt(value)} - _, err := sk.createProofOfPossession(blsSignaturePopDst) - if err == nil { - t.Errorf("createProofOfPossession should've failed but succeeded.") - } -} - -func TestProofOfPossessionG2BytesWorks(t *testing.T) { - sk := genSecretKey(t) - pop, err := sk.createProofOfPossession(blsSignaturePopDst) - if err != nil { - t.Errorf("CreateProofOfPossesionG2 failed but shouldn've succeeded.") - } - out := marshalStruct(pop, t) - if len(out) != ProofOfPossessionSize { - t.Errorf( - "ProofOfPossessionBytes incorrect size: expected %v, got %v", - ProofOfPossessionSize, - len(out), - ) - } - pop2 := new(ProofOfPossession) - err = pop2.UnmarshalBinary(out) - if err != nil { - t.Errorf("ProofOfPossession.UnmarshalBinary failed: %v", err) - } - out2 := marshalStruct(pop2, t) - if !bytes.Equal(out, out2) { - t.Errorf("ProofOfPossession.UnmarshalBinary failed, not equal when deserialized") - } -} - -func TestProofOfPossessionG2BadBytes(t *testing.T) { - zeros := make([]byte, ProofOfPossessionSize) - temp := new(ProofOfPossession) - err := temp.UnmarshalBinary(zeros) - if err == nil { - t.Errorf("ProofOfPossession.UnmarshalBinary shouldn've failed but succeeded.") - } -} - -func TestProofOfPossessionG2Fails(t *testing.T) { - sk := genSecretKey(t) - pop, err := sk.createProofOfPossession(blsSignaturePopDst) - if err != nil { - t.Errorf("Expected createProofOfPossession to succeed but failed.") - } - - ikm := make([]byte, 32) - readRand(ikm, t) - sk = genRandSecretKey(ikm, t) - bad, err := sk.GetPublicKey() - if err != nil { - t.Errorf("Expected PublicKeyG1FromBytes to succeed but failed: %v", err) - } - if res, _ := pop.verify(bad, blsSignaturePopDst); res { - t.Errorf("Expected ProofOfPossession verify to fail but succeeded.") - } -} - -func TestMultiSigG2Bytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - _, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - msig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - msigBytes := marshalStruct(msig, t) - if len(msigBytes) != SignatureSize { - t.Errorf( - "Invalid multi-sig length. Expected %d bytes, found %d", - SignatureSize, - len(msigBytes), - ) - } - msig2 := new(MultiSignature) - err = msig2.UnmarshalBinary(msigBytes) - if err != nil { - t.Errorf("MultiSignatureG2FromBytes failed with %v", err) - } - msigBytes2 := marshalStruct(msig2, t) - - if !bytes.Equal(msigBytes, msigBytes2) { - t.Errorf("Bytes methods not equal.") - } -} - -func TestMultiSigG2BadBytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - _, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - msig, err := bls.AggregateSignatures(sigs...) - if err != nil { - t.Errorf("%v", err) - } - msigBytes := marshalStruct(msig, t) - if len(msigBytes) != SignatureSize { - t.Errorf( - "Invalid multi-sig length. Expected %d bytes, found %d", - SignatureSize, - len(msigBytes), - ) - } - msigBytes[0] = 0 - temp := new(MultiSignature) - err = temp.UnmarshalBinary(msigBytes) - if err == nil { - t.Errorf("MultiSignatureG2FromBytes should've failed but succeeded") - } - msigBytes = make([]byte, SignatureSize) - err = temp.UnmarshalBinary(msigBytes) - if err == nil { - t.Errorf("MultiSignatureG2FromBytes should've failed but succeeded") - } -} - -func TestMultiPubkeyG1Bytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - pks, _ := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - apkBytes := marshalStruct(apk, t) - if len(apkBytes) != PublicKeySize { - t.Errorf("MultiPublicKey has an incorrect size") - } - apk2 := new(MultiPublicKey) - err = apk2.UnmarshalBinary(apkBytes) - if err != nil { - t.Errorf("MultiPublicKey.UnmarshalBinary failed with %v", err) - } - apk2Bytes := marshalStruct(apk2, t) - if !bytes.Equal(apkBytes, apk2Bytes) { - t.Errorf("Bytes methods not equal.") - } -} - -func TestMultiPubkeyG1BadBytes(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 20) - messages[0] = message - pks, _ := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - apk, err := bls.AggregatePublicKeys(pks...) - if err != nil { - t.Errorf("%v", err) - } - apkBytes := marshalStruct(apk, t) - if len(apkBytes) != PublicKeySize { - t.Errorf("MultiPublicKey has an incorrect size") - } - apkBytes[0] = 0 - temp := new(MultiPublicKey) - err = temp.UnmarshalBinary(apkBytes) - if err == nil { - t.Errorf("MultiPublicKey.UnmarshalBinary should've failed but succeeded") - } - apkBytes = make([]byte, PublicKeySize) - err = temp.UnmarshalBinary(apkBytes) - if err == nil { - t.Errorf("MultiPublicKey.UnmarshalBinary should've failed but succeeded") - } -} - -func TestFastAggregateVerifyG2Works(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG2(messages, t) - asigs, _ := aggregateSignatures(sigs...) - bls := NewSigPop() - if res, _ := bls.FastAggregateVerify(pks, message, asigs); !res { - t.Errorf("FastAggregateVerify failed.") - } -} - -func TestFastAggregateVerifyConstituentG2Works(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - if res, _ := bls.FastAggregateVerifyConstituent(pks, message, sigs); !res { - t.Errorf("FastAggregateVerify failed.") - } -} - -func TestFastAggregateVerifyG2Fails(t *testing.T) { - messages := make([][]byte, 1) - message := make([]byte, 1) - messages[0] = message - pks, sigs := initAggregatedTestValuesG2(messages, t) - bls := NewSigPop() - message[0] = 1 - if res, _ := bls.FastAggregateVerifyConstituent(pks, message, sigs); res { - t.Errorf("FastAggregateVerify verified when it should've failed.") - } -} - -func TestCustomPopDstG2Works(t *testing.T) { - bls, _ := NewSigPopWithDst("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_TEST", - "BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_TEST") - msg := make([]byte, 20) - ikm := make([]byte, 32) - pk, sk, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Couldn't create custom dst keys: %v", err) - } - sig, err := bls.Sign(sk, msg) - if err != nil { - t.Errorf("Couldn't sign with custom dst: %v", err) - } - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("verify fails with custom dst") - } - - pks := make([]*PublicKey, 10) - sigs := make([]*Signature, 10) - pks[0] = pk - sigs[0] = sig - for i := 1; i < 10; i++ { - readRand(ikm, t) - pkt, skt, err := bls.KeygenWithSeed(ikm) - if err != nil { - t.Errorf("Couldn't create custom dst keys: %v", err) - } - sigt, err := bls.Sign(skt, msg) - if err != nil { - t.Errorf("Couldn't sign with custom dst: %v", err) - } - pks[i] = pkt - sigs[i] = sigt - } - - if res, _ := bls.FastAggregateVerifyConstituent(pks, msg, sigs); !res { - t.Errorf("FastAggregateVerify failed with custom dst") - } - - pop, err := bls.PopProve(sk) - if err != nil { - t.Errorf("PopProve failed with custom dst") - } - - if res, _ := bls.PopVerify(pk, pop); !res { - t.Errorf("PopVerify failed with custom dst") - } -} - -func TestBlsPopG2KeyGenWithSeed(t *testing.T) { - ikm := []byte("Not enough bytes") - bls := NewSigPop() - _, _, err := bls.KeygenWithSeed(ikm) - if err == nil { - t.Errorf("Expected KeygenWithSeed to fail but succeeded") - } -} - -func TestBlsPopG2KeyGen(t *testing.T) { - bls := NewSigPop() - _, _, err := bls.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } -} - -func TestPopThresholdKeygenBadInputs(t *testing.T) { - bls := NewSigPop() - _, _, err := bls.ThresholdKeygen(0, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(1, 0) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } - _, _, err = bls.ThresholdKeygen(3, 2) - if err == nil { - t.Errorf("ThresholdKeygen should've failed but succeeded") - } -} - -func TestPopThresholdKeygen(t *testing.T) { - bls := NewSigPop() - _, sks, err := bls.ThresholdKeygen(3, 5) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - if len(sks) != 5 { - t.Errorf("ThresholdKeygen did not produce enough shares") - } -} - -func TestPopPartialSign(t *testing.T) { - ikm := make([]byte, 32) - bls := NewSigPop() - pk, sks, err := bls.ThresholdKeygenWithSeed(ikm, 2, 4) - if err != nil { - t.Errorf("ThresholdKeygen failed") - } - msg := make([]byte, 10) - sig1, err := bls.PartialSign(sks[0], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig2, err := bls.PartialSign(sks[1], msg) - if err != nil { - t.Errorf("partialSign failed: %v", err) - } - sig, err := bls.CombineSignatures(sig1, sig2) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - - if res, _ := bls.Verify(pk, msg, sig); !res { - t.Errorf("Combined signature does not verify") - } - - sig, err = bls.CombineSignatures(sig1) - if err == nil { - t.Errorf("CombineSignatures succeeded when it should've failed") - } - if res, _ := bls.Verify(pk, msg, sig); res { - t.Errorf("Combined signature verify succeeded when it should've failed") - } -} - -// Ensure that mixed partial signatures from distinct origins create invalid composite signatures -func TestPopPartialMixupShares(t *testing.T) { - total := uint(5) - ikm := make([]byte, 32) - bls := NewSigPop() - pk1, sks1, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - for i := range ikm { - ikm[i] = 1 - } - pk2, sks2, err := bls.ThresholdKeygenWithSeed(ikm, 3, total) - if err != nil { - t.Errorf("ThresholdKeygen failed: %v", err) - } - - // Generate partial signatures for both sets of keys - msg := make([]byte, 10) - sigs1 := make([]*PartialSignature, total) - sigs2 := make([]*PartialSignature, total) - for i := range sks1 { - sigs1[i], err = bls.PartialSign(sks1[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - sigs2[i], err = bls.PartialSign(sks2[i], msg) - if err != nil { - t.Errorf("PartialSign failed: %v", err) - } - } - - // Try combining 2 from group 1 and 2 from group 2 - sig, err := bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[2], sigs2[3]) - if err != nil { - t.Errorf("CombineSignatures failed: %v", err) - } - // Signature shouldn't validate - if res, _ := bls.Verify(pk1, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - if res, _ := bls.Verify(pk2, msg, sig); res { - t.Errorf( - "CombineSignatures worked with different shares of two secret keys for the same message", - ) - } - // Should error out due to duplicate identifiers - _, err = bls.CombineSignatures(sigs1[0], sigs1[1], sigs2[0], sigs2[1]) - if err == nil { - t.Errorf("CombineSignatures expected to fail but succeeded.") - } -} - -func TestNewSigEth2KeyGen(t *testing.T) { - eth2 := NewSigEth2() - _, _, err := eth2.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } -} - -func TestSigEth2SignRoundTrip(t *testing.T) { - eth2 := NewSigEth2() - pop := NewSigPop() - eth2Pk, eth2Sk, err := eth2.Keygen() - if err != nil { - t.Errorf("Keygen failed: %v", err) - } - - sig, err := pop.Sign(eth2Sk, []byte{0, 0}) - if err != nil { - t.Errorf("Sign failed: %v", err) - } - if ok, err := eth2.Verify(eth2Pk, []byte{0, 0}, sig); err != nil || !ok { - t.Errorf("Verify failed: %v", err) - } -} diff --git a/crypto/signatures/bls/rust/Cargo.toml b/crypto/signatures/bls/rust/Cargo.toml deleted file mode 100755 index 9b17a1f2e..000000000 --- a/crypto/signatures/bls/rust/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "miracl" -version = "0.1.0" -authors = ["Mike Lodder "] -edition = "2018" - -[dependencies] -bls_sigs_ref = "0.3" -hex = "0.4" -miracl_core = { version = "2.3", features = [ - "bls12381", -], default-features = false } -pairing-plus = "0.19" -rand = "0.8" -serious = { version = "0.1", git = "https://github.com/mikelodder7/malutils" } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -sha2 = "0.8" -structopt = "0.3" diff --git a/crypto/signatures/bls/rust/README.md b/crypto/signatures/bls/rust/README.md deleted file mode 100755 index e0f8e8d17..000000000 --- a/crypto/signatures/bls/rust/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Note - -This rust package is added for the sole purpose of comparing the result of our Go package with other -implementations, including the rust package. diff --git a/crypto/signatures/bls/rust/src/main.rs b/crypto/signatures/bls/rust/src/main.rs deleted file mode 100755 index 43aebd966..000000000 --- a/crypto/signatures/bls/rust/src/main.rs +++ /dev/null @@ -1,388 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -use bls_sigs_ref::BLSSignaturePop; -use miracl_core::bls12381::{big::BIG, ecp::ECP, ecp2::ECP2, rom::MODULUS}; -use pairing_plus::{ - bls12_381::{Fr, G1, G2}, - hash_to_field::BaseFromRO, - serdes::SerDes, - CurveProjective, -}; -use rand::prelude::*; -use serde::Deserialize; -use serious::Encoding; -use sha2::digest::generic_array::GenericArray; -use std::{ - fs::File, - io::{self, Cursor, Read}, - path::PathBuf, -}; -use structopt::StructOpt; - -fn main() { - let args = CliArgs::from_args(); - - match args { - CliArgs::Generate { number } => generate(number), - CliArgs::PublicKey { keys } => pubkey(keys), - CliArgs::Sign { number, data } => sign(number, data), - CliArgs::Verify { keys } => verify(keys), - } -} - -fn generate(number: usize) { - let mut rng = thread_rng(); - print!("["); - let mut sep = ""; - for _ in 0..number { - let mut buf = [0u8; 48]; - rng.fill_bytes(&mut buf); - // let mut sk = buf; - let fr = Fr::from_okm(GenericArray::from_slice(&buf)); - let mut pk = G1::one(); - pk.mul_assign(fr); - - pk.serialize(&mut buf.as_mut(), true).unwrap(); - print!("{}\"{}\"", sep, hex::encode(buf)); - sep = ","; - - // Miracl expects 48 bytes for secret key even though the top 16 bytes are zeros - // sk = [0u8; 48]; - // fr.serialize(&mut sk[16..].as_mut(), true).unwrap(); - // let s = BIG::frombytes(&sk[..]); - // let x = _compress_g1(g1mul(&ECP::generator(), &s)); - // - // println!("Miracl = {}", hex::encode(x)); - } - print!("]"); -} - -/// Compress to BLS12-381 standard vs ANSI X9.62 -fn _compress_g1(pk: ECP) -> [u8; 48] { - let mut x = [0u8; 48]; - pk.getx().tobytes(&mut x); - if pk.is_infinity() { - // Set the second-most significant bit to indicate this point - // is at infinity. - x[0] |= 1 << 6; - } else { - let m = BIG { w: MODULUS }; - let mut negy = BIG::new(); - negy.add(&BIG::modneg(&pk.gety(), &m)); - negy.rmod(&m); - negy.norm(); - // Set the third most significant bit if the correct y-coordinate - // is lexicographically largest. - if BIG::comp(&pk.gety(), &negy) == 1 { - x[0] |= 1 << 5; - } - } - // Set highest bit to distinguish this as a compressed element. - x[0] |= 1 << 7; - x -} - -fn _compress_g2(sig: ECP2) -> [u8; 96] { - let mut x = [0u8; 96]; - sig.getx().geta().tobytes(&mut x[..48]); - sig.getx().getb().tobytes(&mut x[48..]); - if sig.is_infinity() { - // Set the second-most significant bit to indicate this point - // is at infinity. - x[0] |= 1 << 6; - } else { - let mut negy = sig.clone(); - negy.neg(); - - // Set the third most significant bit if the correct y-coordinate - // is lexicographically largest. - negy.sub(&sig); - - if negy.gety().sign() > 0 { - x[0] |= 1 << 5; - } - } - // Set highest bit to distinguish this as a compressed element. - x[0] |= 1 << 7; - x -} - -fn pubkey(keys: String) { - let res = read_input(&keys).unwrap(); - - for pubkey in serde_json::from_slice::>(&res).unwrap() { - let res = hex::decode(&pubkey); - if res.is_err() { - println!("Invalid hex format {}", res.unwrap_err()); - continue; - } - let mut key = res.unwrap(); - let mut cur = Cursor::new(key.as_slice()); - print!("ZCash {} - ", pubkey); - let res = G1::deserialize(&mut cur, true); - - if let Err(e) = res { - println!("fail - {}", e); - } else { - println!("pass"); - } - - let res = _uncompress_g1(key.as_mut_slice()); - - print!("Miracl {} - ", pubkey); - if let Err(e) = res { - println!("fail - {}", e); - } else { - println!("pass"); - } - } -} - -fn _uncompress_g1(d: &[u8]) -> Result { - if d.len() != 48 { - return Err("Invalid length".to_string()); - } - - if d[0] & 0x80 != 0x80 { - return Err("Expected compressed point".to_string()); - } - - // Expect point at infinity - if d[0] & 0x40 == 0x40 { - return if !d.iter().skip(1).all(|b| *b == 0) { - Err("Expected point at infinity but found another point".to_string()) - } else { - Ok(ECP::new()) - }; - } - - let s = d[0] & 0x20; - // Unset top bits - let mut dd = [0u8; 48]; - dd.copy_from_slice(d); - dd[0] &= 0x1F; - let x = BIG::frombytes(&dd); - Ok(ECP::new_bigint(&x, s as isize)) -} - -fn _uncompress_g2(d: &[u8]) -> Result { - if d.len() != 96 { - return Err("Invalid length".to_string()); - } - - if d[0] & 0x80 != 0x80 { - return Err("Expected compressed point".to_string()); - } - - // Expect point at infinity - if d[0] & 0x40 == 0x40 { - return if !d.iter().skip(1).all(|b| *b == 0) { - Err("Expected point at infinity but found another point".to_string()) - } else { - Ok(ECP2::new()) - }; - } - - let s = d[0] & 0x20; - let mut dd = [0u8; 97]; - dd[1..].copy_from_slice(d); - dd[1] &= 0x1F; - // Unset top bits - dd[0] = if s > 0 { 0x3 } else { 0x2 }; - Ok(ECP2::frombytes(&dd)) -} - -fn sign(number: usize, data: String) { - let mut rng = thread_rng(); - let bytes = data.as_bytes(); - let mut sep = ""; - print!("["); - for _ in 0..number { - let mut buf = [0u8; 48]; - rng.fill_bytes(&mut buf); - let fr = Fr::from_okm(GenericArray::from_slice(&buf)); - let mut pk = G1::one(); - pk.mul_assign(fr); - - let mut pubkey = [0u8; 48]; - pk.serialize(&mut pubkey.as_mut(), true).unwrap(); - - let signature = G2::sign(fr, bytes); - let mut sig = [0u8; 96]; - signature.serialize(&mut sig.as_mut(), true).unwrap(); - - print!("{}{{", sep); - print!(r#""data":"{}","#, data); - print!( - r#""public_key":"{}","#, - Encoding::encode(pubkey, Encoding::LowHex).into_string() - ); - print!( - r#""signature":"{}""#, - Encoding::encode(sig, Encoding::LowHex).into_string() - ); - print!("}}"); - sep = ","; - } - print!("]"); -} - -fn verify(keys: String) { - let res = read_input(&keys).unwrap(); - - for req in serde_json::from_slice::>(&res).unwrap() { - let pubkey = Encoding::decode(&req.public_key, Encoding::LowHex).unwrap(); - let sig = Encoding::decode(&req.signature, Encoding::LowHex).unwrap(); - let mut cur = Cursor::new(pubkey.as_slice()); - let verkey = G1::deserialize(&mut cur, true).unwrap(); - cur = Cursor::new(sig.as_slice()); - let signature = G2::deserialize(&mut cur, true).unwrap(); - - print!("ZCash {} - ", req.public_key); - if G2::verify(verkey, signature, req.data.as_bytes()) { - println!("pass"); - } else { - println!("fail"); - } - } -} - -#[derive(Debug, StructOpt)] -enum CliArgs { - Generate { - #[structopt(short, long)] - number: usize, - }, - PublicKey { - #[structopt(name = "KEYS")] - keys: String, - }, - Sign { - #[structopt(short, long)] - number: usize, - #[structopt(short, long)] - data: String, - }, - Verify { - #[structopt(name = "KEYS")] - keys: String, - }, -} - -#[derive(Deserialize)] -struct VerifyRequest { - data: String, - public_key: String, - signature: String, -} - -fn read_input(value: &str) -> Result, String> { - if !value.is_empty() { - match get_file(value) { - Some(file) => match File::open(file.as_path()) { - Ok(mut f) => Ok(read_stream(&mut f)), - Err(_) => Err(format!("Unable to read file {}", file.to_str().unwrap())), - }, - None => Ok(value.as_bytes().to_vec()), - } - } else { - let mut f = io::stdin(); - Ok(read_stream(&mut f)) - } -} - -fn read_stream(f: &mut R) -> Vec { - let mut bytes = Vec::new(); - let mut buffer = [0u8; 4096]; - - let mut read = f.read(&mut buffer); - while read.is_ok() { - let n = read.unwrap(); - - if n == 0 { - break; - } - - bytes.extend_from_slice(&buffer[..n]); - - read = f.read(&mut buffer); - } - - bytes -} - -fn get_file(name: &str) -> Option { - if name.len() > 256 { - // too long to be a file - return None; - } - let mut file = PathBuf::new(); - file.push(name); - if file.as_path().is_file() { - let metadata = file - .as_path() - .symlink_metadata() - .expect("symlink_metadata call failed"); - if metadata.file_type().is_symlink() { - if let Ok(f) = file.as_path().read_link() { - file = f - } else { - return None; - } - } - Some(file) - } else { - None - } -} - -// fn from_encoding(src: &str) -> Result { -// Encoding::parse(src).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e)) -// } - -// fn hash_to_g2(d: &[u8]) -> ECP2 { -// const DST: &'static str = "BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"; -// let y = >>::hash_to_curve(d.as_ref(), DST); -// let mut d = [0u8; 193]; -// d[0] = 0x4; -// y.serialize(&mut d[1..].as_mut(), false); -// ECP2::frombytes(&d) -// } - -// fn ceil(a: usize, b: usize) -> usize { -// (a-1)/b+1 -// } -// -// fn hash_to_field(hash: usize, hlen: usize, u: &mut [FP2], dst: &[u8], m: &[u8], ctr: usize) { -// let q = BIG { w: MODULUS }; -// let el = ceil(q.nbits()+AESKEY*16, 8); -// -// let mut okm = [0u8; 512]; -// let mut fd = [0u8; 256]; -// xmd_expand(hash, hlen, &mut okm, el*ctr, &dst, &m); -// u[0] = FP2::new_fps( -// &FP::new_big(&DBIG::frombytes(&okm[0..el]).dmod(&q)), -// &FP::new_big(&DBIG::frombytes(&okm[el..(2*el)]).dmod(&q)) -// ); -// u[1] = FP2::new_fps( -// &FP::new_big(&DBIG::frombytes(&okm[(2*el)..(3*el)]).dmod(&q)), -// &FP::new_big(&DBIG::frombytes(&okm[(3*el)..]).dmod(&q)) -// ); -// } -// -// fn hash_to_ecp2(m: &[u8]) -> ECP2 { -// let dst = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"; -// let mut u = [FP2::new(); 2]; -// hash_to_field(hmac::MC_SHA2, ecp::HASH_TYPE, &mut u, &dst[..], m, 2); -// -// let mut p = ECP2::map2point(&u[0]); -// let q = ECP2::map2point(&u[1]); -// p.add(&q); -// p.cfp(); -// p.affine(); -// p -// } diff --git a/crypto/signatures/bls/tests/bls/main.go b/crypto/signatures/bls/tests/bls/main.go deleted file mode 100644 index db1c8e691..000000000 --- a/crypto/signatures/bls/tests/bls/main.go +++ /dev/null @@ -1,236 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package main - -import ( - "bufio" - "encoding/hex" - "encoding/json" - "flag" - "fmt" - "os" - - bls "github.com/sonr-io/sonr/crypto/signatures/bls/bls_sig" -) - -type signOp struct { - Data string `json:"data"` - PublicKey string `json:"public_key"` - Signature string `json:"signature"` -} - -type cmdFlags struct { - Generate bool - PublicKeys bool - Sign bool - Verify bool - Number int -} - -func parseCliArgs() cmdFlags { - var generate, publickeys, sign, verify bool - var number int - flag.BoolVar(&generate, "g", false, "Generate public keys") - flag.BoolVar(&publickeys, "p", false, "Verify public keys") - flag.BoolVar(&sign, "s", false, "Generate signatures") - flag.BoolVar(&verify, "v", false, "Verify signatures") - flag.IntVar(&number, "n", 25, "The number of items to generate") - flag.Parse() - return cmdFlags{ - generate, publickeys, sign, verify, number, - } -} - -func main() { - flags := parseCliArgs() - - if flags.Generate { - generate(flags.Number) - } else if flags.PublicKeys { - publicKeys() - } else if flags.Sign { - sign(flags.Number) - } else if flags.Verify { - verify() - } -} - -func generate(number int) { - scheme := bls.NewSigPop() - publicKeys := make([]string, number) - for i := 0; i < number; i++ { - publicKey, _, err := scheme.Keygen() - if err != nil { - fmt.Printf("Keygen error occurred: %v\n", err) - os.Exit(1) - } - b, _ := publicKey.MarshalBinary() - publicKeys[i] = hex.EncodeToString(b) - } - out, _ := json.Marshal(publicKeys) - fmt.Println(string(out)) -} - -func publicKeys() { - input, err := getInput() - if err != nil { - fmt.Printf("Unable to read input: %v", err) - os.Exit(1) - } - var pubkeys []string - err = json.Unmarshal(input, &pubkeys) - if err != nil { - fmt.Printf("Unable to parse json input: %v", err) - os.Exit(1) - } - fmt.Printf("Checking public keys") - for _, pk := range pubkeys { - data, err := hex.DecodeString(pk) - if err != nil { - fmt.Printf("Unable to parse hex input: %v", err) - os.Exit(1) - } - pubkey := new(bls.PublicKey) - fmt.Printf("Checking %s - ", pk) - err = pubkey.UnmarshalBinary(data) - if err != nil { - fmt.Printf("fail\n") - os.Exit(1) - } - fmt.Printf("pass\n") - } -} - -func sign(number int) { - tests := []string{ - "", "aaa", "aaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - } - - var err error - scheme := bls.NewSigPop() - secretKeys := make([]*bls.SecretKey, number) - publicKeys := make([]*bls.PublicKey, number) - for i := 0; i < number; i++ { - publicKeys[i], secretKeys[i], err = scheme.Keygen() - if err != nil { - fmt.Printf("Keygen error occurred: %v\n", err) - os.Exit(1) - } - } - - sigs := make([]*signOp, number*len(tests)) - - k := 0 - for _, t := range tests { - for j := 0; j < len(secretKeys); j++ { - signature, err := scheme.Sign(secretKeys[j], []byte(t)) - if err != nil { - fmt.Printf("Signing failed: %v\n", err) - os.Exit(1) - } - pk, _ := publicKeys[j].MarshalBinary() - sig, _ := signature.MarshalBinary() - sigs[k] = &signOp{ - Data: t, - PublicKey: hex.EncodeToString(pk), - Signature: hex.EncodeToString(sig), - } - k++ - } - } - - data, err := json.Marshal(sigs) - if err != nil { - fmt.Printf("Unable to convert signatures to json") - os.Exit(1) - } - fmt.Print(string(data)) -} - -func verify() { - input, err := getInput() - if err != nil { - fmt.Printf("Unable to read input: %v", err) - os.Exit(1) - } - var operations []signOp - err = json.Unmarshal(input, &operations) - if err != nil { - fmt.Printf("Unable to parse json input: %v", err) - os.Exit(1) - } - scheme := bls.NewSigPop() - for _, op := range operations { - fmt.Printf("Checking %s - ", op.PublicKey) - data, err := hex.DecodeString(op.PublicKey) - if err != nil { - fmt.Printf("fail. Unable to parse hex input: %v", err) - os.Exit(1) - } - pubkey := new(bls.PublicKey) - err = pubkey.UnmarshalBinary(data) - if err != nil { - fmt.Printf("fail. Invalid public key: %v", err) - os.Exit(1) - } - data, err = hex.DecodeString(op.Signature) - if err != nil { - fmt.Printf("fail. Unable to parse hex input: %v", err) - os.Exit(1) - } - sig := new(bls.Signature) - err = sig.UnmarshalBinary(data) - if err != nil { - fmt.Printf("fail. Invalid signature format: %v", err) - os.Exit(1) - } - ok, err := scheme.Verify(pubkey, []byte(op.Data), sig) - if !ok || err != nil { - fmt.Printf("fail. Invalid signature") - os.Exit(1) - } - fmt.Printf("pass.") - } -} - -func getInput() ([]byte, error) { - fi, _ := os.Stdin.Stat() - - var data []byte - - if (fi.Mode() & os.ModeCharDevice) == 0 { - // Read from pipe - scanner := bufio.NewScanner(os.Stdin) - for scanner.Scan() { - data = append(data, scanner.Bytes()...) - } - - if err := scanner.Err(); err != nil { - return nil, err - } - } else { - // Read from file - arguments := flag.Args() - if len(arguments) < 1 { - return nil, fmt.Errorf("expected data argument") - } - - _, err := os.Stat(arguments[0]) - - if os.IsNotExist(err) { - data = []byte(arguments[0]) - } else { - contents, err := os.ReadFile(arguments[0]) - if err != nil { - return nil, err - } - data = contents - } - } - - return data, nil -} diff --git a/crypto/signatures/common/challenge.go b/crypto/signatures/common/challenge.go deleted file mode 100644 index 39e4bf529..000000000 --- a/crypto/signatures/common/challenge.go +++ /dev/null @@ -1,14 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Challenge generated by fiat-shamir heuristic -type Challenge = curves.Scalar diff --git a/crypto/signatures/common/commitment.go b/crypto/signatures/common/commitment.go deleted file mode 100644 index 63900361c..000000000 --- a/crypto/signatures/common/commitment.go +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Commitment represents a point Pedersen commitment of one or more -// points multiplied by scalars -type Commitment = curves.Point diff --git a/crypto/signatures/common/hmacdrbg.go b/crypto/signatures/common/hmacdrbg.go deleted file mode 100755 index 025e3dfe8..000000000 --- a/crypto/signatures/common/hmacdrbg.go +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "crypto/hmac" - "hash" -) - -// HmacDrbg is an HMAC deterministic random bit generator -// that can use any hash function. Handles reseeding -// automatically -type HmacDrbg struct { - k, v []byte - count int - hasher func() hash.Hash -} - -func NewHmacDrbg(entropy, nonce, pers []byte, hasher func() hash.Hash) *HmacDrbg { - drbg := new(HmacDrbg) - h := hasher() - drbg.k = make([]byte, h.Size()) - drbg.v = make([]byte, h.Size()) - drbg.count = 0 - drbg.hasher = hasher - - for i := range drbg.v { - drbg.v[i] = 1 - } - - drbg.update([][]byte{entropy, nonce, pers}) - drbg.count += 1 - return drbg -} - -func (drbg *HmacDrbg) Read(dst []byte) (n int, err error) { - toRead := len(dst) - if toRead == 0 { - return 0, nil - } - i := 0 - for i < toRead { - vmac := drbg.getHmac() - _, _ = vmac.Write(drbg.v) - drbg.v = vmac.Sum(nil) - - for j, b := range drbg.v { - dst[i+j] = b - } - i += len(drbg.v) - } - drbg.update(nil) - drbg.count++ - return i, nil -} - -func (drbg *HmacDrbg) Reseed(entropy []byte) { - drbg.update([][]byte{entropy}) -} - -func (drbg *HmacDrbg) getHmac() hash.Hash { - return hmac.New(drbg.hasher, drbg.k) -} - -func (drbg *HmacDrbg) update(seeds [][]byte) { - kmac := drbg.getHmac() - _, _ = kmac.Write(drbg.v) - _, _ = kmac.Write([]byte{0}) - if len(seeds) > 0 { - for _, seed := range seeds { - _, _ = kmac.Write(seed) - } - } - drbg.k = kmac.Sum(nil) - - vmac := drbg.getHmac() - _, _ = vmac.Write(drbg.v) - drbg.v = vmac.Sum(nil) - - if len(seeds) == 0 { - return - } - - kmac = drbg.getHmac() - _, _ = kmac.Write(drbg.v) - _, _ = kmac.Write([]byte{1}) - for _, seed := range seeds { - _, _ = kmac.Write(seed) - } - drbg.k = kmac.Sum(nil) - - vmac = drbg.getHmac() - _, _ = vmac.Write(drbg.v) - drbg.v = vmac.Sum(nil) -} diff --git a/crypto/signatures/common/nonce.go b/crypto/signatures/common/nonce.go deleted file mode 100644 index 93918a914..000000000 --- a/crypto/signatures/common/nonce.go +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Nonce is used for zero-knowledge proofs to prevent replay attacks -// and prove freshness -type Nonce = curves.Scalar diff --git a/crypto/signatures/common/proof_committed_builder.go b/crypto/signatures/common/proof_committed_builder.go deleted file mode 100644 index d08bc4d29..000000000 --- a/crypto/signatures/common/proof_committed_builder.go +++ /dev/null @@ -1,89 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "fmt" - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -const limit = 65535 - -// ProofCommittedBuilder is used to create -// proofs from multiple commitments where -// each secret is committed with a random blinding factor -// and turned into a Schnorr proof -type ProofCommittedBuilder struct { - points []curves.Point - scalars []curves.Scalar - curve *curves.Curve -} - -// NewProofCommittedBuilder creates a new builder using the specified curve -func NewProofCommittedBuilder(curve *curves.Curve) *ProofCommittedBuilder { - return &ProofCommittedBuilder{ - points: []curves.Point{}, - scalars: []curves.Scalar{}, - curve: curve, - } -} - -// CommitRandom uses the specified point and commits a random value to it -func (pcb *ProofCommittedBuilder) CommitRandom(point curves.Point, reader io.Reader) error { - if len(pcb.points) > limit { - return fmt.Errorf("limit for commitments reached") - } - pcb.points = append(pcb.points, point) - pcb.scalars = append(pcb.scalars, pcb.curve.Scalar.Random(reader)) - return nil -} - -// Commit uses the specified point and scalar to create a commitment -func (pcb *ProofCommittedBuilder) Commit(point curves.Point, scalar curves.Scalar) error { - if len(pcb.points) > limit { - return fmt.Errorf("limit for commitments reached") - } - pcb.points = append(pcb.points, point) - pcb.scalars = append(pcb.scalars, scalar) - return nil -} - -// Get returns the point and scalar at the specified index -func (pcb *ProofCommittedBuilder) Get(index int) (curves.Point, curves.Scalar) { - if index >= len(pcb.points) || index < 0 { - return nil, nil - } - return pcb.points[index], pcb.scalars[index] -} - -// GetChallengeContribution returns the bytes that should be added to -// a sigma protocol transcript for generating the challenge -func (pcb ProofCommittedBuilder) GetChallengeContribution() []byte { - commitment := pcb.curve.Point.SumOfProducts(pcb.points, pcb.scalars) - if commitment == nil { - return nil - } - return commitment.ToAffineCompressed() -} - -// GenerateProof converts the blinding factors and secrets into Schnorr proofs -func (pcb ProofCommittedBuilder) GenerateProof( - challenge curves.Scalar, - secrets []curves.Scalar, -) ([]curves.Scalar, error) { - if len(secrets) != len(pcb.scalars) { - return nil, fmt.Errorf("secrets is not equal to blinding factors") - } - - proofs := make([]curves.Scalar, len(pcb.scalars)) - for i, sc := range pcb.scalars { - proofs[i] = secrets[i].MulAdd(challenge, sc) - } - return proofs, nil -} diff --git a/crypto/signatures/common/proof_message.go b/crypto/signatures/common/proof_message.go deleted file mode 100644 index 0a38cc68c..000000000 --- a/crypto/signatures/common/proof_message.go +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// ProofMessage classifies how a message is presented in a proof -// Either Revealed or Hidden. Hidden has two sub categories: -// proof specific i.e. the message is only used for this proof or -// shared i.e. the message should be proved to be common across proofs -type ProofMessage interface { - // IsHidden indicates the message should be hidden - IsHidden() bool - // GetBlinding is used for hidden messages - // blindings can either be proof specific to a signature - // or involved with other proofs like boundchecks, - // set memberships, or inequalities so the blinding - // factor is shared among proofs to produce a common - // schnorr linking proof - GetBlinding(reader io.Reader) curves.Scalar - // GetMessage returns the underlying message - GetMessage() curves.Scalar -} - -type RevealedMessage struct { - Message curves.Scalar -} - -func (r RevealedMessage) IsHidden() bool { - return false -} - -func (r RevealedMessage) GetBlinding(reader io.Reader) curves.Scalar { - return nil -} - -func (r RevealedMessage) GetMessage() curves.Scalar { - return r.Message -} - -type ProofSpecificMessage struct { - Message curves.Scalar -} - -func (ps ProofSpecificMessage) IsHidden() bool { - return true -} - -func (ps ProofSpecificMessage) GetBlinding(reader io.Reader) curves.Scalar { - return ps.Message.Random(reader) -} - -func (ps ProofSpecificMessage) GetMessage() curves.Scalar { - return ps.Message -} - -type SharedBlindingMessage struct { - Message, Blinding curves.Scalar -} - -func (ps SharedBlindingMessage) IsHidden() bool { - return true -} - -func (ps SharedBlindingMessage) GetBlinding(reader io.Reader) curves.Scalar { - return ps.Blinding -} - -func (ps SharedBlindingMessage) GetMessage() curves.Scalar { - return ps.Message -} diff --git a/crypto/signatures/common/signature_blinding.go b/crypto/signatures/common/signature_blinding.go deleted file mode 100644 index 6a84ae9b2..000000000 --- a/crypto/signatures/common/signature_blinding.go +++ /dev/null @@ -1,14 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package common - -import ( - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// SignatureBlinding is a value used for computing blind signatures -type SignatureBlinding = curves.PairingScalar diff --git a/crypto/signatures/schnorr/mina/bitvector.go b/crypto/signatures/schnorr/mina/bitvector.go deleted file mode 100755 index 70f86bd3d..000000000 --- a/crypto/signatures/schnorr/mina/bitvector.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) 2014 Dropbox, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors -// may be used to endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package mina - -// A BitVector is a variable sized vector of bits. It supports -// lookups, sets, appends, insertions, and deletions. -// -// This class is not thread safe. -type BitVector struct { - data []byte - length int -} - -// NewBitVector creates and initializes a new bit vector with length -// elements, using data as its initial contents. -func NewBitVector(data []byte, length int) *BitVector { - return &BitVector{ - data: data, - length: length, - } -} - -// Bytes returns a slice of the contents of the bit vector. If the caller changes the returned slice, -// the contents of the bit vector may change. -func (vector *BitVector) Bytes() []byte { - return vector.data -} - -// Length returns the current number of elements in the bit vector. -func (vector *BitVector) Length() int { - return vector.length -} - -// This function shifts a byte slice one bit lower (less significant). -// bit (either 1 or 0) contains the bit to put in the most significant -// position of the last byte in the slice. -// This returns the bit that was shifted off of the last byte. -func shiftLower(bit byte, b []byte) byte { - bit = bit << 7 - for i := len(b) - 1; i >= 0; i-- { - newByte := b[i] >> 1 - newByte |= bit - bit = (b[i] & 1) << 7 - b[i] = newByte - } - return bit >> 7 -} - -// This function shifts a byte slice one bit higher (more significant). -// bit (either 1 or 0) contains the bit to put in the least significant -// position of the first byte in the slice. -// This returns the bit that was shifted off the last byte. -func shiftHigher(bit byte, b []byte) byte { - for i := 0; i < len(b); i++ { - newByte := b[i] << 1 - newByte |= bit - bit = (b[i] & 0x80) >> 7 - b[i] = newByte - } - return bit -} - -// Returns the minimum number of bytes needed for storing the bit vector. -func (vector *BitVector) bytesLength() int { - lastBitIndex := vector.length - 1 - lastByteIndex := lastBitIndex >> 3 - return lastByteIndex + 1 -} - -// Panics if the given index is not within the bounds of the bit vector. -func (vector *BitVector) indexAssert(i int) { - if i < 0 || i >= vector.length { - panic("Attempted to access element outside buffer") - } -} - -// Append adds a bit to the end of a bit vector. -func (vector *BitVector) Append(bit byte) { - index := uint32(vector.length) - vector.length++ - - if vector.bytesLength() > len(vector.data) { - vector.data = append(vector.data, 0) - } - - byteIndex := index >> 3 - byteOffset := index % 8 - oldByte := vector.data[byteIndex] - var newByte byte - if bit == 1 { - newByte = oldByte | 1<> 3 - byteOffset := uint32(i % 8) - b := vector.data[byteIndex] - // Check the offset bit - return (b >> byteOffset) & 1 -} - -// Set changes the bit in the ith index of the bit vector to the value specified in -// bit. -func (vector *BitVector) Set(bit byte, index int) { - vector.indexAssert(index) - byteIndex := uint32(index >> 3) - byteOffset := uint32(index % 8) - - oldByte := vector.data[byteIndex] - - var newByte byte - if bit == 1 { - // turn on the byteOffset'th bit - newByte = oldByte | 1< len(vector.data) { - vector.data = append(vector.data, 0) - } - - byteIndex := uint32(index >> 3) - byteOffset := uint32(index % 8) - var bitToInsert byte - if bit == 1 { - bitToInsert = 1 << byteOffset - } - - oldByte := vector.data[byteIndex] - // This bit will need to be shifted into the next byte - leftoverBit := (oldByte & 0x80) >> 7 - // Make masks to pull off the bits below and above byteOffset - // This mask has the byteOffset lowest bits set. - bottomMask := byte((1 << byteOffset) - 1) - // This mask has the 8 - byteOffset top bits set. - topMask := ^bottomMask - top := (oldByte & topMask) << 1 - newByte := bitToInsert | (oldByte & bottomMask) | top - - vector.data[byteIndex] = newByte - // Shift the rest of the bytes in the slice one higher, append - // the leftoverBit obtained above. - shiftHigher(leftoverBit, vector.data[byteIndex+1:]) -} - -// Delete removes the bit in the supplied index of the bit vector. All -// bits in positions greater than or equal to index before the call will -// be shifted down by one. -func (vector *BitVector) Delete(index int) { - vector.indexAssert(index) - vector.length-- - byteIndex := uint32(index >> 3) - byteOffset := uint32(index % 8) - - oldByte := vector.data[byteIndex] - - // Shift all the bytes above the byte we're modifying, return the - // leftover bit to include in the byte we're modifying. - bit := shiftLower(0, vector.data[byteIndex+1:]) - - // Modify oldByte. - // At a high level, we want to select the bits above byteOffset, - // and shift them down by one, removing the bit at byteOffset. - - // This selects the bottom bits - bottomMask := byte((1 << byteOffset) - 1) - // This selects the top (8 - byteOffset - 1) bits - topMask := byte(^((1 << (byteOffset + 1)) - 1)) - // newTop is the top bits, shifted down one, combined with the leftover bit from shifting - // the other bytes. - newTop := (oldByte&topMask)>>1 | (bit << 7) - // newByte takes the bottom bits and combines with the new top. - newByte := (bottomMask & oldByte) | newTop - vector.data[byteIndex] = newByte - - // The desired length is the byte index of the last element plus one, - // where the byte index of the last element is the bit index of the last - // element divided by 8. - byteLength := vector.bytesLength() - if byteLength < len(vector.data) { - vector.data = vector.data[:byteLength] - } -} diff --git a/crypto/signatures/schnorr/mina/challenge_derive.go b/crypto/signatures/schnorr/mina/challenge_derive.go deleted file mode 100644 index be0380c41..000000000 --- a/crypto/signatures/schnorr/mina/challenge_derive.go +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type MinaTSchnorrHandler struct{} - -func (m MinaTSchnorrHandler) DeriveChallenge( - msg []byte, - pubKey curves.Point, - r curves.Point, -) (curves.Scalar, error) { - txn := new(Transaction) - err := txn.UnmarshalBinary(msg) - if err != nil { - return nil, err - } - input := new(roinput).Init(3, 75) - txn.addRoInput(input) - - pt, ok := pubKey.(*curves.PointPallas) - if !ok { - return nil, fmt.Errorf("invalid point") - } - R, ok := r.(*curves.PointPallas) - if !ok { - return nil, fmt.Errorf("invalid point") - } - - pk := new(PublicKey) - pk.value = pt.GetEp() - - sc := msgHash(pk, R.X(), input, ThreeW, MainNet) - s := new(curves.ScalarPallas) - s.SetFq(sc) - return s, nil -} diff --git a/crypto/signatures/schnorr/mina/keys.go b/crypto/signatures/schnorr/mina/keys.go deleted file mode 100644 index 82ea8f502..000000000 --- a/crypto/signatures/schnorr/mina/keys.go +++ /dev/null @@ -1,282 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - crand "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/binary" - "fmt" - "io" - - "github.com/mr-tron/base58" - "golang.org/x/crypto/blake2b" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -const ( - version = 0xcb - nonZeroCurvePointVersion = 0x01 - isCompressed = 0x01 -) - -// PublicKey is the verification key -type PublicKey struct { - value *curves.Ep -} - -// GenerateAddress converts the public key to an address -func (pk PublicKey) GenerateAddress() string { - var payload [40]byte - payload[0] = version - payload[1] = nonZeroCurvePointVersion - payload[2] = isCompressed - - buffer := pk.value.ToAffineUncompressed() - copy(payload[3:35], buffer[:32]) - payload[35] = buffer[32] & 1 - hash1 := sha256.Sum256(payload[:36]) - hash2 := sha256.Sum256(hash1[:]) - copy(payload[36:40], hash2[:4]) - return base58.Encode(payload[:]) -} - -// ParseAddress converts a given string into a public key returning an error on failure -func (pk *PublicKey) ParseAddress(b58 string) error { - buffer, err := base58.Decode(b58) - if err != nil { - return err - } - if len(buffer) != 40 { - return fmt.Errorf("invalid byte sequence") - } - if buffer[0] != version { - return fmt.Errorf("invalid version") - } - if buffer[1] != nonZeroCurvePointVersion { - return fmt.Errorf("invalid non-zero curve point version") - } - if buffer[2] != isCompressed { - return fmt.Errorf("invalid compressed flag") - } - hash1 := sha256.Sum256(buffer[:36]) - hash2 := sha256.Sum256(hash1[:]) - if subtle.ConstantTimeCompare(hash2[:4], buffer[36:40]) != 1 { - return fmt.Errorf("invalid checksum") - } - x := buffer[3:35] - x[31] |= buffer[35] << 7 - value, err := new(curves.Ep).FromAffineCompressed(x) - if err != nil { - return err - } - pk.value = value - return nil -} - -func (pk PublicKey) MarshalBinary() ([]byte, error) { - return pk.value.ToAffineCompressed(), nil -} - -func (pk *PublicKey) UnmarshalBinary(input []byte) error { - pt, err := new(curves.Ep).FromAffineCompressed(input) - if err != nil { - return err - } - pk.value = pt - return nil -} - -func (pk *PublicKey) SetPointPallas(pallas *curves.PointPallas) { - pk.value = pallas.GetEp() -} - -// SecretKey is the signing key -type SecretKey struct { - value *fq.Fq -} - -// GetPublicKey returns the corresponding verification -func (sk SecretKey) GetPublicKey() *PublicKey { - pk := new(curves.Ep).Mul(new(curves.Ep).Generator(), sk.value) - return &PublicKey{pk} -} - -func (sk SecretKey) MarshalBinary() ([]byte, error) { - t := sk.value.Bytes() - return t[:], nil -} - -func (sk *SecretKey) UnmarshalBinary(input []byte) error { - if len(input) != 32 { - return fmt.Errorf("invalid byte sequence") - } - var buf [32]byte - copy(buf[:], input) - value, err := new(fq.Fq).SetBytes(&buf) - if err != nil { - return err - } - sk.value = value - return nil -} - -func (sk *SecretKey) SetFq(fq *fq.Fq) { - sk.value = fq -} - -// NewKeys creates a new keypair using a CSPRNG -func NewKeys() (*PublicKey, *SecretKey, error) { - return NewKeysFromReader(crand.Reader) -} - -// NewKeysFromReader creates a new keypair using the specified reader -func NewKeysFromReader(reader io.Reader) (*PublicKey, *SecretKey, error) { - t := new(curves.ScalarPallas).Random(reader) - sc, ok := t.(*curves.ScalarPallas) - if !ok || t.IsZero() { - return nil, nil, fmt.Errorf("invalid key") - } - sk := sc.GetFq() - pk := new(curves.Ep).Mul(new(curves.Ep).Generator(), sk) - if pk.IsIdentity() { - return nil, nil, fmt.Errorf("invalid key") - } - - return &PublicKey{pk}, &SecretKey{sk}, nil -} - -// SignTransaction generates a signature over the specified txn and network id -// See https://github.com/MinaProtocol/c-reference-signer/blob/master/crypto.c#L1020 -func (sk *SecretKey) SignTransaction(transaction *Transaction) (*Signature, error) { - input := new(roinput).Init(3, 75) - transaction.addRoInput(input) - return sk.finishSchnorrSign(input, transaction.NetworkId) -} - -// SignMessage signs a _string_. this is somewhat non-standard; we do it by just adding bytes to the roinput. -// See https://github.com/MinaProtocol/c-reference-signer/blob/master/crypto.c#L1020 -func (sk *SecretKey) SignMessage(message string) (*Signature, error) { - input := new(roinput).Init(0, len(message)) - input.AddBytes([]byte(message)) - return sk.finishSchnorrSign(input, MainNet) -} - -func (sk *SecretKey) finishSchnorrSign(input *roinput, networkId NetworkType) (*Signature, error) { - if sk.value.IsZero() { - return nil, fmt.Errorf("invalid secret key") - } - pk := sk.GetPublicKey() - k := sk.msgDerive(input, pk, networkId) - if k.IsZero() { - return nil, fmt.Errorf("invalid nonce generated") - } - // r = k*G - r := new(curves.Ep).Generator() - r.Mul(r, k) - - if r.Y().IsOdd() { - k.Neg(k) - } - rx := r.X() - e := msgHash(pk, rx, input, ThreeW, networkId) - - // S = k + e*sk - e.Mul(e, sk.value) - s := new(fq.Fq).Add(k, e) - if rx.IsZero() || s.IsZero() { - return nil, fmt.Errorf("invalid signature") - } - return &Signature{ - R: rx, - S: s, - }, nil -} - -// VerifyTransaction checks if the signature is over the given transaction using this public key -func (pk *PublicKey) VerifyTransaction(sig *Signature, transaction *Transaction) error { - input := new(roinput).Init(3, 75) - transaction.addRoInput(input) - return pk.finishSchnorrVerify(sig, input, transaction.NetworkId) -} - -// VerifyMessage checks if the claimed signature on a _string_ is valid. this is nonstandard; see above. -func (pk *PublicKey) VerifyMessage(sig *Signature, message string) error { - input := new(roinput).Init(0, len(message)) - input.AddBytes([]byte(message)) - return pk.finishSchnorrVerify(sig, input, MainNet) -} - -func (pk *PublicKey) finishSchnorrVerify( - sig *Signature, - input *roinput, - networkId NetworkType, -) error { - if pk.value.IsIdentity() { - return fmt.Errorf("invalid public key") - } - if sig.R.IsZero() || sig.S.IsZero() { - return fmt.Errorf("invalid signature") - } - e := msgHash(pk, sig.R, input, ThreeW, networkId) - sg := new(curves.Ep).Generator() - sg.Mul(sg, sig.S) - - epk := new(curves.Ep).Mul(pk.value, e) - epk.Neg(epk) - - r := new(curves.Ep).Add(sg, epk) - if !r.Y().IsOdd() && r.X().Equal(sig.R) { - return nil - } else { - return fmt.Errorf("signature verification failed") - } -} - -func msgHash( - pk *PublicKey, - rx *fp.Fp, - input *roinput, - hashType Permutation, - networkId NetworkType, -) *fq.Fq { - input.AddFp(pk.value.X()) - input.AddFp(pk.value.Y()) - input.AddFp(rx) - - ctx := new(Context).Init(hashType, networkId) - fields := input.Fields() - ctx.Update(fields) - return ctx.Digest() -} - -func (sk SecretKey) msgDerive(msg *roinput, pk *PublicKey, networkId NetworkType) *fq.Fq { - input := msg.Clone() - input.AddFp(pk.value.X()) - input.AddFp(pk.value.Y()) - input.AddFq(sk.value) - input.AddBytes([]byte{byte(networkId)}) - inputBytes := input.Bytes() - - h, _ := blake2b.New(32, []byte{}) - _, _ = h.Write(inputBytes) - hash := h.Sum(nil) - - // Clear top two bits - hash[31] &= 0x3F - tmp := [4]uint64{ - binary.LittleEndian.Uint64(hash[:8]), - binary.LittleEndian.Uint64(hash[8:16]), - binary.LittleEndian.Uint64(hash[16:24]), - binary.LittleEndian.Uint64(hash[24:32]), - } - return new(fq.Fq).SetRaw(&tmp) -} diff --git a/crypto/signatures/schnorr/mina/keys_test.go b/crypto/signatures/schnorr/mina/keys_test.go deleted file mode 100644 index 7ec6067d5..000000000 --- a/crypto/signatures/schnorr/mina/keys_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -func TestNewKeys(t *testing.T) { - pk, sk, err := NewKeys() - require.NoError(t, err) - require.NotNil(t, sk) - require.NotNil(t, pk) - require.False(t, sk.value.IsZero()) - require.False(t, pk.value.IsIdentity()) -} - -func TestSecretKeySignTransaction(t *testing.T) { - // See https://github.com/MinaProtocol/c-reference-signer/blob/master/reference_signer.c#L15 - skValue := &fq.Fq{ - 0xca14d6eed923f6e3, 0x61185a1b5e29e6b2, 0xe26d38de9c30753b, 0x3fdf0efb0a5714, - } - sk := &SecretKey{value: skValue} - /* - This illustrates constructing and signing the following transaction. - amounts are in nanocodas. - { - "common": { - "fee": "3", - "fee_token": "1", - "fee_payer_pk": "B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg", - "nonce": "200", - "valid_until": "10000", - "memo": "E4Yq8cQXC1m9eCYL8mYtmfqfJ5cVdhZawrPQ6ahoAay1NDYfTi44K" - }, - "body": [ - "Payment", - { - "source_pk": "B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg", - "receiver_pk": "B62qrcFstkpqXww1EkSGrqMCwCNho86kuqBd4FrAAUsPxNKdiPzAUsy", - "token_id": "1", - "amount": "42" - } - ] - } - */ - feePayerPk := new(PublicKey) - err := feePayerPk.ParseAddress("B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg") - require.NoError(t, err) - sourcePk := new(PublicKey) - err = sourcePk.ParseAddress("B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg") - require.NoError(t, err) - receiverPk := new(PublicKey) - err = receiverPk.ParseAddress("B62qrcFstkpqXww1EkSGrqMCwCNho86kuqBd4FrAAUsPxNKdiPzAUsy") - require.NoError(t, err) - txn := &Transaction{ - Fee: 3, - FeeToken: 1, - Nonce: 200, - ValidUntil: 10000, - Memo: "this is a memo", - FeePayerPk: feePayerPk, - SourcePk: sourcePk, - ReceiverPk: receiverPk, - TokenId: 1, - Amount: 42, - Locked: false, - Tag: [3]bool{false, false, false}, - NetworkId: MainNet, - } - sig, err := sk.SignTransaction(txn) - require.NoError(t, err) - pk := sk.GetPublicKey() - require.NoError(t, pk.VerifyTransaction(sig, txn)) -} - -func TestSecretKeySignMessage(t *testing.T) { - // See https://github.com/MinaProtocol/c-reference-signer/blob/master/reference_signer.c#L15 - skValue := &fq.Fq{ - 0xca14d6eed923f6e3, 0x61185a1b5e29e6b2, 0xe26d38de9c30753b, 0x3fdf0efb0a5714, - } - sk := &SecretKey{value: skValue} - sig, err := sk.SignMessage("A test message.") - require.NoError(t, err) - pk := sk.GetPublicKey() - require.NoError(t, pk.VerifyMessage(sig, "A test message.")) -} - -func TestSecretKeySignTransactionStaking(t *testing.T) { - // https://github.com/MinaProtocol/c-reference-signer/blob/master/reference_signer.c#L128 - skValue := &fq.Fq{ - 0xca14d6eed923f6e3, 0x61185a1b5e29e6b2, 0xe26d38de9c30753b, 0x3fdf0efb0a5714, - } - sk := &SecretKey{value: skValue} - - feePayerPk := new(PublicKey) - err := feePayerPk.ParseAddress("B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg") - require.NoError(t, err) - sourcePk := new(PublicKey) - err = sourcePk.ParseAddress("B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg") - require.NoError(t, err) - receiverPk := new(PublicKey) - err = receiverPk.ParseAddress("B62qkfHpLpELqpMK6ZvUTJ5wRqKDRF3UHyJ4Kv3FU79Sgs4qpBnx5RR") - require.NoError(t, err) - txn := &Transaction{ - Fee: 3, - FeeToken: 1, - Nonce: 10, - ValidUntil: 4000, - Memo: "more delegates more fun", - FeePayerPk: feePayerPk, - SourcePk: sourcePk, - ReceiverPk: receiverPk, - TokenId: 1, - Amount: 0, - Locked: false, - Tag: [3]bool{false, false, true}, - NetworkId: MainNet, - } - sig, err := sk.SignTransaction(txn) - require.NoError(t, err) - pk := sk.GetPublicKey() - require.NoError(t, pk.VerifyTransaction(sig, txn)) -} diff --git a/crypto/signatures/schnorr/mina/poseidon_config.go b/crypto/signatures/schnorr/mina/poseidon_config.go deleted file mode 100644 index dc0620c31..000000000 --- a/crypto/signatures/schnorr/mina/poseidon_config.go +++ /dev/null @@ -1,112 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" -) - -// SBox is the type of exponentiation to perform -type SBox int - -const ( - Cube = iota // x^3 - Quint // x^5 - Sept // x^7 - Inverse // x^-1 -) - -// Exp mutates f by computing x^3, x^5, x^7 or x^-1 as described in -// https://eprint.iacr.org/2019/458.pdf page 8 -func (sbox SBox) Exp(f *fp.Fp) { - switch sbox { - case Cube: - t := new(fp.Fp).Square(f) - f.Mul(t, f) - case Quint: - t := new(fp.Fp).Square(f) - t.Square(t) - f.Mul(t, f) - case Sept: - f2 := new(fp.Fp).Square(f) - f4 := new(fp.Fp).Square(f2) - t := new(fp.Fp).Mul(f2, f4) - f.Mul(t, f) - case Inverse: - f.Invert(f) - default: - } -} - -// Permutation is the permute function to use -type Permutation int - -const ( - ThreeW = iota - FiveW - Three -) - -// Permute executes the poseidon hash function -func (p Permutation) Permute(ctx *Context) { - switch p { - case ThreeW: - for r := 0; r < ctx.fullRounds; r++ { - ark(ctx, r) - sbox(ctx) - mds(ctx) - } - ark(ctx, ctx.fullRounds) - case Three: - fallthrough - case FiveW: - // Full rounds only - for r := 0; r < ctx.fullRounds; r++ { - sbox(ctx) - mds(ctx) - ark(ctx, r) - } - default: - } -} - -func ark(ctx *Context, round int) { - for i := 0; i < ctx.spongeWidth; i++ { - ctx.state[i].Add(ctx.state[i], ctx.roundKeys[round][i]) - } -} - -func sbox(ctx *Context) { - for i := 0; i < ctx.spongeWidth; i++ { - ctx.sBox.Exp(ctx.state[i]) - } -} - -func mds(ctx *Context) { - state2 := make([]*fp.Fp, len(ctx.state)) - for i := range ctx.state { - state2[i] = new(fp.Fp).SetZero() - } - for row := 0; row < ctx.spongeWidth; row++ { - for col := 0; col < ctx.spongeWidth; col++ { - t := new(fp.Fp).Mul(ctx.state[col], ctx.mdsMatrix[row][col]) - state2[row].Add(state2[row], t) - } - } - for i, f := range state2 { - ctx.state[i].Set(f) - } -} - -// NetworkType is which Mina network id to use -type NetworkType int - -const ( - TestNet = iota - MainNet - NullNet -) diff --git a/crypto/signatures/schnorr/mina/poseidon_hash.go b/crypto/signatures/schnorr/mina/poseidon_hash.go deleted file mode 100644 index d38d40db8..000000000 --- a/crypto/signatures/schnorr/mina/poseidon_hash.go +++ /dev/null @@ -1,1182 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -type Context struct { - state []*fp.Fp - absorbed, spongeWidth, spongeRate, fullRounds int - sBox SBox - pType Permutation - spongeIv [][]*fp.Fp - roundKeys [][]*fp.Fp - mdsMatrix [][]*fp.Fp -} - -var contexts = []*Context{ - // threeW - { - spongeWidth: 3, - spongeRate: 2, - fullRounds: 63, - sBox: Quint, - pType: ThreeW, - roundKeys: [][]*fp.Fp{ - { - {0xd2425a07cfec91d, 0x6130240fd42af5be, 0x3fb56f00f649325, 0x107d26d6fefb125f}, - {0x1dcedf2d0ebcb628, 0x2381dfa5face2460, 0x24e92a6d36d75404, 0xce8a325b8f74c91}, - {0x5df2ca8d054dc3a, 0x7fb9bf2f82379968, 0x424e2934a76cffb8, 0xb775aeab9b31f6a}, - }, - { - {0x9e6d7a567eaacc30, 0xced5d7ac222f233c, 0x2fe5c196ec8ffd26, 0x2a8f0caeda769601}, - {0xdc68662e69f84551, 0x1495455fbfab4087, 0xab2e97a03e2a079d, 0x3e93afa4e82ac2a0}, - {0x4cc46cd35daca246, 0x54dcc54ee433c73f, 0x893be89025513bde, 0x3b52fbe29b9d1b53}, - }, - { - {0xd96382010ec8b913, 0x9921d471216af4b5, 0xa7df09d5ecf06de, 0xa360d0e19232e76}, - {0x408add78a89dcf34, 0xb15031ad7e3ec92, 0x8ef35f1ab8093a79, 0x23276aa7a64b85a4}, - {0xdac52436f6c1cdd0, 0x46257295a42ee0b2, 0x3090799e349ade62, 0x261f8de11adb9313}, - }, - { - {0x51fb0207578466ed, 0xace76bd4ce53012a, 0x45f74735a873a7a6, 0x25be1a7e5c85f326}, - {0xdee055cc9572cc61, 0x9373df1526d6e34b, 0x2084c5641a3122a3, 0x3062d3265012feed}, - {0x1bd9070c51f40e9b, 0x9ea653d50b3fa6f, 0xa31a6b51060fc899, 0x703ce3434f96fea}, - }, - { - {0x937e0bd5442efc15, 0xc1b3a953fbd209b7, 0xb3737616f1f7eb8b, 0x5b10777bdf5dacd}, - {0x10791e59a7d5788a, 0x12f9041014d93ea, 0xb4bc24f34f470c71, 0x2f00cd1954db2d8c}, - {0xe912d7ae74abca54, 0xc5c26a35e725fd41, 0xb6af66a891d1c628, 0x3e5ec2bf0970d4a3}, - }, - { - {0x8340c5579ef76e75, 0x84685beb75f0fd3d, 0xd3a06c47523190d2, 0x308b8895c2d04040}, - {0x457356859f821f53, 0x8abdeeacf3a1ba9e, 0x43b602e5b2ad8b28, 0xc1879b3610fd2f4}, - {0x97b86a707b5809bc, 0x8dd94d73fb34a3ee, 0x5141652598014000, 0x32e8c24d1cee432e}, - }, - { - {0xa998c731389a48f3, 0x74fa8b44a0ab13b, 0x1ad03f591da71333, 0x2f03d178701bcb30}, - {0x8ff226bd0dd22c53, 0x26157e7a0aa47f2a, 0xe2531d8e88c5531d, 0x13d2bbc731281e5f}, - {0x76d7f22ef74ebe99, 0x245727aa206d8c55, 0x4e9bda26e39fe51, 0x72b21a3b6ea088d}, - }, - { - {0x67aff49f723add69, 0xccae0df20e3d633b, 0x85d57c5cda0e022c, 0xa398b1d3e6f2db1}, - {0x3fda2e26bcb6fc68, 0x593102ff961e4b40, 0xcaca5e29529738de, 0x2af42667a6e9b6cc}, - {0x9d05ac0056c6910a, 0x51343579482ba8b5, 0x33398f54089da2a3, 0x1879180149c97c34}, - }, - { - {0xfa93dc63c73d6490, 0x898847d037d78917, 0xf104b998c8ba5384, 0x1c6102bfd9c26df2}, - {0x3b13a7624fe64fc3, 0xae197dfb77fc7968, 0x855c3edfd013edc, 0x247f5769ca4aa6}, - {0x58bf743e0004f4eb, 0xa168da971a4635e8, 0xae0d93fc0aa0ca7c, 0x2e94bd91ee0eedec}, - }, - { - {0x826688455b3034d9, 0xd7a8296917d9820f, 0xbf14001a68903362, 0x3029935cebc0e1b5}, - {0x45622b94048f7c58, 0x1025e0f2169c46c1, 0x93dccace2e8635fa, 0x2110fe2a3a9c405b}, - {0xe6249e1fd6ae6204, 0x359cea9c7fc56811, 0x4561c87d295edc47, 0x3462ff6269ff9b7f}, - }, - { - {0xe88503091bf18fdb, 0xc7c9e48c7792429a, 0x7c2bedc34044daad, 0x239b54131c85ebfe}, - {0x9f92ac6cdf6d115c, 0x64fe79c6ea405241, 0x3fdbbe356870f930, 0x3c0d419e26ff24c1}, - {0xeb4e19e81548807b, 0x30d9ca531360e746, 0xe7fd824c32ef0f3d, 0x25c98a72c313174a}, - }, - { - {0xed7835758762c591, 0xd3a5813b88ed365f, 0x954d02a8633dba6f, 0x3da1af9d7eb3a01e}, - {0x86a8692d3ed59690, 0xf2873c2381bf29b6, 0x5d8735bb1f3f459, 0x3c9a66efcbdbfd6e}, - {0x7acc7d7a0e1d24a3, 0x8614a6c50e15e4f7, 0xac5ee237c5548dd4, 0x12061a68b6963446}, - }, - { - {0x81bc9093c7730d5, 0xbf3e57fb7d94a12f, 0xab7caef0406ad333, 0x30d704e038c83cee}, - {0x53fd9bef62ab35ab, 0xdd9258a43a400a0e, 0x41fc71c1f14a3fe0, 0xaafb95e685e323a}, - {0xbb168efcfbc6417d, 0x6eec41829c340ecc, 0x3e1a203ea728cf86, 0x32403a5339001606}, - }, - { - {0xaa842cc888cce8e1, 0xaf60b8e8cfa84e30, 0xa8345e318e18911e, 0x23adb957cfe95986}, - {0x9b565aa4fc6cbed, 0x715714218a6da1db, 0x60740ecb2b402402, 0x3446170f139a28ee}, - {0x2d56545ce19df759, 0x2e62009452ac4624, 0xf834fd669efdc382, 0x3cdb040c5a2c8135}, - }, - { - {0x2c093b07989ac45b, 0xbc5a7ce41629b4d8, 0xf9f8f9ccd52de847, 0xa6852ff99c0df59}, - {0x62ec3921cae6ad0c, 0xed01dd4b15bc12e2, 0xcf099203d7296486, 0x10c70f52d8e4c35c}, - {0xe3afb13d98e0aa36, 0xd5c2e410a19ecae7, 0x7ef462f8ef00f1ee, 0x3b2666c865ffaf5f}, - }, - { - {0x2a34a9799fb10dea, 0xae3b7ac93a88e642, 0x9ce2e0a5b4676e62, 0x35338d2e290f6835}, - {0x704c2116789cd3e, 0x55c9408a44e87b39, 0x9a178778cf8123ac, 0x2a237d751ce80e22}, - {0xe73cc5f3949b8dac, 0x25fcebdc28f57fc2, 0xb8f4c26538ae8063, 0x160d42c37b816d52}, - }, - { - {0x78bba3a1b4334fec, 0xe1ad733be7312e24, 0x166c29284c5e74cf, 0x1e39c10d204c6e}, - {0xeba34937ed572fb8, 0xec650563d7045e13, 0xbf694cf0e16bc82c, 0x14394f78ca804fcb}, - {0xa28d8e959c93e39c, 0xfe2361a2d86799e3, 0xb04a4d8890bfaa19, 0x3bd58529949c0ff6}, - }, - { - {0x29225c95f5b1b6f9, 0xa6deebafdf12f757, 0x4d08632fbf4f058, 0x22ca57e20c30a4e2}, - {0xbd76f38890b3567b, 0x26cf81518916ab2, 0xe6096fe367359511, 0x1f5e2a08564c51ca}, - {0x522b7903b745f6ae, 0x97976d9feb2f329a, 0x4042a062305c3dd, 0x10e8bfbac34f6ab}, - }, - { - {0x53a7679692da3aa1, 0xe450599e85d31d58, 0x7b0eb8260f95a840, 0x1ace63dc713e7378}, - {0x725231ba432706f4, 0xccfededdca80880, 0xeba96b0dfbc1ccb5, 0x2584d3df4dd8a065}, - {0xe55f4913a1b47696, 0x34767187e1938949, 0xdbe1913ab957b7f2, 0x3c4be85646076541}, - }, - { - {0x96165fe1910385e3, 0xd8d34657e37bf741, 0x2dc65b5bd92b7412, 0x17c70695eabaad8c}, - {0x1aa94fbcda906296, 0x92b63261bad15d4, 0xde1fae454d20bc2, 0xff4dd19e7bb91c}, - {0x9a3c6bb3b3792b29, 0xba9a9d2d8c8f32fb, 0x90cae23b992784b0, 0x682d0d05588a0a4}, - }, - { - {0x8bea2f0e3b07fdae, 0xa2bcf89d80d35726, 0x544cd1414cc270fe, 0x113a9293d2324718}, - {0xae456164d267504c, 0x571cb023dbc1ce73, 0x21bac9730f19acbf, 0x3233efcc4435feb}, - {0x8c75648ce93bee2e, 0x6a7b2664251ea438, 0xca0e6900ef478974, 0x2ea2eb8e4287afe1}, - }, - { - {0x5acd5490088631ea, 0x796fd55cbfe132ea, 0xca378169084f5b20, 0x3bf94c0b770e6732}, - {0x3c7cc5fe22e9da10, 0x8c8312f4ace0a8a5, 0xc87567978ce028f8, 0x5a6f235fb313cd5}, - {0x2e6558b92407dcaf, 0x47e50ce3601012f4, 0x1e5797dd5bec08f6, 0x3f8733eee4c3467}, - }, - { - {0x94d2410224bcb62d, 0x3a926c5d9a86b7d4, 0x4e194b53953a44be, 0x352e9b3d78b5bcc}, - {0x54883a363d4cf9d5, 0x11f8990c505f0d36, 0x6bc1b45721bf8c66, 0x1741726454535739}, - {0x6f9a3ecf74a296b, 0x5de95fe78d089d68, 0xd73cd49e13d43129, 0x2093f7ce8f9a0900}, - }, - { - {0xe9cb00b14e26ff0d, 0x3f08fd94461dc18e, 0x631adca53058abce, 0x3214d344acadc846}, - {0xded7eb4dbd85489a, 0x88fec23b8cd8b77, 0x16d4ed13eab05211, 0x2846ac03154cebb9}, - {0xfac2a0ad57a4f26, 0xc1f76ecd19989adf, 0xaf30edcd16db54f2, 0x126d20470a443867}, - }, - { - {0xcff7162b34203071, 0xe55b077617c9a757, 0x2130b1adac59d068, 0x14c5aaf1e7b110eb}, - {0x699dd6dbcf0482c0, 0xea319e0d0b2bb999, 0xaa9e419d224d713d, 0x1f4d7ca828085388}, - {0xe0ce736d12ec2b2e, 0x2f38bcf04ebf093c, 0x4b4b4eb19457afe9, 0x36a6b22a47328281}, - }, - { - {0x787526c6865dcd1e, 0xc2680fe54617f4a8, 0xb727dbb67712e717, 0x3a271ba53713445c}, - {0x806dc7288ade48b8, 0x37ae24211f9b6b9d, 0x8ca3d974dbf15054, 0x10fd6d9432eb0b68}, - {0xec73bef3a5597993, 0x911600cb416be443, 0x3ea4d6875cf79676, 0x1b77d3b73ff96642}, - }, - { - {0x599dae5eba7bbf12, 0xad64c1aab4e1e894, 0x5d661ccb5ee325bf, 0x126b7751010f9d3f}, - {0x5ed0e07555bb26cd, 0x6e878aa29bf2c2e8, 0xf5a5eeccbaa31dc1, 0x1d3867eb4e090941}, - {0x2937ca036763d28b, 0x86e99a452605b663, 0x724c2748daf8484b, 0xebc687217853e09}, - }, - { - {0x4dbc428bc8ad6e5d, 0xa2f7ba399263b882, 0x7bf0cdf85013257c, 0x28aeab12f70ef4a}, - {0x3c7790781e18b6e, 0x1bb3023fe1e655cb, 0xed1fdfcb455dca1a, 0x32e02d39a4d657a}, - {0x44e6d9c3a1dff228, 0xdf469cea3c0a5407, 0x299c3245b897c072, 0x2be7edf85aee84d5}, - }, - { - {0x7cef1e98b43bf15c, 0x5a8dd042cde4ffe2, 0xd86af3fcf5e44a3b, 0x126fff14c130fdf6}, - {0x902d3cbb3b8bffd3, 0xd0510141c9be133a, 0x1153608479eba1e3, 0x33b9a4fa153248fb}, - {0x2267900dcf1e0fe4, 0xaf0c04b7861398c6, 0x55b20fd2619336f9, 0x3729ba618d213b74}, - }, - { - {0x7bccad65b5fd53a3, 0x275fd70abbee0824, 0x6fce1c43407f5ddd, 0x381402c3966b0d15}, - {0xd4e90f5f5d1b1215, 0x7abfb980598b6f39, 0x6cc413a7353c523b, 0x3af9e5c6dbcecf69}, - {0xfc86b3533d23176f, 0xf2f83c14f801bf0f, 0x5fb324c8b8b84f4c, 0x2a9949609d62d389}, - }, - { - {0xfca79d23caa474da, 0x94af585882c48b4, 0x9184e6e773524de, 0x1971a4bd05472cc6}, - {0xe14a7a9f4d347481, 0xf68eb0d753ed0146, 0x624211b6c3d94cff, 0x399c54dc6cd81b81}, - {0x86039539dbb961f9, 0xa5af68dc06d8ea6, 0xcc02fcf05e368eed, 0xf64acd9952a945b}, - }, - { - {0x88c5c3ea3b0286e6, 0x8c0cf8675f0040d5, 0xc0f11c1177699ea2, 0xe3cc78066df561b}, - {0x49162b2f404f976c, 0x9a40001b3ac29cdd, 0x17287f8ca8386222, 0x39ca8d14934343bf}, - {0xa8dd36db44116537, 0x42dbe51eb9216283, 0xfec6c18c5ea56c1c, 0x9b0bc57ea6681fa}, - }, - { - {0x53684675590d10f8, 0x228bd6ed1447104c, 0xcac8753557c5e945, 0x2533527c9ad29ad6}, - {0x5e26e312638c73b4, 0x34e1114452f840c, 0xc90124a9e02e5aad, 0x2af2662d93aa4250}, - {0x76bb15558221d4af, 0x41d2a02a322e09b9, 0x29727b4d6c29e353, 0x13f30e86ab0297f6}, - }, - { - {0x8b113723e368b29c, 0x2ebddd5dcfd07680, 0x90027a89063fd6b, 0xab82f5420ead368}, - {0x6102c2fbeb0b8f83, 0x37caec74787f8363, 0xef4c7fedf4d49d09, 0x157481ef03f526da}, - {0x897dc99e348f8989, 0xfae2d8c6ca328b03, 0xd2a217387ae7e8fa, 0x2309412d902ce2d3}, - }, - { - {0x57895d8995bb037b, 0x4f303912d7010f4, 0x89d126adee61fd7b, 0x16ae40bb98717e4a}, - {0x970b8cda0d943140, 0xd07503f516f70525, 0xb14ed69e29e5ede5, 0x2316911f23d9bed1}, - {0x632e10c13ba9d605, 0x23723cd16be7a1a3, 0xc0804d9b3264d489, 0x25b18b66bd5a14b1}, - }, - { - {0x2cc13abb89f41136, 0x7b209265228a3e0b, 0xde1b3e0db09f17e0, 0x10e37b1b53ecfceb}, - {0x765eb14dd8c343a4, 0x3359bbc963368294, 0xeb4667bd15fd4a6c, 0x2db8142000298d91}, - {0x916a19d68c0ed401, 0x5002ac7be8c90d22, 0x8ae3857c98f24376, 0xb2557905a7150c}, - }, - { - {0xf2b38d5f2758254d, 0x236745488b58741a, 0x394898e9d7458c8c, 0x37be2b56562adda1}, - {0x4aa28e0e6f54d290, 0x115bb413d8c4a639, 0x3944ec613d50506e, 0xbc68674dac60a3e}, - {0x82db6a2e85fec32c, 0x97802c924aadd00a, 0xbb6cc8685d8b265f, 0x16b975c2e70b76e6}, - }, - { - {0xe2f39f5ef957115b, 0x9a9db22a4623e0fa, 0x86f28972da216598, 0x11dc93268964d29c}, - {0xd8842bd61b12b92a, 0x6b1e45e4a6b4da39, 0xc2541381b20e4fc2, 0x3cc006d14574ded2}, - {0xfe0a6647ec349b4a, 0x7d7f9c30364402f9, 0x8f30b3425f1e6b75, 0xa08c94f56352fda}, - }, - { - {0xe8678e25a4d59721, 0x7c2331e36880e306, 0x82ad2f154d53292f, 0x38f905d3bf125a0d}, - {0x37c5ba5cf32727dd, 0x4e50703bbe74875c, 0x6e81ccf687c1edf3, 0x13d5a0a5cd167d3e}, - {0x549db53e76170f2d, 0x6601954d27f0614d, 0xa2e8516c0a8be8db, 0xe97e0bdc860ec97}, - }, - { - {0xab07a7c64e7a0c19, 0x3231ef6a85c561a2, 0x45cb8d5c9e495f6c, 0x3c130965bd821488}, - {0x4e85b1262b64c882, 0x148a4053173c6bbf, 0x2d30540d2bdf16b4, 0x1c4069538aad6db3}, - {0xe6f0d54ae64a6b4c, 0x8e435e285f5a0431, 0x89f8a4e55b2e5266, 0xc59b65276e7adbf}, - }, - { - {0xb3c5e9a0a063ba3c, 0xa5f4f9456cd30d09, 0x6d04f16139358814, 0xfe50ec7b61f34d3}, - {0x397f9724c5df2d2c, 0xebd5168a65e7dd00, 0x6e2d8f4b4688dfcc, 0x2089bd58ed27155}, - {0x4edc28aa719ba453, 0xd106c9909fe6d1bf, 0x583c7c64a6b2b9b9, 0x337410bcfb086e51}, - }, - { - {0xab6b2a207aa0b5dc, 0x4a8b65d7af08b29c, 0x933af8749e812390, 0x279107e984004c7f}, - {0x905ad996b3c96494, 0x64c09614294ad370, 0xe3a6ebea9d5f50c7, 0x39f0c91fd7487f70}, - {0xfb555601b96a98f6, 0x2779c5a69548b485, 0x1024d8abadf302ac, 0x9d7b11afa205c31}, - }, - { - {0x28cc587976dcbd5f, 0x7ec12e67d9fd9bff, 0x8519c024bfaacb31, 0xc3c59eef0b57c4}, - {0x7049bc5718274ce, 0xc5d45c2b8efbc27b, 0x1f2519b69fd58b2, 0x21d203679cf4943f}, - {0xdf1c276d845b18b, 0x83b415bcfd6f4794, 0x18cd69a7c02ec588, 0x28286f8440aac608}, - }, - { - {0xab9395e8f09c0e5e, 0x54e90df06eeabe37, 0x989b955540f5df9, 0x47eea2cb710d36a}, - {0x1ebb22981a2358d4, 0x978b30395e4ae485, 0x9b80f8337febb2dc, 0x6eadd7dff66e6fc}, - {0x8235f76b05fb36f3, 0xe81d3e6b55c01c67, 0xef1c4fbfd4f2689f, 0x356208269cd6bf63}, - }, - { - {0xdade3c9e413ae12e, 0xf0e6ec9130474658, 0xaf6a528f73acabe0, 0x25fa114c625e684a}, - {0x46eb556fec530561, 0xf037878098d1e6fa, 0x16665ada231de2c6, 0xe5526a3c3f20a1f}, - {0x8cf9f26ffb620afb, 0x10b561ad3be8bf53, 0xd095012a132c7d3f, 0x29dcadbf2a3da8a2}, - }, - { - {0xc1f246cabd2b3006, 0xa36999931ad6917e, 0xa86d5a37a14ebfc6, 0x233db2873238ccef}, - {0x6acabbbf7f09c6ab, 0x62e42b55c506b5ac, 0x20d3e5414eabcf58, 0x3047b6ea2b2ead12}, - {0xebb686baebe27e60, 0x6e299977bf344ce, 0x62074c04b5eaa97, 0x2f8be92e4b475d6c}, - }, - { - {0x68ec476c77321432, 0x6dc59804560e83e6, 0xad6ec6887fa80a57, 0xd2381657826abc9}, - {0xb377a593d24bcde1, 0x9a3338ee6dc43188, 0xfda6b04c6b645795, 0x1ebafbaa3cac50f4}, - {0xf53a7e9aa0eaf7a2, 0xc425d1cf708205ee, 0xc4bf63055e40b848, 0x31fd982712a1810}, - }, - { - {0x6aaec40a5ee97dc6, 0x1b740fec535e8d07, 0x72eb71573af7f8dc, 0x32a6cfd27721af}, - {0x4422e0763e1715cb, 0x2cc98a9c36481c08, 0x90a04c2c1100cf7, 0x14bdba391dc19c19}, - {0xf7ed8041fc74c1ba, 0x2da17664b7e0a39d, 0x7f194ed781738bd0, 0x185a0fb1e41d78e2}, - }, - { - {0x362d5eb8cf158562, 0x2cbda32193e3b946, 0x54a1587b53b6d3e, 0x3f6a83a8d453698e}, - {0xe4f331c807d7dbe4, 0x268c8fd3827cafa, 0x8128d4066a80b733, 0x3ac9356638ef0909}, - {0xc173b74baf5d10c0, 0xef4884b5f01dcb2a, 0x8ee4fbaf7d1af482, 0x3a631a390c1ace3a}, - }, - { - {0x8db20233cb7664ef, 0xcbd2b0d64c8e2b19, 0xb09d212d4b96af9b, 0xa41894a30594d96}, - {0xc87ad145936cc7b5, 0x831d623d07e2d55a, 0xb9f94b89928f0348, 0x32480b57ca35650c}, - {0x8df84ce2e7f6469f, 0x901e9cc791984cf9, 0xc8fcb9b481d64cbe, 0x3f5d039f9330361e}, - }, - { - {0xbf7db6c50e4b6c8e, 0xec86607f277ed803, 0x788b68697fc5fc3d, 0x31e6a675fa09e651}, - {0x1132c9835ce2f214, 0xe753150f8c8b375f, 0x8621813806da885e, 0xefb3b636dc3218c}, - {0x4ce5ce169e972cad, 0x36c4e02c437c353d, 0x91d0f983117961d3, 0x3fab66c8f61b43f4}, - }, - { - {0x26e7f148037e4831, 0xc898cea85a6d9ce7, 0x296eb709b0bce897, 0x13c7e41ce4a9413a}, - {0x364510c0cc6957d1, 0xc25f1640446d6363, 0xa38c8faccf2af7bc, 0x302f893eb7f3a293}, - {0xf47cdc9a193b6a1a, 0xbd3e81440b147a51, 0x1b8e11dc417ad50b, 0xbc7ad99db78ba74}, - }, - { - {0x5693220ff22b64e3, 0x95b8a7d6f5f07e88, 0xbb3aaa303d8a574, 0x20f50189f52021f3}, - {0xac8d038b73e50e93, 0x613109576b0dfb1e, 0x4ac8d41e35f9b309, 0xa7ad75a9d37c68c}, - {0x9c979eb72d6864c7, 0x8f1b33a9db15c462, 0xd9dfc2decd86ff41, 0x536ee7d16b7b5d5}, - }, - { - {0x624a1196b5b7005f, 0xb8d9cdf932bdf18, 0x14682525e48adc4a, 0x1d434955ccf03ab0}, - {0x719a6381517b8c7a, 0x6168713e68dfa531, 0x9b6cf63daf06a7ee, 0x1d259cdc7f7100c8}, - {0x6f1e012d7c9270c9, 0xe523c121eae14ae6, 0x50e570fed81bd490, 0x3604d717343ea349}, - }, - { - {0x4eb31e3e9fb8bc15, 0xaa82d889ed027926, 0x861770ba9013af2c, 0x379ab47829cd822c}, - {0x6f9b1e3a7b6dce3, 0xc5c9ef5c6b7a53d0, 0xc8d12ce69f47f1d6, 0xbc256406e070545}, - {0x6440d55f63d23009, 0x74c5732854d7e658, 0x4f7e9fd81fd40c7b, 0x399992d613926dad}, - }, - { - {0xc29845928af2930, 0xa0130ffd9a9f0e2a, 0x48033877dafbdd89, 0x8c39d86214ce71a}, - {0x9af58f43601d6790, 0xd1af4f75b46b599b, 0x4a8b0b5e6e229017, 0x187b443781223437}, - {0xe4304790543ef2b4, 0x9c231e915d799bd, 0x200b86e24d27b2ce, 0x2b71199749ffc729}, - }, - { - {0xf4ba819f140a9647, 0x959dd33caab9515e, 0xfd99be65b9533f42, 0x28a03868f0a95555}, - {0x6afe5aee6300eeb3, 0x950ea44539e2fa43, 0xbd9aae96c7978e8f, 0x2e3b4f7256ec9b73}, - {0xcc62f85dcccaf357, 0xb56baaa116eae113, 0xd39121b0dcf3259b, 0x46f25e4866044af}, - }, - { - {0xfa220016b44669a2, 0xfbe99bbe5092f557, 0xe04b667a942bafa6, 0x26854edc78b0bd2e}, - {0x93c3a940486a4eb8, 0x74cbbc7bd198d4a2, 0xd64f6e74ed8521f2, 0x80843fa28104df1}, - {0xd544d8f569cb4c5d, 0x9be59548e6b93d2d, 0x65c0c8fe0898dd66, 0x2199702a5841ff1c}, - }, - { - {0xf4502dae36e05405, 0xd06e02b361bd5640, 0x783d406554218c20, 0x2f8b5506aeba914c}, - {0xe3e3f0f92963d863, 0xb3e9c513b7af16e, 0x3248dce06f85e561, 0x257525c4550a214b}, - {0x87b7d8d05103a90b, 0x775220d219e02ff3, 0x930897d4af90307d, 0x14fa87e7b059d3eb}, - }, - { - {0x646e9e36c66167c6, 0x8b8c8990b4cc40f8, 0x2392a8027c056fa3, 0x3468cae95b73113a}, - {0xbcbaaa65cae2ad7b, 0xa381602916655d36, 0x1e74c496a740a52f, 0x3e5d35946fd70251}, - {0x720ef833761a1b2a, 0xd2e1ad032e9ed61f, 0x1284360fc1bc35f0, 0x1d10c1b1e832840d}, - }, - { - {0xf018bd00e4ba7073, 0xc5c912b1fb1f136a, 0x4fa748314dd8ceb2, 0x2a5f7e0ca57c7b77}, - {0xcdf3b35babdc87d5, 0x2475d527ee5ef5e9, 0x7bbb70f05dbf6d98, 0x983fe2aff185429}, - {0x88ab0d4fb8c260a1, 0x78a852ca5a6f034a, 0xd04dfc8b6d06ada9, 0x306dbc4ba1531639}, - }, - { - {0x10dd644c6e5743c2, 0xa2114971e3faae9, 0xd9fbefe6b48e618c, 0x3e38b722e0705ba8}, - {0x46ad6b9283d7e0c3, 0x2e308fb2ac0d8c2a, 0x3e1cb59c2a9f60de, 0x3230c38937f63858}, - {0x77fcd1b48730d90a, 0x388ebff7f7ca5f87, 0xa37bd480d5a52d33, 0x1bee5d4ec9503e54}, - }, - { - {0x9e939970e11081bd, 0x72a0c62c6cf51be1, 0x6e8fd8f7900a914b, 0x36036298567aa99c}, - {0xd6faab04a619d2f5, 0x4a25d62545a6d348, 0xb7ad6f35c22f47b1, 0x1de168bf0fbefdec}, - {0x1345bfdadaae5f21, 0x59e61cc1ee11a507, 0xd8115cbdd6eec40b, 0x139c3f6dd5233369}, - }, - { - {0x58ba96a14e408681, 0xa06d5b071e1ae71c, 0x1a06d51e6e7f692d, 0x1207ba481447ae8d}, - {0xac27f34f246f6412, 0x6419a4c21404724a, 0x5eb99bc09179a67c, 0x251da17ba5f44d7f}, - {0x7c7edb3d3d4d0be, 0xebbd780f9995055f, 0x219149388a5fd89c, 0x46ecaa2536098}, - }, - }, - mdsMatrix: [][]*fp.Fp{ - { - {0x32f4f94379d14f6, 0x666eef381fb1d4b0, 0xd760525c85a9299a, 0x70288de13f861f}, - {0x2ab57684465d1ca, 0xf12514d37806396c, 0x825085389a26a582, 0x308efdddaf47d944}, - {0x1b2098a19e203e93, 0x914dcdea2a56e245, 0xc64ed9aa2aef8379, 0xb176f95c389478e}, - }, - { - {0x8f85e752c76f7c9c, 0x8297f4f031b02763, 0x30e4ea62df5067b7, 0x2821d0423006dcae}, - {0x5cece392cc5d403f, 0x123da1ba8becd2de, 0x193510960c81a54f, 0x1be17f43c42fe5c0}, - {0x65fc36e3c120e5dd, 0x51a4797b81835701, 0x3123b2b88ae51832, 0x19f174900d86138a}, - }, - { - {0xd03df46130dd77b4, 0xe694d8c7d8fd4ef4, 0xf71d2a65470713aa, 0x255c475344778d2c}, - {0x78597119a27f97bb, 0x1b1fb7c15ccb3746, 0xb86d8ab32d6a6edf, 0xb1e00f75148f670}, - {0x875597b15bf7ed8d, 0x73fa4e676bb9cc5f, 0x96babdc32ae359e, 0x31e6d9f5ccaa763e}, - }, - }, - spongeIv: [][]*fp.Fp{ - // Testnet - { - {0x67097c15f1a46d64, 0xc76fd61db3c20173, 0xbdf9f393b220a17, 0x10c0e352378ab1fd}, - {0x57dbbe3a20c2a32, 0x486f1b93a41e04c7, 0xa21341e97da1bdc1, 0x24a095608e4bf2e9}, - {0xd4559679d839ff92, 0x577371d495f4d71b, 0x3227c7db607b3ded, 0x2ca212648a12291e}, - }, - // Mainnet - { - {0xc21e7c13c81e894, 0x710189d783717f27, 0x7825ac132f04e050, 0x6fd140c96a52f28}, - {0x25611817aeec99d8, 0x24e1697f7e63d4b4, 0x13dabc79c3b8bba9, 0x232c7b1c778fbd08}, - {0x70bff575f3c9723c, 0x96818a1c2ae2e7ef, 0x2eec149ee0aacb0c, 0xecf6e7248a576ad}, - }, - }, - }, - // fiveW - { - spongeWidth: 5, - spongeRate: 4, - fullRounds: 53, - sBox: Sept, - roundKeys: [][]*fp.Fp{ - { - {0x6342181358ae2f17, 0x5a321a1614499301, 0x4359bc382232456a, 0x3c06cd69a97c028b}, - {0xc8f709e31405ba8d, 0x2ad4d6aa3c7651a4, 0x64ceac42dd7ccf06, 0x35c6bf27e315e7b9}, - {0x42218b11632afaf, 0x90b0a10532f0546, 0x9e04edfc8863e7f9, 0x1ff6086dc7ed5384}, - {0x16d30e86f07fe92b, 0x49034fc6f7a0437c, 0x7e969951637e0a28, 0x290172d88a15ab18}, - {0xd254d8abb8cde612, 0xd4661c22ac9199eb, 0x512959a2410883d0, 0x35b38913f7bb3552}, - }, - { - {0x49f9638de015c972, 0xad7264c15c3300ef, 0xa62f4865d8c45b04, 0x315e43c0ae02c353}, - {0xb3801cb83df2182f, 0xcaaccf3669280a81, 0xd23d1db585bf366e, 0x116befc5fb4b732a}, - {0x208bcd0d2edd006c, 0x10eb450d1445d24e, 0x430c3ea6421ac01c, 0x2faf9819445679d3}, - {0x7d2dedb966b0ebb4, 0x4209eee542441a34, 0xf0d333d24b06af71, 0x10dedf831bfe44d8}, - {0x382b013bde3a59ae, 0xebafdd87c283d4af, 0x32d9c8ef1bce04a8, 0x37556fb5c9dfe161}, - }, - { - {0xe7016d6ae4ed55a4, 0xbadf50c278ef084f, 0x5f2fc45b67f08884, 0x718c8e8163346fb}, - {0x2d21d77bdfad5760, 0x6ed140b4216a3a63, 0x43b402fb536c00d2, 0xb47d43fb0ea216d}, - {0x36a2aed80574b2f1, 0x43955b0622809eb3, 0x6feacba71072e845, 0x28df76e003ac1ce6}, - {0x95e3a1a7336bd728, 0xd87d937c7f109e25, 0x8ce854afc1645048, 0x2fd788ebb6f37b5e}, - {0x4e4171605858df04, 0x6f56c8c5f323deed, 0x6a570e86d39294ba, 0x6a33164c054814e}, - }, - { - {0xe182b857a075e511, 0x1246b8af401e6e, 0x498681baac02e546, 0x317e99888d6935e3}, - {0xbbb9ff9616a4c70, 0xbd5c5a42104dcf4, 0x92895e7865a8d476, 0x3c40b0adcfe6deb8}, - {0xfc63b58d228c1ad9, 0xb912e4ec588e1a52, 0x601be7d93b9e73fe, 0x1d52635b6bf4a796}, - {0x8defc77d5096467a, 0xfb8b83bb3cee16b9, 0x1498e0216590fc1d, 0x337571eb0ad8f47a}, - {0x8fed932080f3d458, 0x8a1ca06c98c3849f, 0x1644f9415395314f, 0x2919282dc8950b51}, - }, - { - {0x749d4e7efe5fad9b, 0x33b58b4510a5f0a1, 0xce62030d41fdca38, 0x239d5d59f87e0ddf}, - {0x55d59bdcc39fb71b, 0x7c183b304cad27d1, 0xb84182c63c47f121, 0x2469351d6d7b0ac4}, - {0xbe942f1ad599f550, 0xfa1e12f8c552df88, 0x1ce36aa79f22cf45, 0x18e7e49a56a18f41}, - {0x5a85fc171d1c0130, 0xee3b8aebc4fb144c, 0xb7910bda1c5a2946, 0x2ef6a9412227b683}, - {0xe3f397f0634ba64, 0xb24c5da645b804a8, 0x8efdcb393a1c51d1, 0x388a37934aa31a42}, - }, - { - {0xf0aeba711a86d351, 0x917e0a9875d8182e, 0x255ebbbe4e9633da, 0x3edb9c2a8feb51c7}, - {0xf7085a35274435d5, 0x4e859571631715f8, 0xd465913c64aecaac, 0x3df65e7104e3d373}, - {0x95964ef5b04dba5a, 0x86296dcb59e4f8b5, 0x340fae9fdeb8e75e, 0x3c095e04bcd91636}, - {0x6ca87eaf42d54b9d, 0x5efd6b2fd3843e9a, 0x1a9120a05cc3b07c, 0xbb0503c4b83daca}, - {0xfdd237f0786fa203, 0x76e67649a894dff6, 0xcea3a7485eb3522, 0x371ed39b30e34b8}, - }, - { - {0xb9ea58fb107cee4e, 0xea9f1a7f2d6d936f, 0x60883d0bd19662e8, 0x137e698d12aceebf}, - {0x37d5024d477cbc47, 0xbd489bbac329f617, 0x37201ef9b7544c1f, 0x1019235cf42868cb}, - {0xa676a36a225fd2d0, 0x16c1d622bd02030a, 0x71b81aab0eacb647, 0x36af1193dcd5753f}, - {0xe00395d80fc7fa84, 0x2122fd483a170d2e, 0x6786ca04c13fbe30, 0x159d681f1d489146}, - {0xacbab2cc73b4508f, 0x47443d2762112d66, 0x26c9a77344312882, 0xa68b32d6c0b1024}, - }, - { - {0xe5943e9ec5816b5f, 0x78f97275cb9e7f63, 0x28d993db0402e6f5, 0x35023474a298a50a}, - {0xd5f6f7304d58bd86, 0xbeed688b64192acc, 0xd7211bea14f1a406, 0x24f92d631c9c4bc}, - {0x6952a1fd17d693e3, 0xc04dd964f234b8cf, 0x7caf0fe8884ef070, 0x1c1fdcd698bf94b5}, - {0xca8b6804ac41ba2d, 0x81794823bc0576ff, 0xd4a19f41722a0f09, 0x2846565f83dc9972}, - {0x51ea8b6d4a20f06e, 0xcfc9a709b77cbe9d, 0x30ff8818851924e9, 0x211d3ce41b7ee763}, - }, - { - {0xff21fe3230917894, 0xab2870fddeb86f88, 0x62e4a41add2270a6, 0x15884194ae363d14}, - {0x4a6fb13b70e67a19, 0xc5247d0dba887080, 0x31b4c6c5e685c605, 0x2e9f9208fcc2515a}, - {0x1c90f4fb1e0414b4, 0x8ff65aee4323cf80, 0xa13dda064773ad4d, 0x810a513ddf12c38}, - {0xe053ad98a6ec9bef, 0x39b9faf0e080b472, 0x818c7ad0f950eae0, 0xf1cd4227514673}, - {0xd196b25dc683b945, 0xd724c2ad624ad4a9, 0xa02ff7daa5b740a1, 0x15d55dbe3c7b4e13}, - }, - { - {0xb315a1ea41fe829c, 0x18713cd306622126, 0x6118592ab4ec0503, 0x3ed3f347d4db5134}, - {0x5975228afeaccf0c, 0xfe4e4239b60b0efc, 0xc9cca90df89e496b, 0x230f526cd9442560}, - {0x5a49f311ef676e8a, 0xad7cb07e3ed9efad, 0x2a417082abc3cf1a, 0x21601ac12eba703e}, - {0xdf338b83df06f68c, 0x63cd7cb53f8cdce4, 0x1f0fdaf0eecf7ab6, 0xcb74130d7ea6889}, - {0xd99c453addc57eae, 0x2e5ca7b4ccd548e9, 0x1d61848bbc4141ef, 0x1502dc917545edad}, - }, - { - {0x31688174ae3a3088, 0xc2f2735e215a8858, 0xe021199a3e4ad81c, 0x3c3a13210a719854}, - {0x5cd766b0b1aa7928, 0x9469f3c1ab1f06d1, 0x23c181781a8a1af8, 0x669f23736966be7}, - {0x5e43af558f0a0b, 0x7568a76e8644aa47, 0xa49bfc0b2c3a0969, 0xdaabd0e2866cfd8}, - {0x3f57582785bde7cc, 0x95a273aed529176e, 0xef25328aff37a9e8, 0x116b8853ab55ee5a}, - {0xeda91d71ffd7b2a0, 0x6efe645946126c4c, 0xe9f09dd2a7027804, 0x387a2c92b4e648d5}, - }, - { - {0x64ab4aa2e9f0aff2, 0xe966eeaf6883d60c, 0xb94697e6a3a0a4df, 0x38f0fc799ed7a14a}, - {0x1511dd33c4afdbf3, 0xe36ee2b5ffe811cc, 0x505a5de39ec98985, 0x3df8294a06678e64}, - {0xc710119f6242f55d, 0x2466c6cb6d325477, 0xb1774657e651de5, 0x310d190e78ee5dfd}, - {0xb1e6071ea081861b, 0xe92b3ce474295159, 0x77456109d94dc351, 0x1d893fd638fd7a1b}, - {0xc782a16511338c59, 0xd18c9bc3c41203d7, 0x847badef6c2b829f, 0x126c269e06a4a430}, - }, - { - {0xa0e7271d058e1b65, 0xc29f191eed5dc914, 0x89207dbde1650706, 0x1bd2a2d62a9947b2}, - {0x6ae20ca1c2d65d68, 0x80f9d7daed9c8c8c, 0xad5cf3b156b2f1de, 0x509f8b72998a87c}, - {0xb03a6b97357d97f0, 0x593eee3fbeacfe95, 0x9fee173d856a5b7c, 0x133fc88ee7b23b27}, - {0x4b9a0736e24a0f26, 0x405d5a665f66fbc4, 0x4d4d5268d0b8b9d9, 0x3238606d9b26856a}, - {0xd073bfc69cab34f0, 0xb4133b646eb1841b, 0x10a149c352b6f7df, 0x20cf915f29d33c57}, - }, - { - {0x307d2b8cb0fd415, 0xc8319598907073a4, 0x6b773db66a05a6a2, 0x33e6c0d1d806c5ce}, - {0xc08315afa7ec4292, 0xdf1042b5d5054c91, 0xa610476590769545, 0x354676a843acb066}, - {0xa1c7c9de915601be, 0x69cadc4f1bbf31a7, 0x47661b8d743f21e, 0x2939e4566b8e1260}, - {0xf8166d26b5875ae8, 0x391c8625906a68c9, 0x97a671ae3e7920b6, 0xb62d4ddc6a61f73}, - {0x5b13bd8369bec282, 0xe2ea0c100e5347a6, 0x2d9c57262923cb1, 0x1e31165d6dc07d45}, - }, - { - {0x3df3f3bfd54018f2, 0xca762a746d00043e, 0x25022728a3503107, 0xd5efa7f874457bc}, - {0x613e721107b4b48d, 0xf10823eec3d12df3, 0xeb54dfa62698b875, 0x243340259e551904}, - {0x1ce630ba8530b2a4, 0x6f5eddfa4f7ddda2, 0xdffb5a531052c7b4, 0x3c6b192f75dff4c1}, - {0x8d8f971036624659, 0xebd0ccfe39e0803e, 0xebdcb61a65d66931, 0x21868796aae7a40b}, - {0x22e12b186fa512c7, 0x4968f02a800e1ecc, 0x4725f2ec01f4b71e, 0x28e74c6a4f22fcb9}, - }, - { - {0xeffca0f81d56aa11, 0xcb0ae88503b5be82, 0x69b43848fe8e74c1, 0xf0b271c54f3b2a3}, - {0x23db18e63a2414b1, 0x7eba0c1ea4e2d784, 0x72108a3064e1a124, 0x138c36a9897505ac}, - {0xb93afa2c44d2b18f, 0x616aef5e3ec452fe, 0xcb15eebb579916f7, 0xed9d9c3d23aaa60}, - {0x19c722ddc6d11a6c, 0x933aa7e601881608, 0x3d680c98391faed1, 0x2809e56840f1eca3}, - {0x682adeb5d9a53026, 0xcdb02ab94f3e9259, 0xed7adc874c00a2d4, 0x1764188e52d76c52}, - }, - { - {0x2cb2173bfd2a8b7d, 0x742418360f62a8f4, 0xffa5daf7a2f06510, 0x2622bec30f05eda4}, - {0x956300c0a931ef90, 0x3e8dcd122d9b3016, 0xd77959f2fba021a4, 0x51f68f4d9b5836a}, - {0xcca7550f4e2663fb, 0x3a7115aac8cd273a, 0xfa9108f48b6ec0f7, 0x2eb9ac59d63b2756}, - {0x25c658fd552f8699, 0x24c4b27a4de55c10, 0xf2a39825d38a8469, 0x261dc2c828f9be1c}, - {0xf33c05063dced35a, 0xb0dada5d213d36ea, 0xe1a0c81f1f6ca22f, 0x3b5ea3d73588bcf5}, - }, - { - {0x5938e55ad487efbc, 0x65ff0bdaa2002589, 0x24f12d149cfb0ad8, 0x2d7f7be151666e78}, - {0x832fab7224860b2d, 0xc9f4cdbadd955fa2, 0x4aedceb5506c2655, 0x1c44fa130dd1ecc7}, - {0x7d034b1f6a58ddaf, 0xf897b22ef62bf04f, 0xd973ac696faf14aa, 0x31548d27d817dbcc}, - {0xf89844128d9c6ae6, 0xfc4cfe0229c7aab1, 0xac2b0c7d97647680, 0x1e1d5254aa0782f9}, - {0xe8c1dd74ba3631f0, 0xd81c8d077b5a6f56, 0xf3294e721e883318, 0x380d3a1eab70459b}, - }, - { - {0xaba511448d72ecf, 0xbf82f1fdf1687a8e, 0x6313bb88e45ffa56, 0x2ae425e1e1234cff}, - {0xf4a6807d301a531f, 0x96429863d70e0604, 0x15bdd9eae828ddc7, 0x31f0f80173fe31d7}, - {0x3a6d20e8dea8c483, 0x2adca6c88e7509ef, 0x48b1d6d05be6c961, 0x35053945aa6e5402}, - {0xdc5f96bd86658107, 0x5aee32dc2a32affb, 0xe200cec62dc0d495, 0x1055b57944bf554b}, - {0xe1ca0c53b24b06d, 0x528de276ea0c8c5e, 0x1c7ffa0b483f3002, 0x1c72f58595847427}, - }, - { - {0x26a28a08b5b246ea, 0xba3b8d9f4f4b0f41, 0x99c9ed2c1fcf4a3e, 0x58070c1e7b659c5}, - {0x7aa8e9a2d203b7f4, 0x9acb8ddb590fc9a0, 0xd7cf3e5554e162c, 0x17769ee1912d75e1}, - {0x6c6901252870a99d, 0x9a4108b035e55928, 0x297dab35f2c77cae, 0x31f2978ace0f7e2d}, - {0xfcf1119abff1e989, 0xe8502332327be648, 0xa8918572496177c5, 0x1710468c2227c8d6}, - {0xdd2bf9131735dd76, 0xe43ec3b817349505, 0x61ec884ee479524b, 0x377c72d607beacc5}, - }, - { - {0xa9bef84e0b68b0e8, 0x2c4c8f2ab7b0c9fc, 0xee234cad52493f69, 0x1c5bd50dc4a1fced}, - {0x57f989e88a97334c, 0xf99d4d667c1b859a, 0x64164c1e8e48da1b, 0x36b841653e8612c5}, - {0xb55c8effbf87f8d8, 0xe15c71abf8372eb, 0xc606d853488806ff, 0x2c6be0beffd5a9b3}, - {0x97235a2b7f573c80, 0x8f5053ff091130d7, 0x201611ece80cd2e6, 0x22498e90ad20fd7b}, - {0xb25923ea87f4f825, 0x1faf60a8b1d87720, 0x1c480f9378722c18, 0x187ba4d5f603542d}, - }, - { - {0x2553e37a713a8650, 0x4af5a87c8bb53cde, 0x9470f8df7dc4e62a, 0x1147db739156a158}, - {0x7a58fe90b257b6b7, 0x8ee9df6553d968a9, 0x85057b2342c19359, 0x3ca66ad9e8533b29}, - {0xebe091f37f855e8b, 0x78312923a64e1e08, 0xf968ab79c1cb96b, 0x84c6a2f87e5877d}, - {0xd3393bcf45ec7f72, 0xeebaad3d085cc500, 0x8dfb7b13fe964753, 0x29e0048c6a967c5}, - {0x6ee6f52f14c5c52b, 0x51eda970b620a200, 0xe1239122e1ee6ed3, 0x20241311a411c6dd}, - }, - { - {0x3a632070a61738d0, 0x58360c4de1248c90, 0x2007e0611a3ddc78, 0x318e43c7104b5d29}, - {0xe11a8859f0b07f43, 0x22423a78bf5d6ce7, 0xfe8417dfe2f81f05, 0x2a9cf2284ea93e6}, - {0x3c682a7371dae56a, 0xb537b6fc7564fea3, 0x4c8c6573f55fa435, 0x152489488b5a1639}, - {0x3cf49703bdb0de0, 0xf828bf910f380e10, 0x8fb14d900fd140d1, 0x3f6cf44c3e3ff6db}, - {0x7b70aeec460c3296, 0x2afdb7b9dd091761, 0xe5b3b021d8f70e09, 0x1f75fbbd77a4b405}, - }, - { - {0xb824cf8de5beaed8, 0x70a7fe173b87433b, 0x1a8efeec667f72e4, 0x39565d2fad0c609a}, - {0x5cd0203a1d4f951, 0xdb78389b84917080, 0x6c4c97504ab70cd5, 0x29cc98e95cf64495}, - {0x6bc75c72ecd52b50, 0x33afc1a9068b1413, 0x33daf830e0a55f27, 0x71875230561158e}, - {0xb19ed2b87a280098, 0x1e9ed62c5d6a622e, 0xf1c47cd609238e2b, 0x88c1888884476d}, - {0x69ea31042e6e347f, 0x9bb2a44f8642afdb, 0xeccc2d81df513162, 0x3af58f661fb1f19c}, - }, - { - {0x46713a78770b8c85, 0xb3ccf0a4b425690e, 0xc65beb7710375cf8, 0x1c83ac2e75d29e4e}, - {0x8df4d89a09fbc390, 0x4d57e4b593fc2239, 0x94b4e16defc746d7, 0x1e00fdaba6801cc9}, - {0x62d3e199fefcf465, 0xddfca365e5282190, 0xadd48dd560275162, 0x250a1b6745f9c2a6}, - {0x935e7ff4c5ad3690, 0x931629e4dcf656, 0xad870e5416ca92d0, 0x2d2002e4c1a7fb42}, - {0x3020c37bbe98a69f, 0x3bbbef2df0bb0743, 0x735468317fea682d, 0x3bb75622e8ae0e5}, - }, - { - {0x6d101c64f48442cb, 0x9c4d0d7cabbe37d0, 0x6e457716d0cc5c54, 0x131685a66db0333d}, - {0x48bcf6f7121dc6fa, 0x44ea62ad25ddb6aa, 0x8636e258625c8e02, 0x171b08836f73a4a4}, - {0x7b5d53163078c6db, 0x79f022d48797b027, 0x8a6611711def9ec3, 0x281eb0327e36241a}, - {0xe807c130c139b23f, 0x8bd55fb76af83b50, 0x2917722317575e1b, 0x8f90e5cd2c3173a}, - {0x4759babec3357d26, 0x265b8a66badcbb36, 0x44df217c22db1fd1, 0x23c7ef2b68b42cf3}, - }, - { - {0xb6a7c51b7ecb6bc, 0x4d1ae5944bfbeed8, 0x864b9db1caabff7e, 0x39f90ff79f187276}, - {0xd1969a2901b910c2, 0x67af6508acaf97a2, 0x8380c23a59ae6c60, 0x271d877b5644c4a3}, - {0xe17e8fd5a391261a, 0xab17b0e6a4632c50, 0x1c3e97e07f259c9c, 0x2d07bd641a6586e2}, - {0x138aae9b3cd42fb3, 0x81f64f590fb78cb4, 0x885724f615f7f233, 0xa63fee53381d1b6}, - {0x2ec005773e160199, 0x475ef3383e134dd2, 0xce774f49e51de44a, 0x36ef885cefb664f8}, - }, - { - {0x37420d26e384e4a8, 0x1742df50ce970b26, 0x99f3ea60e2297d13, 0x291cc0cacac121bb}, - {0x59992f7b95d59d06, 0xbfbbbce9ffae7ef8, 0x230d4b9bb86868f8, 0x135612cee5c3cbf5}, - {0x6ab6b33ab48fd8b4, 0x2c46df90b0bdae8c, 0x31e33e7cf970f45a, 0x36c4a50b91a1475a}, - {0xaad1c48efff98a5d, 0x7a478e439cc52346, 0xb77125717607cc5d, 0x24c45ff83f2e80a8}, - {0x5103153d6fdd5dfd, 0x45b61844136521c6, 0x41c397561d8772fd, 0x1ed1ee06b89dbf2e}, - }, - { - {0x6c5059eebd2c5991, 0x3d6cf236df839e48, 0xd92711e12b52886b, 0x29829fb71567bb3a}, - {0x771a7702e2a54d3a, 0x29b8e99e7644939b, 0x3d453254475ea815, 0x2e5f8163d03b6cb5}, - {0x263df2c33bcdbc46, 0xfed7cba7787b1a36, 0xc315fa3c16682da4, 0x2ab983af9d9b6f25}, - {0x8a0353e693c8e2c, 0xbe92370d0d219261, 0x723aa4237242dd57, 0x25361783d1e56fc3}, - {0x7e7de67d78a9ff19, 0x83c2d2fd23156a32, 0xe65e5d243aa459b6, 0x35813f92ed31f777}, - }, - { - {0x4819c016f5a5c698, 0x4f72e64273a5868e, 0x61751f954f65b95d, 0x379db14ab6232b32}, - {0x5d8d95a7f9270b96, 0x61541332ec3b7a2b, 0xbf5b05056d41baab, 0xcaf69513fccef00}, - {0x966ebe56652901fd, 0x3d01e1815a5244ad, 0xd62a7487593ee708, 0x5f1ef41b294e025}, - {0xda81a0814d58ed14, 0xe5824bb0a3739516, 0xe559c39f79e50e7f, 0x3cf706e11c52afd4}, - {0xb07502481fd9ac00, 0xbe85d565f578f9e9, 0x25e2168d537c5428, 0x1f8caff53a89afab}, - }, - { - {0x67ef0684d24ef4d6, 0xe479b8723faeeb8a, 0xed152c7174bce1c6, 0x2c3879d3206619b}, - {0xc0d0b18f192aac4d, 0x8ff92db980036473, 0x39a88f384fb77d28, 0x9fe5e9d746e308b}, - {0xf10d5629175358d0, 0xa258ea27ec17d224, 0x3730ea6667ba6289, 0x1f8bfc64890f7e59}, - {0x5f8c12d96d37065d, 0x4d7ee138862aa83, 0x4a18488a63ce6118, 0x1930781a4f270e4}, - {0xbd4453cefd9ebc0c, 0x14827cfda7ed7ee8, 0x3dd6c45400957559, 0x33c9719ccdaab5b6}, - }, - { - {0xed0c855c5de359df, 0x6871e8f1798b7bf5, 0x3803b19eb2c1f511, 0x1b88826bc36516df}, - {0xecec6a0bd180a9c0, 0x954e9adfdd68e064, 0x323c890828d78811, 0x2c89829ba7ac7fe7}, - {0x623862b5c28aed0f, 0x544fea8657153f5f, 0x41139508c925a0b2, 0x10d5e06354bae812}, - {0xeae3b52c47a3ad31, 0xa40c52de4949ba9d, 0x239515052b2d0bb6, 0xc68f2ca20bfa5a4}, - {0x86da286806879c23, 0x2bc62129dce2d327, 0x8f8f1b3f3a607809, 0x257de258bba457f3}, - }, - { - {0xe55015708a8bf114, 0x8f7b7799abb7e89f, 0xcb8fa2a6bf9b602d, 0x1dd3b45e4f2bd1e9}, - {0xa48bd0f7b831b6af, 0xbe6ed2ae7e9b5ea6, 0xecdd091614986315, 0x1bcc64e2d4434539}, - {0xee95991ac731a5d7, 0xb643176046b51d45, 0xf396998dc25f72a3, 0x1474b46564931dc3}, - {0xe8973ad2df550e5e, 0x8561e0de83378bad, 0x90495ddc20bf8d64, 0x2c8ee5b7e87d23ea}, - {0xf15e8598d3360040, 0xd9237d9f5bd4da94, 0x2f32ec74a0b7cb8f, 0x2bfa790791857d69}, - }, - { - {0x51ed3818b8a671e0, 0x93f8de29901b0101, 0xdd6948f429d84a64, 0x339864f118ba5599}, - {0x8070718964c6881, 0x664a56735cd1d096, 0x966ebb68ce0c59be, 0xdb44ab4420ed185}, - {0x390fdea200fe8c8d, 0xb9ddf1781fc7dcfc, 0x6ccc8d97ea91a52b, 0xaf86429842ad1ea}, - {0x6fbc15b9f8ee61d5, 0x485407282205ba19, 0x9f2b3a9eb0762424, 0x1167e61f6e4bd42e}, - {0x9b2e606d2a12a53f, 0xfe4ee2337eadcc76, 0x97152598ff76e36b, 0x275e80f05a7648b6}, - }, - { - {0xc3cc461cc12d86e3, 0x48b15302057c1d0e, 0xef7a34bbb6748beb, 0x286c7795696d139}, - {0x337d4ce46c81b278, 0x2e5feb77948c70d3, 0xd82b4f43ac0ebab0, 0x23a5e817dfdebe91}, - {0x2ce1459a01867e26, 0x224b53d8806aa3a5, 0x1bba8ab295cb47f5, 0x6cbbeb19cc3e900}, - {0x1774396945cf1d1b, 0x325ec3d335425b6b, 0xdaf58659cd291e5, 0x3f8cfcb73cb1aff7}, - {0x31812080ad76a765, 0x76b57d46db21d506, 0xa9f0b894c076a2b, 0x6328153e24ddb21}, - }, - { - {0x635e53a6c9b16d33, 0x39a4746bf0a3364b, 0x61555f31318c6ae0, 0x3b775cd07e4fa0ba}, - {0x2cc47754e893144e, 0x76f56441be34ac0c, 0x580502c5981f6c05, 0x3f1912d87eb51724}, - {0x4ead108af1a4e97c, 0x14ed7a0fc16f0e1a, 0x88a0cf37b2ee10aa, 0x13aa67b47ce7c7fd}, - {0xf54922d903cdce93, 0x825eb6a0321c91fa, 0x6d71f23e5b2a77ae, 0x31d82d03cd7ef1f8}, - {0xf6c8ba6acea0c3a8, 0x3dcdacfe5ace7aa0, 0xbbbff1c714c8bbcb, 0x26b4c61ca5f05c8e}, - }, - { - {0xc2bddbeee6db7663, 0x5de993fdf4bee2bc, 0xc5598a002460bb6a, 0x195ed57ac7350182}, - {0xa3c22c35da970f5e, 0xca1c98fb8ebbea38, 0x1fac0f5c50dfc365, 0x1aef8ca61af69bd9}, - {0x26e8837fb91809f1, 0xf9688f1eec8f7e7e, 0x610d6fea8d7fdb89, 0x3d0a1bd4d427b4ac}, - {0x4805ec51b5a8b95, 0x35841575c48b553f, 0xefc86563cec776dc, 0x2840e92680329f35}, - {0x88aadc874b15e054, 0xf4c407659f438e86, 0xc78f11dc3ac39010, 0xe83c809dce62ea5}, - }, - { - {0xa0d5b4ce25ad95e3, 0x4eb48fba265577ca, 0xec34d547e740b067, 0xf87455a1a87a825}, - {0x7171a3dbff618247, 0x8f77af4f143160e8, 0x639543558218623e, 0x1ad8547be9074db4}, - {0xa0dbdf918c38f312, 0x62d083dc471500fb, 0x5358448cc9aad1d1, 0x5825571f70873cd}, - {0xb9c01a42ad74f7f3, 0x96425e46aa40f166, 0xbc305b6f8c2ca3c1, 0x38885a0e462a0d16}, - {0x1f3b4561c10caa2, 0xe7f7e2edd641ea35, 0xd946c46002ec9b24, 0x22dc4744611dfaf}, - }, - { - {0x89d2596131b9d801, 0x6d61479c7e6f6d9, 0xf5aad5649f5a1c79, 0x225393c033553d15}, - {0x5b0fdd7cbea91565, 0x95e46f19a0dffebc, 0x91d50f19a3a46071, 0x2c03ec2d9ea3aaaf}, - {0xdecba3c94506fd1b, 0xa07f4c4397072961, 0xc072d04541ab3761, 0x250beb5d4be1732e}, - {0x9ce4550f36a82208, 0xad906f79c2991285, 0x82adb87da0fe9206, 0x34aff80145dc173b}, - {0xb84407732055b44d, 0xf9c85a0309677606, 0x1816b1a6361d2c99, 0x302b805797745fa1}, - }, - { - {0xbbfbaa3655132a2f, 0x85de63edc71b8169, 0x231b387734b227a0, 0x791e6d7e390ab58}, - {0x846a348eee728261, 0x91e35881244dcaed, 0x8755e3179f39f84, 0x11c757c8adbbcee2}, - {0xdc5b85ce4ff2e16, 0xe6680a9d77d56b79, 0x2e1d8a190b81a71b, 0x110440e7f341ccbf}, - {0xc5714f4e64e4f5b5, 0x9073123174ba32aa, 0xd1aafcb808fb13a9, 0x2b0bf27c449467b4}, - {0x674d2c9c2a9f6c33, 0xd64a81fc8872e544, 0x54da3af1c7ea91f3, 0x22bb7d2c8479681d}, - }, - { - {0x5ea26e9a08f957a5, 0x531b4a8427d261c2, 0x92a9d9e3c38cfcf0, 0x2006044428827241}, - {0xf0834849c1fecda7, 0xfab565ee5f9319d, 0x3a3b976275b87643, 0x2bc18d1039d22ce7}, - {0x7ad9bd18d3ef9d11, 0x136c2bdc157de581, 0xf1999edaa1f99ec6, 0x3bdb875af3652fea}, - {0xb06ff1fa4faa6be7, 0x7b65a2d09d62e6fe, 0xd52851aa16d4a33d, 0x3b7e6a651e5f1100}, - {0x70b297d3bd617bde, 0x42dfd73b30a28150, 0xbcbc0b930ad9480c, 0x14452569cf1b7495}, - }, - { - {0xb997f89dc4f23510, 0x86aeec894d2eb890, 0x40b5eb4203777c22, 0x3f6900dd45610c9}, - {0xbed1fbbc558ae3b9, 0x7b9919fc76fb8f31, 0xa8155c8d8f223d05, 0x7be199f23efc89b}, - {0x124bd2f29dfdfc99, 0xa3cd06dc334c28dc, 0x8321717bb314584c, 0x7a90593068a94cf}, - {0x6d262cbbd1c3c7a3, 0xfa55dbcbb37ab4e4, 0xdfb0541244749109, 0x1b42310efbbc8ae1}, - {0x159b02d7b19c8807, 0xa3155c41a3100f0b, 0x649691f59c73a27d, 0xb1c6cf5eaa1a3da}, - }, - { - {0x56a321c5d5620a4e, 0xd704e017be94ce48, 0xbb7e58300ff6e106, 0x231353460278eda6}, - {0x7f24d9a9e896902, 0x379dfae44f3dd605, 0xa756baa38400f59f, 0x1ca15e781769cff3}, - {0x3b1d025a762cebf4, 0x9be99c300caf395, 0x1ec3a4ee83fc2b9c, 0x1db9c130790aa77c}, - {0x92f350103a625f89, 0x7f7abde4baa7fe7c, 0xdb4ce7149975b21a, 0x37619aef93207815}, - {0x2df14ae96e32f360, 0x8154a50068c1d6d7, 0x3696523ff84dccbd, 0x3d71103fe9b7d2cc}, - }, - { - {0xdc8f123847c2f6f0, 0x772b9f5f133bb07a, 0xf48472df2de5637d, 0xb30587972382d91}, - {0xd32076031e6caf, 0x7a70c0a191315b1, 0xc72d68ebbd493f22, 0x26a6b863263ca385}, - {0xd1ad7a8f3f52bc58, 0x7fd97d9102a5e717, 0xdc4dea9fba06a94f, 0x24292fae82eb3182}, - {0x9c8f6b9aed0c14a, 0x7ce6499a8da0ffc5, 0x4c575abbd55a091, 0x2ffffd706225c6b5}, - {0x51ff57474553fd13, 0xbcd2c2f63e851309, 0xad42d629fbc07620, 0x37cb8a314456dcb3}, - }, - { - {0x9e725f4a1ea322f0, 0x51275d226f5fc65d, 0xcc96b5ceb521cae0, 0x31697ac9e08fd09a}, - {0xfbbfc3ed25936e24, 0x885d8e71956e9fbf, 0xb8e0d819be1b2b0c, 0x2a27ec07450706e5}, - {0xb86f23d85d56ff2, 0x25630952048f156b, 0x96949d2297030e85, 0x28ed6be9457a4c1d}, - {0x85cefc2d5a4254e4, 0x93335e124a410406, 0xe2caa252d7d83ee, 0x206bb8d1b294acc2}, - {0xaf3c9df6a0ed5396, 0xce5b0093a6e41bfb, 0xdae7d2b6669cdd65, 0x91670d7e0c906e}, - }, - { - {0x848e19c09bf3ab82, 0xd37733a864fbf5b1, 0x5834568186cadc57, 0x3d8894b3840c836b}, - {0xcb24e184ea8d715, 0xdde18b32791992e1, 0xc754f597613dec6e, 0x124ddceb631af8ac}, - {0x200fede77fe9ccaa, 0x4120a35be4499eb2, 0x6bcb74340da3069e, 0x18d40006660a4d9}, - {0x8ccd91c1dc2b219e, 0x1dc15dbbeee5b7cc, 0x30e961143289ebc0, 0x33aebd15476f6d}, - {0xd4c03228e1165ff1, 0xe755127566374ca5, 0x5eb5e5f7835f51b9, 0x11d1f3f590664116}, - }, - { - {0x1c2a43421f2b006a, 0x6258ea61fff6649b, 0x5a847a0bdf1ff16b, 0x2038498881736f80}, - {0xe603ee6ce8b0bbc6, 0x620a0a604d315efa, 0x40378c0521e6518d, 0x2d4d8c63bccec23}, - {0xa77ca49f7f8b90ff, 0xcb7652bf1a0cf5ea, 0x3d911a1c6e5c74c3, 0x1a8c15f40c9e99d6}, - {0x293a2d7589738448, 0xea4c1d5f407e77d5, 0xee7f4d7f7d8d69f0, 0x6d9a037bd4006b5}, - {0x7e0382dbce83b459, 0x8210fa8a33a15c2c, 0x4da8c81848a7e20f, 0x35c902f371d587a5}, - }, - { - {0x3d331566c2c6c483, 0xc66d7c43cf6c6899, 0x7c1c36147e850129, 0x18396a316e009c03}, - {0x16d27bc62b29f952, 0x65a7c24e59dc8b05, 0x5c0acd2a0f886241, 0x15e74885451d7b84}, - {0xe3a5b84fbaedfd4b, 0xfd3304cb4b735b85, 0x8d8df8b6031ccd91, 0x603d2627ed921bc}, - {0x194cd2aa6240d213, 0xa3d4d947c6027d50, 0x7355e133684d2417, 0x3a4ad2ca80689906}, - {0x754062c7dfe10fb, 0x15be7881422ab514, 0xbd3cb5e4447b5b04, 0x267919778e6db957}, - }, - { - {0x9e687a0099aafbe4, 0x8716f500deb883a4, 0xc7c44b3a4227e0f9, 0x36dfbee5ac583fec}, - {0xb9c5848f3b063542, 0xbd7beb77de16d02e, 0x6ed1369422f1597f, 0x35cd85390d4f063e}, - {0x50a256d280092fdc, 0xd2c2b4dbbb258e39, 0x9c6679aa1c4480db, 0x383efabe992c0d62}, - {0xb8fadb8a950482a8, 0x6279eecfb927c631, 0xf8b75e3cffc23fbd, 0x239433b63ac65264}, - {0xaf95feec451ffd03, 0x7ad4f5520a280f0a, 0xfb6d86aa8efee6c6, 0x5ad99e8a107bd86}, - }, - { - {0xd47e6d75a1e72978, 0xec21efdeed48fc4c, 0x3f95628431615152, 0x321e3149a1bd5bda}, - {0x366a1936303c4a03, 0xda1980c0a597dd0f, 0x2fddc599df0832d5, 0x10090314b014c0af}, - {0x9af98513b8fa3e32, 0x76a99773a39804d6, 0x49ed6650bc0128d4, 0x34fce51deddd27d8}, - {0x29ccc4a9b0c2b010, 0x8a8f514b705229fe, 0xc1e6d12b311256f4, 0x3291611fbb2fab1e}, - {0xcb4ebbb08bdb9c9d, 0x744ebe7f914218fb, 0xe77c5babcec8a686, 0x2d42a41428a90175}, - }, - { - {0x8ec3d97ab5616a9e, 0xe8014e7c1141e6ff, 0xa8daca3054309538, 0x1c08ef18d73c76fc}, - {0xcf92950eb4f3789b, 0xaaa450f22a280bf6, 0xc9e4a80c9f2cd996, 0x27f4ac96508752f6}, - {0x7bbd2ed16a76edc6, 0xd8e2186c7de847db, 0x2aa88a2b65118dd0, 0x1c55b5f615dc28ea}, - {0x7ccf57f28acc118a, 0xf5d3c6eb14e65154, 0xdc079fcf442a0f54, 0x11993cb931932e5a}, - {0xf76b4a8906e70667, 0xda7f02e1bf4e36df, 0xaab6b7f1de20dd0f, 0x19fc46ff2ddb173c}, - }, - { - {0x3a3d2dc8cc132eee, 0xf357bef4e1d3a63c, 0xd48a3a0eb2bc1415, 0x2bc75acfaee9db1}, - {0x5fbb66b806674243, 0xf73af3e558a86209, 0x5d30fbb40ede547c, 0x501e03ee293fd1d}, - {0xe90568a8237171ac, 0x650fc27c4da7f2e3, 0x546a3b7012993072, 0x87e3d6d0e54850d}, - {0xd5dfc1afce8127cb, 0xc6874ecb5b959056, 0x17d19ee832e735c7, 0xbf09138a8fe4ccb}, - {0x489c20a8f79b4f58, 0xaa9a7c84d23aedd3, 0xb66eddf614963ee3, 0x2dbf9ab7c2343a43}, - }, - { - {0x3dfd42b46f1e6946, 0x58f29edf399435ba, 0x2521d4287bc79d64, 0x1781fbca8872f93c}, - {0x6d6aed7cb045289f, 0x44132433ac541a78, 0x660c1badd4c7e0de, 0x30330b4022cfe5fa}, - {0x31b90687198ee938, 0xf9b1217c09a47868, 0x1df6bdd931eb2b30, 0x151f40cfa7ce6982}, - {0x9049df43bd2b446c, 0xc117a3d9f6656367, 0xfd356803d03495d8, 0x200e3c9d4c1b8eb8}, - {0x90d2cc13778a0928, 0x9b7d207f836f7d68, 0xac2d328e8bc0cdb3, 0xc70770d5c26e2ae}, - }, - }, - mdsMatrix: [][]*fp.Fp{ - { - {0x32f4f94379d14f6, 0x666eef381fb1d4b0, 0xd760525c85a9299a, 0x70288de13f861f}, - {0x2ab57684465d1ca, 0xf12514d37806396c, 0x825085389a26a582, 0x308efdddaf47d944}, - {0x1b2098a19e203e93, 0x914dcdea2a56e245, 0xc64ed9aa2aef8379, 0xb176f95c389478e}, - {0xf895153087f5dca3, 0xa53543f74c7e98f, 0xf5a0b430a14b8c2d, 0x6ae54007a872b0}, - {0xfd0c32f86be981dc, 0xf60dbc5c1bd0b583, 0xd4f3f8f9a2a4537c, 0x1d71b70d52f42936}, - }, - { - {0x8f85e752c76f7c9c, 0x8297f4f031b02763, 0x30e4ea62df5067b7, 0x2821d0423006dcae}, - {0x5cece392cc5d403f, 0x123da1ba8becd2de, 0x193510960c81a54f, 0x1be17f43c42fe5c0}, - {0x65fc36e3c120e5dd, 0x51a4797b81835701, 0x3123b2b88ae51832, 0x19f174900d86138a}, - {0x6d0db66a74936d4b, 0x1b8aa34d8d4554ad, 0x8605b5c1a219423d, 0x3055d8d876253885}, - {0x9b8b22118b0179db, 0xe14da53ccd481770, 0x109e7ae5ae61278d, 0x13cd85bd55c2f52e}, - }, - { - {0xd03df46130dd77b4, 0xe694d8c7d8fd4ef4, 0xf71d2a65470713aa, 0x255c475344778d2c}, - {0x78597119a27f97bb, 0x1b1fb7c15ccb3746, 0xb86d8ab32d6a6edf, 0xb1e00f75148f670}, - {0x875597b15bf7ed8d, 0x73fa4e676bb9cc5f, 0x96babdc32ae359e, 0x31e6d9f5ccaa763e}, - {0xf27e0f92236fd303, 0x6e607a16f84adab, 0x4cc8addf91894557, 0x1fb0a70aa0f1061c}, - {0xfd2a420b19b31725, 0xddc5361119d53b6e, 0x3d58af3f6737f156, 0x1350a7bb521c58a6}, - }, - { - {0xf88f2f863cb9d6fb, 0x5078f8e89e8f9ff9, 0xc5583fcea6176010, 0x25e363acdb694459}, - {0x2ece0c297d2f49a2, 0x9ccc88a13c91abae, 0x4138c965288c3d87, 0x437768eb72dfb4f}, - {0x9fab22e085f93fe5, 0x63ca08a361b7fb0d, 0x7e9790bf5bd5837a, 0x6080ada873c8216}, - {0x32d3b34d8c43a402, 0x2c7e5748fb940669, 0xc0a36e42a28c6f80, 0x24ac3e6b181bb185}, - {0x470f7d02d1dae46, 0x8cf3cde540035d00, 0xe3c0216f8d5d807b, 0x3e3e8312ef71fa39}, - }, - { - {0x6682f4469913559f, 0x3b053e58dc4560d6, 0xf84c58444b5bdccf, 0xc3230d834c17967}, - {0xbff2a45de17e9da7, 0x6309bfdc8e152f51, 0xb9ae2f9af1f30a1b, 0x27a8797c59f97b06}, - {0xd787c4dd405d1b3f, 0x7da8effab83f1842, 0xb3f8303ad313dac2, 0x3a1a7a3002e72833}, - {0x327b7f748a0695fa, 0x7dde58a92f496b95, 0x8a02b6088016449c, 0x1cef42b151422c3d}, - {0xb22ffb451127fa1a, 0x3c17ca7183462744, 0x4de2e19b12854d65, 0x20938ee131fc7ef0}, - }, - }, - spongeIv: [][]*fp.Fp{ - // Testnet - { - {0x63d01a5eb2171352, 0xa156f498468c138a, 0x6863ea2849c3a1a2, 0x9d3a988f1f410b1}, - {0x7102a042f3032c7a, 0xec792d3bae28c836, 0x56ca8c6f048bc984, 0x1219b5fcf34e0a1f}, - {0x2ac12e04eb8f550a, 0xa5757bca84777f2b, 0xd3c2bf917b1192ea, 0x1989968c7935c607}, - {0xe1d62db2c86caa07, 0xb8ed617d8704c6b, 0x4e71934f60359a00, 0x25459aa434d50ff}, - {0x290a6ff9dd02df5e, 0x6e4c26ecf7984888, 0x8f5fb54612793d95, 0x31404beb90f0fdc8}, - }, - // Mainnet - { - {0x1bc46288607092ee, 0x679d1013fcd27af4, 0x2302588441a00b35, 0x52aa4180a0e1d3f}, - {0xf44d99f5d1788e7c, 0xa808f4bc1c5e8caa, 0xd3fd8806f5f3de6, 0x12ad0b5be60d68f1}, - {0x6928c9d83855c9d, 0x4b93a3d0d8209f22, 0xbbaea51d0f1f12e6, 0x62815b7ee55e6a8}, - {0x1fbd2d82dcfa2d, 0x78ec7156c609e43a, 0xf1e203a769275642, 0x3e15c2753ca6c1d}, - {0x6299f39409f35a31, 0x279b391979868236, 0x87b62f1b72d1deea, 0x3b44d1afce3a530d}, - }, - }, - }, - // three - { - spongeWidth: 3, - spongeRate: 2, - fullRounds: 54, - sBox: Sept, - roundKeys: [][]*fp.Fp{ - { - {0xa7eaec68b00f442f, 0x6f59e1a835643145, 0x5e1085dc39694ee7, 0x31f43b11041ce57e}, - {0xaf9d994fe02cad85, 0xd023d4dba24251f2, 0xab2b289011b10b15, 0x136703f8461e5900}, - {0x17d4dcf1505a5b8e, 0x905301ba46f35eda, 0xbf183c861c890269, 0xcd2255c8e8bfad7}, - }, - { - {0x652519f35396e7b9, 0xf939da87dd2565f7, 0x77863388eeb1739a, 0x2ef0165a2c2e5844}, - {0x477f697921c5a46f, 0x2f5597aaf22a3c0e, 0xea51d9a2b20ef8ee, 0x27f19ea80ac259a1}, - {0x475253132eafc552, 0x691f153f119e2158, 0x3463b3d75dc73170, 0x3875a2611a0025e4}, - }, - { - {0xc1500848eb7005a6, 0x61e2acd1faf26ff8, 0xf50c67341380fa2f, 0x14e95cd68d6778e}, - {0xa82b34cad0ebd99e, 0x771d54af176024ba, 0xa343788ac43bbde2, 0x31c9ab354d21b72a}, - {0x3deb92a1d0140aab, 0xb710f83bb2ce1349, 0xf3dc159cb9171a97, 0x6c3eac66a23c368}, - }, - { - {0xd25cd659b62b584, 0x3a52d26b8092be14, 0xe36c5155d1e135b, 0x16deeee5467c7a70}, - {0x9b446f453cb50aca, 0xeadf51c8f0af7a58, 0x75da6f44c4a04ca2, 0xccc39a8549cb487}, - {0xe09191801b0fdabc, 0xa7452c89066d4bd0, 0x5244883ddc1fd9cf, 0x3862cc172ab37d2f}, - }, - { - {0x6a87a9921ce9aabf, 0x5d701ed9a030bc04, 0xf99642aa2a835ec8, 0x28319fcffc61a144}, - {0xafb8a54d87a15b37, 0x31e93428debef477, 0xd328f47b48852d58, 0x1e9fb7a3f8c8e39f}, - {0xa58f9aa995fcab1, 0x5fb0135046864286, 0x6ad292753e09ec37, 0x24cb4d2ff2e77907}, - }, - { - {0xbebb7c8e57280d90, 0xa2575331fa3f83b, 0x1bdaa15abc6032e4, 0x137f4d26f7fc2b89}, - {0x8ea04d93f2a3faba, 0x76d83e0976143e11, 0xde45171e6c479b69, 0x3ec500ad89afdcfe}, - {0x9741b7a395379855, 0x916b939a142e1e68, 0x4fda77496b815109, 0x19d993fa47fbc1a7}, - }, - { - {0x31d6e313b491fe95, 0x19f07f1a489cb20a, 0x517ac8eb07d91f83, 0x16bd2c0e204bb5dd}, - {0x42170b694f7b1926, 0xdde594e9f6060540, 0xbdb7c66abef575a5, 0x26c2c710d9aea3c9}, - {0xccfb5e566332e76d, 0x4e73df588d423339, 0xa4ede3fda7178916, 0x28fc0255accddbf0}, - }, - { - {0x2fc2f7a5cf4eeb76, 0x709a30d94daa56c0, 0x67a5dd9c696533dc, 0x3ace056f839007b7}, - {0x7769ae0082cae71b, 0xdaa4d4c08c74011a, 0x919a01423e32424d, 0x22467d425c99d5c9}, - {0x6bcd3613ace4871c, 0xb0bc217531069def, 0x55348199fa2b487b, 0x2385b602228e77ee}, - }, - { - {0x7022e34179f7fd32, 0xd7d122a3a91838e2, 0x20e0714f41741103, 0x55ca30203c35d65}, - {0xeac64a4e27a532ac, 0xfad717669ae09d08, 0x16088f7d30d724f1, 0x37bb5a0c062e6400}, - {0x7c34a314bcba4635, 0xbfdd1e4cda8ce53, 0x7b9809bd9828ebbb, 0xbe17455fb915f02}, - }, - { - {0x3eedf4d1439104cc, 0x6944849f8d44d187, 0x4dbe80e8f415dfdc, 0x1df9173c6d047e75}, - {0xbe0b090e46076c2e, 0xdc964a5825b49df4, 0xc8c690008b31f4cc, 0x2a7eea60cbe9e9c2}, - {0x7e3ea7d6debb93ed, 0x697818afff9c8ff8, 0xbd716ed0d057327c, 0xb4a53cd8838ca03}, - }, - { - {0x9249570785f595ac, 0xa8baedefd054d755, 0x4e349f30983cb2d1, 0x20e038ae5219f06f}, - {0x1e6b0d84b6b0bd2b, 0x28036e399a182d83, 0x9b4db5cdc8f5900f, 0xba7d843e40009}, - {0xc1862aa768e1a9de, 0x134ee89ea258d84b, 0xa344c6a98af5c8e1, 0x35868f24584f89c0}, - }, - { - {0x6562561d6d2bd2eb, 0xe906eab7bfb25ce1, 0xdc3286360790ca24, 0x95cf9864fa2e99f}, - {0x8df04360bfee0f49, 0xf36da4b0797f28ab, 0x973b5df087ce6868, 0x31b4ebf5790f547a}, - {0x5236c69070d6a6cd, 0xe3483908bed7cd3a, 0x230cf521e8f636d5, 0x1369fed0b1ebdd4e}, - }, - { - {0x6b84b4d8a249ce56, 0xf8f9e37aee88a381, 0x547e20f39ea3ee67, 0x1a521535f4c4609a}, - {0xece3e35b95cf0b40, 0xc3f355a2343a9bba, 0x352dca283e1dc20, 0x18533c495c159ea5}, - {0x5c080eb0e667f655, 0xae7eedb84aaa82cf, 0xc40800efbbfb36e2, 0x23f8f08e412d848e}, - }, - { - {0xe47de2b666816c07, 0xfd084e96b59c227a, 0xffee4cb4adefb5b9, 0x27873596008bf329}, - {0x74c07063640d932f, 0xdcafa7d16923f8c6, 0x69cc607697b5fa58, 0x3fe8dcd350f158a0}, - {0x4685e7e0534a4487, 0x3e0a5a82c1308413, 0xe8f4882500745f38, 0x15d7152e439e3e39}, - }, - { - {0x1b6a574d8750bc73, 0x106eecce46abf1e6, 0xaac26d11ddaa2fa6, 0x38e31bc0f50b77a8}, - {0x46f4e9b5d03cc39d, 0xcc3f83cbed376830, 0x9b08a2cd1eb3c25c, 0x1b205334b2958429}, - {0xd58f58d5f1219de9, 0x1cfaa7547a262198, 0xcded38f37a2a880d, 0x177392b21a898be2}, - }, - { - {0xabc2d6caf40fda5a, 0xeb350f697f26ad45, 0x3a8945142b944356, 0x646f6d15a42f200}, - {0xff43256a693e8ab0, 0x2d305df7c836dcae, 0xccde78bd165aba3, 0x784cf8c1e09fd03}, - {0x11c0a75dfb1d6922, 0xa7dc5f890e8b9385, 0xaf784b2ec0758e11, 0xb79376b50d40562}, - }, - { - {0x4cfa43b93f239b43, 0x8465e6265d898268, 0x1288bcdb6fff50f4, 0x819462af6ba8c78}, - {0xba07b8ffdba328b0, 0x4215ac492cce28b3, 0x9730ec3e2f2188f3, 0x10bc9871d3004f71}, - {0x5a31626caca7283f, 0x40424e694cc63e9a, 0xcceb1adc2a52c6b9, 0x2836d9e7ccb5b686}, - }, - { - {0xf2191ab8935e3139, 0x6263e421438839a9, 0xf36d5611a925964c, 0x3ad254981c5584f}, - {0x77f3cbe4b7ec0506, 0x14cfd27cad91e7f6, 0xd66382bc65d30343, 0x11eb1499a7eb9296}, - {0x8306372b9fccfce6, 0xff3f90b389214f3f, 0x589837150e5e7261, 0x330673584db884bd}, - }, - { - {0xbf438550dc08ca8c, 0xa67d5b92e6b2d9f4, 0x45f1b4851f11355e, 0x3197089756209bf0}, - {0xa7bb2e56a3383876, 0xa1b85198d1a992d9, 0x807a2bb7e34327c6, 0x1a7be86ebc9ceb25}, - {0xb67db6d33a48b0df, 0x20bcebe6769fcc54, 0x2c5defebf8a107df, 0x3c0e75597f21e444}, - }, - { - {0x3ee09fdbfc3969f8, 0xfa1d3b39ae852fe9, 0xf9a75fb275dc4bf3, 0x2a38ad56c662e4c3}, - {0x436111724d967633, 0x7bc3452ae208f145, 0xfa8b9c79a56e7177, 0x3328b53b61a96c1a}, - {0x7dc685041c4a8de8, 0xcc8d3bf1000d5962, 0x53f0f1b8456b9659, 0xe5633a4ee33b43f}, - }, - { - {0x50e48fb72f31229f, 0xa5b753a3355553ad, 0x1c81ccd682c6dbf0, 0x6c795d332f94020}, - {0xf0fdbce25dad3d31, 0x9c588e128b3cebf0, 0x278767bad1a401ec, 0x12fd7107dacf168b}, - {0x98f200455814ae5c, 0x47f8009a5ae445bd, 0x487393e3ebc8077f, 0x3d579e85ebce0cba}, - }, - { - {0xe8df711446a2a238, 0xde4cc56b9510c04c, 0xb69991b66d096631, 0x1ab962f474f31f94}, - {0x994397076df00b58, 0x655b22de2fc1d376, 0x8c4152fcacaf0b18, 0x20051bcd8c1c3f37}, - {0xd66fe84e8d8d5bcb, 0xba022f54bb73200, 0xdaf17b9ad85c1d89, 0xd939c085418afd2}, - }, - { - {0xd5e63b74c211bc, 0xb12fc9c1def2e171, 0x44eaf0fd6faad3ea, 0x242c8eaf5e3f8025}, - {0xbf97706088f0ff2e, 0x1d8dad8a65750bd0, 0xc29b958d06fc399f, 0x134e81757cb8421e}, - {0x90be439afe7faf2, 0xc4b4762c8cc16bea, 0x1e477be4c4f40c9b, 0x23b4d50dc7ec40d7}, - }, - { - {0x333f64ebf7d2e7a8, 0x870b1f5dbdb11bdf, 0x74c9542dd65f4221, 0x128bb297ac5b8087}, - {0x74cdc264c1c32632, 0xcdbd7f0678ca09f9, 0xeb378a38bded711e, 0x1c4c18ced367bb10}, - {0x436cf961456330a9, 0x5261fdb10401ba02, 0x5aa07cfe8724969b, 0x17d4aa22d7539f30}, - }, - { - {0x22577a304a9a99c0, 0x26990766bceeaf3e, 0xf44a18d2965b75e6, 0x2b9ccb511447556b}, - {0xb4816bee4c57ea14, 0x657c7ff22284eddf, 0x80327f4b561a57a, 0x185d288b2163e408}, - {0x2521ae71bb3e92cd, 0xcfa6a3908f9422a4, 0xc5566b5d0cba3b6a, 0x19186ee34b32adf1}, - }, - { - {0x6ababe0d83a14804, 0x48a2976613fe9c87, 0x8fd28b1e6637a35f, 0x36be57a5b7dc101}, - {0x9409b310f8dedbd5, 0xdcb6ff2dd7ade6e8, 0x58ef424bfb1e96cf, 0x59c25a9e8435caa}, - {0x6017336865718144, 0x3b735147994d3174, 0x556dacb8916ce5fb, 0x6db68d040cf3894}, - }, - { - {0xfb28daa548eae196, 0xdee9f1fb48ad3a18, 0x8aeb7ea74f7458e0, 0x2f9a904f8eca76f4}, - {0x78ab93c53d27c0a9, 0x7cbd38a19659d91e, 0x6190fc4c6fcea287, 0x392493ffebdcf4db}, - {0xc288a18be7c7b29a, 0x293635495be4702a, 0x8eabeaa050c4e742, 0x3ee20e43c9a7e3a9}, - }, - { - {0xb247c20bce94d2fb, 0x7b37f102aba6dc41, 0x4e4cd6f2dfd06908, 0x2a4b7450c10e8656}, - {0xb8530701f1190812, 0x8852c8a7dd78c157, 0xef99612848a09ee6, 0x18cac72301419e17}, - {0x3bf72719696125f9, 0xa9153cf6b92ed66c, 0x5dee1004fa68e8ad, 0x2b0ab9d9c7146b8d}, - }, - { - {0x536e86c644632835, 0xfb528949c3d10378, 0x93cef66ee69cc174, 0xef7cc63c029b540}, - {0x3f71db10b88e45e1, 0x6a1cdfba155d75ba, 0x3ae6893f9c00830, 0x1f4aa1edaeea25af}, - {0x6c911d68b8bae9c7, 0xb562eb9132f9adcf, 0xb99552efd2922e09, 0x1aee619f6e53e5d1}, - }, - { - {0xc3e7eba538b57ce4, 0xe31fc856b301a0ed, 0x907bed9fd07a7f39, 0x2d8b156182efe6c2}, - {0x3c46848a7286379b, 0x8c1ce4abf2bdac01, 0xfe59adadfa57ab2d, 0x118d842df28ba098}, - {0x40346673db347d50, 0x9e9e286fbc221bac, 0x629f295d0d56a062, 0x2c7473af62ed3627}, - }, - { - {0x752c0e54b9084c5e, 0x9876503df35123f2, 0x4033dd4b36b302eb, 0x1f2f3ed1fdf6db7b}, - {0xc1aac2892f6ad5a0, 0xa4d2c62a12460d75, 0xfdfc27280cba16d8, 0x32e7b499b5afa89f}, - {0xa93b9c721205117, 0x29f32892dd66377a, 0x5db34e58446659b5, 0x35b9a957235ce56c}, - }, - { - {0x27dd8772ea8dd6fb, 0x7657580893377a80, 0x98116540d5d734fc, 0x1784ef3dbedaa7f1}, - {0x7ea4b4453558ad1e, 0xe79ae8a84479841f, 0x1448d360ba9dceaf, 0x29004bf2b27c1cc}, - {0x9be743f9caccf63, 0xf852240a936f7e9e, 0xb1cd6029e13842dd, 0x255bdfce8905f3d5}, - }, - { - {0x7415ee9f67631e70, 0x545553ffaf7d2592, 0xde51ae9194c9a7b2, 0x304409b176b5751d}, - {0x9c447ba5504d7b34, 0xfb288ee73506db89, 0x4cb32cefbc235f79, 0x3f2084c1c1605185}, - {0xdd24109730f8173c, 0x58b00f316d07a773, 0x1e86bdb19d121999, 0x3c46e8c04c88a74f}, - }, - { - {0x9ff193f33610856, 0x7cff32dc29fafc7f, 0xab1176764a90b2b5, 0x37a314e9261a12bc}, - {0xea6753fdcff09509, 0x4222dd5e1a66381d, 0x6056412c14d4667e, 0x30f19d0141776609}, - {0x383a756cdd6bbf4a, 0x4b314310043c1039, 0x7aa6b018a79ad7a4, 0x2d78d62918aa8e15}, - }, - { - {0x2c202fafd61e9da3, 0x89be41afc9c1f1fe, 0x15b6d718ea74a2d, 0x1c1c7eb84e510588}, - {0x342bbc7354bde7a5, 0xc995adfbe2005f6b, 0x85a618fbe9ccea3c, 0x3d61c03132b831b7}, - {0x84f0053a596c462a, 0x3725a512ef2e7da, 0x9866bda3e8d65025, 0x16307f53c31b9b2d}, - }, - { - {0xe11a11d7ad7c2941, 0xa196efe53885dac4, 0x401c98e5702a4b4d, 0x2627aedf841d2535}, - {0x6c137315f42a3d7, 0x1b27880c4b80acc2, 0xd2463e7af19c63f8, 0x1ac361c3ae9360d0}, - {0x9ca7acb3c1e8764c, 0xa3abf95002b63ec7, 0x607aec3d66927bd, 0x350322d135e4b5b0}, - }, - { - {0x8767a56f58823fb1, 0xa17115bf335777f7, 0x2d2d011c09bc4b6, 0x23f5c30c8bec1802}, - {0x469e5aee1e354cff, 0x19b662c5ee659a15, 0x8222b7d81ef2e3d0, 0x25dbe21f1dc14bbb}, - {0xcf3036e9bef51413, 0x2ec597011f15b75d, 0x1b6f15cf41987ffb, 0x243e4331eaa8ca3f}, - }, - { - {0x7e12d7264aa9d64a, 0x986866249a40df19, 0x224d9731f988d510, 0x3da1029b04d0699}, - {0x63ce9c82f26c2122, 0xd07b42737417e607, 0xdffe6c18b3e32c4e, 0xcb558a55e33635b}, - {0xa9e72e1bbb1e1ac6, 0x7c0eac490aa84fe, 0xc716b352d91ef297, 0x17c0df062139a3b0}, - }, - { - {0xb6e0e5acafd75f1b, 0xe79ccc9d178be022, 0xa62fb84a4594821, 0x118ff23cec0e9ab7}, - {0xdaeb6bb9649cc9ed, 0x2b1c328f5bb8662f, 0x5512487ef834c9ff, 0x10a6d8b760d8381f}, - {0x55bcd8a0925661ee, 0x92289bf6cb46afe5, 0xa2b1c38630374b57, 0x1a382c83ffa7d479}, - }, - { - {0x5b9ed41d83b22227, 0x861a12cf34e20309, 0x722187ecc9fb01cd, 0x3d7bb8d8fbbf19aa}, - {0x56b2351caaa77660, 0x5649f8afb77f8250, 0x179b134befc40c2a, 0x117b5ac7fab8a73b}, - {0xbb53d76efa39fb63, 0x3821ad8ab6648b10, 0x860e686568c98df, 0x181510039e8bf016}, - }, - { - {0xabcab07505b93cf, 0x4088c208ddc38a79, 0x60aa91fcf3d30a95, 0x1cca89ba50887f72}, - {0x756ea77ac464fb2f, 0xb54ae17c6bba044a, 0x3350ae0df3e90873, 0x186b9034baedae26}, - {0x813cc8de3ccd6501, 0x612bffa93d7579f9, 0x5ad42ea9bc5bbd6c, 0x123ed625db167d32}, - }, - { - {0x2db34a3c43a01e76, 0x93bf90bd39919618, 0xb62aafc5a062e6ec, 0x30e33d44bc2851c0}, - {0x74dcd4e07d98a23b, 0xb390d88ce8c1c12d, 0xc60d4855592f4f12, 0x3d3808ea888bc3ef}, - {0x6b6125132d3b6c9b, 0xefb93b37d8c98901, 0x5396ab9879f061f3, 0x26814970d99a4859}, - }, - { - {0x65a39dff4c093ac6, 0xdb8b03741b7d38b3, 0x34e5285eb2732099, 0xcffcab13b9c402}, - {0xba151ecf346e77e5, 0xdc944d4cedf21de6, 0xbf6157bdc8bf2df3, 0x39a726986b4d3042}, - {0x44150981f7bb214f, 0xdaf82667aa9df080, 0x4cb0e4251cbd837c, 0x96407a7f4c8919d}, - }, - { - {0xab327a1874a4376d, 0x2ac8b215b83ec21, 0x72ccc1310e756e19, 0x337f64158d29681d}, - {0xfdd547b12cd1c47c, 0xeda570d77efb35ef, 0xee673a9c5c5c6c24, 0x1069938e1c2d5fb8}, - {0xe18e30b72b41cebd, 0x9530ddc35a81e36e, 0xcb076c0372dd1f10, 0x1a6810a2f1aee9a3}, - }, - { - {0xf42b4184e45ef9b0, 0x621c9c9f4b7805bb, 0xe64a4966c57c625e, 0x331dfaac4fca1afe}, - {0x5745585e5aa8e18, 0x48138c500616daa7, 0x740880dd14d57c7b, 0x621e4237f79bc67}, - {0x7752004d293d5b5d, 0x32176da95d737cf5, 0xe14bb9ef4281cf03, 0x56e679688dec9b0}, - }, - { - {0xcf96c57a6c6dced2, 0x9d0641008bc1e8e6, 0xaf7c8a61f00aea43, 0x3de7cc921f006f35}, - {0xe5a284274906c87c, 0x3f57a5c227ad9ef7, 0x8ca3d4e109a701b9, 0x23fa54fa0717813}, - {0xa418bb283bcf6e4c, 0xfe2037c5295b505d, 0xcaa0956e946f4a29, 0x2a042a0cc94e6eb7}, - }, - { - {0xd8df14778b795fec, 0x16c27f664e2ea362, 0xe24b2f6edd5eaebe, 0x14c903e18d6d1fc3}, - {0x89586ac5b4450805, 0xadc6ee91f14ae921, 0xc6bc4c3b0f873a03, 0x351fccf49d14543a}, - {0xd3601422d37aaa9e, 0x988c203077dd68e9, 0x1cae7a1d3150e958, 0x1292d11437a1acd4}, - }, - { - {0xe53e955d71efa6c, 0x8fe1b41936d8c2e, 0xc1115be6796700ba, 0x16f2577444f333ac}, - {0xb46fdc6c76b91715, 0xba7c98748d26f41a, 0x8a767b731b64d9a2, 0x380f78e27ff89d8f}, - {0xfd9976c4488e5f16, 0xbeaf3cb1cf0cfc03, 0xf2bc02883a339b2a, 0x3a669a9fec53277f}, - }, - { - {0x7489c5648c85dee1, 0x7f9d020bd71f0bc3, 0xcf347020818fd255, 0x34ce3d2873ef623b}, - {0x82891abb666f3ff4, 0x370d13492155070d, 0x26c0426048d99ec2, 0x89cceef0d956cc}, - {0xf161875b3c921a95, 0xe0ee4bd7518d961a, 0xcd3614b6acaf6d93, 0x27ef7c723667b755}, - }, - { - {0x13fb2dcf933fd4d, 0x103f7deb9f64a5aa, 0x26d375314a7a8189, 0x1fb433f9d0d1a1af}, - {0xa49a8d2583ef3bdd, 0x9a7a627ea2417df1, 0x93277db6c1298ce4, 0x224efdd22b53fe03}, - {0xd9ef2ab6918b48ed, 0xab7f9a26705488c0, 0xc179467a22565381, 0x3c8192acf2659bbf}, - }, - { - {0x90c3c01685741695, 0x8fc7d42cbdf62efb, 0x8ca74bdebec3a42b, 0x2d07192135436805}, - {0x597f91232510722, 0xb6ff30a1505c4ea8, 0xdd22fd456a942afe, 0x1cb7fdcfaa9bdd05}, - {0xdcf520384f1ddaf0, 0xeb0ee12c33953a63, 0x9a3a10c7e3aa6f41, 0x1471506df8d986b4}, - }, - { - {0xcd605e2791e6a5e5, 0x1c27ce94b83f068f, 0xb172e53c549a3c12, 0x21f264ce80eef855}, - {0xfe4a5caf09cd178f, 0xd76b6393a8b8597f, 0x828a31309599f1fa, 0x1d7eb56ca9c920f6}, - {0x589bdbc5eb3cc1fc, 0xa5ab6823129a3ed3, 0x1f5b9bd5aca5d3ec, 0x64aae35f2e4b6bc}, - }, - { - {0x365002f75230793, 0x2b8d834bd6a4c78f, 0x7f445a46d203a93d, 0x265c579246ab3106}, - {0x4983fb4db3ca5acd, 0x770c07654eeefaab, 0x54456b57fa1fd5af, 0xb92cdbcf718c353}, - {0x1ac57ac76f928fe, 0x816c4d52b670680, 0x39b8598cba83c07d, 0x29af1b8a7d9ed796}, - }, - { - {0x715eb17f6f71404f, 0xd081dca0cad01695, 0xdeefdf16929d4947, 0x3d7f767198a2e29b}, - {0xebfb13feb0205761, 0x73e014ef38a3d8cb, 0x113bd31d16c16db7, 0x288eacb7eaa4d63c}, - {0x5d22751f1f2c937d, 0x50cc30867fe04f68, 0x70917ec415d4ac2c, 0x58c8b7c2b87e78b}, - }, - }, - mdsMatrix: [][]*fp.Fp{ - { - {0x19ebb0733ab608d5, 0xba29ddd056f8255c, 0x90b26832e301952d, 0xd393e38c7a5d0ab}, - {0x1370915e16c94656, 0xa9d4f14bbd2ea831, 0xbe629fe93a27e612, 0x21571a7cc32e18af}, - {0xb34a71b4f799ea19, 0x9685275173ff9b6b, 0xc2aa354b7f11d698, 0x15691c24c0a9f088}, - }, - { - {0xae932a9d486aface, 0xbef0293e7653db35, 0x279408c4d244c0d1, 0x39dd8040ea0c8d80}, - {0x9d32fbdbaf9bbe27, 0x999e1c5168806efa, 0x7d5f270b3cb077a8, 0xb4ac0738805f8de}, - {0xcfc1e61e0bcf9d5f, 0x12346d0d47576a9, 0xdbd1b0da710c7b5, 0x1db48905ceecc479}, - }, - { - {0x89dde65da2c627b, 0x873534c4aaf1243a, 0xa4f76bf3e5b626c5, 0x22a75f7cd3cad9d3}, - {0xb58ea56557361c3b, 0xd6cbb2cb0bc99acb, 0x5fee1fb5b71b86dd, 0x11d87bbca8e20fbe}, - {0x1d511fe638baa5c8, 0x7b6c7932776e1032, 0x45b27ee070531360, 0x19eb7c902ac90c5}, - }, - }, - spongeIv: [][]*fp.Fp{ - // Testnet - { - {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}, - }, - // Mainnet - { - {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}, - }, - }, - }, -} - -func (ctx *Context) Init(pType Permutation, networkId NetworkType) *Context { - if ctx == nil { - return nil - } - if pType != ThreeW && pType != FiveW && pType != Three { - return nil - } - if networkId != TestNet && networkId != MainNet && networkId != NullNet { - return nil - } - - ctx.pType = pType - ctx.spongeWidth = contexts[pType].spongeWidth - ctx.spongeRate = contexts[pType].spongeRate - ctx.fullRounds = contexts[pType].fullRounds - ctx.sBox = contexts[pType].sBox - ctx.roundKeys = contexts[pType].roundKeys - ctx.mdsMatrix = contexts[pType].mdsMatrix - ctx.spongeIv = contexts[pType].spongeIv - ctx.state = make([]*fp.Fp, contexts[pType].spongeWidth) - if networkId != NullNet { - iv := contexts[pType].spongeIv[networkId] - for i := range iv { - ctx.state[i] = new(fp.Fp).Set(iv[i]) - } - } else { - for i := range ctx.state { - ctx.state[i] = new(fp.Fp).SetZero() - } - } - ctx.absorbed = 0 - return ctx -} - -func (ctx *Context) Update(fields []*fp.Fp) { - for _, f := range fields { - if ctx.absorbed == ctx.spongeRate { - ctx.pType.Permute(ctx) - ctx.absorbed = 0 - } - ctx.state[ctx.absorbed].Add(ctx.state[ctx.absorbed], f) - ctx.absorbed++ - } -} - -func (ctx *Context) Digest() *fq.Fq { - ctx.pType.Permute(ctx) - res := ctx.state[0].ToRaw() - return new(fq.Fq).SetRaw(&res) -} diff --git a/crypto/signatures/schnorr/mina/poseidon_hash_test.go b/crypto/signatures/schnorr/mina/poseidon_hash_test.go deleted file mode 100644 index b79251d1e..000000000 --- a/crypto/signatures/schnorr/mina/poseidon_hash_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "encoding/hex" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -func TestPoseidonHash(t *testing.T) { - // Reference https://github.com/o1-labs/proof-systems/blob/master/oracle/tests/test_vectors/3w.json - testVectors := []struct { - input []*fp.Fp - output *fq.Fq - }{ - { - input: []*fp.Fp{}, - output: hexToFq("1b3251b6912d82edc78bbb0a5c88f0c6fde1781bc3e654123fa6862a4c63e617"), - }, - { - input: []*fp.Fp{ - hexToFp("df698e389c6f1987ffe186d806f8163738f5bf22e8be02572cce99dc6a4ab030"), - }, - output: hexToFq("f9b1b6c5f8c98017c6b35ac74bc689b6533d6dbbee1fd868831b637a43ea720c"), - }, - { - input: []*fp.Fp{ - hexToFp("56b648a5a85619814900a6b40375676803fe16fb1ad2d1fb79115eb1b52ac026"), - hexToFp("f26a8a03d9c9bbd9c6b2a1324d2a3f4d894bafe25a7e4ad1a498705f4026ff2f"), - }, - output: hexToFq("7a556e93bcfbd27b55867f533cd1df293a7def60dd929a086fdd4e70393b0918"), - }, - { - input: []*fp.Fp{ - hexToFp("075c41fa23e4690694df5ded43624fd60ab7ee6ec6dd48f44dc71bc206cecb26"), - hexToFp("a4e2beebb09bd02ad42bbccc11051e8262b6ef50445d8382b253e91ab1557a0d"), - hexToFp("7dfc23a1242d9c0d6eb16e924cfba342bb2fccf36b8cbaf296851f2e6c469639"), - }, - output: hexToFq("f94b39a919aab06f43f4a4b5a3e965b719a4dbd2b9cd26d2bba4197b10286b35"), - }, - { - input: []*fp.Fp{ - hexToFp("a1a659b14e80d47318c6fcdbbd388de4272d5c2815eb458cf4f196d52403b639"), - hexToFp("5e33065d1801131b64d13038ff9693a7ef6283f24ec8c19438d112ff59d50f04"), - hexToFp("38a8f4d0a9b6d0facdc4e825f6a2ba2b85401d5de119bf9f2bcb908235683e06"), - hexToFp("3456d0313a30d7ccb23bd71ed6aa70ab234dad683d8187b677aef73f42f4f52e"), - }, - output: hexToFq("cc1ccfa964fd6ef9ff1994beb53cfce9ebe1212847ce30e4c64f0777875aec34"), - }, - { - input: []*fp.Fp{ - hexToFp("bccfee48dc76bb991c97bd531cf489f4ee37a66a15f5cfac31bdd4f159d4a905"), - hexToFp("2d106fb21a262f85fd400a995c6d74bad48d8adab2554046871c215e585b072b"), - hexToFp("8300e93ee8587956534d0756bb2aa575e5878c670cff5c8e3e55c62632333c06"), - hexToFp("879c32da31566f6d16afdefff94cba5260fec1057e97f19fc9a61dc2c54a6417"), - hexToFp("9c0aa6e5501cfb2d08aeaea5b3cddac2c9bee85d13324118b44bafb63a59611e"), - }, - output: hexToFq("cf7b9c2128f0e2c0fed4e1eca8d5954b629640c2458d24ba238c1bd3ccbc8e12"), - }, - } - for _, tv := range testVectors { - ctx := new(Context).Init(ThreeW, NetworkType(NullNet)) - ctx.Update(tv.input) - res := ctx.Digest() - require.True(t, res.Equal(tv.output)) - } - testVectors = []struct { - input []*fp.Fp - output *fq.Fq - }{ - { - input: []*fp.Fp{ - hexToFp("0f48c65bd25f85f3e4ea4efebeb75b797bd743603be04b4ead845698b76bd331"), - hexToFp("0f48c65bd25f85f3e4ea4efebeb75b797bd743603be04b4ead845698b76bd331"), - hexToFp("f34b505e1a05ecfb327d8d664ff6272ddf5cc1f69618bb6a4407e9533067e703"), - hexToFp("0f48c65bd25f85f3e4ea4efebeb75b797bd743603be04b4ead845698b76bd331"), - hexToFp("ac7cb9c568955737eca56f855954f394cc6b05ac9b698ba3d974f029177cb427"), - hexToFp("010141eca06991fe68dcbd799d93037522dc6c4dead1d77202e8c2ea8f5b1005"), - hexToFp("0300000000000000010000000000000090010000204e0000021ce8d0d2e64012"), - hexToFp("9b030903692b6b7b030000000000000000000000000000000000800100000000"), - hexToFp("000000a800000000000000000000000000000000000000000000000000000000"), - }, - output: &fq.Fq{ - 1348483115953159504, - 14115862092770957043, - 15858311826851986539, - 1644043871107534594, - }, - }, - } - for _, tv := range testVectors { - ctx := new(Context).Init(ThreeW, NetworkType(MainNet)) - ctx.Update(tv.input) - res := ctx.Digest() - require.True(t, res.Equal(tv.output)) - } -} - -func hexToFp(s string) *fp.Fp { - var buffer [32]byte - input, _ := hex.DecodeString(s) - copy(buffer[:], input) - f, _ := new(fp.Fp).SetBytes(&buffer) - return f -} - -func hexToFq(s string) *fq.Fq { - var buffer [32]byte - input, _ := hex.DecodeString(s) - copy(buffer[:], input) - f, _ := new(fq.Fq).SetBytes(&buffer) - return f -} diff --git a/crypto/signatures/schnorr/mina/roinput.go b/crypto/signatures/schnorr/mina/roinput.go deleted file mode 100644 index 4aa99966e..000000000 --- a/crypto/signatures/schnorr/mina/roinput.go +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -// Handles the packing of bits and fields according to Mina spec -type roinput struct { - fields []*fp.Fp - bits *BitVector -} - -var conv = map[bool]int{ - true: 1, - false: 0, -} - -func (r *roinput) Init(fields int, bytes int) *roinput { - r.fields = make([]*fp.Fp, 0, fields) - r.bits = NewBitVector(make([]byte, bytes), 0) - return r -} - -func (r *roinput) Clone() *roinput { - t := new(roinput) - t.fields = make([]*fp.Fp, len(r.fields)) - for i, f := range r.fields { - t.fields[i] = new(fp.Fp).Set(f) - } - buffer := r.bits.Bytes() - data := make([]byte, len(buffer)) - copy(data, buffer) - t.bits = NewBitVector(data, r.bits.Length()) - return t -} - -func (r *roinput) AddFp(fp *fp.Fp) { - r.fields = append(r.fields, fp) -} - -func (r *roinput) AddFq(fq *fq.Fq) { - scalar := fq.ToRaw() - // Mina handles fields as 255 bit numbers - // with each field we lose a bit - for i := 0; i < 255; i++ { - limb := i / 64 - idx := i % 64 - b := (scalar[limb] >> idx) & 1 - r.bits.Append(byte(b)) - } -} - -func (r *roinput) AddBit(b bool) { - r.bits.Append(byte(conv[b])) -} - -func (r *roinput) AddBytes(input []byte) { - for _, b := range input { - for i := 0; i < 8; i++ { - r.bits.Append(byte((b >> i) & 1)) - } - } -} - -func (r *roinput) AddUint32(x uint32) { - for i := 0; i < 32; i++ { - r.bits.Append(byte((x >> i) & 1)) - } -} - -func (r *roinput) AddUint64(x uint64) { - for i := 0; i < 64; i++ { - r.bits.Append(byte((x >> i) & 1)) - } -} - -func (r roinput) Bytes() []byte { - out := make([]byte, (r.bits.Length()+7)/8+32*len(r.fields)) - res := NewBitVector(out, 0) - // Mina handles fields as 255 bit numbers - // with each field we lose a bit - for _, f := range r.fields { - buf := f.ToRaw() - for i := 0; i < 255; i++ { - limb := i / 64 - idx := i % 64 - b := (buf[limb] >> idx) & 1 - res.Append(byte(b)) - } - } - for i := 0; i < r.bits.Length(); i++ { - res.Append(r.bits.Element(i)) - } - return out -} - -func (r roinput) Fields() []*fp.Fp { - fields := make([]*fp.Fp, 0, len(r.fields)+r.bits.Length()/256) - for _, f := range r.fields { - fields = append(fields, new(fp.Fp).Set(f)) - } - const maxChunkSize = 254 - bitsConsumed := 0 - bitIdx := 0 - - for bitsConsumed < r.bits.Length() { - var chunk [4]uint64 - - remaining := r.bits.Length() - bitsConsumed - var chunkSizeInBits int - if remaining > maxChunkSize { - chunkSizeInBits = maxChunkSize - } else { - chunkSizeInBits = remaining - } - - for i := 0; i < chunkSizeInBits; i++ { - limb := i >> 6 - idx := i & 0x3F - b := r.bits.Element(bitIdx) - chunk[limb] |= uint64(b) << idx - bitIdx++ - } - fields = append(fields, new(fp.Fp).SetRaw(&chunk)) - bitsConsumed += chunkSizeInBits - } - - return fields -} diff --git a/crypto/signatures/schnorr/mina/signature.go b/crypto/signatures/schnorr/mina/signature.go deleted file mode 100644 index 1fbe8fea3..000000000 --- a/crypto/signatures/schnorr/mina/signature.go +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fp" - "github.com/sonr-io/sonr/crypto/core/curves/native/pasta/fq" -) - -// Signature is a Mina compatible signature either for payment or delegation -type Signature struct { - R *fp.Fp - S *fq.Fq -} - -func (sig Signature) MarshalBinary() ([]byte, error) { - var buf [64]byte - rx := sig.R.Bytes() - s := sig.S.Bytes() - copy(buf[:32], rx[:]) - copy(buf[32:], s[:]) - return buf[:], nil -} - -func (sig *Signature) UnmarshalBinary(input []byte) error { - if len(input) != 64 { - return fmt.Errorf("invalid byte sequence") - } - var buf [32]byte - copy(buf[:], input[:32]) - rx, err := new(fp.Fp).SetBytes(&buf) - if err != nil { - return err - } - copy(buf[:], input[32:]) - s, err := new(fq.Fq).SetBytes(&buf) - if err != nil { - return err - } - sig.R = rx - sig.S = s - return nil -} diff --git a/crypto/signatures/schnorr/mina/txn.go b/crypto/signatures/schnorr/mina/txn.go deleted file mode 100644 index 67efec5bb..000000000 --- a/crypto/signatures/schnorr/mina/txn.go +++ /dev/null @@ -1,224 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package mina - -import ( - "encoding/binary" - "encoding/json" - "fmt" - - "github.com/cosmos/btcutil/base58" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// Transaction is a Mina transaction for payments or delegations -type Transaction struct { - Fee, FeeToken uint64 - FeePayerPk *PublicKey - Nonce, ValidUntil uint32 - Memo string - Tag [3]bool - SourcePk, ReceiverPk *PublicKey - TokenId, Amount uint64 - Locked bool - NetworkId NetworkType -} - -type txnJson struct { - Common txnCommonJson - Body [2]any -} - -type txnCommonJson struct { - Fee uint64 `json:"fee"` - FeeToken uint64 `json:"fee_token"` - FeePayerPk string `json:"fee_payer_pk"` - Nonce uint32 `json:"nonce"` - ValidUntil uint32 `json:"valid_until"` - Memo string `json:"memo"` - NetworkId uint8 `json:"network_id"` -} - -type txnBodyPaymentJson struct { - SourcePk string `json:"source_pk"` - ReceiverPk string `json:"receiver_pk"` - TokenId uint64 `json:"token_id"` - Amount uint64 `json:"amount"` -} - -type txnBodyDelegationJson struct { - Delegator string `json:"delegator"` - NewDelegate string `json:"new_delegate"` -} - -func (txn *Transaction) MarshalBinary() ([]byte, error) { - mapper := map[bool]byte{ - true: 1, - false: 0, - } - out := make([]byte, 175) - binary.LittleEndian.PutUint64(out, txn.Fee) - binary.LittleEndian.PutUint64(out[8:16], txn.FeeToken) - copy(out[16:48], txn.FeePayerPk.value.ToAffineCompressed()) - binary.LittleEndian.PutUint32(out[48:52], txn.Nonce) - binary.LittleEndian.PutUint32(out[52:56], txn.ValidUntil) - - out[56] = 0x01 - out[57] = byte(len(txn.Memo)) - copy(out[58:90], txn.Memo[:]) - out[90] = mapper[txn.Tag[0]] - out[91] = mapper[txn.Tag[1]] - out[92] = mapper[txn.Tag[2]] - copy(out[93:125], txn.SourcePk.value.ToAffineCompressed()) - copy(out[125:157], txn.ReceiverPk.value.ToAffineCompressed()) - binary.LittleEndian.PutUint64(out[157:165], txn.TokenId) - binary.LittleEndian.PutUint64(out[165:173], txn.Amount) - out[173] = mapper[txn.Locked] - out[174] = byte(txn.NetworkId) - return out, nil -} - -func (txn *Transaction) UnmarshalBinary(input []byte) error { - mapper := map[byte]bool{ - 1: true, - 0: false, - } - if len(input) < 175 { - return fmt.Errorf("invalid byte sequence") - } - feePayerPk := new(PublicKey) - sourcePk := new(PublicKey) - receiverPk := new(PublicKey) - err := feePayerPk.UnmarshalBinary(input[16:48]) - if err != nil { - return err - } - err = sourcePk.UnmarshalBinary(input[93:125]) - if err != nil { - return err - } - err = receiverPk.UnmarshalBinary(input[125:157]) - if err != nil { - return err - } - txn.Fee = binary.LittleEndian.Uint64(input[:8]) - txn.FeeToken = binary.LittleEndian.Uint64(input[8:16]) - txn.FeePayerPk = feePayerPk - txn.Nonce = binary.LittleEndian.Uint32(input[48:52]) - txn.ValidUntil = binary.LittleEndian.Uint32(input[52:56]) - txn.Memo = string(input[58 : 58+input[57]]) - txn.Tag[0] = mapper[input[90]] - txn.Tag[1] = mapper[input[91]] - txn.Tag[2] = mapper[input[92]] - txn.SourcePk = sourcePk - txn.ReceiverPk = receiverPk - txn.TokenId = binary.LittleEndian.Uint64(input[157:165]) - txn.Amount = binary.LittleEndian.Uint64(input[165:173]) - txn.Locked = mapper[input[173]] - txn.NetworkId = NetworkType(input[174]) - return nil -} - -func (txn *Transaction) UnmarshalJSON(input []byte) error { - var t txnJson - err := json.Unmarshal(input, &t) - if err != nil { - return err - } - strType, ok := t.Body[0].(string) - if !ok { - return fmt.Errorf("unexpected type") - } - memo, _, err := base58.CheckDecode(t.Common.Memo) - if err != nil { - return err - } - switch strType { - case "Payment": - b, ok := t.Body[1].(txnBodyPaymentJson) - if !ok { - return fmt.Errorf("unexpected type") - } - feePayerPk := new(PublicKey) - err = feePayerPk.ParseAddress(b.SourcePk) - if err != nil { - return err - } - receiverPk := new(PublicKey) - err = receiverPk.ParseAddress(b.ReceiverPk) - if err != nil { - return nil - } - txn.FeePayerPk = feePayerPk - txn.ReceiverPk = receiverPk - case "Stake_delegation": - bType, ok := t.Body[1].([2]any) - if !ok { - return fmt.Errorf("unexpected type") - } - delegateType, ok := bType[0].(string) - if !ok { - return fmt.Errorf("unexpected type") - } - if delegateType == "Set_delegate" { - b, ok := bType[1].(txnBodyDelegationJson) - if !ok { - return fmt.Errorf("unexpected type") - } - feePayerPk := new(PublicKey) - err = feePayerPk.ParseAddress(b.Delegator) - if err != nil { - return err - } - receiverPk := new(PublicKey) - err = receiverPk.ParseAddress(b.NewDelegate) - if err != nil { - return err - } - txn.FeePayerPk = feePayerPk - txn.ReceiverPk = receiverPk - } else { - return fmt.Errorf("unexpected type") - } - default: - return fmt.Errorf("unexpected type") - } - txn.Memo = string(memo[2 : 2+memo[1]]) - sourcePk := new(PublicKey) - sourcePk.value = new(curves.Ep).Set(txn.FeePayerPk.value) - txn.Fee = t.Common.Fee - txn.FeeToken = t.Common.FeeToken - txn.Nonce = t.Common.Nonce - txn.ValidUntil = t.Common.ValidUntil - txn.NetworkId = NetworkType(t.Common.NetworkId) - return nil -} - -func (txn Transaction) addRoInput(input *roinput) { - input.AddFp(txn.FeePayerPk.value.X()) - input.AddFp(txn.SourcePk.value.X()) - input.AddFp(txn.ReceiverPk.value.X()) - - input.AddUint64(txn.Fee) - input.AddUint64(txn.FeeToken) - input.AddBit(txn.FeePayerPk.value.Y().IsOdd()) - input.AddUint32(txn.Nonce) - input.AddUint32(txn.ValidUntil) - memo := [34]byte{0x01, byte(len(txn.Memo))} - copy(memo[2:], txn.Memo) - input.AddBytes(memo[:]) - for _, b := range txn.Tag { - input.AddBit(b) - } - - input.AddBit(txn.SourcePk.value.Y().IsOdd()) - input.AddBit(txn.ReceiverPk.value.Y().IsOdd()) - input.AddUint64(txn.TokenId) - input.AddUint64(txn.Amount) - input.AddBit(txn.Locked) -} diff --git a/crypto/signatures/schnorr/nem/ed25519_keccak.go b/crypto/signatures/schnorr/nem/ed25519_keccak.go deleted file mode 100644 index c74673866..000000000 --- a/crypto/signatures/schnorr/nem/ed25519_keccak.go +++ /dev/null @@ -1,323 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// This file implements the Ed25519 signature algorithm. See -// https://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the “seed”. -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. - -package nem - -import ( - "bytes" - "crypto" - cryptorand "crypto/rand" - "fmt" - "io" - - "filippo.io/edwards25519" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/internal" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Bytes returns the publicKey in byte array -func (p PublicKey) Bytes() []byte { - return p -} - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[32:]) - return PublicKey(publicKey) -} - -func Keccak512(data []byte) ([]byte, error) { - k512 := sha3.NewLegacyKeccak512() - _, err := k512.Write(data) - if err != nil { - return nil, err - } - return k512.Sum(nil), nil -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:32]) - return seed -} - -// Sign signs the given message with priv. -// Ed25519 performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to -// indicate the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (priv PrivateKey) Sign( - rand io.Reader, - message []byte, - opts crypto.SignerOpts, -) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, fmt.Errorf("ed25519: cannot sign hashed message") - } - sig, err := Sign(priv, message) - if err != nil { - return nil, err - } - return sig, nil -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptorand.Reader - } - - seed := make([]byte, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey, err := NewKeyFromSeed(seed) - if err != nil { - return nil, nil, err - } - publicKey := make([]byte, PublicKeySize) - copy(publicKey, privateKey[32:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) (PrivateKey, error) { - // Outline the function body so that the returned key can be stack-allocated. - privateKey := make([]byte, PrivateKeySize) - err := newKeyFromSeed(privateKey, seed) - if err != nil { - return nil, err - } - return privateKey, nil -} - -func newKeyFromSeed(privateKey, seed []byte) error { - if l := len(seed); l != SeedSize { - return fmt.Errorf("ed25519: bad seed length: %d", l) - } - - // Weird required step to get compatibility with the NEM test vectors - // Have to reverse the bytes from the given seed - digest, err := Keccak512(internal.ReverseScalarBytes(seed)) - if err != nil { - return err - } - - sc, err := edwards25519.NewScalar().SetBytesWithClamping(digest[:32]) - if err != nil { - return err - } - - A := edwards25519.Point{} - A.ScalarBaseMult(sc) - publicKeyBytes := A.Bytes() - - copy(privateKey, seed) - copy(privateKey[32:], publicKeyBytes[:]) - return nil -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) ([]byte, error) { - // Outline the function body so that the returned signature can be - // stack-allocated. - signature := make([]byte, SignatureSize) - err := sign(signature, privateKey, message) - if err != nil { - return nil, err - } - return signature, nil -} - -func sign(signature, privateKey, message []byte) error { - if l := len(privateKey); l != PrivateKeySize { - return fmt.Errorf("ed25519: bad private key length: %d", l) - } - - seed := privateKey[:32] - digest, err := Keccak512(internal.ReverseScalarBytes(seed)) - if err != nil { - return err - } - - // H(seed) ie. privkey - expandedSecretKey := digest[:32] - sc, err := edwards25519.NewScalar().SetBytesWithClamping(expandedSecretKey) - if err != nil { - return err - } - - // r = H(H(seed) + msg) - hEngine := sha3.NewLegacyKeccak512() - _, err = hEngine.Write(digest[32:]) - if err != nil { - return err - } - - _, err = hEngine.Write(message) - if err != nil { - return err - } - - var hOut1 [64]byte - hEngine.Sum(hOut1[:0]) - - // hash output -> scalar - // Take 64 byte output from keccak512 so need to set bytes as long - r, err := edwards25519.NewScalar().SetUniformBytes(hOut1[:]) - if err != nil { - return err - } - - // R = r*G - R := edwards25519.Point{} - R.ScalarBaseMult(r) - RBytes := R.Bytes() - - // s = H(R + pubkey + msg) - hEngine.Reset() - _, err = hEngine.Write(RBytes) - if err != nil { - return err - } - - _, err = hEngine.Write(privateKey[32:]) - if err != nil { - return err - } - - _, err = hEngine.Write(message) - if err != nil { - return err - } - - var hOut2 [64]byte - hEngine.Sum(hOut2[:0]) - - // hash output -> scalar - // Take 64 byte output from keccak512 so need to set bytes as long - h, err := edwards25519.NewScalar().SetUniformBytes(hOut2[:]) - if err != nil { - return err - } - - // s = (r + h * privKey) - s := edwards25519.NewScalar().MultiplyAdd(h, sc, r) - - copy(signature[:], RBytes) - copy(signature[32:], s.Bytes()) - - return nil -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -// Previously publicKey is of type PublicKey -func Verify(publicKey PublicKey, message, sig []byte) (bool, error) { - if l := len(publicKey); l != PublicKeySize { - return false, fmt.Errorf("ed25519: bad public key length: %d", l) - } - - if len(sig) != SignatureSize || sig[63]&224 != 0 { - return false, fmt.Errorf("ed25519: bad signature size: %d", len(sig)) - } - - RBytes := sig[:32] - sBytes := sig[32:] - - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], publicKey) - - A := edwards25519.Point{} - _, err := A.SetBytes(publicKeyBytes[:]) - if err != nil { - return false, err - } - - negA := edwards25519.Point{} - negA.Negate(&A) - - // h = H(R + pubkey + msg) - hEngine := sha3.NewLegacyKeccak512() - _, err = hEngine.Write(RBytes) - if err != nil { - return false, err - } - - _, err = hEngine.Write(publicKeyBytes[:]) - if err != nil { - return false, err - } - - _, err = hEngine.Write(message) - if err != nil { - return false, err - } - - var hOut1 [64]byte - hEngine.Sum(hOut1[:0]) - - // hash output -> scalar - // Take 64 byte output from keccak512 so need to set bytes as long - h, err := edwards25519.NewScalar().SetUniformBytes(hOut1[:]) - if err != nil { - return false, err - } - - // s was generated in sign so can set as canonical - s, err := edwards25519.NewScalar().SetCanonicalBytes(sBytes) - if err != nil { - return false, err - } - - // R' = s*G - h*Pubkey = h*negPubkey + s*G - RPrime := edwards25519.Point{} - RPrime.VarTimeDoubleScalarBaseMult(h, &negA, s) - RPrimeBytes := RPrime.Bytes() - - // Check R == R' - return bytes.Equal(RBytes, RPrimeBytes), nil -} diff --git a/crypto/signatures/schnorr/nem/ed25519_keccak_test.go b/crypto/signatures/schnorr/nem/ed25519_keccak_test.go deleted file mode 100755 index 39e0d6dad..000000000 --- a/crypto/signatures/schnorr/nem/ed25519_keccak_test.go +++ /dev/null @@ -1,190 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package nem - -import ( - "bytes" - "encoding/hex" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" -) - -type KeyPair struct { - Privkey string `json:"privateKey"` - Pubkey string `json:"publicKey"` -} - -type TestSig struct { - Privkey string `json:"privateKey"` - Pubkey string `json:"publicKey"` - Data string `json:"data"` - Length int `json:"length"` - Sig string `json:"signature"` -} - -// NOTE: NEM provides no test vectors for Keccak512, but has test vectors for Keccak256 -// We use Keccak256 and 512 in the exact same manner, so ensuring this test passes -// gives decent confidence in our Keccak512 use as well -func TestKeccak256SanityCheck(t *testing.T) { - data := "A6151D4904E18EC288243028CEDA30556E6C42096AF7150D6A7232CA5DBA52BD2192E23DAA5FA2BEA3D4BD95EFA2389CD193FCD3376E70A5C097B32C1C62C80AF9D710211545F7CDDDF63747420281D64529477C61E721273CFD78F8890ABB4070E97BAA52AC8FF61C26D195FC54C077DEF7A3F6F79B36E046C1A83CE9674BA1983EC2FB58947DE616DD797D6499B0385D5E8A213DB9AD5078A8E0C940FF0CB6BF92357EA5609F778C3D1FB1E7E36C35DB873361E2BE5C125EA7148EFF4A035B0CCE880A41190B2E22924AD9D1B82433D9C023924F2311315F07B88BFD42850047BF3BE785C4CE11C09D7E02065D30F6324365F93C5E7E423A07D754EB314B5FE9DB4614275BE4BE26AF017ABDC9C338D01368226FE9AF1FB1F815E7317BDBB30A0F36DC69" - toMatch := "4E9E79AB7434F6C7401FB3305D55052EE829B9E46D5D05D43B59FEFB32E9A619" - toMatchBytes, err := hex.DecodeString(toMatch) - require.NoError(t, err) - dataBytes, err := hex.DecodeString(data) - require.NoError(t, err) - k256 := sha3.NewLegacyKeccak256() - _, err = k256.Write(dataBytes) - require.NoError(t, err) - var hashed []byte - hashed = k256.Sum(hashed) - require.Equal(t, hashed, toMatchBytes) -} - -// Test that the pubkey can get derived correctly from privkey -func TestPrivToPubkey(t *testing.T) { - testVectors := GetPrivToPubkeyTestCases() - - for _, pair := range testVectors { - privkeyBytes, err := hex.DecodeString(pair.Privkey) - require.NoError(t, err) - pubkeyBytes, err := hex.DecodeString(pair.Pubkey) - require.NoError(t, err) - - privKeyCalced, err := NewKeyFromSeed(privkeyBytes) - require.NoError(t, err) - - pubKeyCalced := privKeyCalced.Public().(PublicKey) - - require.Equal(t, pubKeyCalced.Bytes(), pubkeyBytes) - } -} - -// Test that we can: -// Get pubkey from privkey -// Obtain the correct signature -// Verify the test vector provided signature -func TestSigs(t *testing.T) { - testVectors := GetSigTestCases() - - for _, ts := range testVectors { - // Test priv -> pubkey again - privkeyBytes, err := hex.DecodeString(ts.Privkey) - require.NoError(t, err) - pubkeyBytes, err := hex.DecodeString(ts.Pubkey) - require.NoError(t, err) - - privKeyCalced, err := NewKeyFromSeed(privkeyBytes) - require.NoError(t, err) - - pubKeyCalced := privKeyCalced.Public().(PublicKey) - - require.True(t, bytes.Equal(pubKeyCalced.Bytes(), pubkeyBytes)) - - dataBytes, err := hex.DecodeString(ts.Data) - require.NoError(t, err) - sigBytes, err := hex.DecodeString(ts.Sig) - require.NoError(t, err) - - // Test sign - sigCalced, err := Sign(privKeyCalced, dataBytes) - require.NoError(t, err) - - require.True(t, bytes.Equal(sigCalced, sigBytes)) - - // Test verify - verified, err := Verify(pubKeyCalced, dataBytes, sigBytes) - require.NoError(t, err) - - require.True(t, verified) - } -} - -// NOTE: Test cases were obtained from NEM -// See link: https://github.com/symbol/test-vectors -// Pulled 5 test vectors for each test case, at time of writing confirmed that all 10000 vectors passed -func GetPrivToPubkeyTestCases() []KeyPair { - var toReturn []KeyPair - - kp1 := KeyPair{ - Privkey: "575DBB3062267EFF57C970A336EBBC8FBCFE12C5BD3ED7BC11EB0481D7704CED", - Pubkey: "C5F54BA980FCBB657DBAAA42700539B207873E134D2375EFEAB5F1AB52F87844", - } - - kp2 := KeyPair{ - Privkey: "5B0E3FA5D3B49A79022D7C1E121BA1CBBF4DB5821F47AB8C708EF88DEFC29BFE", - Pubkey: "96EB2A145211B1B7AB5F0D4B14F8ABC8D695C7AEE31A3CFC2D4881313C68EEA3", - } - - kp3 := KeyPair{ - Privkey: "738BA9BB9110AEA8F15CAA353ACA5653B4BDFCA1DB9F34D0EFED2CE1325AEEDA", - Pubkey: "2D8425E4CA2D8926346C7A7CA39826ACD881A8639E81BD68820409C6E30D142A", - } - - kp4 := KeyPair{ - Privkey: "E8BF9BC0F35C12D8C8BF94DD3A8B5B4034F1063948E3CC5304E55E31AA4B95A6", - Pubkey: "4FEED486777ED38E44C489C7C4E93A830E4C4A907FA19A174E630EF0F6ED0409", - } - - kp5 := KeyPair{ - Privkey: "C325EA529674396DB5675939E7988883D59A5FC17A28CA977E3BA85370232A83", - Pubkey: "83EE32E4E145024D29BCA54F71FA335A98B3E68283F1A3099C4D4AE113B53E54", - } - - toReturn = append(toReturn, kp1, kp2, kp3, kp4, kp5) - - return toReturn -} - -func GetSigTestCases() []TestSig { - var toReturn []TestSig - - t1 := TestSig{ - Privkey: "ABF4CF55A2B3F742D7543D9CC17F50447B969E6E06F5EA9195D428AB12B7318D", - Pubkey: "8A558C728C21C126181E5E654B404A45B4F0137CE88177435A69978CC6BEC1F4", - Data: "8CE03CD60514233B86789729102EA09E867FC6D964DEA8C2018EF7D0A2E0E24BF7E348E917116690B9", - Length: 41, - Sig: "D9CEC0CC0E3465FAB229F8E1D6DB68AB9CC99A18CB0435F70DEB6100948576CD5C0AA1FEB550BDD8693EF81EB10A556A622DB1F9301986827B96716A7134230C", - } - - t2 := TestSig{ - Privkey: "6AA6DAD25D3ACB3385D5643293133936CDDDD7F7E11818771DB1FF2F9D3F9215", - Pubkey: "BBC8CBB43DDA3ECF70A555981A351A064493F09658FFFE884C6FAB2A69C845C6", - Data: "E4A92208A6FC52282B620699191EE6FB9CF04DAF48B48FD542C5E43DAA9897763A199AAA4B6F10546109F47AC3564FADE0", - Length: 49, - Sig: "98BCA58B075D1748F1C3A7AE18F9341BC18E90D1BEB8499E8A654C65D8A0B4FBD2E084661088D1E5069187A2811996AE31F59463668EF0F8CB0AC46A726E7902", - } - - t3 := TestSig{ - Privkey: "8E32BC030A4C53DE782EC75BA7D5E25E64A2A072A56E5170B77A4924EF3C32A9", - Pubkey: "72D0E65F1EDE79C4AF0BA7EC14204E10F0F7EA09F2BC43259CD60EA8C3A087E2", - Data: "13ED795344C4448A3B256F23665336645A853C5C44DBFF6DB1B9224B5303B6447FBF8240A2249C55", - Length: 40, - Sig: "EF257D6E73706BB04878875C58AA385385BF439F7040EA8297F7798A0EA30C1C5EFF5DDC05443F801849C68E98111AE65D088E726D1D9B7EECA2EB93B677860C", - } - - t4 := TestSig{ - Privkey: "C83CE30FCB5B81A51BA58FF827CCBC0142D61C13E2ED39E78E876605DA16D8D7", - Pubkey: "3EC8923F9EA5EA14F8AAA7E7C2784653ED8C7DE44E352EF9FC1DEE81FC3FA1A3", - Data: "A2704638434E9F7340F22D08019C4C8E3DBEE0DF8DD4454A1D70844DE11694F4C8CA67FDCB08FED0CEC9ABB2112B5E5F89", - Length: 49, - Sig: "0C684E71B35FED4D92B222FC60561DB34E0D8AFE44BDD958AAF4EE965911BEF5991236F3E1BCED59FC44030693BCAC37F34D29E5AE946669DC326E706E81B804", - } - - t5 := TestSig{ - Privkey: "2DA2A0AAE0F37235957B51D15843EDDE348A559692D8FA87B94848459899FC27", - Pubkey: "D73D0B14A9754EEC825FCB25EF1CFA9AE3B1370074EDA53FC64C22334A26C254", - Data: "D2488E854DBCDFDB2C9D16C8C0B2FDBC0ABB6BAC991BFE2B14D359A6BC99D66C00FD60D731AE06D0", - Length: 40, - Sig: "6F17F7B21EF9D6907A7AB104559F77D5A2532B557D95EDFFD6D88C073D87AC00FC838FC0D05282A0280368092A4BD67E95C20F3E14580BE28D8B351968C65E03", - } - - toReturn = append(toReturn, t1, t2, t3, t4, t5) - - return toReturn -} diff --git a/crypto/subtle/hkdf.go b/crypto/subtle/hkdf.go deleted file mode 100644 index 6aaa59138..000000000 --- a/crypto/subtle/hkdf.go +++ /dev/null @@ -1,58 +0,0 @@ -package subtle - -import ( - "fmt" - "io" - - "golang.org/x/crypto/hkdf" -) - -const ( - // Minimum tag size in bytes. This provides minimum 80-bit security strength. - minTagSizeInBytes = uint32(10) -) - -// validateHKDFParams validates parameters of HKDF constructor. -func validateHKDFParams(hash string, _ uint32, tagSize uint32) error { - // validate tag size - digestSize, err := GetHashDigestSize(hash) - if err != nil { - return err - } - if tagSize > 255*digestSize { - return fmt.Errorf("tag size too big") - } - if tagSize < minTagSizeInBytes { - return fmt.Errorf("tag size too small") - } - return nil -} - -// ComputeHKDF extracts a pseudorandom key. -func ComputeHKDF( - hashAlg string, - key []byte, - salt []byte, - info []byte, - tagSize uint32, -) ([]byte, error) { - keySize := uint32(len(key)) - if err := validateHKDFParams(hashAlg, keySize, tagSize); err != nil { - return nil, fmt.Errorf("hkdf: %s", err) - } - hashFunc := GetHashFunc(hashAlg) - if hashFunc == nil { - return nil, fmt.Errorf("hkdf: invalid hash algorithm") - } - if len(salt) == 0 { - salt = make([]byte, hashFunc().Size()) - } - - result := make([]byte, tagSize) - kdf := hkdf.New(hashFunc, key, salt, info) - n, err := io.ReadFull(kdf, result) - if n != len(result) || err != nil { - return nil, fmt.Errorf("compute of hkdf failed") - } - return result, nil -} diff --git a/crypto/subtle/random/random.go b/crypto/subtle/random/random.go deleted file mode 100644 index 9bfc537a3..000000000 --- a/crypto/subtle/random/random.go +++ /dev/null @@ -1,22 +0,0 @@ -package random - -import ( - "crypto/rand" - "encoding/binary" -) - -// GetRandomBytes randomly generates n bytes. -func GetRandomBytes(n uint32) []byte { - buf := make([]byte, n) - _, err := rand.Read(buf) - if err != nil { - panic(err) // out of randomness, should never happen - } - return buf -} - -// GetRandomUint32 randomly generates an unsigned 32-bit integer. -func GetRandomUint32() uint32 { - b := GetRandomBytes(4) - return binary.BigEndian.Uint32(b) -} diff --git a/crypto/subtle/subtle.go b/crypto/subtle/subtle.go deleted file mode 100644 index 88754fbe8..000000000 --- a/crypto/subtle/subtle.go +++ /dev/null @@ -1,130 +0,0 @@ -package subtle - -import ( - "crypto/elliptic" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "errors" - "hash" - "math/big" -) - -var errNilHashFunc = errors.New("nil hash function") - -// hashDigestSize maps hash algorithms to their digest size in bytes. -var hashDigestSize = map[string]uint32{ - "SHA1": uint32(20), - "SHA224": uint32(28), - "SHA256": uint32(32), - "SHA384": uint32(48), - "SHA512": uint32(64), -} - -// GetHashDigestSize returns the digest size of the specified hash algorithm. -func GetHashDigestSize(hash string) (uint32, error) { - digestSize, ok := hashDigestSize[hash] - if !ok { - return 0, errors.New("invalid hash algorithm") - } - return digestSize, nil -} - -// TODO(ckl): Perhaps return an explicit error instead of ""/nil for the -// following functions. - -// ConvertHashName converts different forms of a hash name to the -// hash name that tink recognizes. -func ConvertHashName(name string) string { - switch name { - case "SHA-224": - return "SHA224" - case "SHA-256": - return "SHA256" - case "SHA-384": - return "SHA384" - case "SHA-512": - return "SHA512" - case "SHA-1": - return "SHA1" - default: - return "" - } -} - -// ConvertCurveName converts different forms of a curve name to the -// name that tink recognizes. -func ConvertCurveName(name string) string { - switch name { - case "secp256r1", "P-256": - return "NIST_P256" - case "secp384r1", "P-384": - return "NIST_P384" - case "secp521r1", "P-521": - return "NIST_P521" - default: - return "" - } -} - -// GetHashFunc returns the corresponding hash function of the given hash name. -func GetHashFunc(hash string) func() hash.Hash { - switch hash { - case "SHA1": - return sha1.New - case "SHA224": - return sha256.New224 - case "SHA256": - return sha256.New - case "SHA384": - return sha512.New384 - case "SHA512": - return sha512.New - default: - return nil - } -} - -// GetCurve returns the curve object that corresponds to the given curve type. -// It returns null if the curve type is not supported. -func GetCurve(curve string) elliptic.Curve { - switch curve { - case "NIST_P256": - return elliptic.P256() - case "NIST_P384": - return elliptic.P384() - case "NIST_P521": - return elliptic.P521() - default: - return nil - } -} - -// ComputeHash calculates a hash of the given data using the given hash function. -func ComputeHash(hashFunc func() hash.Hash, data []byte) ([]byte, error) { - if hashFunc == nil { - return nil, errNilHashFunc - } - h := hashFunc() - - _, err := h.Write(data) - if err != nil { - return nil, err - } - - return h.Sum(nil), nil -} - -// NewBigIntFromHex returns a big integer from a hex string. -func NewBigIntFromHex(s string) (*big.Int, error) { - if len(s)%2 == 1 { - s = "0" + s - } - b, err := hex.DecodeString(s) - if err != nil { - return nil, err - } - ret := new(big.Int).SetBytes(b) - return ret, nil -} diff --git a/crypto/subtle/x25519.go b/crypto/subtle/x25519.go deleted file mode 100644 index 7a869c552..000000000 --- a/crypto/subtle/x25519.go +++ /dev/null @@ -1,25 +0,0 @@ -package subtle - -import ( - "crypto/rand" - - "golang.org/x/crypto/curve25519" -) - -// GeneratePrivateKeyX25519 generates a new 32-byte private key. -func GeneratePrivateKeyX25519() ([]byte, error) { - privKey := make([]byte, curve25519.ScalarSize) - _, err := rand.Read(privKey) - return privKey, err -} - -// ComputeSharedSecretX25519 returns the 32-byte shared key, i.e. -// privKey * pubValue on the curve. -func ComputeSharedSecretX25519(privKey, pubValue []byte) ([]byte, error) { - return curve25519.X25519(privKey, pubValue) -} - -// PublicFromPrivateX25519 computes privKey's corresponding public key. -func PublicFromPrivateX25519(privKey []byte) ([]byte, error) { - return ComputeSharedSecretX25519(privKey, curve25519.Basepoint) -} diff --git a/crypto/tecdsa/dklsv1/README.md b/crypto/tecdsa/dklsv1/README.md deleted file mode 100755 index 738ec9dbd..000000000 --- a/crypto/tecdsa/dklsv1/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## Secure Two-party Threshold ECDSA from ECDSA Assumptions - -Package dkls implements the 2-of-2 threshold ECDSA signing algorithm of -[Secure Two-party Threshold ECDSA from ECDSA Assumptions](https://eprint.iacr.org/2018/499). diff --git a/crypto/tecdsa/dklsv1/boilerplate.go b/crypto/tecdsa/dklsv1/boilerplate.go deleted file mode 100644 index ab0e4c4e0..000000000 --- a/crypto/tecdsa/dklsv1/boilerplate.go +++ /dev/null @@ -1,436 +0,0 @@ -package dklsv1 - -import ( - "hash" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/refresh" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/sign" -) - -// AliceDkg DKLS DKG implementation that satisfies the protocol iterator interface. -type AliceDkg struct { - protoStepper - *dkg.Alice -} - -// BobDkg DKLS DKG implementation that satisfies the protocol iterator interface. -type BobDkg struct { - protoStepper - *dkg.Bob -} - -// AliceSign DKLS sign implementation that satisfies the protocol iterator interface. -type AliceSign struct { - protoStepper - *sign.Alice -} - -// BobSign DKLS sign implementation that satisfies the protocol iterator interface. -type BobSign struct { - protoStepper - *sign.Bob -} - -// AliceRefresh DKLS refresh implementation that satisfies the protocol iterator interface. -type AliceRefresh struct { - protoStepper - *refresh.Alice -} - -// BobRefresh DKLS refresh implementation that satisfies the protocol iterator interface. -type BobRefresh struct { - protoStepper - *refresh.Bob -} - -var ( - // Static type assertions - _ protocol.Iterator = &AliceDkg{} - _ protocol.Iterator = &BobDkg{} - _ protocol.Iterator = &AliceSign{} - _ protocol.Iterator = &BobSign{} - _ protocol.Iterator = &AliceRefresh{} - _ protocol.Iterator = &BobRefresh{} -) - -// NewAliceDkg creates a new protocol that can compute a DKG as Alice -func NewAliceDkg(curve *curves.Curve, version uint) *AliceDkg { - a := &AliceDkg{Alice: dkg.NewAlice(curve)} - a.steps = []func(*protocol.Message) (*protocol.Message, error){ - func(input *protocol.Message) (*protocol.Message, error) { - bobSeed, err := decodeDkgRound2Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - roundOutput, err := a.Round2CommitToProof(bobSeed) - if err != nil { - return nil, err - } - return encodeDkgRound2Output(roundOutput, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - proof, err := decodeDkgRound4Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - aliceProof, err := a.Round4VerifyAndReveal(proof) - if err != nil { - return nil, err - } - return encodeDkgRound4Output(aliceProof, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - proof, err := decodeDkgRound6Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - choices, err := a.Round6DkgRound2Ot(proof) - if err != nil { - return nil, err - } - return encodeDkgRound6Output(choices, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - challenge, err := decodeDkgRound8Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - responses, err := a.Round8DkgRound4Ot(challenge) - if err != nil { - return nil, err - } - return encodeDkgRound8Output(responses, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - opening, err := decodeDkgRound10Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - if err := a.Round10DkgRound6Ot(opening); err != nil { - return nil, err - } - return nil, nil - }, - } - return a -} - -// Result Returns an encoded version of Alice as sequence of bytes that can be used to initialize an AliceSign protocol. -func (a *AliceDkg) Result(version uint) (*protocol.Message, error) { - // Sanity check - if !a.complete() { - return nil, nil - } - if a.Alice == nil { - return nil, protocol.ErrNotInitialized - } - - result := a.Output() - return EncodeAliceDkgOutput(result, version) -} - -// NewBobDkg Creates a new protocol that can compute a DKG as Bob. -func NewBobDkg(curve *curves.Curve, version uint) *BobDkg { - b := &BobDkg{Bob: dkg.NewBob(curve)} - b.steps = []func(message *protocol.Message) (*protocol.Message, error){ - func(*protocol.Message) (*protocol.Message, error) { - commitment, err := b.Round1GenerateRandomSeed() - if err != nil { - return nil, err - } - return encodeDkgRound1Output(commitment, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round3Input, err := decodeDkgRound3Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - bobProof, err := b.Round3SchnorrProve(round3Input) - if err != nil { - return nil, err - } - return encodeDkgRound3Output(bobProof, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - proof, err := decodeDkgRound5Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - bobProof, err := b.Round5DecommitmentAndStartOt(proof) - if err != nil { - return nil, err - } - return encodeDkgRound5Output(bobProof, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - choices, err := decodeDkgRound7Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - challenge, err := b.Round7DkgRound3Ot(choices) - if err != nil { - return nil, err - } - return encodeDkgRound7Output(challenge, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - responses, err := decodeDkgRound9Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - opening, err := b.Round9DkgRound5Ot(responses) - if err != nil { - return nil, err - } - return encodeDkgRound9Output(opening, version) - }, - } - return b -} - -// Result returns an encoded version of Bob as sequence of bytes that can be used to initialize an BobSign protocol. -func (b *BobDkg) Result(version uint) (*protocol.Message, error) { - // Sanity check - if !b.complete() { - return nil, nil - } - if b.Bob == nil { - return nil, protocol.ErrNotInitialized - } - - result := b.Output() - return EncodeBobDkgOutput(result, version) -} - -// NewAliceSign creates a new protocol that can compute a signature as Alice. -// Requires dkg state that was produced at the end of DKG.Output(). -func NewAliceSign( - curve *curves.Curve, - hash hash.Hash, - message []byte, - dkgResultMessage *protocol.Message, - version uint, -) (*AliceSign, error) { - dkgResult, err := DecodeAliceDkgResult(dkgResultMessage) - if err != nil { - return nil, errors.WithStack(err) - } - a := &AliceSign{Alice: sign.NewAlice(curve, hash, dkgResult)} - a.steps = []func(message *protocol.Message) (*protocol.Message, error){ - func(*protocol.Message) (*protocol.Message, error) { - aliceCommitment, err := a.Round1GenerateRandomSeed() - if err != nil { - return nil, err - } - return encodeSignRound1Output(aliceCommitment, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round2Output, err := decodeSignRound3Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round3Output, err := a.Round3Sign(message, round2Output) - if err != nil { - return nil, errors.WithStack(err) - } - return encodeSignRound3Output(round3Output, version) - }, - } - return a, nil -} - -// NewBobSign creates a new protocol that can compute a signature as Bob. -// Requires dkg state that was produced at the end of DKG.Output(). -func NewBobSign( - curve *curves.Curve, - hash hash.Hash, - message []byte, - dkgResultMessage *protocol.Message, - version uint, -) (*BobSign, error) { - dkgResult, err := DecodeBobDkgResult(dkgResultMessage) - if err != nil { - return nil, errors.WithStack(err) - } - b := &BobSign{Bob: sign.NewBob(curve, hash, dkgResult)} - b.steps = []func(message *protocol.Message) (*protocol.Message, error){ - func(input *protocol.Message) (*protocol.Message, error) { - commitment, err := decodeSignRound2Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round2Output, err := b.Round2Initialize(commitment) - if err != nil { - return nil, errors.WithStack(err) - } - return encodeSignRound2Output(round2Output, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round4Input, err := decodeSignRound4Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - - if err = b.Round4Final(message, round4Input); err != nil { - return nil, errors.WithStack(err) - } - return nil, nil - }, - } - return b, nil -} - -// Result always returns an error. -// Alice does not compute a signature in the DKLS protocol; only Bob computes the signature. -func (a *AliceSign) Result(_ uint) (*protocol.Message, error) { - return nil, errors.New("dkls.Alice does not produce a signature") -} - -// Result returns the signature that Bob computed as a *core.EcdsaSignature if the signing protocol completed successfully. -func (b *BobSign) Result(version uint) (*protocol.Message, error) { - // We can't produce a signature until the protocol completes - if !b.complete() { - return nil, nil - } - if b.Bob == nil { - // Object wasn't created with NewXSign() - return nil, protocol.ErrNotInitialized - } - return encodeSignature(b.Bob.Signature, version) -} - -// NewAliceRefresh creates a new protocol that can compute a key refresh as Alice -func NewAliceRefresh( - curve *curves.Curve, - dkgResultMessage *protocol.Message, - version uint, -) (*AliceRefresh, error) { - dkgResult, err := DecodeAliceDkgResult(dkgResultMessage) - if err != nil { - return nil, errors.WithStack(err) - } - - a := &AliceRefresh{Alice: refresh.NewAlice(curve, dkgResult)} - a.steps = []func(*protocol.Message) (*protocol.Message, error){ - func(_ *protocol.Message) (*protocol.Message, error) { - aliceSeed := a.Round1RefreshGenerateSeed() - return encodeRefreshRound1Output(aliceSeed, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round3Input, err := decodeRefreshRound3Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round3Output, err := a.Round3RefreshMultiplyRound2Ot(round3Input) - if err != nil { - return nil, err - } - return encodeRefreshRound3Output(round3Output, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round5Input, err := decodeRefreshRound5Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round5Output, err := a.Round5RefreshRound4Ot(round5Input) - if err != nil { - return nil, err - } - return encodeRefreshRound5Output(round5Output, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round7Input, err := decodeRefreshRound7Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - if err := a.Round7DkgRound6Ot(round7Input); err != nil { - return nil, err - } - return nil, nil - }, - } - return a, nil -} - -// Result Returns an encoded version of Alice as sequence of bytes that can be used to initialize an AliceSign protocol. -func (a *AliceRefresh) Result(version uint) (*protocol.Message, error) { - // Sanity check - if !a.complete() { - return nil, nil - } - if a.Alice == nil { - return nil, protocol.ErrNotInitialized - } - - result := a.Output() - return EncodeAliceDkgOutput(result, version) -} - -// NewBobRefresh Creates a new protocol that can compute a refresh as Bob. -func NewBobRefresh( - curve *curves.Curve, - dkgResultMessage *protocol.Message, - version uint, -) (*BobRefresh, error) { - dkgResult, err := DecodeBobDkgResult(dkgResultMessage) - if err != nil { - return nil, errors.WithStack(err) - } - - b := &BobRefresh{Bob: refresh.NewBob(curve, dkgResult)} - b.steps = []func(message *protocol.Message) (*protocol.Message, error){ - func(input *protocol.Message) (*protocol.Message, error) { - round2Input, err := decodeRefreshRound2Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round2Output, err := b.Round2RefreshProduceSeedAndMultiplyAndStartOT(round2Input) - if err != nil { - return nil, err - } - return encodeRefreshRound2Output(round2Output, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round4Input, err := decodeRefreshRound4Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round4Output, err := b.Round4RefreshRound3Ot(round4Input) - if err != nil { - return nil, err - } - return encodeRefreshRound4Output(round4Output, version) - }, - func(input *protocol.Message) (*protocol.Message, error) { - round6Input, err := decodeRefreshRound6Input(input) - if err != nil { - return nil, errors.WithStack(err) - } - round6Output, err := b.Round6RefreshRound5Ot(round6Input) - if err != nil { - return nil, err - } - return encodeRefreshRound6Output(round6Output, version) - }, - } - return b, nil -} - -// Result returns an encoded version of Bob as sequence of bytes that can be used to initialize an BobSign protocol. -func (b *BobRefresh) Result(version uint) (*protocol.Message, error) { - // Sanity check - if !b.complete() { - return nil, nil - } - if b.Bob == nil { - return nil, protocol.ErrNotInitialized - } - - result := b.Output() - return EncodeBobDkgOutput(result, version) -} diff --git a/crypto/tecdsa/dklsv1/dealer/dealer.go b/crypto/tecdsa/dklsv1/dealer/dealer.go deleted file mode 100644 index f638c3d46..000000000 --- a/crypto/tecdsa/dklsv1/dealer/dealer.go +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package dealer implements key generation via a trusted dealer for the protocol [DKLs18](https://eprint.iacr.org/2018/499.pdf). -// The trusted dealer produces the same output as the corresponding DKG protocol and can be used for signing without -// additional modifications. -// Note that running actual DKG is ALWAYS recommended over a trusted dealer. -package dealer - -import ( - "crypto/rand" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" -) - -// GenerateAndDeal produces private key material for alice and bob which they can later use in signing. -// Running actual DKG is ALWAYS recommended over using this function, as this function breaks the security guarantees of DKG. -// only use this function if you have a very good reason to. -func GenerateAndDeal(curve *curves.Curve) (*dkg.AliceOutput, *dkg.BobOutput, error) { - aliceSecretShare, bobSecretShare, publicKey := produceKeyShares(curve) - aliceOTOutput, bobOTOutput, err := produceOTResults(curve) - if err != nil { - return nil, nil, errors.Wrap(err, "couldn't produce OT results") - } - alice := &dkg.AliceOutput{ - PublicKey: publicKey, - SecretKeyShare: aliceSecretShare, - SeedOtResult: aliceOTOutput, - } - bob := &dkg.BobOutput{ - PublicKey: publicKey, - SecretKeyShare: bobSecretShare, - SeedOtResult: bobOTOutput, - } - return alice, bob, nil -} - -func produceKeyShares( - curve *curves.Curve, -) (aliceSecretShare curves.Scalar, bobSecretShare curves.Scalar, publicKey curves.Point) { - aliceSecretShare = curve.Scalar.Random(rand.Reader) - bobSecretShare = curve.Scalar.Random(rand.Reader) - publicKey = curve.ScalarBaseMult(aliceSecretShare.Mul(bobSecretShare)) - return aliceSecretShare, bobSecretShare, publicKey -} - -func produceOTResults( - curve *curves.Curve, -) (*simplest.ReceiverOutput, *simplest.SenderOutput, error) { - oneTimePadEncryptionKeys := make([]simplest.OneTimePadEncryptionKeys, kos.Kappa) - oneTimePadDecryptionKey := make([]simplest.OneTimePadDecryptionKey, kos.Kappa) - - // we'll need a receiver because in its constructor random bits will be selected. - receiver, err := simplest.NewReceiver(curve, kos.Kappa, [simplest.DigestSize]byte{}) - if err != nil { - return nil, nil, errors.Wrap(err, "couldn't initialize a receiver") - } - packedRandomChoiceBits, randomChoiceBits := receiver.Output.PackedRandomChoiceBits, receiver.Output.RandomChoiceBits - - for i := 0; i < kos.Kappa; i++ { - if _, err := rand.Read(oneTimePadEncryptionKeys[i][0][:]); err != nil { - return nil, nil, errors.WithStack(err) - } - if _, err := rand.Read(oneTimePadEncryptionKeys[i][1][:]); err != nil { - return nil, nil, errors.WithStack(err) - } - oneTimePadDecryptionKey[i] = oneTimePadEncryptionKeys[i][randomChoiceBits[i]] - } - - senderOutput := &simplest.SenderOutput{ - OneTimePadEncryptionKeys: oneTimePadEncryptionKeys, - } - receiverOutput := &simplest.ReceiverOutput{ - PackedRandomChoiceBits: packedRandomChoiceBits, - RandomChoiceBits: randomChoiceBits, - OneTimePadDecryptionKey: oneTimePadDecryptionKey, - } - return receiverOutput, senderOutput, nil -} diff --git a/crypto/tecdsa/dklsv1/dealer/dealer_test.go b/crypto/tecdsa/dklsv1/dealer/dealer_test.go deleted file mode 100644 index 9ccb46b3f..000000000 --- a/crypto/tecdsa/dklsv1/dealer/dealer_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package dealer_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dealer" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/sign" -) - -func Test_DealerCanGenerateKeysThatSign(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - aliceOutput, bobOutput, err := dealer.GenerateAndDeal(curve) - require.NoError(t, err) - - alice := sign.NewAlice(curve, sha3.New256(), aliceOutput) - bob := sign.NewBob(curve, sha3.New256(), bobOutput) - - message := []byte("A message.") - seed, err := alice.Round1GenerateRandomSeed() - require.NoError(t, err) - round3Output, err := bob.Round2Initialize(seed) - require.NoError(t, err) - round4Output, err := alice.Round3Sign(message, round3Output) - require.NoError(t, err) - err = bob.Round4Final(message, round4Output) - require.NoError(t, err, "curve: %s", curve.Name) - } -} - -func Test_DealerGeneratesDifferentResultsEachTime(t *testing.T) { - curve := curves.K256() - aliceOutput1, bobOutput1, err := dealer.GenerateAndDeal(curve) - require.NoError(t, err) - aliceOutput2, bobOutput2, err := dealer.GenerateAndDeal(curve) - require.NoError(t, err) - - require.NotEqual(t, aliceOutput1.SecretKeyShare, aliceOutput2.SecretKeyShare) - require.NotEqual(t, bobOutput1.SecretKeyShare, bobOutput2.SecretKeyShare) - require.NotEqualValues( - t, - aliceOutput1.SeedOtResult.RandomChoiceBits, - aliceOutput2.SeedOtResult.RandomChoiceBits, - ) - require.NotEqualValues( - t, - bobOutput1.SeedOtResult.OneTimePadEncryptionKeys, - bobOutput2.SeedOtResult.OneTimePadEncryptionKeys, - ) -} diff --git a/crypto/tecdsa/dklsv1/dkg/dkg.go b/crypto/tecdsa/dklsv1/dkg/dkg.go deleted file mode 100644 index 134bfa124..000000000 --- a/crypto/tecdsa/dklsv1/dkg/dkg.go +++ /dev/null @@ -1,309 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package dkg implements the Distributed Key Generation (DKG) protocol of [DKLs18](https://eprint.iacr.org/2018/499.pdf). -// The DKG protocol is defined in "Protocol 2" page 7, of the paper. The Zero Knowledge Proof ideal functionalities are -// realized using schnorr proofs. Moreover, the seed OT is realized using the Verified Simplest OT protocol. -package dkg - -import ( - "crypto/rand" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -// AliceOutput is the result of running DKG for Alice. It contains both the public and secret values that are needed -// for signing. -type AliceOutput struct { - // PublicKey is the joint public key of Alice and Bob. - // This value is public. - PublicKey curves.Point - - // SecretKeyShare is Alice's secret key for the joint public key. - // This output must be kept secret. If it is lost, the users will lose access and cannot create signatures. - SecretKeyShare curves.Scalar - - // SeedOtResult are the outputs that the receiver will obtain as a result of running the "random" OT protocol. - // This output must be kept secret. Although, if it is lost the users can run another OT protocol and obtain - // new values to replace it. - SeedOtResult *simplest.ReceiverOutput -} - -// BobOutput is the result of running DKG for Bob. It contains both the public and secret values that are needed -// for signing. -type BobOutput struct { - // PublicKey is the joint public key of Alice and Bob. - // This value is public. - PublicKey curves.Point - - // SecretKeyShare is Bob's secret key for the joint public key. - // This output must be kept secret. If it is lost, the users will lose access and cannot create signatures. - SecretKeyShare curves.Scalar - - // SeedOtResult are the outputs that the sender will obtain as a result of running the "random" OT protocol. - // This output must be kept secret. Although, if it is lost the users can run another OT protocol and obtain - // new values to replace it. - SeedOtResult *simplest.SenderOutput -} - -// Alice struct encoding Alice's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Alice will NOT obtain the signature. -type Alice struct { - // prover is a schnorr prover for Alice's portion of public key. - prover *schnorr.Prover - - // proof is alice's proof to her portion of the public key. It is stored as an intermediate value, during commitment phase. - proof *schnorr.Proof - - // receiver is the base OT receiver. - receiver *simplest.Receiver - - // secretKeyShare is Alice's secret key for the joint public key. - secretKeyShare curves.Scalar - - // publicKey is the joint public key of Alice and Bob. - publicKey curves.Point - - curve *curves.Curve - - transcript *merlin.Transcript -} - -// Bob struct encoding Bob's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Bob will obtain the signature. -type Bob struct { - // prover is a schnorr prover for Bob's portion of public key. - prover *schnorr.Prover // this is a "schnorr statement" for pkB. - - // sender is the base OT sender. - sender *simplest.Sender - - // secretKeyShare is Bob's secret key for the joint public key. - secretKeyShare curves.Scalar - - // publicKey is the joint public key of Alice and Bob. - publicKey curves.Point - - // schnorr proof commitment to Alice's schnorr proof. - aliceCommitment schnorr.Commitment - // 32-byte transcript salt which will be used for Alice's schnorr proof - aliceSalt [simplest.DigestSize]byte - - curve *curves.Curve - - transcript *merlin.Transcript -} - -// Round2Output contains the output of the 2nd round of DKG. -type Round2Output struct { - // Seed is the random value used to derive the joint unique session id. - Seed [simplest.DigestSize]byte - - // Commitment is the commitment to the ZKP to Alice's secret key share. - Commitment schnorr.Commitment -} - -// NewAlice creates a party that can participate in 2-of-2 DKG and threshold signature. -func NewAlice(curve *curves.Curve) *Alice { - return &Alice{ - curve: curve, - transcript: merlin.NewTranscript("Coinbase_DKLs_DKG"), - } -} - -// NewBob creates a party that can participate in 2-of-2 DKG and threshold signature. This party -// is the receiver of the signature at the end. -func NewBob(curve *curves.Curve) *Bob { - return &Bob{ - curve: curve, - transcript: merlin.NewTranscript("Coinbase_DKLs_DKG"), - } -} - -// Round1GenerateRandomSeed Bob flips random coins, and sends these to Alice -// in this round, Bob flips 32 random bytes and sends them to Alice. -// note that this is not _explicitly_ given as part of the protocol in https://eprint.iacr.org/2018/499.pdf, Protocol 1). -// rather, it is part of our generation of a unique session identifier, for use in subsequent schnorr proofs / seed OT / etc. -// we do it by having each party sample 32 bytes, then by appending _both_ as salts. secure if either party is honest -func (bob *Bob) Round1GenerateRandomSeed() ([simplest.DigestSize]byte, error) { - bobSeed := [simplest.DigestSize]byte{} - if _, err := rand.Read(bobSeed[:]); err != nil { - return [simplest.DigestSize]byte{}, errors.Wrap( - err, - "generating random bytes in bob DKG round 1 generate", - ) - } - bob.transcript.AppendMessage( - []byte("session_id_bob"), - bobSeed[:], - ) // note: bob appends first here - return bobSeed, nil -} - -// Round2CommitToProof steps 1) and 2) of protocol 2 on page 7. -func (alice *Alice) Round2CommitToProof(bobSeed [simplest.DigestSize]byte) (*Round2Output, error) { - aliceSeed := [simplest.DigestSize]byte{} - if _, err := rand.Read(aliceSeed[:]); err != nil { - return nil, errors.Wrap(err, "generating random bytes in bob DKG round 1 generate") - } - alice.transcript.AppendMessage([]byte("session_id_bob"), bobSeed[:]) - alice.transcript.AppendMessage([]byte("session_id_alice"), aliceSeed[:]) - - var err error - uniqueSessionId := [simplest.DigestSize]byte{} // note: will use and re-use this below for sub-session IDs. - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("salt for simplest OT"), simplest.DigestSize), - ) - alice.receiver, err = simplest.NewReceiver(alice.curve, kos.Kappa, uniqueSessionId) - if err != nil { - return nil, errors.Wrap(err, "alice constructing new seed OT receiver in Alice DKG round 1") - } - - alice.secretKeyShare = alice.curve.Scalar.Random(rand.Reader) - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("salt for alice schnorr"), simplest.DigestSize), - ) - alice.prover = schnorr.NewProver(alice.curve, nil, uniqueSessionId[:]) - var commitment schnorr.Commitment - alice.proof, commitment, err = alice.prover.ProveCommit( - alice.secretKeyShare, - ) // will mutate `pkA` - if err != nil { - return nil, errors.Wrap(err, "prove + commit in alice DKG Commit round 1") - } - return &Round2Output{ - Commitment: commitment, - Seed: aliceSeed, - }, nil -} - -// Round3SchnorrProve receives Bob's Commitment and returns schnorr statment + proof. -// Steps 1 and 3 of protocol 2 on page 7. -func (bob *Bob) Round3SchnorrProve(round2Output *Round2Output) (*schnorr.Proof, error) { - bob.transcript.AppendMessage([]byte("session_id_alice"), round2Output.Seed[:]) - - bob.aliceCommitment = round2Output.Commitment // store it, so that we can check when alice decommits - - var err error - uniqueSessionId := [simplest.DigestSize]byte{} // note: will use and re-use this below for sub-session IDs. - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("salt for simplest OT"), simplest.DigestSize), - ) - bob.sender, err = simplest.NewSender(bob.curve, kos.Kappa, uniqueSessionId) - if err != nil { - return nil, errors.Wrap(err, "bob constructing new OT sender in DKG round 2") - } - // extract alice's salt in the right order; we won't use this until she reveals her proof and we verify it below - copy( - bob.aliceSalt[:], - bob.transcript.ExtractBytes([]byte("salt for alice schnorr"), simplest.DigestSize), - ) - bob.secretKeyShare = bob.curve.Scalar.Random(rand.Reader) - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("salt for bob schnorr"), simplest.DigestSize), - ) - bob.prover = schnorr.NewProver(bob.curve, nil, uniqueSessionId[:]) - proof, err := bob.prover.Prove(bob.secretKeyShare) - if err != nil { - return nil, errors.Wrap(err, "bob schnorr proving in DKG round 2") - } - return proof, err -} - -// Round4VerifyAndReveal step 4 of protocol 2 on page 7. -func (alice *Alice) Round4VerifyAndReveal(proof *schnorr.Proof) (*schnorr.Proof, error) { - var err error - uniqueSessionId := [simplest.DigestSize]byte{} - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("salt for bob schnorr"), simplest.DigestSize), - ) - if err = schnorr.Verify(proof, alice.curve, nil, uniqueSessionId[:]); err != nil { - return nil, errors.Wrap( - err, - "alice's verification of Bob's schnorr proof failed in DKG round 3", - ) - } - alice.publicKey = proof.Statement.Mul(alice.secretKeyShare) - return alice.proof, nil -} - -// Round5DecommitmentAndStartOt step 5 of protocol 2 on page 7. -func (bob *Bob) Round5DecommitmentAndStartOt(proof *schnorr.Proof) (*schnorr.Proof, error) { - var err error - if err = schnorr.DecommitVerify(proof, bob.aliceCommitment, bob.curve, nil, bob.aliceSalt[:]); err != nil { - return nil, errors.Wrap(err, "decommit + verify failed in bob's DKG round 4") - } - bob.publicKey = proof.Statement.Mul(bob.secretKeyShare) - seedOTRound1Output, err := bob.sender.Round1ComputeAndZkpToPublicKey() - if err != nil { - return nil, errors.Wrap(err, "bob computing round 1 of seed OT within DKG round 4") - } - return seedOTRound1Output, nil -} - -// Round6DkgRound2Ot is a thin wrapper around the 2nd round of seed OT protocol. -func (alice *Alice) Round6DkgRound2Ot( - proof *schnorr.Proof, -) ([]simplest.ReceiversMaskedChoices, error) { - return alice.receiver.Round2VerifySchnorrAndPadTransfer(proof) -} - -// Round7DkgRound3Ot is a thin wrapper around the 3rd round of seed OT protocol. -func (bob *Bob) Round7DkgRound3Ot( - compressedReceiversMaskedChoice []simplest.ReceiversMaskedChoices, -) ([]simplest.OtChallenge, error) { - return bob.sender.Round3PadTransfer(compressedReceiversMaskedChoice) -} - -// Round8DkgRound4Ot is a thin wrapper around the 4th round of seed OT protocol. -func (alice *Alice) Round8DkgRound4Ot( - challenge []simplest.OtChallenge, -) ([]simplest.OtChallengeResponse, error) { - return alice.receiver.Round4RespondToChallenge(challenge) -} - -// Round9DkgRound5Ot is a thin wrapper around the 5th round of seed OT protocol. -func (bob *Bob) Round9DkgRound5Ot( - challengeResponses []simplest.OtChallengeResponse, -) ([]simplest.ChallengeOpening, error) { - return bob.sender.Round5Verify(challengeResponses) -} - -// Round10DkgRound6Ot is a thin wrapper around the 6th round of seed OT protocol. -func (alice *Alice) Round10DkgRound6Ot(challengeOpenings []simplest.ChallengeOpening) error { - return alice.receiver.Round6Verify(challengeOpenings) -} - -// Output returns the output of the DKG operation. Must be called after step 9. Calling it before that step -// has undefined behaviour. -func (alice *Alice) Output() *AliceOutput { - return &AliceOutput{ - PublicKey: alice.publicKey, - SecretKeyShare: alice.secretKeyShare, - SeedOtResult: alice.receiver.Output, - } -} - -// Output returns the output of the DKG operation. Must be called after step 9. Calling it before that step -// has undefined behaviour. -func (bob *Bob) Output() *BobOutput { - return &BobOutput{ - PublicKey: bob.publicKey, - SecretKeyShare: bob.secretKeyShare, - SeedOtResult: bob.sender.Output, - } -} diff --git a/crypto/tecdsa/dklsv1/dkg/dkg_test.go b/crypto/tecdsa/dklsv1/dkg/dkg_test.go deleted file mode 100644 index 214af5086..000000000 --- a/crypto/tecdsa/dklsv1/dkg/dkg_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package dkg - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" -) - -func TestDkg(t *testing.T) { - t.Parallel() - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - boundCurve := curve - t.Run(fmt.Sprintf("testing dkg for curve %s", boundCurve.Name), func(tt *testing.T) { - tt.Parallel() - alice := NewAlice(boundCurve) - bob := NewBob(boundCurve) - - seed, err := bob.Round1GenerateRandomSeed() - require.NoError(tt, err) - round3Output, err := alice.Round2CommitToProof(seed) - require.NoError(tt, err) - proof, err := bob.Round3SchnorrProve(round3Output) - require.NoError(tt, err) - proof, err = alice.Round4VerifyAndReveal(proof) - require.NoError(tt, err) - proof, err = bob.Round5DecommitmentAndStartOt(proof) - require.NoError(tt, err) - compressedReceiversMaskedChoice, err := alice.Round6DkgRound2Ot(proof) - require.NoError(tt, err) - challenge, err := bob.Round7DkgRound3Ot(compressedReceiversMaskedChoice) - require.NoError(tt, err) - challengeResponse, err := alice.Round8DkgRound4Ot(challenge) - require.NoError(tt, err) - challengeOpenings, err := bob.Round9DkgRound5Ot(challengeResponse) - require.NoError(tt, err) - err = alice.Round10DkgRound6Ot(challengeOpenings) - require.NoError(tt, err) - // Verify correctness of the OT subprotocol after has completed - for i := 0; i < kos.Kappa; i++ { - if alice.receiver.Output.OneTimePadDecryptionKey[i] != bob.sender.Output.OneTimePadEncryptionKeys[i][alice.receiver.Output.RandomChoiceBits[i]] { - tt.Errorf("oblivious transfer is incorrect at index i=%v", i) - } - } - - pkA := boundCurve.ScalarBaseMult(alice.Output().SecretKeyShare) - pkB := boundCurve.ScalarBaseMult(bob.Output().SecretKeyShare) - - computedPublicKeyA := pkA.Mul(bob.Output().SecretKeyShare) - require.True(tt, computedPublicKeyA.Equal(alice.Output().PublicKey)) - require.True(tt, computedPublicKeyA.Equal(bob.Output().PublicKey)) - - computedPublicKeyB := pkB.Mul(alice.Output().SecretKeyShare) - require.True(tt, computedPublicKeyB.Equal(alice.Output().PublicKey)) - require.True(tt, computedPublicKeyB.Equal(bob.Output().PublicKey)) - }) - } -} - -func BenchmarkDkg(b *testing.B) { - if testing.Short() { - b.SkipNow() - } - curve := curves.K256() - - for n := 0; n < b.N; n++ { - alice := NewAlice(curve) - bob := NewBob(curve) - - seed, err := bob.Round1GenerateRandomSeed() - require.NoError(b, err) - round3Output, err := alice.Round2CommitToProof(seed) - require.NoError(b, err) - proof, err := bob.Round3SchnorrProve(round3Output) - require.NoError(b, err) - proof, err = alice.Round4VerifyAndReveal(proof) - require.NoError(b, err) - proof, err = bob.Round5DecommitmentAndStartOt(proof) - require.NoError(b, err) - compressedReceiversMaskedChoice, err := alice.Round6DkgRound2Ot(proof) - require.NoError(b, err) - challenge, err := bob.Round7DkgRound3Ot(compressedReceiversMaskedChoice) - require.NoError(b, err) - challengeResponse, err := alice.Round8DkgRound4Ot(challenge) - require.NoError(b, err) - challengeOpenings, err := bob.Round9DkgRound5Ot(challengeResponse) - require.NoError(b, err) - err = alice.Round10DkgRound6Ot(challengeOpenings) - require.NoError(b, err) - } -} diff --git a/crypto/tecdsa/dklsv1/dkgserializers.go b/crypto/tecdsa/dklsv1/dkgserializers.go deleted file mode 100644 index 00a601221..000000000 --- a/crypto/tecdsa/dklsv1/dkgserializers.go +++ /dev/null @@ -1,327 +0,0 @@ -package dklsv1 - -import ( - "bytes" - "encoding/gob" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -const payloadKey = "direct" - -func newDkgProtocolMessage(payload []byte, round string, version uint) *protocol.Message { - return &protocol.Message{ - Protocol: protocol.Dkls18Dkg, - Version: version, - Payloads: map[string][]byte{payloadKey: payload}, - Metadata: map[string]string{"round": round}, - } -} - -func registerTypes() { - gob.Register(&curves.ScalarK256{}) - gob.Register(&curves.PointK256{}) - gob.Register(&curves.ScalarP256{}) - gob.Register(&curves.PointP256{}) -} - -func encodeDkgRound1Output(commitment [32]byte, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(&commitment); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "1", version), nil -} - -func decodeDkgRound2Input(m *protocol.Message) ([32]byte, error) { - if m.Version != protocol.Version1 { - return [32]byte{}, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := [32]byte{} - if err := dec.Decode(&decoded); err != nil { - return [32]byte{}, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound2Output(output *dkg.Round2Output, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(output); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "2", version), nil -} - -func decodeDkgRound3Input(m *protocol.Message) (*dkg.Round2Output, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(dkg.Round2Output) - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound3Output(proof *schnorr.Proof, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(proof); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "3", version), nil -} - -func decodeDkgRound4Input(m *protocol.Message) (*schnorr.Proof, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(schnorr.Proof) - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound4Output(proof *schnorr.Proof, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(proof); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "4", version), nil -} - -func decodeDkgRound5Input(m *protocol.Message) (*schnorr.Proof, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(schnorr.Proof) - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound5Output(proof *schnorr.Proof, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(proof); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "5", version), nil -} - -func decodeDkgRound6Input(m *protocol.Message) (*schnorr.Proof, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(schnorr.Proof) - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound6Output( - choices []simplest.ReceiversMaskedChoices, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(choices); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "6", version), nil -} - -func decodeDkgRound7Input(m *protocol.Message) ([]simplest.ReceiversMaskedChoices, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.ReceiversMaskedChoices{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound7Output( - challenge []simplest.OtChallenge, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(challenge); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "7", version), nil -} - -func decodeDkgRound8Input(m *protocol.Message) ([]simplest.OtChallenge, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.OtChallenge{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound8Output( - responses []simplest.OtChallengeResponse, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(responses); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "8", version), nil -} - -func decodeDkgRound9Input(m *protocol.Message) ([]simplest.OtChallengeResponse, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.OtChallengeResponse{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeDkgRound9Output( - opening []simplest.ChallengeOpening, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(opening); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "9", version), nil -} - -func decodeDkgRound10Input(m *protocol.Message) ([]simplest.ChallengeOpening, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.ChallengeOpening{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -// EncodeAliceDkgOutput serializes Alice DKG output based on the protocol version. -func EncodeAliceDkgOutput(result *dkg.AliceOutput, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "alice-output", version), nil -} - -// DecodeAliceDkgResult deserializes Alice DKG output. -func DecodeAliceDkgResult(m *protocol.Message) (*dkg.AliceOutput, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - registerTypes() - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(dkg.AliceOutput) - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -// EncodeBobDkgOutput serializes Bob DKG output based on the protocol version. -func EncodeBobDkgOutput(result *dkg.BobOutput, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.WithStack(err) - } - return newDkgProtocolMessage(buf.Bytes(), "bob-output", version), nil -} - -// DecodeBobDkgResult deserializes Bob DKG output. -func DecodeBobDkgResult(m *protocol.Message) (*dkg.BobOutput, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(dkg.BobOutput) - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} diff --git a/crypto/tecdsa/dklsv1/protocol.go b/crypto/tecdsa/dklsv1/protocol.go deleted file mode 100644 index f29573fa3..000000000 --- a/crypto/tecdsa/dklsv1/protocol.go +++ /dev/null @@ -1,33 +0,0 @@ -// package dklsv1 provides a wrapper around the [DKLs18](https://eprint.iacr.org/2018/499.pdf) sign and dkg and provides -// serialization, serialization, and versioning for the serialized data. -package dklsv1 - -import ( - "github.com/sonr-io/sonr/crypto/core/protocol" -) - -// Basic protocol interface implementation that calls the next step func in a pre-defined list -type protoStepper struct { - steps []func(input *protocol.Message) (*protocol.Message, error) - step int -} - -// Next runs the next step in the protocol and reports errors or increments the step index -func (p *protoStepper) Next(input *protocol.Message) (*protocol.Message, error) { - if p.complete() { - return nil, protocol.ErrProtocolFinished - } - - // Run the current protocol step and report any errors - output, err := p.steps[p.step](input) - if err != nil { - return nil, err - } - - // Increment the step index and report success - p.step++ - return output, nil -} - -// Reports true if the step index exceeds the number of steps -func (p *protoStepper) complete() bool { return p.step >= len(p.steps) /**/ } diff --git a/crypto/tecdsa/dklsv1/protocol_test.go b/crypto/tecdsa/dklsv1/protocol_test.go deleted file mode 100644 index d6249863e..000000000 --- a/crypto/tecdsa/dklsv1/protocol_test.go +++ /dev/null @@ -1,428 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package dklsv1 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" -) - -// For DKG bob starts first. For refresh and sign, Alice starts first. -func runIteratedProtocol( - firstParty protocol.Iterator, - secondParty protocol.Iterator, -) (error, error) { - var ( - message *protocol.Message - aErr error - bErr error - ) - - for aErr != protocol.ErrProtocolFinished || bErr != protocol.ErrProtocolFinished { - // Crank each protocol forward one iteration - message, bErr = firstParty.Next(message) - if bErr != nil && bErr != protocol.ErrProtocolFinished { - return nil, bErr - } - - message, aErr = secondParty.Next(message) - if aErr != nil && aErr != protocol.ErrProtocolFinished { - return aErr, nil - } - } - return aErr, bErr -} - -// Running steps in sequence ensures that no hidden read/write dependency exist in the read/write interfaces. -func TestDkgProto(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - alice := NewAliceDkg(curve, protocol.Version1) - bob := NewBobDkg(curve, protocol.Version1) - aErr, bErr := runIteratedProtocol(bob, alice) - - t.Run("both alice/bob complete simultaneously", func(t *testing.T) { - require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) - require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) - }) - - for i := 0; i < kos.Kappa; i++ { - if alice.Alice.Output().SeedOtResult.OneTimePadDecryptionKey[i] != bob.Bob.Output().SeedOtResult.OneTimePadEncryptionKeys[i][alice.Alice.Output().SeedOtResult.RandomChoiceBits[i]] { - t.Errorf("oblivious transfer is incorrect at index i=%v", i) - } - } - - t.Run("Both parties produces identical composite pubkey", func(t *testing.T) { - require.True(t, alice.Alice.Output().PublicKey.Equal(bob.Bob.Output().PublicKey)) - }) - - var aliceResult *dkg.AliceOutput - var bobResult *dkg.BobOutput - t.Run("alice produces valid result", func(t *testing.T) { - // Get the result - r, err := alice.Result(protocol.Version1) - - // Test - require.NoError(t, err) - require.NotNil(t, r) - aliceResult, err = DecodeAliceDkgResult(r) - require.NoError(t, err) - }) - t.Run("bob produces valid result", func(t *testing.T) { - // Get the result - r, err := bob.Result(protocol.Version1) - - // Test - require.NoError(t, err) - require.NotNil(t, r) - bobResult, err = DecodeBobDkgResult(r) - require.NoError(t, err) - }) - - t.Run("alice/bob agree on pubkey", func(t *testing.T) { - require.Equal(t, aliceResult.PublicKey, bobResult.PublicKey) - }) - } -} - -// -// // DKG > Refresh > Sign -// func TestRefreshProto(t *testing.T) { -// t.Parallel() -// curveInstances := []*curves.Curve{ -// curves.K256(), -// curves.P256(), -// } -// for _, curve := range curveInstances { -// boundCurve := curve -// t.Run(fmt.Sprintf("testing refresh for curve %s", boundCurve.Name), func(tt *testing.T) { -// tt.Parallel() -// // DKG -// aliceDkg := NewAliceDkg(boundCurve, protocol.Version1) -// bobDkg := NewBobDkg(boundCurve, protocol.Version1) -// -// aDkgErr, bDkgErr := runIteratedProtocol(bobDkg, aliceDkg) -// require.ErrorIs(tt, aDkgErr, protocol.ErrProtocolFinished) -// require.ErrorIs(tt, bDkgErr, protocol.ErrProtocolFinished) -// -// aliceDkgResultMessage, err := aliceDkg.Result(protocol.Version1) -// require.NoError(tt, err) -// bobDkgResultMessage, err := bobDkg.Result(protocol.Version1) -// require.NoError(tt, err) -// -// // Refresh -// aliceRefreshResultMessage, bobRefreshResultMessage := refreshV1(t, boundCurve, aliceDkgResultMessage, bobDkgResultMessage) -// -// // sign -// signV1(t, boundCurve, aliceRefreshResultMessage, bobRefreshResultMessage) -// }) -// } -// } - -// DKG > Output > NewDklsSign > Sign > Output -func TestDkgSignProto(t *testing.T) { - // Setup - curve := curves.K256() - - aliceDkg := NewAliceDkg(curve, protocol.Version1) - bobDkg := NewBobDkg(curve, protocol.Version1) - - // DKG - aErr, bErr := runIteratedProtocol(bobDkg, aliceDkg) - require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) - require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) - - // Output - aliceDkgResultMessage, err := aliceDkg.Result(protocol.Version1) - require.NoError(t, err) - - bobDkgResultMessage, err := bobDkg.Result(protocol.Version1) - require.NoError(t, err) - - // New DklsSign - msg := []byte("As soon as you trust yourself, you will know how to live.") - aliceSign, err := NewAliceSign( - curve, - sha3.New256(), - msg, - aliceDkgResultMessage, - protocol.Version1, - ) - require.NoError(t, err) - bobSign, err := NewBobSign(curve, sha3.New256(), msg, bobDkgResultMessage, protocol.Version1) - require.NoError(t, err) - - // Sign - t.Run("sign", func(t *testing.T) { - aErr, bErr = runIteratedProtocol(aliceSign, bobSign) - require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) - require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) - }) - // Don't continue to verifying results if sign didn't run to completion. - require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) - require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) - - // Output - var result *curves.EcdsaSignature - t.Run("bob produces result of correct type", func(t *testing.T) { - resultMessage, err := bobSign.Result(protocol.Version1) - require.NoError(t, err) - result, err = DecodeSignature(resultMessage) - require.NoError(t, err) - }) - require.NotNil(t, result) - - t.Run("valid signature", func(t *testing.T) { - hash := sha3.New256() - _, err = hash.Write(msg) - require.NoError(t, err) - digest := hash.Sum(nil) - unCompressedAffinePublicKey := aliceDkg.Output().PublicKey.ToAffineUncompressed() - require.Equal(t, 65, len(unCompressedAffinePublicKey)) - x := new(big.Int).SetBytes(unCompressedAffinePublicKey[1:33]) - y := new(big.Int).SetBytes(unCompressedAffinePublicKey[33:]) - ecCurve, err := curve.ToEllipticCurve() - require.NoError(t, err) - publicKey := &curves.EcPoint{ - Curve: ecCurve, - X: x, - Y: y, - } - require.True(t, - curves.VerifyEcdsa(publicKey, - digest[:], - result, - ), - "signature failed verification", - ) - }) -} - -// -// // Decode > NewDklsSign > Sign > Output -// // NOTE: this cold-start test ensures backwards compatibility with durable, -// // encoding DKG state that may exist within production systems like test -// // Breaking changes must consider downstream production impacts. -// func TestSignColdStart(t *testing.T) { -// // Decode alice/bob state from file -// aliceDkg, err := os.ReadFile("testdata/alice-dkls-v1-dkg.bin") -// require.NoError(t, err) -// bobDkg, err := os.ReadFile("testdata/bob-dkls-v1-dkg.bin") -// require.NoError(t, err) -// -// // The choice of json marshaling is arbitrary, the binary could have been marshaled in other forms as well -// // The purpose here is to obtain an instance of `protocol.Message` -// -// aliceDkgMessage := &protocol.Message{} -// err = json.Unmarshal(aliceDkg, aliceDkgMessage) -// require.NoError(t, err) -// -// bobDkgMessage := &protocol.Message{} -// err = json.Unmarshal(bobDkg, bobDkgMessage) -// require.NoError(t, err) -// -// signV1(t, curves.K256(), aliceDkgMessage, bobDkgMessage) -// } -// -// func TestEncodeDecode(t *testing.T) { -// curve := curves.K256() -// -// alice := NewAliceDkg(curve, protocol.Version1) -// bob := NewBobDkg(curve, protocol.Version1) -// _, _ = runIteratedProtocol(bob, alice) -// -// var aliceBytes []byte -// var bobBytes []byte -// t.Run("Encode Alice/Bob", func(t *testing.T) { -// aliceDkgMessage, err := EncodeAliceDkgOutput(alice.Alice.Output(), protocol.Version1) -// require.NoError(t, err) -// aliceBytes, err = json.Marshal(aliceDkgMessage) -// require.NoError(t, err) -// -// bobDkgMessage, err := EncodeBobDkgOutput(bob.Bob.Output(), protocol.Version1) -// require.NoError(t, err) -// bobBytes, err = json.Marshal(bobDkgMessage) -// require.NoError(t, err) -// }) -// require.NotEmpty(t, aliceBytes) -// require.NotEmpty(t, bobBytes) -// -// t.Run("Decode Alice", func(t *testing.T) { -// decodedAliceMessage := &protocol.Message{} -// err := json.Unmarshal(aliceBytes, decodedAliceMessage) -// require.NoError(t, err) -// require.NotNil(t, decodedAliceMessage) -// decodedAlice, err := DecodeAliceDkgResult(decodedAliceMessage) -// require.NoError(t, err) -// -// require.True(t, alice.Output().PublicKey.Equal(decodedAlice.PublicKey)) -// require.Equal(t, alice.Output().SecretKeyShare, decodedAlice.SecretKeyShare) -// }) -// -// t.Run("Decode Bob", func(t *testing.T) { -// decodedBobMessage := &protocol.Message{} -// err := json.Unmarshal(bobBytes, decodedBobMessage) -// require.NoError(t, err) -// require.NotNil(t, decodedBobMessage) -// decodedBob, err := DecodeBobDkgResult(decodedBobMessage) -// require.NoError(t, err) -// -// require.True(t, bob.Output().PublicKey.Equal(decodedBob.PublicKey)) -// require.Equal(t, bob.Output().SecretKeyShare, decodedBob.SecretKeyShare) -// }) -// } -// -// func signV1(t *testing.T, curve *curves.Curve, aliceDkgResultMessage *protocol.Message, bobDkgResultMessage *protocol.Message) { -// t.Helper() -// // New DklsSign -// msg := []byte("As soon as you trust yourself, you will know how to live.") -// aliceSign, err := NewAliceSign(curve, sha3.New256(), msg, aliceDkgResultMessage, protocol.Version1) -// require.NoError(t, err) -// bobSign, err := NewBobSign(curve, sha3.New256(), msg, bobDkgResultMessage, protocol.Version1) -// require.NoError(t, err) -// -// // Sign -// var aErr error -// var bErr error -// t.Run("sign", func(t *testing.T) { -// aErr, bErr = runIteratedProtocol(aliceSign, bobSign) -// require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) -// require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) -// }) -// // Don't continue to verifying results if sign didn't run to completion. -// require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) -// require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) -// -// // Output -// var result *curves.EcdsaSignature -// t.Run("bob produces result of correct type", func(t *testing.T) { -// resultMessage, err := bobSign.Result(protocol.Version1) -// require.NoError(t, err) -// result, err = DecodeSignature(resultMessage) -// require.NoError(t, err) -// }) -// require.NotNil(t, result) -// -// aliceDkg, err := DecodeAliceDkgResult(aliceDkgResultMessage) -// require.NoError(t, err) -// -// t.Run("valid signature", func(t *testing.T) { -// hash := sha3.New256() -// _, err = hash.Write(msg) -// require.NoError(t, err) -// digest := hash.Sum(nil) -// unCompressedAffinePublicKey := aliceDkg.PublicKey.ToAffineUncompressed() -// require.Equal(t, 65, len(unCompressedAffinePublicKey)) -// x := new(big.Int).SetBytes(unCompressedAffinePublicKey[1:33]) -// y := new(big.Int).SetBytes(unCompressedAffinePublicKey[33:]) -// ecCurve, err := curve.ToEllipticCurve() -// require.NoError(t, err) -// publicKey := &curves.EcPoint{ -// Curve: ecCurve, -// X: x, -// Y: y, -// } -// require.True(t, -// curves.VerifyEcdsa(publicKey, -// digest[:], -// result, -// ), -// "signature failed verification", -// ) -// }) -// } -// -// func refreshV1(t *testing.T, curve *curves.Curve, aliceDkgResultMessage, bobDkgResultMessage *protocol.Message) (aliceRefreshResultMessage, bobRefreshResultMessage *protocol.Message) { -// t.Helper() -// aliceRefresh, err := NewAliceRefresh(curve, aliceDkgResultMessage, protocol.Version1) -// require.NoError(t, err) -// bobRefresh, err := NewBobRefresh(curve, bobDkgResultMessage, protocol.Version1) -// require.NoError(t, err) -// -// aErr, bErr := runIteratedProtocol(aliceRefresh, bobRefresh) -// require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) -// require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) -// -// aliceRefreshResultMessage, err = aliceRefresh.Result(protocol.Version1) -// require.NoError(t, err) -// require.NotNil(t, aliceRefreshResultMessage) -// _, err = DecodeAliceRefreshResult(aliceRefreshResultMessage) -// require.NoError(t, err) -// -// bobRefreshResultMessage, err = bobRefresh.Result(protocol.Version1) -// require.NoError(t, err) -// require.NotNil(t, bobRefreshResultMessage) -// _, err = DecodeBobRefreshResult(bobRefreshResultMessage) -// require.NoError(t, err) -// -// return aliceRefreshResultMessage, bobRefreshResultMessage -// } -// -// func BenchmarkDKGProto(b *testing.B) { -// curveInstances := []*curves.Curve{ -// curves.K256(), -// curves.P256(), -// } -// for _, curve := range curveInstances { -// alice := NewAliceDkg(curve, protocol.Version1) -// bob := NewBobDkg(curve, protocol.Version1) -// aErr, bErr := runIteratedProtocol(bob, alice) -// -// b.Run("both alice/bob complete simultaneously", func(t *testing.B) { -// require.ErrorIs(t, aErr, protocol.ErrProtocolFinished) -// require.ErrorIs(t, bErr, protocol.ErrProtocolFinished) -// }) -// -// for i := 0; i < kos.Kappa; i++ { -// if alice.Alice.Output().SeedOtResult.OneTimePadDecryptionKey[i] != bob.Bob.Output().SeedOtResult.OneTimePadEncryptionKeys[i][alice.Alice.Output().SeedOtResult.RandomChoiceBits[i]] { -// b.Errorf("oblivious transfer is incorrect at index i=%v", i) -// } -// } -// -// b.Run("Both parties produces identical composite pubkey", func(t *testing.B) { -// require.True(t, alice.Alice.Output().PublicKey.Equal(bob.Bob.Output().PublicKey)) -// }) -// -// var aliceResult *dkg.AliceOutput -// var bobResult *dkg.BobOutput -// b.Run("alice produces valid result", func(t *testing.B) { -// // Get the result -// r, err := alice.Result(protocol.Version1) -// -// // Test -// require.NoError(t, err) -// require.NotNil(t, r) -// aliceResult, err = DecodeAliceDkgResult(r) -// require.NoError(t, err) -// }) -// b.Run("bob produces valid result", func(t *testing.B) { -// // Get the result -// r, err := bob.Result(protocol.Version1) -// -// // Test -// require.NoError(t, err) -// require.NotNil(t, r) -// bobResult, err = DecodeBobDkgResult(r) -// require.NoError(t, err) -// }) -// -// b.Run("alice/bob agree on pubkey", func(t *testing.B) { -// require.Equal(t, aliceResult.PublicKey, bobResult.PublicKey) -// }) -// } -// } diff --git a/crypto/tecdsa/dklsv1/refresh/refresh.go b/crypto/tecdsa/dklsv1/refresh/refresh.go deleted file mode 100644 index 8e818104a..000000000 --- a/crypto/tecdsa/dklsv1/refresh/refresh.go +++ /dev/null @@ -1,193 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// This file implements the key refresh protocol of [DKLs18](https://eprint.iacr.org/2018/499.pdf). -// The key refresh protocol is defined as follows: -// 1. Key Share: -// 1.1. alice generates k_A <-- F_q; writes it to merlin transcript. sends it to bob. -// 1.2. bob receives k_A and writes it to merlin transcript. generates k_B <-- F_q and writes it to merlin transcript. reads k out of merlin transcript. overwrites sk_B *= k. sends k_B to Alice. -// 1.3. alice writes k_B to merlin transcript. reads k from it. overwrites sk_A *= k^{-1}. -// 2. OT: Redo OT (as it is done in the DKG) -package refresh - -import ( - "crypto/rand" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -// Alice struct encoding Alice's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Alice will NOT obtain the signature. -type Alice struct { - // receiver is the base OT receiver. - receiver *simplest.Receiver - - // secretKeyShare is Alice's secret key for the joint public key. - secretKeyShare curves.Scalar - - // publicKey is the joint public key of Alice and Bob. - publicKey curves.Point - - curve *curves.Curve - - transcript *merlin.Transcript -} - -// Bob struct encoding Bob's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Bob will obtain the signature. -type Bob struct { - // sender is the base OT sender. - sender *simplest.Sender - - // secretKeyShare is Bob's secret key for the joint public key. - secretKeyShare curves.Scalar - - // publicKey is the joint public key of Alice and Bob. - publicKey curves.Point - - curve *curves.Curve - - transcript *merlin.Transcript -} - -type RefreshRound2Output struct { - SeedOTRound1Output *schnorr.Proof - BobMultiplier curves.Scalar -} - -// NewAliceRefresh creates a party that can participate in 2-of-2 key refresh. -func NewAlice(curve *curves.Curve, dkgOutput *dkg.AliceOutput) *Alice { - return &Alice{ - curve: curve, - secretKeyShare: dkgOutput.SecretKeyShare, - publicKey: dkgOutput.PublicKey, - transcript: merlin.NewTranscript("Coinbase_DKLs_Refresh"), - } -} - -// NewBobRefresh creates a party that can participate in 2-of-2 key refresh. -func NewBob(curve *curves.Curve, dkgOutput *dkg.BobOutput) *Bob { - return &Bob{ - curve: curve, - secretKeyShare: dkgOutput.SecretKeyShare, - publicKey: dkgOutput.PublicKey, - transcript: merlin.NewTranscript("Coinbase_DKLs_Refresh"), - } -} - -func (alice *Alice) Round1RefreshGenerateSeed() curves.Scalar { - refreshSeed := alice.curve.Scalar.Random(rand.Reader) - alice.transcript.AppendMessage([]byte("alice refresh seed"), refreshSeed.Bytes()) - return refreshSeed -} - -func (bob *Bob) Round2RefreshProduceSeedAndMultiplyAndStartOT( - aliceSeed curves.Scalar, -) (*RefreshRound2Output, error) { - bob.transcript.AppendMessage([]byte("alice refresh seed"), aliceSeed.Bytes()) - bobSeed := bob.curve.Scalar.Random(rand.Reader) - bob.transcript.AppendMessage([]byte("bob refresh seed"), bobSeed.Bytes()) - k, err := bob.curve.NewScalar().SetBytes( - bob.transcript.ExtractBytes([]byte("secret key share multiplier"), simplest.DigestSize), - ) - if err != nil { - return nil, errors.Wrap(err, "couldn't produce bob's secret key share multiplier") - } - bob.secretKeyShare = bob.secretKeyShare.Mul(k) - - uniqueSessionId := [simplest.DigestSize]byte{} // note: will use and re-use this below for sub-session IDs. - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("salt for simplest OT"), simplest.DigestSize), - ) - bob.sender, err = simplest.NewSender(bob.curve, kos.Kappa, uniqueSessionId) - if err != nil { - return nil, errors.Wrap(err, "bob constructing new OT sender in refresh round 2") - } - seedOTRound1Output, err := bob.sender.Round1ComputeAndZkpToPublicKey() - if err != nil { - return nil, errors.Wrap(err, "bob computing round 1 of seed OT within refresh round 2") - } - - return &RefreshRound2Output{ - SeedOTRound1Output: seedOTRound1Output, - BobMultiplier: bobSeed, - }, nil -} - -func (alice *Alice) Round3RefreshMultiplyRound2Ot( - input *RefreshRound2Output, -) ([]simplest.ReceiversMaskedChoices, error) { - alice.transcript.AppendMessage([]byte("bob refresh seed"), input.BobMultiplier.Bytes()) - k, err := alice.curve.NewScalar().SetBytes( - alice.transcript.ExtractBytes([]byte("secret key share multiplier"), simplest.DigestSize), - ) - if err != nil { - return nil, errors.Wrap(err, "couldn't produce bob's secret key share multiplier") - } - kInverse, err := k.Invert() - if err != nil { - return nil, errors.Wrap(err, "couldn't produce k inverse (alice's secret key share)") - } - alice.secretKeyShare = alice.secretKeyShare.Mul(kInverse) - - uniqueSessionId := [simplest.DigestSize]byte{} // note: will use and re-use this below for sub-session IDs. - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("salt for simplest OT"), simplest.DigestSize), - ) - alice.receiver, err = simplest.NewReceiver(alice.curve, kos.Kappa, uniqueSessionId) - if err != nil { - return nil, errors.Wrap(err, "couldn't construct OT receiver") - } - - return alice.receiver.Round2VerifySchnorrAndPadTransfer(input.SeedOTRound1Output) -} - -func (bob *Bob) Round4RefreshRound3Ot( - compressedReceiversMaskedChoice []simplest.ReceiversMaskedChoices, -) ([]simplest.OtChallenge, error) { - return bob.sender.Round3PadTransfer(compressedReceiversMaskedChoice) -} - -func (alice *Alice) Round5RefreshRound4Ot( - challenge []simplest.OtChallenge, -) ([]simplest.OtChallengeResponse, error) { - return alice.receiver.Round4RespondToChallenge(challenge) -} - -func (bob *Bob) Round6RefreshRound5Ot( - challengeResponses []simplest.OtChallengeResponse, -) ([]simplest.ChallengeOpening, error) { - return bob.sender.Round5Verify(challengeResponses) -} - -func (alice *Alice) Round7DkgRound6Ot(challengeOpenings []simplest.ChallengeOpening) error { - return alice.receiver.Round6Verify(challengeOpenings) -} - -func (alice *Alice) Output() *dkg.AliceOutput { - return &dkg.AliceOutput{ - PublicKey: alice.publicKey, - SecretKeyShare: alice.secretKeyShare, - SeedOtResult: alice.receiver.Output, - } -} - -func (bob *Bob) Output() *dkg.BobOutput { - return &dkg.BobOutput{ - PublicKey: bob.publicKey, - SecretKeyShare: bob.secretKeyShare, - SeedOtResult: bob.sender.Output, - } -} diff --git a/crypto/tecdsa/dklsv1/refresh/refresh_test.go b/crypto/tecdsa/dklsv1/refresh/refresh_test.go deleted file mode 100644 index 2e830a597..000000000 --- a/crypto/tecdsa/dklsv1/refresh/refresh_test.go +++ /dev/null @@ -1,215 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package refresh_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/refresh" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/sign" -) - -func performDKG(t *testing.T, curve *curves.Curve) (*dkg.Alice, *dkg.Bob) { - t.Helper() - - alice := dkg.NewAlice(curve) - bob := dkg.NewBob(curve) - - seed, err := bob.Round1GenerateRandomSeed() - require.NoError(t, err) - round3Output, err := alice.Round2CommitToProof(seed) - require.NoError(t, err) - proof, err := bob.Round3SchnorrProve(round3Output) - require.NoError(t, err) - proof, err = alice.Round4VerifyAndReveal(proof) - require.NoError(t, err) - proof, err = bob.Round5DecommitmentAndStartOt(proof) - require.NoError(t, err) - compressedReceiversMaskedChoice, err := alice.Round6DkgRound2Ot(proof) - require.NoError(t, err) - challenge, err := bob.Round7DkgRound3Ot(compressedReceiversMaskedChoice) - require.NoError(t, err) - challengeResponse, err := alice.Round8DkgRound4Ot(challenge) - require.NoError(t, err) - challengeOpenings, err := bob.Round9DkgRound5Ot(challengeResponse) - require.NoError(t, err) - err = alice.Round10DkgRound6Ot(challengeOpenings) - require.NoError(t, err) - - return alice, bob -} - -func performRefresh( - t *testing.T, - curve *curves.Curve, - aliceSecretKeyShare, bobSecretKeyShare curves.Scalar, -) (*refresh.Alice, *refresh.Bob) { - t.Helper() - alice := refresh.NewAlice(curve, &dkg.AliceOutput{SecretKeyShare: aliceSecretKeyShare}) - bob := refresh.NewBob(curve, &dkg.BobOutput{SecretKeyShare: bobSecretKeyShare}) - - round1Output := alice.Round1RefreshGenerateSeed() - require.False(t, round1Output.IsZero()) - round2Output, err := bob.Round2RefreshProduceSeedAndMultiplyAndStartOT(round1Output) - require.NoError(t, err) - round3Output, err := alice.Round3RefreshMultiplyRound2Ot(round2Output) - require.NoError(t, err) - round4Output, err := bob.Round4RefreshRound3Ot(round3Output) - require.NoError(t, err) - round5Output, err := alice.Round5RefreshRound4Ot(round4Output) - require.NoError(t, err) - round6Output, err := bob.Round6RefreshRound5Ot(round5Output) - require.NoError(t, err) - err = alice.Round7DkgRound6Ot(round6Output) - require.NoError(t, err) - return alice, bob -} - -func Test_RefreshLeadsToTheSamePublicKeyButDifferentPrivateMaterial(t *testing.T) { - t.Parallel() - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - boundCurve := curve - t.Run(fmt.Sprintf("testing refresh for curve %s", boundCurve.Name), func(tt *testing.T) { - tt.Parallel() - alice, bob := performDKG(tt, boundCurve) - - publicKey := alice.Output().PublicKey - require.True(tt, publicKey.Equal(bob.Output().PublicKey)) - - aliceRefreshed, bobRefreshed := performRefresh( - tt, - boundCurve, - alice.Output().SecretKeyShare, - bob.Output().SecretKeyShare, - ) - - require.NotEqual( - tt, - aliceRefreshed.Output().SecretKeyShare, - alice.Output().SecretKeyShare, - ) - require.NotEqual(tt, bobRefreshed.Output().SeedOtResult, bob.Output().SecretKeyShare) - require.NotEqualValues( - tt, - aliceRefreshed.Output().SeedOtResult.OneTimePadDecryptionKey, - alice.Output().SeedOtResult.OneTimePadDecryptionKey, - ) - require.NotEqualValues( - tt, - aliceRefreshed.Output().SeedOtResult.PackedRandomChoiceBits, - alice.Output().SeedOtResult.PackedRandomChoiceBits, - ) - require.NotEqualValues( - tt, - aliceRefreshed.Output().SeedOtResult.RandomChoiceBits, - alice.Output().SeedOtResult.RandomChoiceBits, - ) - require.NotEqualValues( - tt, - bobRefreshed.Output().SeedOtResult.OneTimePadEncryptionKeys, - bob.Output().SeedOtResult.OneTimePadEncryptionKeys, - ) - - pkA := boundCurve.ScalarBaseMult(aliceRefreshed.Output().SecretKeyShare) - computedPublicKeyA := pkA.Mul(bobRefreshed.Output().SecretKeyShare) - require.True(tt, computedPublicKeyA.Equal(publicKey)) - - pkB := boundCurve.ScalarBaseMult(bobRefreshed.Output().SecretKeyShare) - computedPublicKeyB := pkB.Mul(aliceRefreshed.Output().SecretKeyShare) - require.True(tt, computedPublicKeyB.Equal(publicKey)) - }) - } -} - -func Test_RefreshOTIsCorrect(t *testing.T) { - t.Parallel() - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - boundCurve := curve - t.Run( - fmt.Sprintf("testing OT correctness of key refresh for curve %s", boundCurve.Name), - func(tt *testing.T) { - tt.Parallel() - alice, bob := performDKG(tt, boundCurve) - aliceRefreshed, bobRefreshed := performRefresh( - tt, - boundCurve, - alice.Output().SecretKeyShare, - bob.Output().SecretKeyShare, - ) - for i := 0; i < kos.Kappa; i++ { - if aliceRefreshed.Output().SeedOtResult.OneTimePadDecryptionKey[i] != bobRefreshed.Output().SeedOtResult.OneTimePadEncryptionKeys[i][aliceRefreshed.Output().SeedOtResult.RandomChoiceBits[i]] { - tt.Errorf("oblivious transfer is incorrect at index i=%v", i) - } - } - }, - ) - } -} - -func Test_CanSignAfterRefresh(t *testing.T) { - t.Parallel() - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - boundCurve := curve - t.Run( - fmt.Sprintf("testing sign after refresh for curve %s", boundCurve.Name), - func(tt *testing.T) { - tt.Parallel() - aliceDKG, bobDKG := performDKG(tt, boundCurve) - - publicKey := aliceDKG.Output().PublicKey - require.True(tt, publicKey.Equal(bobDKG.Output().PublicKey)) - - aliceRefreshed, bobRefreshed := performRefresh( - tt, - boundCurve, - aliceDKG.Output().SecretKeyShare, - bobDKG.Output().SecretKeyShare, - ) - - alice := sign.NewAlice(boundCurve, sha3.New256(), &dkg.AliceOutput{ - SeedOtResult: aliceRefreshed.Output().SeedOtResult, - SecretKeyShare: aliceRefreshed.Output().SecretKeyShare, - PublicKey: publicKey, - }) - bob := sign.NewBob(boundCurve, sha3.New256(), &dkg.BobOutput{ - SeedOtResult: bobRefreshed.Output().SeedOtResult, - SecretKeyShare: bobRefreshed.Output().SecretKeyShare, - PublicKey: publicKey, - }) - - message := []byte("A message.") - seed, err := alice.Round1GenerateRandomSeed() - require.NoError(tt, err) - round3Output, err := bob.Round2Initialize(seed) - require.NoError(tt, err) - round4Output, err := alice.Round3Sign(message, round3Output) - require.NoError(tt, err) - err = bob.Round4Final(message, round4Output) - require.NoError(tt, err, "curve: %s", boundCurve.Name) - }, - ) - } -} diff --git a/crypto/tecdsa/dklsv1/refreshserializers.go b/crypto/tecdsa/dklsv1/refreshserializers.go deleted file mode 100644 index c7e992665..000000000 --- a/crypto/tecdsa/dklsv1/refreshserializers.go +++ /dev/null @@ -1,253 +0,0 @@ -package dklsv1 - -import ( - "bytes" - "encoding/gob" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/refresh" -) - -func newRefreshProtocolMessage(payload []byte, round string, version uint) *protocol.Message { - return &protocol.Message{ - Protocol: protocol.Dkls18Refresh, - Version: version, - Payloads: map[string][]byte{payloadKey: payload}, - Metadata: map[string]string{"round": round}, - } -} - -func versionIsSupported(messageVersion uint) error { - if messageVersion < uint(protocol.Version1) { - return errors.New("only version 1 is supported.") - } - return nil -} - -func encodeRefreshRound1Output(seed curves.Scalar, version uint) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(&seed); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "1", version), nil -} - -func decodeRefreshRound2Input(m *protocol.Message) (curves.Scalar, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(curves.Scalar) - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return *decoded, nil -} - -func encodeRefreshRound2Output( - output *refresh.RefreshRound2Output, - version uint, -) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(output); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "2", version), nil -} - -func decodeRefreshRound3Input(m *protocol.Message) (*refresh.RefreshRound2Output, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(refresh.RefreshRound2Output) - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeRefreshRound3Output( - choices []simplest.ReceiversMaskedChoices, - version uint, -) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(choices); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "3", version), nil -} - -func decodeRefreshRound4Input(m *protocol.Message) ([]simplest.ReceiversMaskedChoices, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.ReceiversMaskedChoices{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeRefreshRound4Output( - challenge []simplest.OtChallenge, - version uint, -) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(challenge); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "4", version), nil -} - -func decodeRefreshRound5Input(m *protocol.Message) ([]simplest.OtChallenge, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.OtChallenge{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeRefreshRound5Output( - responses []simplest.OtChallengeResponse, - version uint, -) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(responses); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "5", version), nil -} - -func decodeRefreshRound6Input(m *protocol.Message) ([]simplest.OtChallengeResponse, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.OtChallengeResponse{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeRefreshRound6Output( - opening []simplest.ChallengeOpening, - version uint, -) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(opening); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "6", version), nil -} - -func decodeRefreshRound7Input(m *protocol.Message) ([]simplest.ChallengeOpening, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := []simplest.ChallengeOpening{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -// EncodeAliceRefreshOutput serializes Alice Refresh output based on the protocol version. -func EncodeAliceRefreshOutput(result *dkg.AliceOutput, version uint) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "alice-output", version), nil -} - -// DecodeAliceRefreshResult deserializes Alice refresh output. -func DecodeAliceRefreshResult(m *protocol.Message) (*dkg.AliceOutput, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - registerTypes() - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(dkg.AliceOutput) - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -// EncodeBobRefreshOutput serializes Bob refresh output based on the protocol version. -func EncodeBobRefreshOutput(result *dkg.BobOutput, version uint) (*protocol.Message, error) { - if err := versionIsSupported(version); err != nil { - return nil, errors.Wrap(err, "version error") - } - registerTypes() - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.WithStack(err) - } - return newRefreshProtocolMessage(buf.Bytes(), "bob-output", version), nil -} - -// DecodeBobRefreshResult deserializes Bob refhresh output. -func DecodeBobRefreshResult(m *protocol.Message) (*dkg.BobOutput, error) { - if err := versionIsSupported(m.Version); err != nil { - return nil, errors.Wrap(err, "version error") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := new(dkg.BobOutput) - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} diff --git a/crypto/tecdsa/dklsv1/sign/multiply.go b/crypto/tecdsa/dklsv1/sign/multiply.go deleted file mode 100644 index 7905aaa8e..000000000 --- a/crypto/tecdsa/dklsv1/sign/multiply.go +++ /dev/null @@ -1,299 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sign - -import ( - "crypto/rand" - "crypto/subtle" - "fmt" - "math/big" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" -) - -// This implements the Multiplication protocol of DKLs, protocol 5. https://eprint.iacr.org/2018/499.pdf -// two parties---the "sender" and "receiver", let's say---each input a scalar modulo q. -// the functionality multiplies their two scalars modulo q, and then randomly additively shares the product mod q. -// it then returns the two respective additive shares to the two parties. - -// MultiplySender is the party that plays the role of Sender in the multiplication protocol (protocol 5 of the paper). -type MultiplySender struct { - cOtSender *kos.Sender // underlying cOT sender struct, used by mult. - outputAdditiveShare curves.Scalar // ultimate output share of mult. - gadget [kos.L]curves.Scalar - curve *curves.Curve - transcript *merlin.Transcript - uniqueSessionId [simplest.DigestSize]byte -} - -// MultiplyReceiver is the party that plays the role of Sender in the multiplication protocol (protocol 5 of the paper). -type MultiplyReceiver struct { - cOtReceiver *kos.Receiver // underlying cOT receiver struct, used by mult. - outputAdditiveShare curves.Scalar // ultimate output share of mult. - omega [kos.COtBlockSizeBytes]byte // this is used as an intermediate result during the course of mult. - gadget [kos.L]curves.Scalar - curve *curves.Curve - transcript *merlin.Transcript - uniqueSessionId [simplest.DigestSize]byte -} - -func generateGadgetVector(curve *curves.Curve) ([kos.L]curves.Scalar, error) { - var err error - gadget := [kos.L]curves.Scalar{} - for i := 0; i < kos.Kappa; i++ { - gadget[i], err = curve.Scalar.SetBigInt(new(big.Int).Lsh(big.NewInt(1), uint(i))) - if err != nil { - return gadget, errors.Wrap(err, "creating gadget scalar from big int") - } - } - shake := sha3.NewCShake256(nil, []byte("Coinbase DKLs gadget vector")) - for i := kos.Kappa; i < kos.L; i++ { - var err error - bytes := [simplest.DigestSize]byte{} - if _, err = shake.Read(bytes[:]); err != nil { - return gadget, err - } - gadget[i], err = curve.Scalar.SetBytes(bytes[:]) - if err != nil { - return gadget, errors.Wrap(err, "creating gadget scalar from bytes") - } - } - return gadget, nil -} - -// NewMultiplySender generates a `MultiplySender` instance, ready to take part in multiplication as the "sender". -// You must supply it the _output_ of a seed OT, from the receiver's point of view, as well as params and a unique ID. -// That is, the mult sender must run the base OT as the receiver; note the (apparent) reversal of roles. -func NewMultiplySender( - seedOtResults *simplest.ReceiverOutput, - curve *curves.Curve, - uniqueSessionId [simplest.DigestSize]byte, -) (*MultiplySender, error) { - sender := kos.NewCOtSender(seedOtResults, curve) - gadget, err := generateGadgetVector(curve) - if err != nil { - return nil, errors.Wrap(err, "error generating gadget vector in new multiply sender") - } - - transcript := merlin.NewTranscript("Coinbase_DKLs_Multiply") - transcript.AppendMessage([]byte("session_id"), uniqueSessionId[:]) - return &MultiplySender{ - cOtSender: sender, - curve: curve, - transcript: transcript, - uniqueSessionId: uniqueSessionId, - gadget: gadget, - }, nil -} - -// NewMultiplyReceiver generates a `MultiplyReceiver` instance, ready to take part in multiplication as the "receiver". -// You must supply it the _output_ of a seed OT, from the sender's point of view, as well as params and a unique ID. -// That is, the mult sender must run the base OT as the sender; note the (apparent) reversal of roles. -func NewMultiplyReceiver( - seedOtResults *simplest.SenderOutput, - curve *curves.Curve, - uniqueSessionId [simplest.DigestSize]byte, -) (*MultiplyReceiver, error) { - receiver := kos.NewCOtReceiver(seedOtResults, curve) - gadget, err := generateGadgetVector(curve) - if err != nil { - return nil, errors.Wrap(err, "error generating gadget vector in new multiply receiver") - } - transcript := merlin.NewTranscript("Coinbase_DKLs_Multiply") - transcript.AppendMessage([]byte("session_id"), uniqueSessionId[:]) - return &MultiplyReceiver{ - cOtReceiver: receiver, - curve: curve, - transcript: transcript, - uniqueSessionId: uniqueSessionId, - gadget: gadget, - }, nil -} - -// MultiplyRound2Output is the output of the second round of the multiplication protocol. -type MultiplyRound2Output struct { - COTRound2Output *kos.Round2Output - R [kos.L]curves.Scalar - U curves.Scalar -} - -// Algorithm 5. in DKLs. "Encodes" Bob's secret input scalars `beta` in the right way, using the opts. -// The idea is that if Bob were to just put beta's as the choice vector, then Alice could learn a few of Bob's bits. -// using selective failure attacks. so you subtract random components of a public random vector. see paper for details. -func (receiver *MultiplyReceiver) encode(beta curves.Scalar) ([kos.COtBlockSizeBytes]byte, error) { - // passing beta by value, so that we can mutate it locally. check that this does what i want. - encoding := [kos.COtBlockSizeBytes]byte{} - bytesOfBetaMinusDotProduct := beta.Bytes() - if _, err := rand.Read(encoding[kos.KappaBytes:]); err != nil { - return encoding, errors.Wrap( - err, - "sampling `gamma` random bytes in multiply receiver encode", - ) - } - for j := kos.Kappa; j < kos.L; j++ { - jthBitOfGamma := simplest.ExtractBitFromByteVector(encoding[:], j) - // constant-time computation of the dot product beta - < gR, gamma >. - // we can only `ConstantTimeCopy` byte slices (as opposed to big ints). so keep them as bytes. - option0, err := receiver.curve.Scalar.SetBytes(bytesOfBetaMinusDotProduct[:]) - if err != nil { - return encoding, errors.Wrap(err, "setting masking bits scalar from bytes") - } - option0Bytes := option0.Bytes() - option1 := option0.Sub(receiver.gadget[j]) - option1Bytes := option1.Bytes() - bytesOfBetaMinusDotProduct = option0Bytes - subtle.ConstantTimeCopy(int(jthBitOfGamma), bytesOfBetaMinusDotProduct[:], option1Bytes) - } - copy(encoding[0:kos.KappaBytes], internal.ReverseScalarBytes(bytesOfBetaMinusDotProduct[:])) - return encoding, nil -} - -// Round1Initialize Protocol 5., Multiplication, 3). Bob (receiver) encodes beta and initiates the cOT extension -func (receiver *MultiplyReceiver) Round1Initialize(beta curves.Scalar) (*kos.Round1Output, error) { - var err error - if receiver.omega, err = receiver.encode(beta); err != nil { - return nil, errors.Wrap(err, "encoding input beta in receiver round 1 initialize") - } - cOtRound1Output, err := receiver.cOtReceiver.Round1Initialize( - receiver.uniqueSessionId, - receiver.omega, - ) - if err != nil { - return nil, errors.Wrap( - err, - "error in cOT round 1 initialize within multiply round 1 initialize", - ) - } - // write the output of the first round to the transcript - for i := 0; i < kos.Kappa; i++ { - label := []byte(fmt.Sprintf("row %d of U", i)) - receiver.transcript.AppendMessage(label, cOtRound1Output.U[i][:]) - } - receiver.transcript.AppendMessage([]byte("wPrime"), cOtRound1Output.WPrime[:]) - receiver.transcript.AppendMessage([]byte("vPrime"), cOtRound1Output.VPrime[:]) - return cOtRound1Output, nil -} - -// Round2Multiply Protocol 5., steps 3) 5), 7). Alice _responds_ to Bob's initial cOT message, using alpha as input. -// Doesn't actually send the message yet, only stashes it and moves onto the next steps of the multiplication protocol -// specifically, Alice can then do step 5) (compute the outputs of the multiplication protocol), also stashes this. -// Finishes by taking care of 7), after that, Alice is totally done with multiplication and has stashed the outputs. -func (sender *MultiplySender) Round2Multiply( - alpha curves.Scalar, - round1Output *kos.Round1Output, -) (*MultiplyRound2Output, error) { - var err error - alphaHat := sender.curve.Scalar.Random(rand.Reader) - input := [kos.L][2]curves.Scalar{} // sender's input, namely integer "sums" in case w_j == 1. - for j := 0; j < kos.L; j++ { - input[j][0] = alpha - input[j][1] = alphaHat - } - round2Output := &MultiplyRound2Output{} - round2Output.COTRound2Output, err = sender.cOtSender.Round2Transfer( - sender.uniqueSessionId, - input, - round1Output, - ) - if err != nil { - return nil, errors.Wrap(err, "error in cOT within round 2 multiply") - } - // write the output of the first round to the transcript - for i := 0; i < kos.Kappa; i++ { - label := []byte(fmt.Sprintf("row %d of U", i)) - sender.transcript.AppendMessage(label, round1Output.U[i][:]) - } - sender.transcript.AppendMessage([]byte("wPrime"), round1Output.WPrime[:]) - sender.transcript.AppendMessage([]byte("vPrime"), round1Output.VPrime[:]) - // write our own output of the second round to the transcript - chiWidth := 2 - for i := 0; i < kos.Kappa; i++ { - for k := 0; k < chiWidth; k++ { - label := []byte(fmt.Sprintf("row %d of Tau", i)) - sender.transcript.AppendMessage(label, round2Output.COTRound2Output.Tau[i][k].Bytes()) - } - } - chi := make([]curves.Scalar, chiWidth) - for k := 0; k < 2; k++ { - label := []byte(fmt.Sprintf("draw challenge chi %d", k)) - randomBytes := sender.transcript.ExtractBytes(label, kos.KappaBytes) - chi[k], err = sender.curve.Scalar.SetBytes(randomBytes) - if err != nil { - return nil, errors.Wrap(err, "setting chi scalar from bytes") - } - } - sender.outputAdditiveShare = sender.curve.Scalar.Zero() - for j := 0; j < kos.L; j++ { - round2Output.R[j] = sender.curve.Scalar.Zero() - for k := 0; k < chiWidth; k++ { - round2Output.R[j] = round2Output.R[j].Add( - chi[k].Mul(sender.cOtSender.OutputAdditiveShares[j][k]), - ) - } - sender.outputAdditiveShare = sender.outputAdditiveShare.Add( - sender.gadget[j].Mul(sender.cOtSender.OutputAdditiveShares[j][0]), - ) - } - round2Output.U = chi[0].Mul(alpha).Add(chi[1].Mul(alphaHat)) - return round2Output, nil -} - -// Round3Multiply Protocol 5., Multiplication, 3) and 6). Bob finalizes the cOT extension. -// using that and Alice's multiplication message, Bob completes the multiplication protocol, including checks. -// At the end, Bob's values tB_j are populated. -func (receiver *MultiplyReceiver) Round3Multiply(round2Output *MultiplyRound2Output) error { - chiWidth := 2 - // write the output of the second round to the transcript - for i := 0; i < kos.Kappa; i++ { - for k := 0; k < chiWidth; k++ { - label := []byte(fmt.Sprintf("row %d of Tau", i)) - receiver.transcript.AppendMessage(label, round2Output.COTRound2Output.Tau[i][k].Bytes()) - } - } - if err := receiver.cOtReceiver.Round3Transfer(round2Output.COTRound2Output); err != nil { - return errors.Wrap(err, "error within cOT round 3 transfer within round 3 multiply") - } - var err error - chi := make([]curves.Scalar, chiWidth) - for k := 0; k < chiWidth; k++ { - label := []byte(fmt.Sprintf("draw challenge chi %d", k)) - randomBytes := receiver.transcript.ExtractBytes(label, kos.KappaBytes) - chi[k], err = receiver.curve.Scalar.SetBytes(randomBytes) - if err != nil { - return errors.Wrap(err, "setting chi scalar from bytes") - } - } - - receiver.outputAdditiveShare = receiver.curve.Scalar.Zero() - for j := 0; j < kos.L; j++ { - // compute the LHS of bob's step 6) for j. note that we're "adding r_j" to both sides"; so this LHS includes r_j. - // the reason to do this is so that the constant-time (i.e., independent of w_j) calculation of w_j * u can proceed more cleanly. - leftHandSideOfCheck := round2Output.R[j] - for k := 0; k < chiWidth; k++ { - leftHandSideOfCheck = leftHandSideOfCheck.Add( - chi[k].Mul(receiver.cOtReceiver.OutputAdditiveShares[j][k]), - ) - } - rightHandSideOfCheck := [simplest.DigestSize]byte{} - jthBitOfOmega := simplest.ExtractBitFromByteVector(receiver.omega[:], j) - subtle.ConstantTimeCopy(int(jthBitOfOmega), rightHandSideOfCheck[:], round2Output.U.Bytes()) - if subtle.ConstantTimeCompare(rightHandSideOfCheck[:], leftHandSideOfCheck.Bytes()) != 1 { - return fmt.Errorf("alice's values R and U failed to check in round 3 multiply") - } - receiver.outputAdditiveShare = receiver.outputAdditiveShare.Add( - receiver.gadget[j].Mul(receiver.cOtReceiver.OutputAdditiveShares[j][0]), - ) - } - return nil -} diff --git a/crypto/tecdsa/dklsv1/sign/multiply_test.go b/crypto/tecdsa/dklsv1/sign/multiply_test.go deleted file mode 100644 index c4af12d0f..000000000 --- a/crypto/tecdsa/dklsv1/sign/multiply_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sign - -import ( - "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/ot/ottest" -) - -func TestMultiply(t *testing.T) { - curve := curves.K256() - hashKeySeed := [simplest.DigestSize]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(t, err) - - baseOtSenderOutput, baseOtReceiverOutput, err := ottest.RunSimplestOT( - curve, - kos.Kappa, - hashKeySeed, - ) - require.NoError(t, err) - - sender, err := NewMultiplySender(baseOtReceiverOutput, curve, hashKeySeed) - require.NoError(t, err) - receiver, err := NewMultiplyReceiver(baseOtSenderOutput, curve, hashKeySeed) - require.NoError(t, err) - - alpha := curve.Scalar.Random(rand.Reader) - beta := curve.Scalar.Random(rand.Reader) - - round1Output, err := receiver.Round1Initialize(beta) - require.Nil(t, err) - round2Output, err := sender.Round2Multiply(alpha, round1Output) - require.Nil(t, err) - err = receiver.Round3Multiply(round2Output) - require.Nil(t, err) - - product := alpha.Mul(beta) - sum := sender.outputAdditiveShare.Add(receiver.outputAdditiveShare) - require.Equal(t, product, sum) -} diff --git a/crypto/tecdsa/dklsv1/sign/sign.go b/crypto/tecdsa/dklsv1/sign/sign.go deleted file mode 100644 index 0679ac31e..000000000 --- a/crypto/tecdsa/dklsv1/sign/sign.go +++ /dev/null @@ -1,409 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package sign implements the 2-2 threshold signature protocol of [DKLs18](https://eprint.iacr.org/2018/499.pdf). -// The signing protocol is defined in "Protocol 4" page 9, of the paper. The Zero Knowledge Proof ideal functionalities are -// realized using schnorr proofs. -package sign - -import ( - "crypto/ecdsa" - "crypto/rand" - "fmt" - "hash" - "math/big" - - "github.com/gtank/merlin" - "github.com/pkg/errors" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" - "github.com/sonr-io/sonr/crypto/zkp/schnorr" -) - -const multiplicationCount = 2 - -// Alice struct encoding Alice's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Alice will not possess the signature. -type Alice struct { - hash hash.Hash // which hash function should we use to compute message (i.e, teh digest) - seedOtResults *simplest.ReceiverOutput - secretKeyShare curves.Scalar // the witness - publicKey curves.Point - curve *curves.Curve - transcript *merlin.Transcript -} - -// Bob struct encoding Bob's state during one execution of the overall signing algorithm. -// At the end of the joint computation, Bob will obtain the signature. -type Bob struct { - // Signature is the resulting digital signature and is the output of this protocol. - Signature *curves.EcdsaSignature - - hash hash.Hash // which hash function should we use to compute message - seedOtResults *simplest.SenderOutput - secretKeyShare curves.Scalar - publicKey curves.Point - transcript *merlin.Transcript - // multiplyReceivers are 2 receivers that are used to perform the two multiplications needed: - // 1. (phi + 1/kA) * (1/kB) - // 2. skA/KA * skB/kB - multiplyReceivers [multiplicationCount]*MultiplyReceiver - kB curves.Scalar - dB curves.Point - curve *curves.Curve -} - -// NewAlice creates a party that can participate in protocol runs of DKLs sign, in the role of Alice. -func NewAlice(curve *curves.Curve, hash hash.Hash, dkgOutput *dkg.AliceOutput) *Alice { - return &Alice{ - hash: hash, - seedOtResults: dkgOutput.SeedOtResult, - curve: curve, - secretKeyShare: dkgOutput.SecretKeyShare, - publicKey: dkgOutput.PublicKey, - transcript: merlin.NewTranscript("Coinbase_DKLs_Sign"), - } -} - -// NewBob creates a party that can participate in protocol runs of DKLs sign, in the role of Bob. -// This party receives the signature at the end. -func NewBob(curve *curves.Curve, hash hash.Hash, dkgOutput *dkg.BobOutput) *Bob { - return &Bob{ - hash: hash, - seedOtResults: dkgOutput.SeedOtResult, - curve: curve, - secretKeyShare: dkgOutput.SecretKeyShare, - publicKey: dkgOutput.PublicKey, - transcript: merlin.NewTranscript("Coinbase_DKLs_Sign"), - } -} - -// SignRound2Output is the output of the 3rd round of the protocol. -type SignRound2Output struct { - // KosRound1Outputs is the output of the first round of OT Extension, stored for future rounds. - KosRound1Outputs [multiplicationCount]*kos.Round1Output - - // DB is D_{B} = k_{B} . G from the paper. - DB curves.Point - - // Seed is the random value used to derive the joint unique session id. - Seed [simplest.DigestSize]byte -} - -// SignRound3Output is the output of the 3rd round of the protocol. -type SignRound3Output struct { - // MultiplyRound2Outputs is the output of the second round of multiply sub-protocol. Stored to use in future rounds. - MultiplyRound2Outputs [multiplicationCount]*MultiplyRound2Output - - // RSchnorrProof is ZKP for the value R = k_{A} . D_{B} from the paper. - RSchnorrProof *schnorr.Proof - - // RPrime is R' = k'_{A} . D_{B} from the paper. - RPrime curves.Point - - // EtaPhi is the Eta_{Phi} from the paper. - EtaPhi curves.Scalar - - // EtaSig is the Eta_{Sig} from the paper. - EtaSig curves.Scalar -} - -// Round1GenerateRandomSeed first step of the generation of the shared random salt `idExt` -// in this round, Alice flips 32 random bytes and sends them to Bob. -// Note that this is not _explicitly_ given as part of the protocol in https://eprint.iacr.org/2018/499.pdf, Protocol 1). -// Rather, it is part of our generation of `idExt`, the shared random salt which both parties must use in cOT. -// This value introduced in Protocol 9), very top of page 16. it is not indicated how it should be derived. -// We do it by having each party sample 32 bytes, then by appending _both_ as salts. Secure if either party is honest -func (alice *Alice) Round1GenerateRandomSeed() ([simplest.DigestSize]byte, error) { - aliceSeed := [simplest.DigestSize]byte{} - if _, err := rand.Read(aliceSeed[:]); err != nil { - return [simplest.DigestSize]byte{}, errors.Wrap( - err, - "generating random bytes in alice round 1 generate", - ) - } - alice.transcript.AppendMessage([]byte("session_id_alice"), aliceSeed[:]) - return aliceSeed, nil -} - -// Round2Initialize Bob's initial message, which kicks off the signature process. Protocol 1, Bob's steps 1) - 3). -// Bob's work here entails beginning the Diffie–Hellman-like construction of the instance key / nonce, -// as well as preparing the inputs which he will feed into the multiplication protocol, -// and moreover actually initiating the (first respective messages of) the multiplication protocol using these inputs. -// This latter step in turn amounts to sending the initial message in a new cOT extension. -// All the resulting data gets packaged and sent to Alice. -func (bob *Bob) Round2Initialize(aliceSeed [simplest.DigestSize]byte) (*SignRound2Output, error) { - bobSeed := [simplest.DigestSize]byte{} - if _, err := rand.Read(bobSeed[:]); err != nil { - return nil, errors.Wrap(err, "flipping random coins in bob round 2 initialize") - } - bob.transcript.AppendMessage([]byte("session_id_alice"), aliceSeed[:]) - bob.transcript.AppendMessage([]byte("session_id_bob"), bobSeed[:]) - - var err error - uniqueSessionId := [simplest.DigestSize]byte{} // will use and _re-use_ this throughout, for sub-session IDs - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("multiply receiver id 0"), simplest.DigestSize), - ) - bob.multiplyReceivers[0], err = NewMultiplyReceiver( - bob.seedOtResults, - bob.curve, - uniqueSessionId, - ) - if err != nil { - return nil, errors.Wrap(err, "error creating multiply receiver 0 in Bob sign round 3") - } - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("multiply receiver id 1"), simplest.DigestSize), - ) - bob.multiplyReceivers[1], err = NewMultiplyReceiver( - bob.seedOtResults, - bob.curve, - uniqueSessionId, - ) - if err != nil { - return nil, errors.Wrap(err, "error creating multiply receiver 1 in Bob sign round 3") - } - round2Output := &SignRound2Output{ - Seed: bobSeed, - } - bob.kB = bob.curve.Scalar.Random(rand.Reader) - bob.dB = bob.curve.ScalarBaseMult(bob.kB) - round2Output.DB = bob.dB - kBInv := bob.curve.Scalar.One().Div(bob.kB) - - round2Output.KosRound1Outputs[0], err = bob.multiplyReceivers[0].Round1Initialize(kBInv) - if err != nil { - return nil, errors.Wrap( - err, - "error in multiply round 1 initialize 0 within Bob sign round 3 initialize", - ) - } - round2Output.KosRound1Outputs[1], err = bob.multiplyReceivers[1].Round1Initialize( - bob.secretKeyShare.Mul(kBInv), - ) - if err != nil { - return nil, errors.Wrap( - err, - "error in multiply round 1 initialize 1 within Bob sign round 3 initialize", - ) - } - return round2Output, nil -} - -// Round3Sign Alice's first message. Alice is the _responder_; she is responding to Bob's initial message. -// This is Protocol 1 (p. 6), and contains Alice's steps 3) -- 8). these can all be combined into one message. -// Alice's job here is to finish computing the shared instance key / nonce, as well as multiplication input values; -// then to invoke the multiplication on these two input values (stashing the outputs in her running result struct), -// then to use the _output_ of the multiplication (which she already possesses as of the end of her computation), -// and use that to compute some final values which will help Bob compute the final signature. -func (alice *Alice) Round3Sign( - message []byte, - round2Output *SignRound2Output, -) (*SignRound3Output, error) { - alice.transcript.AppendMessage([]byte("session_id_bob"), round2Output.Seed[:]) - - multiplySenders := [multiplicationCount]*MultiplySender{} - var err error - uniqueSessionId := [simplest.DigestSize]byte{} // will use and _re-use_ this throughout, for sub-session IDs - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("multiply receiver id 0"), simplest.DigestSize), - ) - if multiplySenders[0], err = NewMultiplySender(alice.seedOtResults, alice.curve, uniqueSessionId); err != nil { - return nil, errors.Wrap(err, "creating multiply sender 0 in Alice round 4 sign") - } - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("multiply receiver id 1"), simplest.DigestSize), - ) - if multiplySenders[1], err = NewMultiplySender(alice.seedOtResults, alice.curve, uniqueSessionId); err != nil { - return nil, errors.Wrap(err, "creating multiply sender 1 in Alice round 4 sign") - } - round3Output := &SignRound3Output{} - kPrimeA := alice.curve.Scalar.Random(rand.Reader) - round3Output.RPrime = round2Output.DB.Mul(kPrimeA) - hashRPrimeBytes := sha3.Sum256(round3Output.RPrime.ToAffineCompressed()) - hashRPrime, err := alice.curve.Scalar.SetBytes(hashRPrimeBytes[:]) - if err != nil { - return nil, errors.Wrap(err, "setting hashRPrime scalar from bytes") - } - kA := hashRPrime.Add(kPrimeA) - copy( - uniqueSessionId[:], - alice.transcript.ExtractBytes([]byte("schnorr proof for R"), simplest.DigestSize), - ) - rSchnorrProver := schnorr.NewProver(alice.curve, round2Output.DB, uniqueSessionId[:]) - round3Output.RSchnorrProof, err = rSchnorrProver.Prove(kA) - if err != nil { - return nil, errors.Wrap( - err, - "generating schnorr proof for R = kA * DB in alice round 4 sign", - ) - } - // reassign / stash the below value here just for notational clarity. - // this is _the_ key public point R in the ECDSA signature. we'll use its coordinate X in various places. - r := round3Output.RSchnorrProof.Statement - phi := alice.curve.Scalar.Random(rand.Reader) - kAInv := alice.curve.Scalar.One().Div(kA) - - if round3Output.MultiplyRound2Outputs[0], err = multiplySenders[0].Round2Multiply(phi.Add(kAInv), round2Output.KosRound1Outputs[0]); err != nil { - return nil, errors.Wrap(err, "error in round 2 multiply 0 within alice round 4 sign") - } - if round3Output.MultiplyRound2Outputs[1], err = multiplySenders[1].Round2Multiply(alice.secretKeyShare.Mul(kAInv), round2Output.KosRound1Outputs[1]); err != nil { - return nil, errors.Wrap(err, "error in round 2 multiply 1 within alice round 4 sign") - } - - one := alice.curve.Scalar.One() - gamma1 := alice.curve.ScalarBaseMult(kA.Mul(phi).Add(one)) - other := r.Mul(multiplySenders[0].outputAdditiveShare.Neg()) - gamma1 = gamma1.Add(other) - hashGamma1Bytes := sha3.Sum256(gamma1.ToAffineCompressed()) - hashGamma1, err := alice.curve.Scalar.SetBytes(hashGamma1Bytes[:]) - if err != nil { - return nil, errors.Wrap(err, "setting hashGamma1 scalar from bytes") - } - round3Output.EtaPhi = hashGamma1.Add(phi) - if _, err = alice.hash.Write(message); err != nil { - return nil, errors.Wrap(err, "writing message to hash in alice round 4 sign") - } - digest := alice.hash.Sum(nil) - hOfMAsInteger, err := alice.curve.Scalar.SetBytes(digest) - if err != nil { - return nil, errors.Wrap(err, "setting hOfMAsInteger scalar from bytes") - } - affineCompressedForm := r.ToAffineCompressed() - if len(affineCompressedForm) != 33 { - return nil, errors.New("the compressed form must be exactly 33 bytes") - } - // Discard the leading byte and parse the rest as the X coordinate. - rX, err := alice.curve.Scalar.SetBytes(affineCompressedForm[1:]) - if err != nil { - return nil, errors.Wrap(err, "setting rX scalar from bytes") - } - - sigA := hOfMAsInteger.Mul(multiplySenders[0].outputAdditiveShare). - Add(rX.Mul(multiplySenders[1].outputAdditiveShare)) - gamma2 := alice.publicKey.Mul(multiplySenders[0].outputAdditiveShare) - other = alice.curve.ScalarBaseMult(multiplySenders[1].outputAdditiveShare.Neg()) - gamma2 = gamma2.Add(other) - hashGamma2Bytes := sha3.Sum256(gamma2.ToAffineCompressed()) - hashGamma2, err := alice.curve.Scalar.SetBytes(hashGamma2Bytes[:]) - if err != nil { - return nil, errors.Wrap(err, "setting hashGamma2 scalar from bytes") - } - round3Output.EtaSig = hashGamma2.Add(sigA) - return round3Output, nil -} - -// Round4Final this is Bob's last portion of the signature computation, and ultimately results in the complete signature -// corresponds to Protocol 1, Bob's steps 3) -- 10). -// Bob begins by _finishing_ the OT-based multiplication, using Alice's one and only message to him re: the mult. -// Bob then move's onto the remainder of Alice's message, which contains extraneous data used to finish the signature. -// Using this data, Bob completes the signature, which gets stored in `Bob.Sig`. Bob also verifies it. -func (bob *Bob) Round4Final(message []byte, round3Output *SignRound3Output) error { - if err := bob.multiplyReceivers[0].Round3Multiply(round3Output.MultiplyRound2Outputs[0]); err != nil { - return errors.Wrap(err, "error in round 3 multiply 0 within sign round 5") - } - if err := bob.multiplyReceivers[1].Round3Multiply(round3Output.MultiplyRound2Outputs[1]); err != nil { - return errors.Wrap(err, "error in round 3 multiply 1 within sign round 5") - } - rPrimeHashedBytes := sha3.Sum256(round3Output.RPrime.ToAffineCompressed()) - rPrimeHashed, err := bob.curve.Scalar.SetBytes(rPrimeHashedBytes[:]) - if err != nil { - return errors.Wrap(err, "setting rPrimeHashed scalar from bytes") - } - r := bob.dB.Mul(rPrimeHashed) - r = r.Add(round3Output.RPrime) - // To ensure that the correct public statement is used, we use the public statement that we have calculated - // instead of the open Alice sent us. - round3Output.RSchnorrProof.Statement = r - uniqueSessionId := [simplest.DigestSize]byte{} - copy( - uniqueSessionId[:], - bob.transcript.ExtractBytes([]byte("schnorr proof for R"), simplest.DigestSize), - ) - if err = schnorr.Verify(round3Output.RSchnorrProof, bob.curve, bob.dB, uniqueSessionId[:]); err != nil { - return errors.Wrap(err, "bob's verification of alice's schnorr proof re: r failed") - } - zero := bob.curve.Scalar.Zero() - affineCompressedForm := r.ToAffineCompressed() - if len(affineCompressedForm) != 33 { - return errors.New("the compressed form must be exactly 33 bytes") - } - rY := affineCompressedForm[0] & 0x1 // this is bit(0) of Y coordinate - rX, err := bob.curve.Scalar.SetBytes(affineCompressedForm[1:]) - if err != nil { - return errors.Wrap(err, "setting rX scalar from bytes") - } - bob.Signature = &curves.EcdsaSignature{ - R: rX.Add(zero). - BigInt(), - // slight trick here; add it to 0 just to mod it by q (now it's mod p!) - V: int(rY), - } - gamma1 := r.Mul(bob.multiplyReceivers[0].outputAdditiveShare) - gamma1HashedBytes := sha3.Sum256(gamma1.ToAffineCompressed()) - gamma1Hashed, err := bob.curve.Scalar.SetBytes(gamma1HashedBytes[:]) - if err != nil { - return errors.Wrap(err, "setting gamma1Hashed scalar from bytes") - } - phi := round3Output.EtaPhi.Sub(gamma1Hashed) - theta := bob.multiplyReceivers[0].outputAdditiveShare.Sub(phi.Div(bob.kB)) - if _, err = bob.hash.Write(message); err != nil { - return errors.Wrap(err, "writing message to hash in Bob sign round 5 final") - } - digestBytes := bob.hash.Sum(nil) - digest, err := bob.curve.Scalar.SetBytes(digestBytes) - if err != nil { - return errors.Wrap(err, "setting digest scalar from bytes") - } - capitalR, err := bob.curve.Scalar.SetBigInt(bob.Signature.R) - if err != nil { - return errors.Wrap(err, "setting capitalR scalar from big int") - } - sigB := digest.Mul(theta).Add(capitalR.Mul(bob.multiplyReceivers[1].outputAdditiveShare)) - gamma2 := bob.curve.ScalarBaseMult(bob.multiplyReceivers[1].outputAdditiveShare) - other := bob.publicKey.Mul(theta.Neg()) - gamma2 = gamma2.Add(other) - gamma2HashedBytes := sha3.Sum256(gamma2.ToAffineCompressed()) - gamma2Hashed, err := bob.curve.Scalar.SetBytes(gamma2HashedBytes[:]) - if err != nil { - return errors.Wrap(err, "setting gamma2Hashed scalar from bytes") - } - scalarS := sigB.Add(round3Output.EtaSig.Sub(gamma2Hashed)) - bob.Signature.S = scalarS.BigInt() - if bob.Signature.S.Bit(255) == 1 { - bob.Signature.S = scalarS.Neg().BigInt() - bob.Signature.V ^= 1 - } - // now verify the signature - unCompressedAffinePublicKey := bob.publicKey.ToAffineUncompressed() - if len(unCompressedAffinePublicKey) != 65 { - return errors.New("the uncompressed form must have exactly 65 bytes") - } - x := new(big.Int).SetBytes(unCompressedAffinePublicKey[1:33]) - y := new(big.Int).SetBytes(unCompressedAffinePublicKey[33:]) - ellipticCurve, err := bob.curve.ToEllipticCurve() - if err != nil { - return errors.Wrap(err, "invalid curve") - } - if !ecdsa.Verify( - &ecdsa.PublicKey{Curve: ellipticCurve, X: x, Y: y}, - digestBytes, - bob.Signature.R, - bob.Signature.S, - ) { - return fmt.Errorf("final signature failed to verify") - } - return nil -} diff --git a/crypto/tecdsa/dklsv1/sign/sign_test.go b/crypto/tecdsa/dklsv1/sign/sign_test.go deleted file mode 100644 index 272f8787e..000000000 --- a/crypto/tecdsa/dklsv1/sign/sign_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package sign - -import ( - "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/ot/base/simplest" - "github.com/sonr-io/sonr/crypto/ot/extension/kos" - "github.com/sonr-io/sonr/crypto/ot/ottest" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/dkg" -) - -func TestSign(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - } - for _, curve := range curveInstances { - hashKeySeed := [simplest.DigestSize]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(t, err) - - baseOtSenderOutput, baseOtReceiverOutput, err := ottest.RunSimplestOT( - curve, - kos.Kappa, - hashKeySeed, - ) - require.NoError(t, err) - - secretKeyShareA := curve.Scalar.Random(rand.Reader) - secretKeyShareB := curve.Scalar.Random(rand.Reader) - require.NoError(t, err) - publicKey := curve.ScalarBaseMult(secretKeyShareA.Mul(secretKeyShareB)) - alice := NewAlice( - curve, - sha3.New256(), - &dkg.AliceOutput{ - SeedOtResult: baseOtReceiverOutput, - SecretKeyShare: secretKeyShareA, - PublicKey: publicKey, - }, - ) - bob := NewBob( - curve, - sha3.New256(), - &dkg.BobOutput{ - SeedOtResult: baseOtSenderOutput, - SecretKeyShare: secretKeyShareB, - PublicKey: publicKey, - }, - ) - - message := []byte("A message.") - seed, err := alice.Round1GenerateRandomSeed() - require.NoError(t, err) - round3Output, err := bob.Round2Initialize(seed) - require.NoError(t, err) - round4Output, err := alice.Round3Sign(message, round3Output) - require.NoError(t, err) - err = bob.Round4Final(message, round4Output) - require.NoError(t, err, "curve: %s", curve.Name) - } -} - -func BenchmarkSign(b *testing.B) { - curve := curves.K256() - hashKeySeed := [simplest.DigestSize]byte{} - _, err := rand.Read(hashKeySeed[:]) - require.NoError(b, err) - - baseOtSenderOutput, baseOtReceiverOutput, err := ottest.RunSimplestOT( - curve, - kos.Kappa, - hashKeySeed, - ) - require.NoError(b, err) - - secretKeyShareA := curve.Scalar.Random(rand.Reader) - secretKeyShareB := curve.Scalar.Random(rand.Reader) - publicKey := curve.ScalarBaseMult(secretKeyShareA.Mul(secretKeyShareB)) - alice := NewAlice( - curve, - sha3.New256(), - &dkg.AliceOutput{ - SeedOtResult: baseOtReceiverOutput, - SecretKeyShare: secretKeyShareA, - PublicKey: publicKey, - }, - ) - bob := NewBob( - curve, - sha3.New256(), - &dkg.BobOutput{ - SeedOtResult: baseOtSenderOutput, - SecretKeyShare: secretKeyShareB, - PublicKey: publicKey, - }, - ) - - message := []byte("A message.") - for n := 0; n < b.N; n++ { - seed, err := alice.Round1GenerateRandomSeed() - require.NoError(b, err) - round3Output, err := bob.Round2Initialize(seed) - require.NoError(b, err) - round4Output, err := alice.Round3Sign(message, round3Output) - require.NoError(b, err) - err = bob.Round4Final(message, round4Output) - require.NoError(b, err) - } -} diff --git a/crypto/tecdsa/dklsv1/signserializers.go b/crypto/tecdsa/dklsv1/signserializers.go deleted file mode 100644 index 04ebea3a4..000000000 --- a/crypto/tecdsa/dklsv1/signserializers.go +++ /dev/null @@ -1,128 +0,0 @@ -package dklsv1 - -import ( - "bytes" - "encoding/gob" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/core/protocol" - "github.com/sonr-io/sonr/crypto/tecdsa/dklsv1/sign" -) - -func newSignProtocolMessage(payload []byte, round string, version uint) *protocol.Message { - return &protocol.Message{ - Protocol: protocol.Dkls18Sign, - Version: version, - Payloads: map[string][]byte{payloadKey: payload}, - Metadata: map[string]string{"round": round}, - } -} - -func encodeSignRound1Output(commitment [32]byte, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(&commitment); err != nil { - return nil, errors.WithStack(err) - } - return newSignProtocolMessage(buf.Bytes(), "1", version), nil -} - -func decodeSignRound2Input(m *protocol.Message) ([32]byte, error) { - if m.Version != protocol.Version1 { - return [32]byte{}, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := [32]byte{} - if err := dec.Decode(&decoded); err != nil { - return [32]byte{}, errors.WithStack(err) - } - return decoded, nil -} - -func encodeSignRound2Output( - output *sign.SignRound2Output, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(output); err != nil { - return nil, errors.WithStack(err) - } - return newSignProtocolMessage(buf.Bytes(), "2", version), nil -} - -func decodeSignRound3Input(m *protocol.Message) (*sign.SignRound2Output, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := &sign.SignRound2Output{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeSignRound3Output( - output *sign.SignRound3Output, - version uint, -) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(output); err != nil { - return nil, errors.WithStack(err) - } - return newSignProtocolMessage(buf.Bytes(), "3", version), nil -} - -func decodeSignRound4Input(m *protocol.Message) (*sign.SignRound3Output, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := &sign.SignRound3Output{} - if err := dec.Decode(&decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} - -func encodeSignature(signature *curves.EcdsaSignature, version uint) (*protocol.Message, error) { - if version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer([]byte{}) - enc := gob.NewEncoder(buf) - if err := enc.Encode(signature); err != nil { - return nil, errors.WithStack(err) - } - return newSignProtocolMessage(buf.Bytes(), "signature", version), nil -} - -// DecodeSignature serializes the signature. -func DecodeSignature(m *protocol.Message) (*curves.EcdsaSignature, error) { - if m.Version != protocol.Version1 { - return nil, errors.New("only version 1 is supported") - } - buf := bytes.NewBuffer(m.Payloads[payloadKey]) - dec := gob.NewDecoder(buf) - decoded := &curves.EcdsaSignature{} - if err := dec.Decode(decoded); err != nil { - return nil, errors.WithStack(err) - } - return decoded, nil -} diff --git a/crypto/ted25519/frost/README.md b/crypto/ted25519/frost/README.md deleted file mode 100755 index c7ecc4a7b..000000000 --- a/crypto/ted25519/frost/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -aliases: [README] -tags: [] -title: README -linter-yaml-title-alias: README -date created: Wednesday, April 17th 2024, 4:11:40 pm -date modified: Thursday, April 18th 2024, 8:19:25 am ---- - -## FROST: Flexible Round-Optimized Schnorr Threshold Signatures - -This package is an implementation of t-of-n threshold signature of -[FROST: Flexible Round-Optimized Schnorr Threshold Signatures](https://eprint.iacr.org/2020/852.pdf) diff --git a/crypto/ted25519/frost/challenge_derive.go b/crypto/ted25519/frost/challenge_derive.go deleted file mode 100644 index 836745a21..000000000 --- a/crypto/ted25519/frost/challenge_derive.go +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "crypto/sha512" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type ChallengeDerive interface { - DeriveChallenge(msg []byte, pubKey curves.Point, r curves.Point) (curves.Scalar, error) -} - -type Ed25519ChallengeDeriver struct{} - -func (ed Ed25519ChallengeDeriver) DeriveChallenge( - msg []byte, - pubKey curves.Point, - r curves.Point, -) (curves.Scalar, error) { - h := sha512.New() - _, _ = h.Write(r.ToAffineCompressed()) - _, _ = h.Write(pubKey.ToAffineCompressed()) - _, _ = h.Write(msg) - return new(curves.ScalarEd25519).SetBytesWide(h.Sum(nil)) -} diff --git a/crypto/ted25519/frost/participant.go b/crypto/ted25519/frost/participant.go deleted file mode 100644 index bf6003ded..000000000 --- a/crypto/ted25519/frost/participant.go +++ /dev/null @@ -1,89 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package frost is an implementation of t-of-n threshold signature of https://eprint.iacr.org/2020/852.pdf -package frost - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/dkg/frost" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Signer is a tSchnorr player performing the signing operation. -type Signer struct { - skShare curves.Scalar // secret signing share for this signer - vkShare curves.Point // store verification key share - verificationKey curves.Point // verification key - id uint32 // The ID assigned to this signer's shamir share - threshold uint32 - curve *curves.Curve - round uint - lCoeffs map[uint32]curves.Scalar // lCoeffs are Lagrange coefficients of each cosigner. - cosigners []uint32 - state *state // Accumulated intermediate values associated with signing - challengeDeriver ChallengeDerive -} - -type state struct { - // Round 1 - capD, capE curves.Point // capD, capE are commitments this signer generates in signing round 1 - smallD, smallE curves.Scalar // smallD, smallE are scalars this signer generates in signing round 1 - - // Round 2 - commitments map[uint32]*Round1Bcast // Store commitments broadcast after signing round 1 - msg []byte - c curves.Scalar - capRs map[uint32]curves.Point - sumR curves.Point -} - -// NewSigner create a signer from a dkg participant -// Note that we can pre-assign Lagrange coefficients lcoeffs of each cosigner. This optimizes performance. -// See paragraph 3 of section 3 in the draft - https://tools.ietf.org/pdf/draft-komlo-frost-00.pdf -func NewSigner( - info *frost.DkgParticipant, - id, thresh uint32, - lcoeffs map[uint32]curves.Scalar, - cosigners []uint32, - challengeDeriver ChallengeDerive, -) (*Signer, error) { - if info == nil || len(cosigners) == 0 || len(lcoeffs) == 0 { - return nil, internal.ErrNilArguments - } - - if thresh > uint32(len(cosigners)) { - return nil, fmt.Errorf("threshold is higher than number of signers") - } - - if len(lcoeffs) != len(cosigners) { - return nil, fmt.Errorf("expected coefficients to be equal to number of cosigners") - } - - // Check if cosigners and lcoeffs contain the same IDs - for i := 0; i < len(cosigners); i++ { - id := cosigners[i] - if _, ok := lcoeffs[id]; !ok { - return nil, fmt.Errorf("lcoeffs and cosigners have inconsistent ID") - } - } - - return &Signer{ - skShare: info.SkShare, - vkShare: info.VkShare, - verificationKey: info.VerificationKey, - id: id, - threshold: thresh, - curve: info.Curve, - round: 1, - lCoeffs: lcoeffs, - cosigners: cosigners, - state: &state{}, - challengeDeriver: challengeDeriver, - }, nil -} diff --git a/crypto/ted25519/frost/round1.go b/crypto/ted25519/frost/round1.go deleted file mode 100644 index 5b0ea8ad5..000000000 --- a/crypto/ted25519/frost/round1.go +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "bytes" - crand "crypto/rand" - "encoding/gob" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Round1Bcast contains values to be broadcast to all players after the completion of signing round 1. -type Round1Bcast struct { - Di, Ei curves.Point -} - -func (result *Round1Bcast) Encode() ([]byte, error) { - gob.Register(result.Di) // just the point for now - gob.Register(result.Ei) - buf := &bytes.Buffer{} - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return buf.Bytes(), nil -} - -func (result *Round1Bcast) Decode(input []byte) error { - buf := bytes.NewBuffer(input) - dec := gob.NewDecoder(buf) - if err := dec.Decode(result); err != nil { - return errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return nil -} - -func (signer *Signer) SignRound1() (*Round1Bcast, error) { - // Make sure signer is not empty - if signer == nil || signer.curve == nil { - return nil, internal.ErrNilArguments - } - - // Make sure round number is correct - if signer.round != 1 { - return nil, internal.ErrInvalidRound - } - - // Step 1 - Sample di, ei - di := signer.curve.Scalar.Random(crand.Reader) - - ei := signer.curve.Scalar.Random(crand.Reader) - - // Step 2 - Compute Di, Ei - Di := signer.curve.ScalarBaseMult(di) - - Ei := signer.curve.ScalarBaseMult(ei) - - // Update round number - signer.round = 2 - - // Store di, ei, Di, Ei locally and broadcast Di, Ei - signer.state.capD = Di - signer.state.capE = Ei - signer.state.smallD = di - signer.state.smallE = ei - return &Round1Bcast{ - Di, - Ei, - }, nil -} diff --git a/crypto/ted25519/frost/round2.go b/crypto/ted25519/frost/round2.go deleted file mode 100644 index dca71cb17..000000000 --- a/crypto/ted25519/frost/round2.go +++ /dev/null @@ -1,189 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "bytes" - "encoding/gob" - "fmt" - - "github.com/pkg/errors" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Round2Bcast contains values that will be broadcast to other signers after completion of round 2. -type Round2Bcast struct { - Zi curves.Scalar - Vki curves.Point -} - -func (result *Round2Bcast) Encode() ([]byte, error) { - gob.Register(result.Zi) - gob.Register(result.Vki) // just the point for now - buf := &bytes.Buffer{} - enc := gob.NewEncoder(buf) - if err := enc.Encode(result); err != nil { - return nil, errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return buf.Bytes(), nil -} - -func (result *Round2Bcast) Decode(input []byte) error { - buf := bytes.NewBuffer(input) - dec := gob.NewDecoder(buf) - if err := dec.Decode(result); err != nil { - return errors.Wrap(err, "couldn't encode round 1 broadcast") - } - return nil -} - -// SignRound2 implements FROST signing round 2. -func (signer *Signer) SignRound2( - msg []byte, - round2Input map[uint32]*Round1Bcast, -) (*Round2Bcast, error) { - // Make sure necessary items of signer are not empty - if signer == nil || signer.curve == nil || signer.state == nil { - return nil, internal.ErrNilArguments - } - - // Make sure those private d is not empty and not zero - if signer.state.smallD == nil || signer.state.smallD.IsZero() { - return nil, fmt.Errorf("empty d or d is zero") - } - - // Make sure those private e is not empty and not zero - if signer.state.smallE == nil || signer.state.smallE.IsZero() { - return nil, fmt.Errorf("empty e or e is zero") - } - - // Make sure msg is not empty - if len(msg) == 0 { - return nil, internal.ErrNilArguments - } - - // Make sure the round number is correct - if signer.round != 2 { - return nil, internal.ErrInvalidRound - } - - // Check length of round2Input - if uint32(len(round2Input)) != signer.threshold { - return nil, fmt.Errorf("invalid length of round2Input") - } - - // Step 2 - Check Dj, Ej on the curve and Store round2Input - for id, input := range round2Input { - if input == nil || input.Di == nil || input.Ei == nil { - return nil, fmt.Errorf("round2Input is nil from participant with id %d", id) - } - if !input.Di.IsOnCurve() || input.Di.IsIdentity() { - return nil, fmt.Errorf("commitment Di is not on the curve with id %d", id) - } - if !input.Ei.IsOnCurve() || input.Ei.IsIdentity() { - return nil, fmt.Errorf("commitment Ei is not on the curve with id %d", id) - } - } - // Store Dj, Ej for further usage. - signer.state.commitments = round2Input - - // Step 3-6 - R := signer.curve.NewIdentityPoint() - var ri curves.Scalar - Rs := make(map[uint32]curves.Point, signer.threshold) - for id, data := range round2Input { - // Construct the blob (j, m, {Dj, Ej}) - blob := concatHashArray(id, msg, round2Input, signer.cosigners) - - // Step 4 - rj = H(j,m,{Dj,Ej}_{j in [1...t]}) - rj := signer.curve.Scalar.Hash(blob) - if signer.id == id { - ri = rj - } - - // Step 5 - R_j = D_j + r_j*E_j - rjEj := data.Ei.Mul(rj) - Rj := rjEj.Add(data.Di) - // assign Rj - Rs[id] = Rj - - // Step 6 - R = R+Rj - R = R.Add(Rj) - } - - // Step 7 - c = H(m, R) - c, err := signer.challengeDeriver.DeriveChallenge(msg, signer.verificationKey, R) - if err != nil { - return nil, err - } - - // Step 8 - Record c, R, Rjs - signer.state.c = c - signer.state.capRs = Rs - signer.state.sumR = R - - // Step 9 - zi = di + ei*ri + Li*ski*c - Li := signer.lCoeffs[signer.id] - Liski := Li.Mul(signer.skShare) - - Liskic := Liski.Mul(c) - - if R.IsNegative() { - signer.state.smallE = signer.state.smallE.Neg() - signer.state.smallD = signer.state.smallD.Neg() - } - - eiri := signer.state.smallE.Mul(ri) - - // Compute zi = di+ei*ri+Li*ski*c - zi := Liskic.Add(eiri) - zi = zi.Add(signer.state.smallD) - - // Update round number and store message - signer.round = 3 - signer.state.msg = msg - - // set smallD and smallE to zero since they are one-time use - signer.state.smallD = signer.curve.NewScalar() - signer.state.smallE = signer.curve.NewScalar() - - // Step 10 - Broadcast zi, vki to other participants - return &Round2Bcast{ - zi, - signer.vkShare, - }, nil -} - -// concatHashArray puts id, msg and (Dj,Ej), j=1...t into a byte array -func concatHashArray( - id uint32, - msg []byte, - round2Input map[uint32]*Round1Bcast, - cosigners []uint32, -) []byte { - var blob []byte - // Append identity id - blob = append(blob, byte(id)) - - // Append message msg - blob = append(blob, msg...) - - // Append (Dj, Ej) for all j in [1...t] - for i := 0; i < len(cosigners); i++ { - id := cosigners[i] - bytesDi := round2Input[id].Di.ToAffineCompressed() - bytesEi := round2Input[id].Ei.ToAffineCompressed() - - // Following the spec, we should add each party's identity. - blob = append(blob, byte(id)) - blob = append(blob, bytesDi...) - blob = append(blob, bytesEi...) - } - return blob -} diff --git a/crypto/ted25519/frost/round3.go b/crypto/ted25519/frost/round3.go deleted file mode 100644 index 732fd660e..000000000 --- a/crypto/ted25519/frost/round3.go +++ /dev/null @@ -1,169 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - "github.com/sonr-io/sonr/crypto/internal" -) - -// Round3Bcast contains the output of FROST signature, i.e., it contains FROST signature (z,c) and the -// corresponding message msg. -type Round3Bcast struct { - R curves.Point - Z, C curves.Scalar - msg []byte -} - -// Define frost signature type -type Signature struct { - Z curves.Scalar - C curves.Scalar -} - -func (signer *Signer) SignRound3(round3Input map[uint32]*Round2Bcast) (*Round3Bcast, error) { - // Make sure signer is not empty - if signer == nil || signer.curve == nil { - return nil, internal.ErrNilArguments - } - - // Make sure signer's smallD and smallE are zero - if !signer.state.smallD.IsZero() || !signer.state.smallE.IsZero() { - return nil, fmt.Errorf( - "signer's private smallD and smallE should be zero since one-time use", - ) - } - - // Make sure the signer has had the msg - if len(signer.state.msg) == 0 { - return nil, internal.ErrNilArguments - } - - // Validate Round3Input - if round3Input == nil { - return nil, internal.ErrNilArguments - } - for _, data := range round3Input { - if data == nil { - return nil, internal.ErrNilArguments - } - } - - // Make sure the signer has commitments stored at the end of round 1. - if signer.state.commitments == nil || len(signer.state.commitments) != len(round3Input) { - return nil, internal.ErrNilArguments - } - - // Make sure the round number is correct - if signer.round != 3 { - return nil, internal.ErrInvalidRound - } - - // Round2 Input has different length of threshold - if uint32(len(round3Input)) != signer.threshold { - return nil, fmt.Errorf("invalid length of round3Input") - } - - // Step 1-3 - // Step 1: For j in [1...t] - z := signer.curve.NewScalar() - negate := signer.state.sumR.IsNegative() - for id, data := range round3Input { - zj := data.Zi - vkj := data.Vki - - // Step 2: Verify zj*G = Rj + c*Lj*vkj - // zj*G - zjG := signer.curve.ScalarBaseMult(zj) - - // c*Lj - cLj := signer.state.c.Mul(signer.lCoeffs[id]) - - // cLjvkj - cLjvkj := vkj.Mul(cLj) - - // Rj + c*Lj*vkj - Rj := signer.state.capRs[id] - if negate { - Rj = Rj.Neg() - } - right := cLjvkj.Add(Rj) - - // Check equation - if !zjG.Equal(right) { - return nil, fmt.Errorf("zjG != right with participant id %d", id) - } - - // Step 3 - z = z+zj - z = z.Add(zj) - } - - // Step 4 - 7: Self verify the signature (z, c) - // Step 5 - R' = z*G + (-c)*vk - zG := signer.curve.ScalarBaseMult(z) - cvk := signer.verificationKey.Mul(signer.state.c.Neg()) - tempR := zG.Add(cvk) - // Step 6 - c' = H(m, R') - tempC, err := signer.challengeDeriver.DeriveChallenge( - signer.state.msg, - signer.verificationKey, - tempR, - ) - if err != nil { - return nil, err - } - - // Step 7 - Check c = c' - if tempC.Cmp(signer.state.c) != 0 { - return nil, fmt.Errorf("invalid signature: c != c'") - } - - // Updating round number - signer.round = 4 - - // Step 8 - Broadcast signature and message - return &Round3Bcast{ - signer.state.sumR, - z, - signer.state.c, - signer.state.msg, - }, nil -} - -// Method to verify a frost signature. -func Verify( - curve *curves.Curve, - challengeDeriver ChallengeDerive, - vk curves.Point, - msg []byte, - signature *Signature, -) (bool, error) { - if vk == nil || msg == nil || len(msg) == 0 || signature.C == nil || signature.Z == nil { - return false, fmt.Errorf("invalid input") - } - z := signature.Z - c := signature.C - - // R' = z*G - c*vk - zG := curve.ScalarBaseMult(z) - cvk := vk.Mul(c.Neg()) - tempR := zG.Add(cvk) - - // c' = H(m, R') - tempC, err := challengeDeriver.DeriveChallenge(msg, vk, tempR) - if err != nil { - return false, err - } - - // Check c == c' - if tempC.Cmp(c) != 0 { - return false, fmt.Errorf("invalid signature: c != c'") - } - return true, nil -} diff --git a/crypto/ted25519/frost/rounds_test.go b/crypto/ted25519/frost/rounds_test.go deleted file mode 100644 index daed8222c..000000000 --- a/crypto/ted25519/frost/rounds_test.go +++ /dev/null @@ -1,439 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package frost - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - dkg "github.com/sonr-io/sonr/crypto/dkg/frost" - "github.com/sonr-io/sonr/crypto/sharing" -) - -var ( - testCurve = curves.ED25519() - ctx = "string to prevent replay attack" -) - -// Create two DKG participants. -func PrepareDkgOutput(t *testing.T) (*dkg.DkgParticipant, *dkg.DkgParticipant) { - // Initiate two participants and running DKG round 1 - p1, err := dkg.NewDkgParticipant(1, 2, ctx, testCurve, 2) - require.NoError(t, err) - p2, err := dkg.NewDkgParticipant(2, 2, ctx, testCurve, 1) - require.NoError(t, err) - bcast1, p2psend1, _ := p1.Round1(nil) - bcast2, p2psend2, _ := p2.Round1(nil) - bcast := make(map[uint32]*dkg.Round1Bcast) - p2p1 := make(map[uint32]*sharing.ShamirShare) - p2p2 := make(map[uint32]*sharing.ShamirShare) - bcast[1] = bcast1 - bcast[2] = bcast2 - p2p1[2] = p2psend2[1] - p2p2[1] = p2psend1[2] - - // Running DKG round 2 - _, _ = p1.Round2(bcast, p2p1) - _, _ = p2.Round2(bcast, p2p2) - return p1, p2 -} - -// Test FROST signing round 1 -func TestSignRound1Works(t *testing.T) { - p1, p2 := PrepareDkgOutput(t) - require.NotNil(t, p1) - require.NotNil(t, p2) - - scheme, _ := sharing.NewShamir(2, 2, testCurve) - lCoeffs, err := scheme.LagrangeCoeffs([]uint32{p1.Id, p2.Id}) - require.NoError(t, err) - signer1, err := NewSigner(p1, 1, 2, lCoeffs, []uint32{1, 2}, &Ed25519ChallengeDeriver{}) - require.NoError(t, err) - round1Out, _ := signer1.SignRound1() - require.NotNil(t, round1Out.Ei) - require.NotNil(t, round1Out.Di) - require.NotNil(t, signer1.state.smallE) - require.NotNil(t, signer1.state.smallD) - require.NotNil(t, signer1.state.capD) - require.NotNil(t, signer1.state.capE) - require.Equal(t, signer1.round, uint(2)) - require.Equal(t, signer1.cosigners, []uint32{1, 2}) -} - -func TestSignRound1RepeatCall(t *testing.T) { - p1, p2 := PrepareDkgOutput(t) - scheme, _ := sharing.NewShamir(2, 2, testCurve) - lCoeffs, err := scheme.LagrangeCoeffs([]uint32{p1.Id, p2.Id}) - require.NoError(t, err) - signer1, _ := NewSigner(p1, 1, 2, lCoeffs, []uint32{1, 2}, &Ed25519ChallengeDeriver{}) - _, err = signer1.SignRound1() - require.NoError(t, err) - _, err = signer1.SignRound1() - require.Error(t, err) -} - -func PrepareNewSigners(t *testing.T) (*Signer, *Signer) { - threshold := uint32(2) - limit := uint32(2) - p1, p2 := PrepareDkgOutput(t) - require.Equal(t, p1.VerificationKey, p2.VerificationKey) - scheme, err := sharing.NewShamir(threshold, limit, testCurve) - // field = sharing.NewField(p1.curve.Params().N) - require.NotNil(t, scheme) - require.NoError(t, err) - lCoeffs, err := scheme.LagrangeCoeffs([]uint32{p1.Id, p2.Id}) - require.NotNil(t, lCoeffs[1]) - require.NotNil(t, lCoeffs[2]) - require.NoError(t, err) - signer1, err := NewSigner( - p1, - p1.Id, - threshold, - lCoeffs, - []uint32{p1.Id, p2.Id}, - &Ed25519ChallengeDeriver{}, - ) - require.NotNil(t, signer1) - require.NoError(t, err) - signer2, err := NewSigner( - p2, - p2.Id, - threshold, - lCoeffs, - []uint32{p1.Id, p2.Id}, - &Ed25519ChallengeDeriver{}, - ) - require.NotNil(t, signer2) - require.NoError(t, err) - return signer1, signer2 -} - -func TestSignRound2Works(t *testing.T) { - // Preparing round 2 inputs - signer1, signer2 := PrepareNewSigners(t) - require.Equal(t, signer1.verificationKey, signer2.verificationKey) - require.NotNil(t, signer1) - require.NotNil(t, signer2) - round1Out1, _ := signer1.SignRound1() - round1Out2, _ := signer2.SignRound1() - round2Input := make(map[uint32]*Round1Bcast) - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - - // Actual Test - msg := []byte("message") - round2Out, err := signer1.SignRound2(msg, round2Input) - require.NotNil(t, round2Out) - require.NoError(t, err) - require.Equal(t, signer1.round, uint(3)) - require.NotNil(t, signer1.state.commitments) - require.Equal(t, signer1.state.msg, msg) - require.True(t, signer1.state.smallD.IsZero()) - require.True(t, signer1.state.smallE.IsZero()) -} - -func TestSignRound2RepeatCall(t *testing.T) { - // Preparing round 2 inputs - signer1, signer2 := PrepareNewSigners(t) - require.NotNil(t, signer1) - require.NotNil(t, signer2) - round1Out1, _ := signer1.SignRound1() - round1Out2, _ := signer2.SignRound1() - round2Input := make(map[uint32]*Round1Bcast) - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - - // Actual Test - msg := []byte("message") - _, err := signer1.SignRound2(msg, round2Input) - require.NoError(t, err) - _, err = signer1.SignRound2(msg, round2Input) - require.Error(t, err) -} - -func TestSignRound2BadInput(t *testing.T) { - // Preparing round 2 inputs - signer1, signer2 := PrepareNewSigners(t) - _, _ = signer1.SignRound1() - round1Out2, _ := signer2.SignRound1() - round2Input := make(map[uint32]*Round1Bcast) - - // Actual Test: Set an input to nil - round2Input[signer1.id] = nil - round2Input[signer2.id] = round1Out2 - msg := []byte("message") - _, err := signer1.SignRound2(msg, round2Input) - require.Error(t, err) - - // Preparing round 2 inputs - signer1, signer2 = PrepareNewSigners(t) - round1Out1, _ := signer1.SignRound1() - round1Out2, _ = signer2.SignRound1() - round2Input = make(map[uint32]*Round1Bcast) - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - // Actual Test: Nil message - _, err = signer1.SignRound2(nil, round2Input) - require.Error(t, err) - - // Preparing round 2 inputs - signer1, signer2 = PrepareNewSigners(t) - round1Out1, _ = signer1.SignRound1() - round1Out2, _ = signer2.SignRound1() - round2Input = make(map[uint32]*Round1Bcast) - - // Actual Test: Set invalid round2Input length - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - round2Input[3] = round1Out2 - _, err = signer1.SignRound2(msg, round2Input) - require.Error(t, err) - - // Preparing round 2 inputs - signer1, signer2 = PrepareNewSigners(t) - round1Out1, _ = signer1.SignRound1() - round1Out2, _ = signer2.SignRound1() - round2Input = make(map[uint32]*Round1Bcast) - - // Actual Test: Set invalid round2Input length - round1Out2.Ei = nil - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - _, err = signer1.SignRound2(msg, round2Input) - require.Error(t, err) - - // Preparing round 2 inputs - signer1, signer2 = PrepareNewSigners(t) - round1Out1, _ = signer1.SignRound1() - round1Out2, _ = signer2.SignRound1() - round2Input = make(map[uint32]*Round1Bcast) - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - - // Actual Test: Set nil smallD and smallE - signer1.state.smallD = testCurve.NewScalar() - signer1.state.smallE = nil - _, err = signer1.SignRound2(msg, round2Input) - require.Error(t, err) -} - -func PrepareRound3Input(t *testing.T) (*Signer, *Signer, map[uint32]*Round2Bcast) { - // Running sign round 1 - threshold := uint32(2) - limit := uint32(2) - p1, p2 := PrepareDkgOutput(t) - require.Equal(t, p1.VerificationKey, p2.VerificationKey) - scheme, err := sharing.NewShamir(threshold, limit, testCurve) - require.NotNil(t, scheme) - require.NoError(t, err) - lCoeffs, err := scheme.LagrangeCoeffs([]uint32{p1.Id, p2.Id}) - require.NotNil(t, lCoeffs[1]) - require.NotNil(t, lCoeffs[2]) - require.NoError(t, err) - - signer1, err := NewSigner( - p1, - p1.Id, - threshold, - lCoeffs, - []uint32{p1.Id, p2.Id}, - &Ed25519ChallengeDeriver{}, - ) - require.NotNil(t, signer1) - require.NoError(t, err) - signer2, err := NewSigner( - p2, - p2.Id, - threshold, - lCoeffs, - []uint32{p1.Id, p2.Id}, - &Ed25519ChallengeDeriver{}, - ) - require.NotNil(t, signer2) - require.NoError(t, err) - - round1Out1, _ := signer1.SignRound1() - round1Out2, _ := signer2.SignRound1() - round2Input := make(map[uint32]*Round1Bcast, threshold) - round2Input[signer1.id] = round1Out1 - round2Input[signer2.id] = round1Out2 - - // Running sign round 2 - msg := []byte("message") - round2Out1, _ := signer1.SignRound2(msg, round2Input) - round2Out2, _ := signer2.SignRound2(msg, round2Input) - round3Input := make(map[uint32]*Round2Bcast, threshold) - round3Input[signer1.id] = round2Out1 - round3Input[signer2.id] = round2Out2 - return signer1, signer2, round3Input -} - -func TestSignRound3Works(t *testing.T) { - signer1, signer2, round3Input := PrepareRound3Input(t) - round3Out1, err := signer1.SignRound3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out1) - round3Out2, err := signer2.SignRound3(round3Input) - require.NoError(t, err) - require.NotNil(t, round3Out2) - // signer1 and signer2 outputs the same signature - require.Equal(t, round3Out1.Z, round3Out2.Z) - require.Equal(t, round3Out1.C, round3Out2.C) - - // test verify method - msg := []byte("message") - signature := &Signature{ - round3Out1.Z, - round3Out1.C, - } - vk := signer1.verificationKey - ok, err := Verify(signer1.curve, signer1.challengeDeriver, vk, msg, signature) - require.True(t, ok) - require.NoError(t, err) - - ok, err = Verify(signer2.curve, signer2.challengeDeriver, vk, msg, signature) - require.True(t, ok) - require.NoError(t, err) -} - -func TestSignRound3RepeatCall(t *testing.T) { - signer1, _, round3Input := PrepareRound3Input(t) - _, err := signer1.SignRound3(round3Input) - require.NoError(t, err) - _, err = signer1.SignRound3(round3Input) - require.Error(t, err) -} - -func TestSignRound3BadInput(t *testing.T) { - signer1, _, round3Input := PrepareRound3Input(t) - - // Actual test: nil input - round3Input[signer1.id] = nil - _, err := signer1.SignRound3(round3Input) - require.Error(t, err) - round3Input = nil - _, err = signer1.SignRound3(round3Input) - require.Error(t, err) - - // Actual test: set invalid length of round3Input - signer1, _, round3Input = PrepareRound3Input(t) - round3Input[100] = round3Input[signer1.id] - _, err = signer1.SignRound3(round3Input) - require.Error(t, err) - - // Actual test: maul the round3Input - signer1, _, round3Input = PrepareRound3Input(t) - round3Input[signer1.id].Zi = round3Input[signer1.id].Zi.Add(testCurve.Scalar.New(2)) - _, err = signer1.SignRound3(round3Input) - require.Error(t, err) - - // Actual test: set non-zero smallD and smallE - signer1, _, round3Input = PrepareRound3Input(t) - signer1.state.smallD = testCurve.Scalar.New(1) - _, err = signer1.SignRound3(round3Input) - require.Error(t, err) -} - -func TestFullRoundsWorks(t *testing.T) { - // Give a full-round test (FROST DKG + FROST Signing) with threshold = 2 and limit = 3, same as the test of tECDSA - threshold := 2 - limit := 3 - - // Prepare DKG participants - participants := make(map[uint32]*dkg.DkgParticipant, limit) - for i := 1; i <= limit; i++ { - otherIds := make([]uint32, limit-1) - idx := 0 - for j := 1; j <= limit; j++ { - if i == j { - continue - } - otherIds[idx] = uint32(j) - idx++ - } - p, err := dkg.NewDkgParticipant(uint32(i), uint32(threshold), ctx, testCurve, otherIds...) - require.NoError(t, err) - participants[uint32(i)] = p - } - - // FROST DKG round 1 - rnd1Bcast := make(map[uint32]*dkg.Round1Bcast, len(participants)) - rnd1P2p := make(map[uint32]dkg.Round1P2PSend, len(participants)) - for id, p := range participants { - bcast, p2psend, err := p.Round1(nil) - require.NoError(t, err) - rnd1Bcast[id] = bcast - rnd1P2p[id] = p2psend - } - - // FROST DKG round 2 - for id := range rnd1Bcast { - rnd1P2pForP := make(map[uint32]*sharing.ShamirShare) - for jid := range rnd1P2p { - if jid == id { - continue - } - rnd1P2pForP[jid] = rnd1P2p[jid][id] - } - _, err := participants[id].Round2(rnd1Bcast, rnd1P2pForP) - require.NoError(t, err) - } - - // Prepare Lagrange coefficients - scheme, _ := sharing.NewShamir(uint32(threshold), uint32(limit), testCurve) - - // Here we use {1, 3} as 2 of 3 cosigners, we can also set cosigners as {1, 2}, {2, 3} - signerIds := []uint32{1, 3} - lCoeffs, err := scheme.LagrangeCoeffs(signerIds) - require.NoError(t, err) - signers := make(map[uint32]*Signer, threshold) - for _, id := range signerIds { - signers[id], err = NewSigner( - participants[id], - id, - uint32(threshold), - lCoeffs, - signerIds, - &Ed25519ChallengeDeriver{}, - ) - require.NoError(t, err) - require.NotNil(t, signers[id].skShare) - } - - // Running sign round 1 - round2Input := make(map[uint32]*Round1Bcast, threshold) - for id := range signers { - round1Out, err := signers[id].SignRound1() - require.NoError(t, err) - round2Input[signers[id].id] = round1Out - } - - // Running sign round 2 - msg := []byte("message") - round3Input := make(map[uint32]*Round2Bcast, threshold) - for id := range signers { - round2Out, err := signers[id].SignRound2(msg, round2Input) - require.NoError(t, err) - round3Input[signers[id].id] = round2Out - } - - // Running sign round 3 - result := make(map[uint32]*Round3Bcast, threshold) - for id := range signers { - round3Out, err := signers[id].SignRound3(round3Input) - require.NoError(t, err) - result[signers[id].id] = round3Out - } - - // Every signer has the same output Schnorr signature - require.Equal(t, result[1].Z, result[3].Z) - // require.Equal(t, z, result[3].Z) - require.Equal(t, result[1].C, result[3].C) - // require.Equal(t, c, result[3].C) -} diff --git a/crypto/ted25519/ted25519/ed25519.go b/crypto/ted25519/ted25519/ed25519.go deleted file mode 100644 index 9765d90f5..000000000 --- a/crypto/ted25519/ted25519/ed25519.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ted25519 implements the Ed25519 signature algorithm. See https://ed25519.cr.yp.to/ -// -// These functions are also compatible with the "Ed25519" function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the "seed". -// This code is a port of the public domain, “ref10” implementation of ed25519 -// from SUPERCOP. -package ted25519 - -import ( - "bytes" - "crypto" - cryptorand "crypto/rand" - "crypto/sha512" - "fmt" - "io" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Bytes returns the publicKey in byte array -func (p PublicKey) Bytes() []byte { - return p -} - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[32:]) - return PublicKey(publicKey) -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:32]) - return seed -} - -// Sign signs the given message with priv. -// Ed25519 performs two passes over messages to be signed and therefore cannot -// handle pre-hashed messages. Thus opts.HashFunc() must return zero to -// indicate the message hasn't been hashed. This can be achieved by passing -// crypto.Hash(0) as the value for opts. -func (priv PrivateKey) Sign( - rand io.Reader, - message []byte, - opts crypto.SignerOpts, -) (signature []byte, err error) { - if opts.HashFunc() != crypto.Hash(0) { - return nil, fmt.Errorf("ed25519: cannot sign hashed message") - } - sig, err := Sign(priv, message) - if err != nil { - return nil, err - } - return sig, nil -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptorand.Reader - } - - seed := make([]byte, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey, err := NewKeyFromSeed(seed) - if err != nil { - return nil, nil, err - } - publicKey := make([]byte, PublicKeySize) - copy(publicKey, privateKey[32:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) (PrivateKey, error) { - // Outline the function body so that the returned key can be stack-allocated. - privateKey := make([]byte, PrivateKeySize) - err := newKeyFromSeed(privateKey, seed) - if err != nil { - return nil, err - } - return privateKey, nil -} - -func newKeyFromSeed(privateKey, seed []byte) error { - if l := len(seed); l != SeedSize { - return fmt.Errorf("ed25519: bad seed length: %d", l) - } - - digest := sha512.Sum512(seed) - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - - var hBytes [32]byte - copy(hBytes[:], digest[:]) - - h, err := new(curves.ScalarEd25519).SetBytesClamping(hBytes[:]) - if err != nil { - return err - } - ed25519 := curves.ED25519() - A := ed25519.ScalarBaseMult(h) - - publicKeyBytes := A.ToAffineCompressed() - copy(privateKey, seed) - copy(privateKey[32:], publicKeyBytes[:]) - return nil -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) ([]byte, error) { - // Outline the function body so that the returned signature can be - // stack-allocated. - signature := make([]byte, SignatureSize) - err := sign(signature, privateKey, message) - if err != nil { - return nil, err - } - return signature, nil -} - -func sign(signature, privateKey, message []byte) error { - if l := len(privateKey); l != PrivateKeySize { - return fmt.Errorf("ed25519: bad private key length: %d", l) - } - - var err error - h := sha512.New() - _, err = h.Write(privateKey[:32]) - if err != nil { - return err - } - - var digest1, messageDigest, hramDigest [64]byte - var expandedSecretKey [32]byte - _ = h.Sum(digest1[:0]) - copy(expandedSecretKey[:], digest1[:]) - expandedSecretKey[0] &= 248 - expandedSecretKey[31] &= 63 - expandedSecretKey[31] |= 64 - - h.Reset() - _, err = h.Write(digest1[32:]) - if err != nil { - return err - } - _, err = h.Write(message) - if err != nil { - return err - } - _ = h.Sum(messageDigest[:0]) - - r, err := new(curves.ScalarEd25519).SetBytesWide(messageDigest[:]) - if err != nil { - return err - } - - // R = r * G - R := curves.ED25519().Point.Generator().Mul(r) - encodedR := R.ToAffineCompressed() - - h.Reset() - _, err = h.Write(encodedR[:]) - if err != nil { - return err - } - _, err = h.Write(privateKey[32:]) - if err != nil { - return err - } - _, err = h.Write(message) - if err != nil { - return err - } - _ = h.Sum(hramDigest[:0]) - - // Set k and s - k, err := new(curves.ScalarEd25519).SetBytesWide(hramDigest[:]) - if err != nil { - return err - } - - s, err := new(curves.ScalarEd25519).SetBytesClamping(expandedSecretKey[:]) - if err != nil { - return err - } - - // S = k*s + r - S := k.MulAdd(s, r) - copy(signature[:], encodedR[:]) - copy(signature[32:], S.Bytes()[:]) - return nil -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -// Previously publicKey is of type PublicKey -func Verify(publicKey PublicKey, message, sig []byte) (bool, error) { - if l := len(publicKey); l != PublicKeySize { - return false, fmt.Errorf("ed25519: bad public key length: %d", l) - } - - if len(sig) != SignatureSize || sig[63]&224 != 0 { - return false, fmt.Errorf("ed25519: bad signature size: %d", len(sig)) - } - - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], publicKey) - - A, err := new(curves.PointEd25519).FromAffineCompressed(publicKeyBytes[:]) - if err != nil { - return false, err - } - - // Negate sets A = -A, and returns A. It actually negates X and T but keep Y and Z - negA := A.Neg() - - h := sha512.New() - _, err = h.Write(sig[:32]) - if err != nil { - panic(err) - } - - _, err = h.Write(publicKey[:]) - if err != nil { - return false, err - } - - _, err = h.Write(message) - if err != nil { - return false, err - } - - var digest [64]byte - _ = h.Sum(digest[:0]) - - hReduced, err := new(curves.ScalarEd25519).SetBytesWide(digest[:]) - if err != nil { - return false, err - } - - var s [32]byte - copy(s[:], sig[32:]) - sScalar, err := new(curves.ScalarEd25519).SetBytesCanonical(s[:]) - if err != nil { - return false, err - } - - // R' = hash * A + s * BasePoint - R := new(curves.PointEd25519).VarTimeDoubleScalarBaseMult(hReduced, negA, sScalar) - // Check R == R' - return bytes.Equal(sig[:32], R.ToAffineCompressed()), nil -} diff --git a/crypto/ted25519/ted25519/ed25519_test.go b/crypto/ted25519/ted25519/ed25519_test.go deleted file mode 100644 index 01366a12e..000000000 --- a/crypto/ted25519/ted25519/ed25519_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ted25519 - -import ( - "bytes" - "crypto" - "crypto/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// sign.input.gz is a selection of test cases from -// https://ed25519.cr.yp.to/python/sign.input - -type zeroReader struct{} - -func (zeroReader) Read(buf []byte) (int, error) { - for i := range buf { - buf[i] = 0 - } - return len(buf), nil -} - -func TestUnmarshalMarshal(t *testing.T) { - pub, _, err := GenerateKey(rand.Reader) - require.NoError(t, err) - - var publicKeyBytes [32]byte - copy(publicKeyBytes[:], pub) - - A, err := new(curves.PointEd25519).FromAffineCompressed(publicKeyBytes[:]) - require.NoError(t, err) - var pub2 [32]byte - copy(pub2[:], A.ToAffineCompressed()) - - if publicKeyBytes != pub2 { - t.Errorf("FromBytes(%v)->ToBytes does not round-trip, got %x\n", publicKeyBytes, pub2) - } -} - -func TestSignVerify(t *testing.T) { - var zero zeroReader - public, private, err := GenerateKey(zero) - require.NoError(t, err) - - message := []byte("test message") - sig, err := Sign(private, message) - require.NoError(t, err) - ok, _ := Verify(public, message, sig) - require.True(t, ok) - - wrongMessage := []byte("wrong message") - ok, _ = Verify(public, wrongMessage, sig) - require.True(t, !ok) -} - -func TestCryptoSigner(t *testing.T) { - var zero zeroReader - public, private, _ := GenerateKey(zero) - - signer := crypto.Signer(private) - - publicInterface := signer.Public() - public2, ok := publicInterface.(PublicKey) - if !ok { - t.Fatalf("expected PublicKey from Public() but got %T", publicInterface) - } - - if !bytes.Equal(public, public2) { - t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2) - } - - message := []byte("message") - var noHash crypto.Hash - signature, err := signer.Sign(zero, message, noHash) - if err != nil { - t.Fatalf("error from Sign(): %s", err) - } - - ok, _ = Verify(public, message, signature) - if !ok { - t.Errorf("Verify failed on signature from Sign()") - } -} - -func TestMalleability(t *testing.T) { - // https://tools.ietf.org/html/rfc8032#section-5.1.7 adds an additional test - // that s be in [0, order). This prevents someone from adding a multiple of - // order to s and obtaining a second valid signature for the same message. - msg := []byte{0x54, 0x65, 0x73, 0x74} - sig := []byte{ - 0x7c, 0x38, 0xe0, 0x26, 0xf2, 0x9e, 0x14, 0xaa, 0xbd, 0x05, 0x9a, - 0x0f, 0x2d, 0xb8, 0xb0, 0xcd, 0x78, 0x30, 0x40, 0x60, 0x9a, 0x8b, - 0xe6, 0x84, 0xdb, 0x12, 0xf8, 0x2a, 0x27, 0x77, 0x4a, 0xb0, 0x67, - 0x65, 0x4b, 0xce, 0x38, 0x32, 0xc2, 0xd7, 0x6f, 0x8f, 0x6f, 0x5d, - 0xaf, 0xc0, 0x8d, 0x93, 0x39, 0xd4, 0xee, 0xf6, 0x76, 0x57, 0x33, - 0x36, 0xa5, 0xc5, 0x1e, 0xb6, 0xf9, 0x46, 0xb3, 0x1d, - } - publicKey := []byte{ - 0x7d, 0x4d, 0x0e, 0x7f, 0x61, 0x53, 0xa6, 0x9b, 0x62, 0x42, 0xb5, - 0x22, 0xab, 0xbe, 0xe6, 0x85, 0xfd, 0xa4, 0x42, 0x0f, 0x88, 0x34, - 0xb1, 0x08, 0xc3, 0xbd, 0xae, 0x36, 0x9e, 0xf5, 0x49, 0xfa, - } - - ok, _ := Verify(publicKey, msg, sig) - if ok { - t.Fatal("non-canonical signature accepted") - } -} - -func BenchmarkKeyGeneration(b *testing.B) { - var zero zeroReader - for i := 0; i < b.N; i++ { - if _, _, err := GenerateKey(zero); err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkNewKeyFromSeed(b *testing.B) { - seed := make([]byte, SeedSize) - b.ReportAllocs() - for i := 0; i < b.N; i++ { - _, _ = NewKeyFromSeed(seed) - } -} - -func BenchmarkSigning(b *testing.B) { - var zero zeroReader - _, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = Sign(priv, message) - } -} - -func BenchmarkVerification(b *testing.B) { - var zero zeroReader - pub, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - signature, _ := Sign(priv, message) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = Verify(pub, message, signature) - } -} diff --git a/crypto/ted25519/ted25519/ext.go b/crypto/ted25519/ted25519/ext.go deleted file mode 100644 index bd1ed4633..000000000 --- a/crypto/ted25519/ted25519/ext.go +++ /dev/null @@ -1,123 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "crypto/sha512" - "strconv" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// GeAdd returns the sum of two public keys, a and b. -func GeAdd(a PublicKey, b PublicKey) PublicKey { - aPoint, err := new(curves.PointEd25519).FromAffineCompressed(a) - if err != nil { - panic("attempted to add invalid point: a") - } - bPoint, err := new(curves.PointEd25519).FromAffineCompressed(b) - if err != nil { - panic("attempted to add invalid point: b") - } - - sum := aPoint.Add(bPoint) - return sum.ToAffineCompressed() -} - -// ExpandSeed applies the standard Ed25519 transform to the seed to turn it into the real private -// key that is used for signing. It returns the expanded seed. -func ExpandSeed(seed []byte) []byte { - digest := sha512.Sum512(seed) - digest[0] &= 248 - digest[31] &= 127 - digest[31] |= 64 - return digest[:32] -} - -// reverseBytes returns a new slice of the input bytes reversed -func reverseBytes(inBytes []byte) []byte { - outBytes := make([]byte, len(inBytes)) - - for i, j := 0, len(inBytes)-1; j >= 0; i, j = i+1, j-1 { - outBytes[i] = inBytes[j] - } - - return outBytes -} - -// ThresholdSign is used for creating signatures for threshold protocols that replace the values of -// the private key and nonce with shamir shares instead. Because of this we must have a custom -// signing implementation that accepts arguments for values that cannot be derived anymore and -// removes the extended key generation since that should be done before the secret is shared. -// -// expandedSecretKeyShare and rShare must be little-endian. -func ThresholdSign( - expandedSecretKeyShare []byte, publicKey PublicKey, - message []byte, - rShare []byte, R PublicKey, // nolint:gocritic -) []byte { - // These length checks are are sanity checks where we panic if a provided value falls outside of the expected range. - // These should never fail in practice but serve to protect us from some bug that would cause us to produce - // signatures using a zero value or clipping off extra bytes unintentionally. - // - // We don't specifically check for 32 byte values as any value within the subgroup field could show up here. This is - // different than the upstream Ed25519 which does, but this seems to be a result of how they initialize their byte - // slices to constants and does not guarantee the value itself is 32 bytes without padding. - if l := len(expandedSecretKeyShare); l == 0 || l > 32 { - panic("ed25519: bad key share length: " + strconv.Itoa(l)) - } - if l := len(rShare); l == 0 || l > 32 { - panic("ed25519: bad nonce share length: " + strconv.Itoa(l)) - } - - var expandedSecretKey, rBytes [32]byte - copy(expandedSecretKey[:], expandedSecretKeyShare) - copy(rBytes[:], rShare) - - // c = H(R || A || m) mod q - var hramDigest [64]byte - var err error - h := sha512.New() - _, err = h.Write(R[:]) - if err != nil { - panic(err) - } - _, err = h.Write(publicKey[:]) - if err != nil { - panic(err) - } - _, err = h.Write(message) - if err != nil { - panic(err) - } - _ = h.Sum(hramDigest[:0]) - - // Set c, x and r - c, err := new(curves.ScalarEd25519).SetBytesWide(hramDigest[:]) - if err != nil { - panic(err) - } - - x, err := new(curves.ScalarEd25519).SetBytesCanonical(expandedSecretKey[:]) - if err != nil { - panic(err) - } - - r, err := new(curves.ScalarEd25519).SetBytesCanonical(rBytes[:]) - if err != nil { - panic(err) - } - - // s = cx+r - s := c.MulAdd(x, r) - - signature := make([]byte, SignatureSize) - copy(signature, R[:]) - copy(signature[32:], s.Bytes()[:]) - - return signature -} diff --git a/crypto/ted25519/ted25519/ext_test.go b/crypto/ted25519/ted25519/ext_test.go deleted file mode 100644 index c3bcfdda2..000000000 --- a/crypto/ted25519/ted25519/ext_test.go +++ /dev/null @@ -1,143 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "crypto/rand" - "encoding/hex" - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -const ( - expectedSeedHex = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60" - expectedPrivKeyHex = "307c83864f2833cb427a2ef1c00a013cfdff2768d980c0a3a520f006904de94f" -) - -func TestExpandSeed(t *testing.T) { - seedBytes, err := hex.DecodeString(expectedSeedHex) - require.NoError(t, err) - privKeyHex := hex.EncodeToString(ExpandSeed(seedBytes)) - require.Equal(t, expectedPrivKeyHex, privKeyHex) -} - -func TestThresholdSign(t *testing.T) { - pub, priv, err := generateKey() - require.NoError(t, err) - field := curves.NewField(curves.Ed25519Order()) - keyShare := v1.NewShamirShare(0, priv, field) - r := big.NewInt(123456789).Bytes() - nonceShare := v1.NewShamirShare(0, r, field) - - r = reverseBytes(r) - var rInput [32]byte - copy(rInput[:], r) - scalar, err := new(curves.ScalarEd25519).SetBytesCanonical(rInput[:]) - require.NoError(t, err) - noncePub := curves.ED25519().Point.Generator().Mul(scalar) - - message := []byte("fnord!") - wrongMessage := []byte("23") - sig := ThresholdSign( - reverseBytes(keyShare.Value.Bytes()), - pub, - message, - reverseBytes(nonceShare.Value.Bytes()), - noncePub.ToAffineCompressed(), - ) - - ok, _ := Verify(pub, message, sig) - require.True(t, ok) - ok, _ = Verify(pub, wrongMessage, sig) - require.False(t, ok) -} - -func TestThresholdSign_invalid_secrets(t *testing.T) { - message := []byte("fnord!") - - secret := []byte{0x02} - secret = reverseBytes(secret) - var sInput [32]byte - copy(sInput[:], secret) - scalar, err := new(curves.ScalarEd25519).SetBytesCanonical(sInput[:]) - require.NoError(t, err) - pub := curves.ED25519().Point.Generator().Mul(scalar) - - nonce := []byte{0x03} - nonce = reverseBytes(nonce) - var nInput [32]byte - copy(nInput[:], nonce) - nScalar, err := new(curves.ScalarEd25519).SetBytesCanonical(nInput[:]) - require.NoError(t, err) - noncePub := curves.ED25519().Point.Generator().Mul(nScalar) - - require.PanicsWithValue(t, "ed25519: bad key share length: 0", - func() { - ThresholdSign( - make([]byte, 0), - pub.ToAffineCompressed(), - message, - nonce, - noncePub.ToAffineCompressed(), - ) - }, - ) - - require.PanicsWithValue(t, "ed25519: bad key share length: 33", - func() { - ThresholdSign( - make([]byte, 33), - pub.ToAffineCompressed(), - message, - nonce, - noncePub.ToAffineCompressed(), - ) - }, - ) - - require.PanicsWithValue(t, "ed25519: bad nonce share length: 0", - func() { - ThresholdSign( - secret, - pub.ToAffineCompressed(), - message, - make([]byte, 0), - noncePub.ToAffineCompressed(), - ) - }, - ) - - require.PanicsWithValue(t, "ed25519: bad nonce share length: 33", - func() { - ThresholdSign( - secret, - pub.ToAffineCompressed(), - message, - make([]byte, 33), - noncePub.ToAffineCompressed(), - ) - }, - ) -} - -// generateKey is the same as generateSharableKey, but used only for testing -func generateKey() (PublicKey, []byte, error) { - pub, priv, err := GenerateKey(rand.Reader) - if err != nil { - return nil, nil, err - } - seed := priv.Seed() - expandedSeed := reverseBytes(ExpandSeed(seed)) - field := &curves.Field{Int: curves.Ed25519Order()} - expandedSeedReduced := field.ReducedElementFromBytes(expandedSeed) - return pub, expandedSeedReduced.Bytes(), nil -} diff --git a/crypto/ted25519/ted25519/keygen.go b/crypto/ted25519/ted25519/keygen.go deleted file mode 100644 index 7b0ff6b66..000000000 --- a/crypto/ted25519/ted25519/keygen.go +++ /dev/null @@ -1,243 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "encoding/binary" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -// PublicKeyFromBytes converts byte array into PublicKey byte array -func PublicKeyFromBytes(bytes []byte) ([]byte, error) { - if l := len(bytes); l != PublicKeySize { - return nil, fmt.Errorf("invalid public key size: %d", l) - } - - return bytes, nil -} - -// KeyShare represents a share of a generated key. -type KeyShare struct { - *v1.ShamirShare -} - -// NewKeyShare is a KeyShare constructor. -func NewKeyShare(identifier byte, secret []byte) *KeyShare { - field := curves.NewField(curves.Ed25519Order()) - return &KeyShare{v1.NewShamirShare(uint32(identifier), secret, field)} -} - -// Commitments is a collection of public keys with each coefficient of a polynomial as the secret keys. -type Commitments []curves.Point - -// CommitmentsToBytes converts commitments to bytes -func (commitments Commitments) CommitmentsToBytes() [][]byte { - bytes := make([][]byte, len(commitments)) - - for i, c := range commitments { - bytes[i] = c.ToAffineCompressed() - } - - return bytes -} - -// CommitmentsFromBytes converts bytes to commitments -func CommitmentsFromBytes(bytes [][]byte) (Commitments, error) { - comms := make([]curves.Point, len(bytes)) - for i, pubKeyBytes := range bytes { - pubKey, err := PublicKeyFromBytes(pubKeyBytes) - if err != nil { - return nil, err - } - comms[i], err = new(curves.PointEd25519).FromAffineCompressed(pubKey) - if err != nil { - return nil, err - } - } - return comms, nil -} - -// KeyShareFromBytes converts byte array into KeyShare type -func KeyShareFromBytes(bytes []byte) *KeyShare { - field := curves.NewField(curves.Ed25519Order()) - element := field.ElementFromBytes(bytes[4:]) - - // We set first 4 bytes as identifier - identifier := binary.BigEndian.Uint32(bytes[:4]) - return &KeyShare{&v1.ShamirShare{Identifier: identifier, Value: element}} -} - -// ShareConfiguration sets threshold and limit for the protocol -type ShareConfiguration struct { - T int // threshold - N int // total shares -} - -// generateSharableKey generates a random key and returns the public key and private key in -// big-endian encoding. It returns an error if it cannot acquire sufficient randomness. -func generateSharableKey() (PublicKey, []byte, error) { - pub, priv, err := GenerateKey(nil) - if err != nil { - return nil, nil, err - } - - // Internally the PrivateKey type is represented as the seed || public key, but we want to pull - // out seed to share which is the actual private key. - seed := priv.Seed() - - // We must apply the key expansion to the seed before splitting the key. - // Ed25519 signing by default will apply this during signature generation, but since it involves - // a hash function, it breaks the relationship between shares and breaks aggregating signatures. - // Our signature generation does not apply this mutation at signing time. - // - // As per anything that comes from the ed25519 library this value should be treated as - // little-endian so we reverse it before using it. - expandedSeed := reverseBytes(ExpandSeed(seed)) - - // Lastly we must reduce this value into the size of the field so we can share it. This diverges - // from how the standard implementation treats this because their scalar multiplication accepts - // values up to the curve order but we must constrain it to be able to split it and aggregate. - // - // If you read the documentation for the ReducedElementFromBytes function we call below, it - // includes a big warning about how it will return non-uniform outputs depending on the input. - // This is true, but not a concern for keygen specifically because the value we are providing it - // has been generated as the ed25519 spec requires, which has a slight bias by definition of how - // the ExpandSeed operation works. - field := &curves.Field{Int: curves.Ed25519Order()} - expandedSeedReduced := field.ReducedElementFromBytes(expandedSeed) - - return pub, expandedSeedReduced.Bytes(), nil -} - -// GenerateSharedKey generates a random key, splits it, and returns the public key, shares, and VSS commitments. -func GenerateSharedKey(config *ShareConfiguration) (PublicKey, []*KeyShare, Commitments, error) { - pub, priv, err := generateSharableKey() - // pub, priv, err := ed25519.GenerateKey(nil) - if err != nil { - return nil, nil, nil, err - } - - keyShares, commitments, err := splitPrivateKey(config, priv) - if err != nil { - return nil, nil, nil, err - } - - return pub, keyShares, commitments, nil -} - -// splitPrivateKey splits the secret into a set of secret shares and creates a set of commitments of them. -func splitPrivateKey(config *ShareConfiguration, priv []byte) ([]*KeyShare, Commitments, error) { - commitments, shares, err := split(priv, config) - if err != nil { - return nil, nil, err - } - - keyShares := make([]*KeyShare, len(shares)) - for i, s := range shares { - keyShares[i] = &KeyShare{s} - } - return keyShares, commitments, nil -} - -// split contains core operations to split the secret and generate commitments. -func split(secret []byte, config *ShareConfiguration) ([]curves.Point, []*v1.ShamirShare, error) { - field := curves.NewField(curves.Ed25519Order()) - shamir, err := v1.NewShamir(config.T, config.N, field) - if err != nil { - return nil, nil, fmt.Errorf("error in NewShamir") - } - shares, poly, err := shamir.GetSharesAndPolynomial(secret) - if err != nil { - return nil, nil, fmt.Errorf("error in GetSharesAndPolynomial") - } - - // Generate the verifiable commitments to the polynomial for the shares - verifiers := make([]curves.Point, len(poly.Coefficients)) - // curve := sharing.Ed25519() - for i, c := range poly.Coefficients { - // We have to reverse each coefficient, which is different than the method sharing.Split - reverseC := reverseBytes(c.Bytes()) - var reverseInput [32]byte - copy(reverseInput[:], reverseC) - cScalar, err := new(curves.ScalarEd25519).SetBytesCanonical(reverseInput[:]) - if err != nil { - return nil, nil, fmt.Errorf("error in SetBytesCanonical reverseC") - } - v := curves.ED25519().Point.Generator().Mul(cScalar) - verifiers[i] = v - } - return verifiers, shares, nil -} - -// Reconstruct recovers the secret from a set of secret shares. -func Reconstruct(keyShares []*KeyShare, config *ShareConfiguration) ([]byte, error) { - curve := v1.Ed25519() - field := curves.NewField(curve.Params().N) - shamir, err := v1.NewShamir(config.T, config.N, field) - if err != nil { - return nil, err - } - - shares := make([]*v1.ShamirShare, len(keyShares)) - for i, s := range keyShares { - shares[i] = s.ShamirShare - } - return shamir.Combine(shares...) -} - -// VerifyVSS validates that a Share represents a solution to a Shamir polynomial -// in which len(commitments) + 1 solutions are required to construct the private -// key for the public key at commitments[0]. -func (share *KeyShare) VerifyVSS( - commitments Commitments, - config *ShareConfiguration, -) (bool, error) { - if len(commitments) < config.T { - return false, fmt.Errorf("not enough verifiers to check") - } - field := curves.NewField(curves.Ed25519Order()) - xBytes := make([]byte, 4) - binary.BigEndian.PutUint32(xBytes, share.Identifier) - x := field.ElementFromBytes(xBytes) - i := share.Value.Modulus.One() - - // c_0 - rhs := commitments[0] - - // Compute the sum of products - // c_0 * c_1^i * c_2^{i^2} *c_3^{i^3} - for j := 1; j < len(commitments); j++ { - // i *= x - i = i.Mul(x) - - var iBytes [32]byte - copy(iBytes[:], i.Bytes()[:]) - iScalar, err := new(curves.ScalarEd25519).SetBytesCanonical(iBytes[:]) - if err != nil { - return false, fmt.Errorf("error in SetBytesCanonical iBytes") - } - c := commitments[j].Mul(iScalar) - - // ...* c_j^{i^j} - rhs = rhs.Add(c) - } - - vValue := reverseBytes(share.Value.Bytes()) - var vInput [32]byte - copy(vInput[:], vValue) - vScalar, err := new(curves.ScalarEd25519).SetBytes(vInput[:]) - if err != nil { - return false, err - } - lhs := curves.ED25519().ScalarBaseMult(vScalar) - - // Check if lhs == rhs - return lhs.Equal(rhs), nil -} diff --git a/crypto/ted25519/ted25519/keygen_test.go b/crypto/ted25519/ted25519/keygen_test.go deleted file mode 100644 index d3536d3c2..000000000 --- a/crypto/ted25519/ted25519/keygen_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -func TestGenerateEd25519Key(t *testing.T) { - config := ShareConfiguration{T: 2, N: 3} - - // Generate and verify correct number of shares are produced - pub, shares, _, err := GenerateSharedKey(&config) - require.NoError(t, err) - require.Equal(t, config.N, len(shares)) - - // Verify reconstuction works for all permutations of shares - shareVec := make([]*KeyShare, 2) - shareVec[0] = shares[0] - shareVec[1] = shares[1] - secret1, err := Reconstruct(shareVec, &config) - require.Nil(t, err) - shareVec[0] = shares[1] - shareVec[1] = shares[2] - secret2, err := Reconstruct(shareVec, &config) - require.Nil(t, err) - shareVec[0] = shares[0] - shareVec[1] = shares[2] - secret3, err := Reconstruct(shareVec, &config) - require.Nil(t, err) - require.Equal(t, secret1, secret2) - require.Equal(t, secret2, secret3) - - // Need to reverse secret1 - secret1 = reverseBytes(secret1) - var secret1Bytes [32]byte - copy(secret1Bytes[:], secret1) - scalar1, err := new(curves.ScalarEd25519).SetBytesCanonical(secret1Bytes[:]) - require.NoError(t, err) - ed25519 := curves.ED25519() - pubFromSeed := ed25519.Point.Generator().Mul(scalar1) - - require.NoError(t, err) - require.Equal(t, pubFromSeed.ToAffineCompressed(), pub.Bytes()) -} - -func TestGenerateEd25519KeyInvalidConfig(t *testing.T) { - invalidConfig := ShareConfiguration{T: 1, N: 1} - _, _, _, err := GenerateSharedKey(&invalidConfig) - require.NotNil(t, err) - require.Error(t, err) - - invalidConfig = ShareConfiguration{T: 2, N: 1} - _, _, _, err = GenerateSharedKey(&invalidConfig) - require.NotNil(t, err) - require.Error(t, err) -} - -func TestVerifyVSSEd25519(t *testing.T) { - config := ShareConfiguration{T: 2, N: 3} - pubKey1, shares1, commitments1, err := GenerateSharedKey(&config) - require.NoError(t, err) - pubKey2, shares2, commitments2, err := GenerateSharedKey(&config) - require.NoError(t, err) - - require.Equal(t, pubKey1.Bytes(), commitments1[0].ToAffineCompressed()) - require.Equal(t, pubKey2.Bytes(), commitments2[0].ToAffineCompressed()) - - for _, s := range shares1 { - ok, err := s.VerifyVSS(commitments1, &config) - require.NoError(t, err) - require.True(t, ok) - ok, _ = s.VerifyVSS(commitments2, &config) - require.True(t, !ok) - } - - for _, s := range shares2 { - ok, err := s.VerifyVSS(commitments2, &config) - require.NoError(t, err) - require.True(t, ok) - ok, _ = s.VerifyVSS(commitments1, &config) - require.True(t, !ok) - } -} - -func TestCommitmentsFromBytes(t *testing.T) { - config := ShareConfiguration{T: 2, N: 3} - _, _, comms, err := GenerateSharedKey(&config) - require.NoError(t, err) - - recoveredComms, err := CommitmentsFromBytes(comms.CommitmentsToBytes()) - require.NoError(t, err) - require.Equal(t, len(comms), len(recoveredComms)) - for i := range comms { - require.True(t, comms[i].Equal(recoveredComms[i])) - } - _, err = CommitmentsFromBytes([][]byte{{0x01}}) - require.Error(t, err) -} - -func TestPublicKeyFromBytes(t *testing.T) { - _, err := PublicKeyFromBytes([]byte{0x01}) - require.EqualError(t, err, "invalid public key size: 1") -} - -func TestKeyShareFromBytes(t *testing.T) { - field := curves.NewField(curves.Ed25519Order()) - share := &v1.ShamirShare{ - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - } - shareBytes := share.Bytes() - recoveredShare := KeyShareFromBytes(shareBytes) - require.Equal(t, recoveredShare.ShamirShare, share) -} diff --git a/crypto/ted25519/ted25519/noncegen.go b/crypto/ted25519/ted25519/noncegen.go deleted file mode 100644 index bc3d7170f..000000000 --- a/crypto/ted25519/ted25519/noncegen.go +++ /dev/null @@ -1,123 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "crypto/rand" - "crypto/sha256" - "io" - - "golang.org/x/crypto/hkdf" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -// NonceShare represents a share of a generated nonce. -type NonceShare struct { - *KeyShare -} - -// NewNonceShare is a NonceShare construction -func NewNonceShare(identifier byte, secret []byte) *NonceShare { - return &NonceShare{NewKeyShare(identifier, secret)} -} - -// NonceShareFromBytes unmashals a NonceShare from its bytes representation -func NonceShareFromBytes(bytes []byte) *NonceShare { - return &NonceShare{KeyShareFromBytes(bytes)} -} - -func generateSharableNonce(s *KeyShare, p PublicKey, m Message) (PublicKey, []byte, error) { - // Create an HKDF reader that produces random bytes that we will use to create a nonce - hkdf, err := generateRandomHkdf(s, p, m) - if err != nil { - return nil, nil, err - } - - // Generate a random nonce that is within the field range so that we can share it. - // - // This diverges from how the standard implementation treats it because their scalar - // multiplication accepts values up to the curve order, but we must constrain it to be able to - // split it and aggregate. - // - // WARN: This operation is not constant time and we are dealing with a secret value - nonce, err := curves.NewField(curves.Ed25519Order()).RandomElement(hkdf) - if err != nil { - return nil, nil, err - } - - nonceBytes := nonce.Bytes() - reverseBytes := reverseBytes(nonceBytes) - var reverseInput [32]byte - copy(reverseInput[:], reverseBytes) - scalar, err := new(curves.ScalarEd25519).SetBytesCanonical(reverseInput[:]) - if err != nil { - return nil, nil, err - } - - // Generate the nonce pubkey by multiplying it by the base point. - noncePubkey := curves.ED25519().Point.Generator().Mul(scalar) - - return noncePubkey.ToAffineCompressed(), nonceBytes, nil -} - -// GenerateSharedNonce generates a random nonce, splits it, and returns the nonce pubkey, nonce shares, and -// VSS commitments. -func GenerateSharedNonce(config *ShareConfiguration, s *KeyShare, p PublicKey, m Message) ( - PublicKey, - []*NonceShare, - Commitments, - error, -) { - noncePubkey, nonce, err := generateSharableNonce(s, p, m) - if err != nil { - return nil, nil, nil, err - } - keyShares, vssCommitments, err := splitPrivateKey(config, nonce) - if err != nil { - return nil, nil, nil, err - } - - nonceShares := make([]*NonceShare, len(keyShares)) - for i, k := range keyShares { - nonceShares[i] = &NonceShare{k} - } - return noncePubkey, nonceShares, vssCommitments, nil -} - -// Add returns the sum of two NonceShares. -func (n NonceShare) Add(other *NonceShare) *NonceShare { - return &NonceShare{ - &KeyShare{ - // use Add method from the shamir.Share type to sum the shares - // WARN: This is not constant time and deals with secrets - n.ShamirShare.Add(other.ShamirShare), - }, - } -} - -// generateRandomHkdf returns an HMAC-based extract-and-expand Key Derivation Function (see RFC 5869). -func generateRandomHkdf(s *KeyShare, p PublicKey, m Message) (io.Reader, error) { - // We _must_ introduce randomness to the HKDF to make the output non-deterministic because deterministic nonces open - // up threshold schemes to potential nonce-reuse attacks. We continue to use the HKDF that takes in context about - // what is going to be signed as it adds some protection against bad local randomness. - randNonce := make([]byte, SeedSize) - if _, err := io.ReadFull(rand.Reader, randNonce); err != nil { - return nil, err - } - - var secret []byte - secret = append(secret, s.Bytes()...) - secret = append(secret, randNonce...) - - info := []byte("ted25519nonce") - // We use info for non-secret inputs to limit an attacker's ability to influence the key. - info = append(info, p.Bytes()...) - info = append(info, m...) - - return hkdf.New(sha256.New, secret, nil, info), nil -} diff --git a/crypto/ted25519/ted25519/noncegen_test.go b/crypto/ted25519/ted25519/noncegen_test.go deleted file mode 100644 index 584c25df5..000000000 --- a/crypto/ted25519/ted25519/noncegen_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -func TestNonceShareFromBytes(t *testing.T) { - field := curves.NewField(curves.Ed25519Order()) - share := &v1.ShamirShare{ - Identifier: 2, - Value: field.NewElement(big.NewInt(3)), - } - shareBytes := share.Bytes() - recoveredShare := NonceShareFromBytes(shareBytes) - require.Equal(t, recoveredShare.ShamirShare, share) - require.Equal(t, share.Identifier, uint32(2)) -} - -func TestGenerateSharedNonce_congruence(t *testing.T) { - config := &ShareConfiguration{T: 2, N: 3} - message := []byte("fnord!") - pubKey, keyShares, _, err := GenerateSharedKey(config) - require.NoError(t, err) - nonceCommitment, nonceShares, _, err := GenerateSharedNonce( - config, - keyShares[0], - pubKey, - message, - ) - require.NoError(t, err) - field := curves.NewField(curves.Ed25519Order()) - shamir, err := v1.NewShamir(config.T, config.N, field) - require.NoError(t, err) - nonce, err := shamir.Combine(toShamirShare(nonceShares)...) - require.NoError(t, err) - - nonce = reverseBytes(nonce) - var nonceBytes [32]byte - copy(nonceBytes[:], nonce) - nonceScalar, err := new(curves.ScalarEd25519).SetBytesCanonical(nonceBytes[:]) - require.NoError(t, err) - ed25519 := curves.ED25519() - recoveredCommitment := ed25519.Point.Generator().Mul(nonceScalar) - require.Equal(t, recoveredCommitment.ToAffineCompressed(), nonceCommitment.Bytes()) -} - -func TestGenerateNonce_non_determinism(t *testing.T) { - config := &ShareConfiguration{T: 2, N: 3} - message := []byte("fnord!") - pubKey, keyShares, _, err := GenerateSharedKey(config) - require.NoError(t, err) - - _, nonceShares1, _, err := GenerateSharedNonce(config, keyShares[0], pubKey, message) - require.NoError(t, err) - field := curves.NewField(curves.Ed25519Order()) - shamir, err := v1.NewShamir(config.T, config.N, field) - require.NoError(t, err) - nonce1, err := shamir.Combine(toShamirShare(nonceShares1)...) - require.NoError(t, err) - - _, nonceShares2, _, err := GenerateSharedNonce(config, keyShares[1], pubKey, message) - require.NoError(t, err) - nonce2, err := shamir.Combine(toShamirShare(nonceShares2)...) - require.NoError(t, err) - - _, nonceShares3, _, err := GenerateSharedNonce(config, keyShares[0], pubKey, message) - require.NoError(t, err) - nonce3, err := shamir.Combine(toShamirShare(nonceShares3)...) - require.NoError(t, err) - - require.NotEqual(t, nonce1, nonce2) - require.NotEqual(t, nonce1, nonce3) -} - -func TestNonceSharesAdd(t *testing.T) { - one := NewNonceShare(0, []byte{0x01}) - two := NewNonceShare(0, []byte{0x02}) - - // basic addition - sum := one.Add(two) - require.Equal(t, uint32(0), sum.Identifier) - require.Equal(t, []byte{0x03}, sum.Value.Bytes()) -} - -func TestNonceSharesAdd_errors(t *testing.T) { - one := NewNonceShare(0, []byte{0x01}) - two := NewNonceShare(1, []byte{0x02}) - require.PanicsWithValue(t, "identifiers must match for valid addition", func() { - one.Add(two) - }) -} - -func toShamirShare(nonceShares []*NonceShare) []*v1.ShamirShare { - shamirShares := make([]*v1.ShamirShare, len(nonceShares)) - for i, n := range nonceShares { - shamirShares[i] = n.ShamirShare - } - return shamirShares -} diff --git a/crypto/ted25519/ted25519/partialsig.go b/crypto/ted25519/ted25519/partialsig.go deleted file mode 100755 index 5b5cafb57..000000000 --- a/crypto/ted25519/ted25519/partialsig.go +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import "strconv" - -type Message []byte - -func (m Message) String() string { - return string(m) -} - -const signatureLength = 64 - -type PartialSignature struct { - ShareIdentifier byte // x-coordinate of which signer produced signature - Sig []byte // 64-byte signature: R || s -} - -// NewPartialSignature creates a new PartialSignature -func NewPartialSignature(identifier byte, sig []byte) *PartialSignature { - if l := len(sig); l != signatureLength { - panic("ted25519: invalid partial signature length: " + strconv.Itoa(l)) - } - return &PartialSignature{ShareIdentifier: identifier, Sig: sig} -} - -// R returns the R component of the signature -func (sig *PartialSignature) R() []byte { - return sig.Sig[:32] -} - -// S returns the s component of the signature -func (sig *PartialSignature) S() []byte { - return sig.Sig[32:] -} - -func (sig *PartialSignature) Bytes() []byte { - return sig.Sig -} - -// TSign generates a signature that can later be aggregated with others to produce a signature valid -// under the provided public key and nonce pair. -func TSign( - message Message, - key *KeyShare, - pub PublicKey, - nonce *NonceShare, - noncePub PublicKey, -) *PartialSignature { - sig := ThresholdSign( - reverseBytes(key.Value.Bytes()), pub, - message, - reverseBytes(nonce.Value.Bytes()), noncePub, - ) - return NewPartialSignature(byte(key.ShamirShare.Identifier), sig) -} diff --git a/crypto/ted25519/ted25519/partialsig_test.go b/crypto/ted25519/ted25519/partialsig_test.go deleted file mode 100644 index c343c34d8..000000000 --- a/crypto/ted25519/ted25519/partialsig_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "math/big" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestPartialSignNormalSignature(t *testing.T) { - pub, priv, err := generateSharableKey() - require.NoError(t, err) - keyShare := NewKeyShare(0, priv) - r := big.NewInt(123456789).Bytes() - nonceShare := NewNonceShare(0, r) - - r = reverseBytes(r) - var rInput [32]byte - copy(rInput[:], r) - scalar, err := new(curves.ScalarEd25519).SetBytesCanonical(rInput[:]) - require.NoError(t, err) - noncePub := curves.ED25519().Point.Generator().Mul(scalar) - - message := []byte("test message") - wrongMessage := []byte("wrong message") - sig := TSign(message, keyShare, pub, nonceShare, noncePub.ToAffineCompressed()) - - ok, _ := Verify(pub, message, sig.Sig) - require.True(t, ok) - ok, _ = Verify(pub, wrongMessage, sig.Sig) - require.False(t, ok) -} - -func TestNewPartialSignature(t *testing.T) { - s := []byte("11111111111111111111111111111111") - r := []byte("22222222222222222222222222222222") - sigBytes := []byte("2222222222222222222222222222222211111111111111111111111111111111") - sig := NewPartialSignature(1, sigBytes) - - require.Equal(t, byte(1), sig.ShareIdentifier) - require.Equal(t, s, sig.S()) - require.Equal(t, r, sig.R()) - require.Equal(t, sigBytes, sig.Bytes()) - - require.PanicsWithValue(t, "ted25519: invalid partial signature length: 3", func() { - NewPartialSignature(1, []byte("sig")) - }) -} diff --git a/crypto/ted25519/ted25519/sigagg.go b/crypto/ted25519/ted25519/sigagg.go deleted file mode 100644 index 34c5c565f..000000000 --- a/crypto/ted25519/ted25519/sigagg.go +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "bytes" - "fmt" - - "github.com/sonr-io/sonr/crypto/core/curves" - v1 "github.com/sonr-io/sonr/crypto/sharing/v1" -) - -type Signature = []byte - -func Aggregate(sigs []*PartialSignature, config *ShareConfiguration) (Signature, error) { - if len(sigs) == 0 { - return nil, fmt.Errorf("ted25519: sigs must be non-empty") - } - - // Verify all nonce pubKeys are the same by checking they all match the first one. - noncePubkey := sigs[0].R() - for i := 1; i < len(sigs); i++ { - if !bytes.Equal(sigs[i].R(), noncePubkey) { - return nil, fmt.Errorf( - "ted25519: unexpected nonce pubkey. got: %x expected: %x", - sigs[i].R(), - noncePubkey, - ) - } - } - - // Convert signatures to a Shamir share representation so we can recombine them - sigShares := make([]*v1.ShamirShare, len(sigs)) - field := curves.NewField(curves.Ed25519Order()) - shamir, err := v1.NewShamir(config.T, config.N, field) - if err != nil { - return nil, err - } - - for i, sig := range sigs { - sigShares[i] = v1.NewShamirShare( - uint32(sig.ShareIdentifier), - reverseBytes(sig.S()), - field, - ) - } - - sigS, err := shamir.Combine(sigShares...) - if err != nil { - return nil, err - } - - sig := make([]byte, signatureLength) - copy(sig[:32], noncePubkey) // R is the same on all sigs - copy(sig[32:], reverseBytes(sigS)) // be-to-le - - return sig, nil -} diff --git a/crypto/ted25519/ted25519/sigagg_test.go b/crypto/ted25519/ted25519/sigagg_test.go deleted file mode 100755 index 8a94adab9..000000000 --- a/crypto/ted25519/ted25519/sigagg_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -package ted25519 - -import ( - "encoding/hex" - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSigAgg(t *testing.T) { - config := ShareConfiguration{T: 2, N: 3} - pub, secretShares, _, err := GenerateSharedKey(&config) - require.NoError(t, err) - - message := []byte("test message") - - // Each party generates a nonce and we combine them together into an aggregate one - noncePub1, nonceShares1, _, err := GenerateSharedNonce(&config, secretShares[0], pub, message) - require.NoError(t, err) - noncePub2, nonceShares2, _, err := GenerateSharedNonce(&config, secretShares[1], pub, message) - require.NoError(t, err) - noncePub3, nonceShares3, _, err := GenerateSharedNonce(&config, secretShares[2], pub, message) - require.NoError(t, err) - nonceShares := []*NonceShare{ - nonceShares1[0].Add(nonceShares2[0]).Add(nonceShares3[0]), - nonceShares1[1].Add(nonceShares2[1]).Add(nonceShares3[1]), - nonceShares1[2].Add(nonceShares2[2]).Add(nonceShares3[2]), - } - - noncePub := GeAdd(GeAdd(noncePub1, noncePub2), noncePub3) - - sig1 := TSign(message, secretShares[0], pub, nonceShares[0], noncePub) - sig2 := TSign(message, secretShares[1], pub, nonceShares[1], noncePub) - sig3 := TSign(message, secretShares[2], pub, nonceShares[2], noncePub) - - // Test signer 1&2 verification - sig, err := Aggregate([]*PartialSignature{sig1, sig2}, &config) - require.NoError(t, err) - assertSignatureVerifies(t, pub, message, sig) - - // Test signer 2&3 verification - sig, err = Aggregate([]*PartialSignature{sig2, sig3}, &config) - require.NoError(t, err) - assertSignatureVerifies(t, pub, message, sig) - - // Test signer 1&3 verification - sig, err = Aggregate([]*PartialSignature{sig1, sig3}, &config) - require.NoError(t, err) - assertSignatureVerifies(t, pub, message, sig) -} - -func TestSigAgg_validations(t *testing.T) { - config := ShareConfiguration{T: 2, N: 3} - _, err := Aggregate([]*PartialSignature{}, &config) - require.EqualError(t, err, "ted25519: sigs must be non-empty") - - sig1bytes, _ := hex.DecodeString( - "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155" + - "5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", - ) - sig2bytes, _ := hex.DecodeString( - "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da" + - "085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", - ) - sig1 := NewPartialSignature(1, sig1bytes) - sig2 := NewPartialSignature(2, sig2bytes) - - _, err = Aggregate([]*PartialSignature{sig1, sig2}, &config) - require.EqualError( - t, - err, - fmt.Sprintf( - "ted25519: unexpected nonce pubkey. got: %x expected: %x", - sig2bytes[:32], - sig1bytes[:32], - ), - ) -} - -func assertSignatureVerifies(t *testing.T, pub, message, sig []byte) { - ok, _ := Verify(pub, message, sig) - if !ok { - t.Errorf("valid signature rejected") - } - wrongMessage := []byte("wrong message") - ok, _ = Verify(pub, wrongMessage, sig) - if ok { - t.Errorf("signature of different message accepted") - } -} diff --git a/crypto/ted25519/ted25519/twobytwo_test.go b/crypto/ted25519/ted25519/twobytwo_test.go deleted file mode 100644 index 3c59f19f7..000000000 --- a/crypto/ted25519/ted25519/twobytwo_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -/* -* This is a simple example of a 2x2 signature scheme to prove out a simpler case than the threshold -* variants. We don't intend to use it and it is not modeled off of any specific known protocol. - */ -package ted25519 - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func AggregateSignatures(sig1, sig2 *PartialSignature) []byte { - field := curves.NewField(curves.Ed25519Order()) - sig1s := field.ElementFromBytes(reverseBytes(sig1.S())) - sig2s := field.ElementFromBytes(reverseBytes(sig2.S())) - sigS := sig1s.Add(sig2s) - - // Create signature as R || s. The R is the same so we use the same one - sig := make([]byte, SignatureSize) - copy(sig, sig1.R()) - copy(sig[32:], reverseBytes(sigS.Bytes())) - return sig -} - -func TestTwoByTwoSigning(t *testing.T) { - // generate shared pubkey - pub1, priv1, _ := generateSharableKey() - pub2, priv2, _ := generateSharableKey() - pub := GeAdd(pub1, pub2) - - // generate shared nonce - pubr1, r1, _ := generateSharableKey() - pubr2, r2, _ := generateSharableKey() - noncePub := GeAdd(pubr1, pubr2) - - // generate partial sigs - msg := []byte("test message") - sig1 := TSign(msg, NewKeyShare(0, priv1), pub, NewNonceShare(0, r1), noncePub) - sig2 := TSign(msg, NewKeyShare(0, priv2), pub, NewNonceShare(0, r2), noncePub) - - // add sigs (s+s) - sig := AggregateSignatures(sig1, sig2) - - ok, _ := Verify(pub, msg, sig) - require.True(t, ok, "signature failed verification") -} diff --git a/crypto/ucan/capability.go b/crypto/ucan/capability.go deleted file mode 100644 index b8d2e32d2..000000000 --- a/crypto/ucan/capability.go +++ /dev/null @@ -1,860 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "encoding/json" - "fmt" - "strings" - "time" -) - -// Token represents a UCAN JWT token with parsed claims -type Token struct { - Raw string `json:"raw"` - Issuer string `json:"iss"` - Audience string `json:"aud"` - ExpiresAt int64 `json:"exp,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Attenuations []Attenuation `json:"att"` - Proofs []Proof `json:"prf,omitempty"` - Facts []Fact `json:"fct,omitempty"` -} - -// Attenuation represents a UCAN capability attenuation -type Attenuation struct { - Capability Capability `json:"can"` - Resource Resource `json:"with"` -} - -// Proof represents a UCAN delegation proof (either JWT or CID) -type Proof string - -// Fact represents arbitrary facts in UCAN tokens -type Fact struct { - Data json.RawMessage `json:"data"` -} - -// Capability defines what actions can be performed -type Capability interface { - // GetActions returns the list of actions this capability grants - GetActions() []string - // Grants checks if this capability grants the required abilities - Grants(abilities []string) bool - // Contains checks if this capability contains another capability - Contains(other Capability) bool - // String returns a string representation - String() string -} - -// Resource defines what resource the capability applies to -type Resource interface { - // GetScheme returns the resource scheme (e.g., "https", "ipfs") - GetScheme() string - // GetValue returns the resource value/path - GetValue() string - // GetURI returns the full URI string - GetURI() string - // Matches checks if this resource matches another resource - Matches(other Resource) bool -} - -// SimpleCapability implements Capability for single actions -type SimpleCapability struct { - Action string `json:"action"` -} - -// GetActions returns the single action -func (c *SimpleCapability) GetActions() []string { - return []string{c.Action} -} - -// Grants checks if the capability grants all required abilities -func (c *SimpleCapability) Grants(abilities []string) bool { - if len(abilities) != 1 { - return false - } - return c.Action == abilities[0] || c.Action == "*" -} - -// Contains checks if this capability contains another capability -func (c *SimpleCapability) Contains(other Capability) bool { - if c.Action == "*" { - return true - } - - otherActions := other.GetActions() - if len(otherActions) != 1 { - return false - } - - return c.Action == otherActions[0] -} - -// String returns string representation -func (c *SimpleCapability) String() string { - return c.Action -} - -// MultiCapability implements Capability for multiple actions -type MultiCapability struct { - Actions []string `json:"actions"` -} - -// GetActions returns all actions -func (c *MultiCapability) GetActions() []string { - return c.Actions -} - -// Grants checks if the capability grants all required abilities -func (c *MultiCapability) Grants(abilities []string) bool { - actionSet := make(map[string]bool) - for _, action := range c.Actions { - actionSet[action] = true - } - - // Check if we have wildcard permission - if actionSet["*"] { - return true - } - - // Check each required ability - for _, ability := range abilities { - if !actionSet[ability] { - return false - } - } - - return true -} - -// Contains checks if this capability contains another capability -func (c *MultiCapability) Contains(other Capability) bool { - actionSet := make(map[string]bool) - for _, action := range c.Actions { - actionSet[action] = true - } - - // Wildcard contains everything - if actionSet["*"] { - return true - } - - // Check if all other actions are contained - for _, otherAction := range other.GetActions() { - if !actionSet[otherAction] { - return false - } - } - - return true -} - -// String returns string representation -func (c *MultiCapability) String() string { - return strings.Join(c.Actions, ",") -} - -// SimpleResource implements Resource for basic URI resources -type SimpleResource struct { - Scheme string `json:"scheme"` - Value string `json:"value"` - URI string `json:"uri"` -} - -// GetScheme returns the resource scheme -func (r *SimpleResource) GetScheme() string { - return r.Scheme -} - -// GetValue returns the resource value -func (r *SimpleResource) GetValue() string { - return r.Value -} - -// GetURI returns the full URI -func (r *SimpleResource) GetURI() string { - return r.URI -} - -// Matches checks if resources are equivalent -func (r *SimpleResource) Matches(other Resource) bool { - return r.URI == other.GetURI() -} - -// VaultResource represents vault-specific resources with metadata -type VaultResource struct { - SimpleResource - VaultAddress string `json:"vault_address,omitempty"` - EnclaveDataCID string `json:"enclave_data_cid,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// ServiceResource represents service-specific resources -type ServiceResource struct { - SimpleResource - ServiceID string `json:"service_id"` - Domain string `json:"domain"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// CreateSimpleAttenuation creates a basic attenuation -func CreateSimpleAttenuation(action, resourceURI string) Attenuation { - return Attenuation{ - Capability: &SimpleCapability{Action: action}, - Resource: parseResourceURI(resourceURI), - } -} - -// CreateMultiAttenuation creates an attenuation with multiple actions -func CreateMultiAttenuation(actions []string, resourceURI string) Attenuation { - return Attenuation{ - Capability: &MultiCapability{Actions: actions}, - Resource: parseResourceURI(resourceURI), - } -} - -// CreateVaultAttenuation creates a vault-specific attenuation -func CreateVaultAttenuation(actions []string, enclaveDataCID, vaultAddress string) Attenuation { - resource := &VaultResource{ - SimpleResource: SimpleResource{ - Scheme: "ipfs", - Value: enclaveDataCID, - URI: fmt.Sprintf("ipfs://%s", enclaveDataCID), - }, - VaultAddress: vaultAddress, - EnclaveDataCID: enclaveDataCID, - } - - return Attenuation{ - Capability: &MultiCapability{Actions: actions}, - Resource: resource, - } -} - -// CreateServiceAttenuation creates a service-specific attenuation -func CreateServiceAttenuation(actions []string, serviceID, domain string) Attenuation { - resourceURI := fmt.Sprintf("service://%s", serviceID) - resource := &ServiceResource{ - SimpleResource: SimpleResource{ - Scheme: "service", - Value: serviceID, - URI: resourceURI, - }, - ServiceID: serviceID, - Domain: domain, - } - - return Attenuation{ - Capability: &MultiCapability{Actions: actions}, - Resource: resource, - } -} - -// parseResourceURI creates a Resource from URI string -func parseResourceURI(uri string) Resource { - parts := strings.SplitN(uri, "://", 2) - if len(parts) != 2 { - return &SimpleResource{ - Scheme: "unknown", - Value: uri, - URI: uri, - } - } - - return &SimpleResource{ - Scheme: parts[0], - Value: parts[1], - URI: uri, - } -} - -// CapabilityTemplate provides validation and construction utilities -type CapabilityTemplate struct { - AllowedActions map[string][]string `json:"allowed_actions"` // resource_type -> []actions - DefaultExpiration time.Duration `json:"default_expiration"` // default token lifetime - MaxExpiration time.Duration `json:"max_expiration"` // maximum allowed lifetime -} - -// NewCapabilityTemplate creates a new capability template -func NewCapabilityTemplate() *CapabilityTemplate { - return &CapabilityTemplate{ - AllowedActions: make(map[string][]string), - DefaultExpiration: 24 * time.Hour, - MaxExpiration: 30 * 24 * time.Hour, // 30 days - } -} - -// AddAllowedActions adds allowed actions for a resource type -func (ct *CapabilityTemplate) AddAllowedActions(resourceType string, actions []string) { - ct.AllowedActions[resourceType] = actions -} - -// ValidateAttenuation validates an attenuation against the template -func (ct *CapabilityTemplate) ValidateAttenuation(att Attenuation) error { - resourceType := att.Resource.GetScheme() - allowedActions, exists := ct.AllowedActions[resourceType] - - if !exists { - // Allow unknown resource types for backward compatibility - return nil - } - - // Create action set for efficient lookup - actionSet := make(map[string]bool) - for _, action := range allowedActions { - actionSet[action] = true - } - - // Check if all capability actions are allowed - for _, action := range att.Capability.GetActions() { - if action == "*" { - // Wildcard requires explicit permission - if !actionSet["*"] { - return fmt.Errorf("wildcard action not allowed for resource type %s", resourceType) - } - continue - } - - if !actionSet[action] { - return fmt.Errorf("action %s not allowed for resource type %s", action, resourceType) - } - } - - return nil -} - -// ValidateExpiration validates token expiration time -func (ct *CapabilityTemplate) ValidateExpiration(expiresAt int64) error { - if expiresAt == 0 { - return nil // No expiration is allowed - } - - now := time.Now() - expiry := time.Unix(expiresAt, 0) - - if expiry.Before(now) { - return fmt.Errorf("token expiration is in the past") - } - - if expiry.Sub(now) > ct.MaxExpiration { - return fmt.Errorf("token expiration exceeds maximum allowed duration") - } - - return nil -} - -// GetDefaultExpirationTime returns the default expiration timestamp -func (ct *CapabilityTemplate) GetDefaultExpirationTime() int64 { - return time.Now().Add(ct.DefaultExpiration).Unix() -} - -// StandardVaultTemplate returns a standard template for vault operations -func StandardVaultTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions( - "ipfs", - []string{"read", "write", "sign", "export", "import", "delete", VaultAdminAction}, - ) - template.AddAllowedActions( - "vault", - []string{"read", "write", "sign", "export", "import", "delete", "admin", "*"}, - ) - return template -} - -// StandardServiceTemplate returns a standard template for service operations -func StandardServiceTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions( - "service", - []string{"read", "write", "admin", "register", "update", "delete"}, - ) - template.AddAllowedActions("https", []string{"read", "write"}) - template.AddAllowedActions("http", []string{"read", "write"}) - return template -} - -// AttenuationList provides utilities for working with multiple attenuations -type AttenuationList []Attenuation - -// Contains checks if the list contains attenuations for a specific resource -func (al AttenuationList) Contains(resourceURI string) bool { - for _, att := range al { - if att.Resource.GetURI() == resourceURI { - return true - } - } - return false -} - -// GetCapabilitiesForResource returns all capabilities for a specific resource -func (al AttenuationList) GetCapabilitiesForResource(resourceURI string) []Capability { - var capabilities []Capability - for _, att := range al { - if att.Resource.GetURI() == resourceURI { - capabilities = append(capabilities, att.Capability) - } - } - return capabilities -} - -// CanPerform checks if the attenuations allow specific actions on a resource -func (al AttenuationList) CanPerform(resourceURI string, actions []string) bool { - capabilities := al.GetCapabilitiesForResource(resourceURI) - for _, cap := range capabilities { - if cap.Grants(actions) { - return true - } - } - return false -} - -// IsSubsetOf checks if this list is a subset of another list -func (al AttenuationList) IsSubsetOf(parent AttenuationList) bool { - for _, childAtt := range al { - if !parent.containsAttenuation(childAtt) { - return false - } - } - return true -} - -// containsAttenuation checks if the list contains an equivalent attenuation -func (al AttenuationList) containsAttenuation(att Attenuation) bool { - for _, parentAtt := range al { - if parentAtt.Resource.Matches(att.Resource) { - if parentAtt.Capability.Contains(att.Capability) { - return true - } - } - } - return false -} - -// Module-Specific Capability Types - -// DIDCapability implements Capability for DID module operations -type DIDCapability struct { - Action string `json:"action"` - Actions []string `json:"actions,omitempty"` - Caveats []string `json:"caveats,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// GetActions returns the actions this DID capability grants -func (c *DIDCapability) GetActions() []string { - if len(c.Actions) > 0 { - return c.Actions - } - return []string{c.Action} -} - -// Grants checks if this capability grants the required abilities -func (c *DIDCapability) Grants(abilities []string) bool { - if c.Action == "*" { - return true - } - - grantedActions := make(map[string]bool) - for _, action := range c.GetActions() { - grantedActions[action] = true - } - - for _, ability := range abilities { - if !grantedActions[ability] { - return false - } - } - return true -} - -// Contains checks if this capability contains another capability -func (c *DIDCapability) Contains(other Capability) bool { - if c.Action == "*" { - return true - } - - ourActions := make(map[string]bool) - for _, action := range c.GetActions() { - ourActions[action] = true - } - - for _, otherAction := range other.GetActions() { - if !ourActions[otherAction] { - return false - } - } - return true -} - -// String returns string representation -func (c *DIDCapability) String() string { - if len(c.Actions) > 1 { - return strings.Join(c.Actions, ",") - } - return c.Action -} - -// DWNCapability implements Capability for DWN module operations -type DWNCapability struct { - Action string `json:"action"` - Actions []string `json:"actions,omitempty"` - Caveats []string `json:"caveats,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// GetActions returns the actions this DWN capability grants -func (c *DWNCapability) GetActions() []string { - if len(c.Actions) > 0 { - return c.Actions - } - return []string{c.Action} -} - -// Grants checks if this capability grants the required abilities -func (c *DWNCapability) Grants(abilities []string) bool { - if c.Action == "*" { - return true - } - - grantedActions := make(map[string]bool) - for _, action := range c.GetActions() { - grantedActions[action] = true - } - - for _, ability := range abilities { - if !grantedActions[ability] { - return false - } - } - return true -} - -// Contains checks if this capability contains another capability -func (c *DWNCapability) Contains(other Capability) bool { - if c.Action == "*" { - return true - } - - ourActions := make(map[string]bool) - for _, action := range c.GetActions() { - ourActions[action] = true - } - - for _, otherAction := range other.GetActions() { - if !ourActions[otherAction] { - return false - } - } - return true -} - -// String returns string representation -func (c *DWNCapability) String() string { - if len(c.Actions) > 1 { - return strings.Join(c.Actions, ",") - } - return c.Action -} - -// DEXCapability implements Capability for DEX module operations -type DEXCapability struct { - Action string `json:"action"` - Actions []string `json:"actions,omitempty"` - Caveats []string `json:"caveats,omitempty"` - MaxAmount string `json:"max_amount,omitempty"` // For swap limits - Metadata map[string]string `json:"metadata,omitempty"` -} - -// GetActions returns the actions this DEX capability grants -func (c *DEXCapability) GetActions() []string { - if len(c.Actions) > 0 { - return c.Actions - } - return []string{c.Action} -} - -// Grants checks if this capability grants the required abilities -func (c *DEXCapability) Grants(abilities []string) bool { - if c.Action == "*" { - return true - } - - grantedActions := make(map[string]bool) - for _, action := range c.GetActions() { - grantedActions[action] = true - } - - for _, ability := range abilities { - if !grantedActions[ability] { - return false - } - } - return true -} - -// Contains checks if this capability contains another capability -func (c *DEXCapability) Contains(other Capability) bool { - if c.Action == "*" { - return true - } - - ourActions := make(map[string]bool) - for _, action := range c.GetActions() { - ourActions[action] = true - } - - for _, otherAction := range other.GetActions() { - if !ourActions[otherAction] { - return false - } - } - return true -} - -// String returns string representation -func (c *DEXCapability) String() string { - if len(c.Actions) > 1 { - return strings.Join(c.Actions, ",") - } - return c.Action -} - -// Module-Specific Resource Types - -// DIDResource represents DID-specific resources -type DIDResource struct { - SimpleResource - DIDMethod string `json:"did_method,omitempty"` - DIDSubject string `json:"did_subject,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// DWNResource represents DWN-specific resources -type DWNResource struct { - SimpleResource - RecordType string `json:"record_type,omitempty"` - Protocol string `json:"protocol,omitempty"` - Owner string `json:"owner,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// DEXResource represents DEX-specific resources -type DEXResource struct { - SimpleResource - PoolID string `json:"pool_id,omitempty"` - AssetPair string `json:"asset_pair,omitempty"` - OrderID string `json:"order_id,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// Enhanced ServiceResource adds delegation capabilities -func (r *ServiceResource) SupportsDelegate() bool { - return r.Metadata != nil && r.Metadata["supports_delegation"] == "true" -} - -// Module-Specific Capability Templates - -// StandardDIDTemplate returns a standard template for DID operations -func StandardDIDTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions("did", []string{ - "create", "register", "update", "deactivate", "revoke", - "add-verification-method", "remove-verification-method", - "add-service", "remove-service", "issue-credential", - "revoke-credential", "link-wallet", "register-webauthn", "*", - }) - return template -} - -// StandardDWNTemplate returns a standard template for DWN operations -func StandardDWNTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions("dwn", []string{ - "records-write", "records-delete", "protocols-configure", - "permissions-grant", "permissions-revoke", "create", "read", - "update", "delete", "*", - }) - return template -} - -// EnhancedServiceTemplate returns enhanced service template with delegation support -func EnhancedServiceTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions("service", []string{ - "register", "update", "delete", "verify-domain", - "initiate-domain-verification", "delegate", "*", - }) - template.AddAllowedActions("svc", []string{ - "register", "verify-domain", "delegate", "*", - }) - template.AddAllowedActions("https", []string{"read", "write"}) - template.AddAllowedActions("http", []string{"read", "write"}) - return template -} - -// StandardDEXTemplate returns a standard template for DEX operations -func StandardDEXTemplate() *CapabilityTemplate { - template := NewCapabilityTemplate() - template.AddAllowedActions("dex", []string{ - "register-account", "swap", "provide-liquidity", "remove-liquidity", - "create-limit-order", "cancel-order", "*", - }) - template.AddAllowedActions("pool", []string{ - "swap", "provide-liquidity", "remove-liquidity", "*", - }) - return template -} - -// Module-Specific Attenuation Constructors - -// CreateDIDAttenuation creates a DID-specific attenuation -func CreateDIDAttenuation(actions []string, didPattern string, caveats []string) Attenuation { - resourceURI := fmt.Sprintf("did:%s", didPattern) - resource := &DIDResource{ - SimpleResource: SimpleResource{ - Scheme: "did", - Value: didPattern, - URI: resourceURI, - }, - } - - return Attenuation{ - Capability: &DIDCapability{ - Actions: actions, - Caveats: caveats, - }, - Resource: resource, - } -} - -// CreateDWNAttenuation creates a DWN-specific attenuation -func CreateDWNAttenuation(actions []string, recordPattern string, caveats []string) Attenuation { - resourceURI := fmt.Sprintf("dwn:records/%s", recordPattern) - resource := &DWNResource{ - SimpleResource: SimpleResource{ - Scheme: "dwn", - Value: fmt.Sprintf("records/%s", recordPattern), - URI: resourceURI, - }, - RecordType: recordPattern, - } - - return Attenuation{ - Capability: &DWNCapability{ - Actions: actions, - Caveats: caveats, - }, - Resource: resource, - } -} - -// CreateDEXAttenuation creates a DEX-specific attenuation -func CreateDEXAttenuation(actions []string, poolPattern string, caveats []string, maxAmount string) Attenuation { - resourceURI := fmt.Sprintf("dex:pool/%s", poolPattern) - resource := &DEXResource{ - SimpleResource: SimpleResource{ - Scheme: "dex", - Value: fmt.Sprintf("pool/%s", poolPattern), - URI: resourceURI, - }, - PoolID: poolPattern, - } - - return Attenuation{ - Capability: &DEXCapability{ - Actions: actions, - Caveats: caveats, - MaxAmount: maxAmount, - }, - Resource: resource, - } -} - -// Cross-Module Capability Composition - -// CrossModuleCapability allows composing capabilities across modules -type CrossModuleCapability struct { - Modules map[string]Capability `json:"modules"` -} - -// GetActions returns all actions across all modules -func (c *CrossModuleCapability) GetActions() []string { - var actions []string - for _, cap := range c.Modules { - actions = append(actions, cap.GetActions()...) - } - return actions -} - -// Grants checks if required abilities are granted across modules -func (c *CrossModuleCapability) Grants(abilities []string) bool { - allActions := make(map[string]bool) - for _, cap := range c.Modules { - for _, action := range cap.GetActions() { - allActions[action] = true - } - } - - for _, ability := range abilities { - if !allActions[ability] { - return false - } - } - return true -} - -// Contains checks if this cross-module capability contains another -func (c *CrossModuleCapability) Contains(other Capability) bool { - // For cross-module capabilities, check each module - if otherCross, ok := other.(*CrossModuleCapability); ok { - for module, otherCap := range otherCross.Modules { - if ourCap, exists := c.Modules[module]; exists { - if !ourCap.Contains(otherCap) { - return false - } - } else { - return false - } - } - return true - } - - // For single capabilities, check if any module contains it - for _, cap := range c.Modules { - if cap.Contains(other) { - return true - } - } - return false -} - -// String returns string representation -func (c *CrossModuleCapability) String() string { - var moduleStrs []string - for module, cap := range c.Modules { - moduleStrs = append(moduleStrs, fmt.Sprintf("%s:%s", module, cap.String())) - } - return strings.Join(moduleStrs, ";") -} - -// Gasless Transaction Support - -// GaslessCapability wraps other capabilities with gasless transaction support -type GaslessCapability struct { - Capability - AllowGasless bool `json:"allow_gasless"` - GasLimit uint64 `json:"gas_limit,omitempty"` -} - -// SupportsGasless returns whether this capability supports gasless transactions -func (c *GaslessCapability) SupportsGasless() bool { - return c.AllowGasless -} - -// GetGasLimit returns the gas limit for gasless transactions -func (c *GaslessCapability) GetGasLimit() uint64 { - return c.GasLimit -} diff --git a/crypto/ucan/crypto.go b/crypto/ucan/crypto.go deleted file mode 100644 index f69b3b39a..000000000 --- a/crypto/ucan/crypto.go +++ /dev/null @@ -1,352 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "crypto" - "crypto/ed25519" - "crypto/rsa" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "fmt" - "hash" - "strings" - - "github.com/golang-jwt/jwt/v5" -) - -// SupportedSigningMethods returns the list of supported JWT signing methods for UCAN -func SupportedSigningMethods() []jwt.SigningMethod { - return []jwt.SigningMethod{ - jwt.SigningMethodRS256, - jwt.SigningMethodRS384, - jwt.SigningMethodRS512, - jwt.SigningMethodEdDSA, - } -} - -// ValidateSignature validates the cryptographic signature of a UCAN token -func ValidateSignature(tokenString string, verifyKey any) error { - // Parse token without verification first to get signing method - token, err := jwt.ParseWithClaims( - tokenString, - jwt.MapClaims{}, - func(token *jwt.Token) (any, error) { - return verifyKey, nil - }, - ) - if err != nil { - return fmt.Errorf("signature validation failed: %w", err) - } - - if !token.Valid { - return fmt.Errorf("token signature is invalid") - } - - return nil -} - -// ExtractUnsignedToken extracts the unsigned portion of a JWT token (header + payload) -func ExtractUnsignedToken(tokenString string) (string, error) { - parts := strings.Split(tokenString, ".") - if len(parts) != 3 { - return "", fmt.Errorf("invalid JWT format: expected 3 parts, got %d", len(parts)) - } - - return strings.Join(parts[:2], "."), nil -} - -// ExtractSignature extracts the signature portion of a JWT token -func ExtractSignature(tokenString string) ([]byte, error) { - parts := strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, fmt.Errorf("invalid JWT format: expected 3 parts, got %d", len(parts)) - } - - signatureBytes, err := base64.RawURLEncoding.DecodeString(parts[2]) - if err != nil { - return nil, fmt.Errorf("failed to decode signature: %w", err) - } - - return signatureBytes, nil -} - -// VerifyRSASignature verifies an RSA signature using the specified hash algorithm -func VerifyRSASignature( - signingString string, - signature []byte, - publicKey *rsa.PublicKey, - hashAlg crypto.Hash, -) error { - // Create hash of signing string - hasher := hashAlg.New() - hasher.Write([]byte(signingString)) - hashed := hasher.Sum(nil) - - // Verify signature - err := rsa.VerifyPKCS1v15(publicKey, hashAlg, hashed, signature) - if err != nil { - return fmt.Errorf("RSA signature verification failed: %w", err) - } - - return nil -} - -// VerifyEd25519Signature verifies an Ed25519 signature -func VerifyEd25519Signature( - signingString string, - signature []byte, - publicKey ed25519.PublicKey, -) error { - valid := ed25519.Verify(publicKey, []byte(signingString), signature) - if !valid { - return fmt.Errorf("Ed25519 signature verification failed") - } - - return nil -} - -// GetHashAlgorithmForMethod returns the appropriate hash algorithm for a JWT signing method -func GetHashAlgorithmForMethod(method jwt.SigningMethod) (crypto.Hash, error) { - switch method { - case jwt.SigningMethodRS256: - return crypto.SHA256, nil - case jwt.SigningMethodRS384: - return crypto.SHA384, nil - case jwt.SigningMethodRS512: - return crypto.SHA512, nil - case jwt.SigningMethodEdDSA: - // Ed25519 doesn't use a separate hash algorithm - return crypto.Hash(0), nil - default: - return crypto.Hash(0), fmt.Errorf("unsupported signing method: %v", method) - } -} - -// CreateHasher creates a hasher for the given crypto.Hash algorithm -func CreateHasher(hashAlg crypto.Hash) (hash.Hash, error) { - switch hashAlg { - case crypto.SHA256: - return sha256.New(), nil - case crypto.SHA384: - return sha512.New384(), nil - case crypto.SHA512: - return sha512.New(), nil - default: - return nil, fmt.Errorf("unsupported hash algorithm: %v", hashAlg) - } -} - -// SigningValidator provides cryptographic validation for UCAN tokens -type SigningValidator struct { - allowedMethods map[string]jwt.SigningMethod -} - -// NewSigningValidator creates a new signing validator with default allowed methods -func NewSigningValidator() *SigningValidator { - allowed := make(map[string]jwt.SigningMethod) - for _, method := range SupportedSigningMethods() { - allowed[method.Alg()] = method - } - - return &SigningValidator{ - allowedMethods: allowed, - } -} - -// NewSigningValidatorWithMethods creates a validator with specific allowed methods -func NewSigningValidatorWithMethods(methods []jwt.SigningMethod) *SigningValidator { - allowed := make(map[string]jwt.SigningMethod) - for _, method := range methods { - allowed[method.Alg()] = method - } - - return &SigningValidator{ - allowedMethods: allowed, - } -} - -// ValidateSigningMethod checks if a signing method is allowed -func (sv *SigningValidator) ValidateSigningMethod(method jwt.SigningMethod) error { - if _, ok := sv.allowedMethods[method.Alg()]; !ok { - return fmt.Errorf("signing method %s is not allowed", method.Alg()) - } - return nil -} - -// ValidateTokenSignature validates the cryptographic signature of a token -func (sv *SigningValidator) ValidateTokenSignature( - tokenString string, - keyFunc jwt.Keyfunc, -) (*jwt.Token, error) { - // Parse with validation - token, err := jwt.Parse(tokenString, keyFunc, jwt.WithValidMethods(sv.getAllowedMethodNames())) - if err != nil { - return nil, fmt.Errorf("token signature validation failed: %w", err) - } - - // Additional signing method validation - if err := sv.ValidateSigningMethod(token.Method); err != nil { - return nil, err - } - - return token, nil -} - -// getAllowedMethodNames returns the names of allowed signing methods -func (sv *SigningValidator) getAllowedMethodNames() []string { - methods := make([]string, 0, len(sv.allowedMethods)) - for name := range sv.allowedMethods { - methods = append(methods, name) - } - return methods -} - -// KeyValidator provides validation for cryptographic keys -type KeyValidator struct{} - -// NewKeyValidator creates a new key validator -func NewKeyValidator() *KeyValidator { - return &KeyValidator{} -} - -// ValidateRSAPublicKey validates an RSA public key for UCAN usage -func (kv *KeyValidator) ValidateRSAPublicKey(key *rsa.PublicKey) error { - if key == nil { - return fmt.Errorf("RSA public key is nil") - } - - // Check minimum key size (2048 bits recommended for security) - keySize := key.N.BitLen() - if keySize < 2048 { - return fmt.Errorf("RSA key size too small: %d bits (minimum 2048 bits required)", keySize) - } - - // Check maximum reasonable key size to prevent DoS - if keySize > 8192 { - return fmt.Errorf("RSA key size too large: %d bits (maximum 8192 bits allowed)", keySize) - } - - return nil -} - -// ValidateEd25519PublicKey validates an Ed25519 public key for UCAN usage -func (kv *KeyValidator) ValidateEd25519PublicKey(key ed25519.PublicKey) error { - if key == nil { - return fmt.Errorf("Ed25519 public key is nil") - } - - if len(key) != ed25519.PublicKeySize { - return fmt.Errorf( - "invalid Ed25519 public key size: %d bytes (expected %d)", - len(key), - ed25519.PublicKeySize, - ) - } - - return nil -} - -// SignatureInfo contains information about a token's signature -type SignatureInfo struct { - Algorithm string - KeyType string - SigningString string - Signature []byte - Valid bool -} - -// ExtractSignatureInfo extracts signature information from a JWT token -func ExtractSignatureInfo(tokenString string, verifyKey any) (*SignatureInfo, error) { - // Parse token to get method and claims - token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) { - return verifyKey, nil - }) - - var sigInfo SignatureInfo - sigInfo.Valid = (err == nil && token.Valid) - - if token != nil { - sigInfo.Algorithm = token.Method.Alg() - - // Get signing string - parts := strings.Split(tokenString, ".") - if len(parts) >= 2 { - sigInfo.SigningString = strings.Join(parts[:2], ".") - } - - // Get signature - if len(parts) == 3 { - sig, decodeErr := base64.RawURLEncoding.DecodeString(parts[2]) - if decodeErr == nil { - sigInfo.Signature = sig - } - } - - // Determine key type - switch verifyKey.(type) { - case *rsa.PublicKey: - sigInfo.KeyType = "RSA" - case ed25519.PublicKey: - sigInfo.KeyType = "Ed25519" - default: - sigInfo.KeyType = "Unknown" - } - } - - return &sigInfo, err -} - -// SecurityConfig contains security configuration for UCAN validation -type SecurityConfig struct { - AllowedSigningMethods []jwt.SigningMethod - MinRSAKeySize int - MaxRSAKeySize int - RequireSecureAlgs bool -} - -// DefaultSecurityConfig returns a secure default configuration -func DefaultSecurityConfig() *SecurityConfig { - return &SecurityConfig{ - AllowedSigningMethods: SupportedSigningMethods(), - MinRSAKeySize: 2048, - MaxRSAKeySize: 8192, - RequireSecureAlgs: true, - } -} - -// RestrictiveSecurityConfig returns a more restrictive configuration -func RestrictiveSecurityConfig() *SecurityConfig { - return &SecurityConfig{ - AllowedSigningMethods: []jwt.SigningMethod{ - jwt.SigningMethodRS256, // Only RS256 and EdDSA - jwt.SigningMethodEdDSA, - }, - MinRSAKeySize: 3072, // Higher minimum - MaxRSAKeySize: 4096, // Lower maximum - RequireSecureAlgs: true, - } -} - -// ValidateSecurityConfig validates that a security configuration is reasonable -func ValidateSecurityConfig(config *SecurityConfig) error { - if len(config.AllowedSigningMethods) == 0 { - return fmt.Errorf("no signing methods allowed") - } - - if config.MinRSAKeySize < 1024 { - return fmt.Errorf("minimum RSA key size too small: %d", config.MinRSAKeySize) - } - - if config.MaxRSAKeySize < config.MinRSAKeySize { - return fmt.Errorf("maximum RSA key size smaller than minimum") - } - - if config.MaxRSAKeySize > 16384 { - return fmt.Errorf("maximum RSA key size too large: %d", config.MaxRSAKeySize) - } - - return nil -} diff --git a/crypto/ucan/jwt.go b/crypto/ucan/jwt.go deleted file mode 100644 index 95ce860a2..000000000 --- a/crypto/ucan/jwt.go +++ /dev/null @@ -1,595 +0,0 @@ -package ucan - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -var ( - // StandardTemplate provides default authorization template - StandardTemplate = NewCapabilityTemplate() - - // Revoked tokens tracking - revokedTokens = make(map[string]bool) -) - -func init() { - // Setup standard templates with module-specific capabilities - StandardTemplate.AddAllowedActions( - "vault", - []string{"read", "write", "sign", "export", "import", "delete", "*"}, - ) - StandardTemplate.AddAllowedActions( - "service", - []string{"read", "write", "register", "update", "delete"}, - ) - StandardTemplate.AddAllowedActions( - "did", - []string{ - "create", "register", "update", "deactivate", "revoke", - "add-verification-method", "remove-verification-method", - "add-service", "remove-service", "issue-credential", - "revoke-credential", "link-wallet", "register-webauthn", "*", - }, - ) - StandardTemplate.AddAllowedActions( - "dwn", - []string{ - "records-write", "records-delete", "protocols-configure", - "permissions-grant", "permissions-revoke", "create", "read", - "update", "delete", "*", - }, - ) - StandardTemplate.AddAllowedActions( - "dex", - []string{ - "register-account", "swap", "provide-liquidity", "remove-liquidity", - "create-limit-order", "cancel-order", "*", - }, - ) - StandardTemplate.AddAllowedActions( - "pool", - []string{"swap", "provide-liquidity", "remove-liquidity", "*"}, - ) - StandardTemplate.AddAllowedActions( - "svc", - []string{"register", "verify-domain", "delegate", "*"}, - ) -} - -// GenerateJWTToken creates a UCAN JWT token with given capability and expiration -func GenerateJWTToken(attenuation Attenuation, duration time.Duration) (string, error) { - // Default expiration handling - if duration == 0 { - duration = 24 * time.Hour - } - - // Create JWT claims - claims := jwt.MapClaims{ - "iss": "did:sonr:local", // Default issuer - "exp": time.Now().Add(duration).Unix(), - "iat": time.Now().Unix(), - } - - // Add capability to claims - separate resource and capability - capabilityBytes, err := json.Marshal(map[string]any{ - "can": attenuation.Capability, - "with": attenuation.Resource, - }) - if err != nil { - return "", fmt.Errorf("failed to serialize capability: %v", err) - } - claims["can"] = base64.URLEncoding.EncodeToString(capabilityBytes) - - // Create token - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - - // Dummy secret for signing - in real-world, use proper key management - tokenString, err := token.SignedString([]byte("sonr-ucan-secret")) - if err != nil { - return "", fmt.Errorf("failed to sign token: %v", err) - } - - return tokenString, nil -} - -// VerifyJWTToken validates and parses a UCAN JWT token -func VerifyJWTToken(tokenString string) (*Token, error) { - // Check if token is revoked - if revokedTokens[tokenString] { - return nil, fmt.Errorf("token has been revoked") - } - - // Parse token with custom claims - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { - // Dummy secret verification - replace with proper key validation - return []byte("sonr-ucan-secret"), nil - }, jwt.WithLeeway(5*time.Minute)) - if err != nil { - return nil, fmt.Errorf("token parsing failed: %v", err) - } - - // Extract claims - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid token claims") - } - - // Manual expiration check - exp, ok := claims["exp"].(float64) - if !ok { - return nil, fmt.Errorf("no expiration time found") - } - if time.Now().Unix() > int64(exp) { - return nil, fmt.Errorf("token has expired") - } - - // Decode capability - capabilityStr, ok := claims["can"].(string) - if !ok { - return nil, fmt.Errorf("no capability found in token") - } - - capabilityBytes, err := base64.URLEncoding.DecodeString(capabilityStr) - if err != nil { - return nil, fmt.Errorf("failed to decode capability: %v", err) - } - - // Parse capability and resource separately - var capabilityMap map[string]any - err = json.Unmarshal(capabilityBytes, &capabilityMap) - if err != nil { - return nil, fmt.Errorf("failed to parse capability: %v", err) - } - - // Determine capability type - var capability Capability - var capData map[string]any - switch v := capabilityMap["can"].(type) { - case map[string]any: - capData = v - case string: - // If it's a string, assume it's a simple action - capability = &SimpleCapability{Action: v} - capData = nil - default: - return nil, fmt.Errorf("invalid capability structure") - } - - // Parse capability if needed - if capData != nil { - // Attempt to infer capability type - if actions, ok := capData["actions"].([]any); ok { - // MultiCapability - stringActions := make([]string, len(actions)) - for i, action := range actions { - if str, ok := action.(string); ok { - stringActions[i] = str - } - } - capability = &MultiCapability{Actions: stringActions} - } else if action, ok := capData["action"].(string); ok { - // SingleCapability - capability = &SimpleCapability{Action: action} - } else { - return nil, fmt.Errorf("unable to parse capability type") - } - } - - // Parse resource - var resourceData map[string]any - switch resource := capabilityMap["with"].(type) { - case map[string]any: - resourceData = resource - case string: - // If it's a string, assume it's a simple URI - resourceData = map[string]any{ - "Scheme": "generic", - "Value": resource, - "URI": resource, - } - default: - return nil, fmt.Errorf("invalid resource structure") - } - - // Create resource based on scheme - scheme, _ := resourceData["Scheme"].(string) - value, _ := resourceData["Value"].(string) - uri, _ := resourceData["URI"].(string) - - resource := &SimpleResource{ - Scheme: scheme, - Value: value, - URI: uri, - } - - // Validate attenuation - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - // Use standard template to validate - err = StandardTemplate.ValidateAttenuation(attenuation) - if err != nil { - return nil, fmt.Errorf("capability validation failed: %v", err) - } - - // Construct Token object - parsedToken := &Token{ - Raw: tokenString, - Issuer: claims["iss"].(string), - ExpiresAt: int64(exp), - Attenuations: []Attenuation{attenuation}, - } - - return parsedToken, nil -} - -// RevokeCapability adds a capability to the revocation list -func RevokeCapability(attenuation Attenuation) error { - // Generate token to get its string representation - token, err := GenerateJWTToken(attenuation, time.Hour) - if err != nil { - return err - } - - // Add to revoked tokens - revokedTokens[token] = true - return nil -} - -// NewCapability is a helper function to create a basic capability -func NewCapability(issuer, resource string, abilities []string) (Attenuation, error) { - capability := &MultiCapability{Actions: abilities} - resourceObj := &SimpleResource{ - Scheme: "generic", - Value: resource, - URI: resource, - } - - return Attenuation{ - Capability: capability, - Resource: resourceObj, - }, nil -} - -// Enhanced JWT generation functions for module-specific capabilities - -// GenerateModuleJWTToken creates a UCAN JWT token with module-specific capabilities -func GenerateModuleJWTToken(attenuations []Attenuation, issuer, audience string, duration time.Duration) (string, error) { - if duration == 0 { - duration = 24 * time.Hour - } - - // Create JWT claims with enhanced structure - claims := jwt.MapClaims{ - "iss": issuer, - "aud": audience, - "exp": time.Now().Add(duration).Unix(), - "iat": time.Now().Unix(), - "nbf": time.Now().Unix(), - } - - // Add attenuations to claims with module-specific serialization - attClaims := make([]map[string]any, len(attenuations)) - for i, att := range attenuations { - attMap, err := serializeModuleAttenuation(att) - if err != nil { - return "", fmt.Errorf("failed to serialize attenuation %d: %w", i, err) - } - attClaims[i] = attMap - } - claims["att"] = attClaims - - // Create and sign token - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - tokenString, err := token.SignedString([]byte("sonr-ucan-secret")) - if err != nil { - return "", fmt.Errorf("failed to sign token: %w", err) - } - - return tokenString, nil -} - -// serializeModuleAttenuation serializes an attenuation based on its module type -func serializeModuleAttenuation(att Attenuation) (map[string]any, error) { - attMap := map[string]any{ - "with": att.Resource.GetURI(), - } - - scheme := att.Resource.GetScheme() - switch scheme { - case "did": - return serializeDIDAttenuation(att, attMap) - case "dwn": - return serializeDWNAttenuation(att, attMap) - case "dex", "pool": - return serializeDEXAttenuation(att, attMap) - case "service", "svc": - return serializeServiceAttenuation(att, attMap) - case "vault", "ipfs": - return serializeVaultAttenuation(att, attMap) - default: - return serializeGenericAttenuation(att, attMap) - } -} - -// serializeDIDAttenuation serializes DID-specific attenuations -func serializeDIDAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - didCap, ok := att.Capability.(*DIDCapability) - if !ok { - return serializeGenericAttenuation(att, attMap) - } - - if didCap.Action != "" { - attMap["can"] = didCap.Action - } else { - attMap["can"] = didCap.Actions - } - - if len(didCap.Caveats) > 0 { - attMap["caveats"] = didCap.Caveats - } - if len(didCap.Metadata) > 0 { - attMap["metadata"] = didCap.Metadata - } - - return attMap, nil -} - -// serializeDWNAttenuation serializes DWN-specific attenuations -func serializeDWNAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - dwnCap, ok := att.Capability.(*DWNCapability) - if !ok { - return serializeGenericAttenuation(att, attMap) - } - - if dwnCap.Action != "" { - attMap["can"] = dwnCap.Action - } else { - attMap["can"] = dwnCap.Actions - } - - if len(dwnCap.Caveats) > 0 { - attMap["caveats"] = dwnCap.Caveats - } - if len(dwnCap.Metadata) > 0 { - attMap["metadata"] = dwnCap.Metadata - } - - // Add DWN-specific fields - if dwnRes, ok := att.Resource.(*DWNResource); ok { - if dwnRes.RecordType != "" { - attMap["record_type"] = dwnRes.RecordType - } - if dwnRes.Protocol != "" { - attMap["protocol"] = dwnRes.Protocol - } - if dwnRes.Owner != "" { - attMap["owner"] = dwnRes.Owner - } - } - - return attMap, nil -} - -// serializeDEXAttenuation serializes DEX-specific attenuations -func serializeDEXAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - dexCap, ok := att.Capability.(*DEXCapability) - if !ok { - return serializeGenericAttenuation(att, attMap) - } - - if dexCap.Action != "" { - attMap["can"] = dexCap.Action - } else { - attMap["can"] = dexCap.Actions - } - - if len(dexCap.Caveats) > 0 { - attMap["caveats"] = dexCap.Caveats - } - if dexCap.MaxAmount != "" { - attMap["max_amount"] = dexCap.MaxAmount - } - if len(dexCap.Metadata) > 0 { - attMap["metadata"] = dexCap.Metadata - } - - // Add DEX-specific fields - if dexRes, ok := att.Resource.(*DEXResource); ok { - if dexRes.PoolID != "" { - attMap["pool_id"] = dexRes.PoolID - } - if dexRes.AssetPair != "" { - attMap["asset_pair"] = dexRes.AssetPair - } - if dexRes.OrderID != "" { - attMap["order_id"] = dexRes.OrderID - } - } - - return attMap, nil -} - -// serializeServiceAttenuation serializes Service-specific attenuations -func serializeServiceAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - // Service capabilities still use MultiCapability - multiCap, ok := att.Capability.(*MultiCapability) - if !ok { - return serializeGenericAttenuation(att, attMap) - } - - attMap["can"] = multiCap.Actions - - // Add service-specific fields - if svcRes, ok := att.Resource.(*ServiceResource); ok { - if svcRes.ServiceID != "" { - attMap["service_id"] = svcRes.ServiceID - } - if svcRes.Domain != "" { - attMap["domain"] = svcRes.Domain - } - if len(svcRes.Metadata) > 0 { - attMap["metadata"] = svcRes.Metadata - } - } - - return attMap, nil -} - -// serializeVaultAttenuation serializes Vault-specific attenuations -func serializeVaultAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - vaultCap, ok := att.Capability.(*VaultCapability) - if !ok { - return serializeGenericAttenuation(att, attMap) - } - - if vaultCap.Action != "" { - attMap["can"] = vaultCap.Action - } else { - attMap["can"] = vaultCap.Actions - } - - if vaultCap.VaultAddress != "" { - attMap["vault"] = vaultCap.VaultAddress - } - if len(vaultCap.Caveats) > 0 { - attMap["caveats"] = vaultCap.Caveats - } - if vaultCap.EnclaveDataCID != "" { - attMap["enclave_data_cid"] = vaultCap.EnclaveDataCID - } - if len(vaultCap.Metadata) > 0 { - attMap["metadata"] = vaultCap.Metadata - } - - return attMap, nil -} - -// serializeGenericAttenuation serializes generic attenuations -func serializeGenericAttenuation(att Attenuation, attMap map[string]any) (map[string]any, error) { - actions := att.Capability.GetActions() - if len(actions) == 1 { - attMap["can"] = actions[0] - } else { - attMap["can"] = actions - } - return attMap, nil -} - -// Enhanced verification with module-specific support - -// VerifyModuleJWTToken validates and parses a UCAN JWT token with module-specific capabilities -func VerifyModuleJWTToken(tokenString string, expectedIssuer, expectedAudience string) (*Token, error) { - // Check if token is revoked - if revokedTokens[tokenString] { - return nil, fmt.Errorf("token has been revoked") - } - - // Parse token with custom claims - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { - // Dummy secret verification - replace with proper key validation - return []byte("sonr-ucan-secret"), nil - }, jwt.WithLeeway(5*time.Minute)) - if err != nil { - return nil, fmt.Errorf("token parsing failed: %w", err) - } - - // Extract claims - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid token claims") - } - - // Validate issuer and audience if provided - if expectedIssuer != "" { - if iss, ok := claims["iss"].(string); !ok || iss != expectedIssuer { - return nil, fmt.Errorf("invalid issuer: expected %s", expectedIssuer) - } - } - if expectedAudience != "" { - if aud, ok := claims["aud"].(string); !ok || aud != expectedAudience { - return nil, fmt.Errorf("invalid audience: expected %s", expectedAudience) - } - } - - // Manual expiration check - exp, ok := claims["exp"].(float64) - if !ok { - return nil, fmt.Errorf("no expiration time found") - } - if time.Now().Unix() > int64(exp) { - return nil, fmt.Errorf("token has expired") - } - - // Parse attenuations with module-specific support - attenuations, err := parseEnhancedAttenuations(claims) - if err != nil { - return nil, fmt.Errorf("failed to parse attenuations: %w", err) - } - - // Validate attenuations against templates - for _, att := range attenuations { - if err := StandardTemplate.ValidateAttenuation(att); err != nil { - return nil, fmt.Errorf("capability validation failed: %w", err) - } - } - - // Construct Token object - issuer, _ := claims["iss"].(string) - audience, _ := claims["aud"].(string) - nbf, _ := claims["nbf"].(float64) - - parsedToken := &Token{ - Raw: tokenString, - Issuer: issuer, - Audience: audience, - ExpiresAt: int64(exp), - NotBefore: int64(nbf), - Attenuations: attenuations, - } - - return parsedToken, nil -} - -// parseEnhancedAttenuations parses attenuations with module-specific capabilities -func parseEnhancedAttenuations(claims jwt.MapClaims) ([]Attenuation, error) { - attClaims, ok := claims["att"] - if !ok { - return nil, fmt.Errorf("no attenuations found in token") - } - - attSlice, ok := attClaims.([]any) - if !ok { - return nil, fmt.Errorf("invalid attenuations format") - } - - attenuations := make([]Attenuation, 0, len(attSlice)) - for i, attItem := range attSlice { - attMap, ok := attItem.(map[string]any) - if !ok { - return nil, fmt.Errorf("invalid attenuation %d format", i) - } - - att, err := parseEnhancedAttenuation(attMap) - if err != nil { - return nil, fmt.Errorf("failed to parse attenuation %d: %w", i, err) - } - attenuations = append(attenuations, att) - } - - return attenuations, nil -} - -// parseEnhancedAttenuation parses a single attenuation with module-specific support -func parseEnhancedAttenuation(attMap map[string]any) (Attenuation, error) { - // Use the existing enhanced verifier logic - verifier := &Verifier{} // Create temporary verifier for parsing - return verifier.parseAttenuation(attMap) -} diff --git a/crypto/ucan/mpc.go b/crypto/ucan/mpc.go deleted file mode 100644 index 947a7e02c..000000000 --- a/crypto/ucan/mpc.go +++ /dev/null @@ -1,625 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "context" - "crypto/sha256" - "fmt" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/ipfs/go-cid" - "github.com/multiformats/go-multihash" - "github.com/sonr-io/sonr/crypto/keys" - "github.com/sonr-io/sonr/crypto/mpc" -) - -// MPCSigningMethod implements JWT signing using MPC enclaves -type MPCSigningMethod struct { - Name string - enclave mpc.Enclave -} - -// NewMPCSigningMethod creates a new MPC-based JWT signing method -func NewMPCSigningMethod(name string, enclave mpc.Enclave) *MPCSigningMethod { - return &MPCSigningMethod{ - Name: name, - enclave: enclave, - } -} - -// Alg returns the signing method algorithm name -func (m *MPCSigningMethod) Alg() string { - return m.Name -} - -// Verify verifies a JWT signature using the MPC enclave -func (m *MPCSigningMethod) Verify(signingString string, signature []byte, key any) error { - // signature is already decoded bytes - sig := signature - - // Hash the signing string - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to verify signature - valid, err := m.enclave.Verify(digest, sig) - if err != nil { - return fmt.Errorf("failed to verify signature: %w", err) - } - - if !valid { - return fmt.Errorf("signature verification failed") - } - - return nil -} - -// Sign signs a JWT string using the MPC enclave -func (m *MPCSigningMethod) Sign(signingString string, key any) ([]byte, error) { - // Hash the signing string - hasher := sha256.New() - hasher.Write([]byte(signingString)) - digest := hasher.Sum(nil) - - // Use MPC enclave to sign the digest - sig, err := m.enclave.Sign(digest) - if err != nil { - return nil, fmt.Errorf("failed to sign with MPC: %w", err) - } - - return sig, nil -} - -// MPCTokenBuilder creates UCAN tokens using MPC signing -type MPCTokenBuilder struct { - enclave mpc.Enclave - issuerDID string - address string - signingMethod *MPCSigningMethod -} - -// NewMPCTokenBuilder creates a new MPC-based UCAN token builder -func NewMPCTokenBuilder(enclave mpc.Enclave) (*MPCTokenBuilder, error) { - if !enclave.IsValid() { - return nil, fmt.Errorf("invalid MPC enclave provided") - } - - // Derive issuer DID and address from enclave public key - pubKeyBytes := enclave.PubKeyBytes() - issuerDID, address := deriveIssuerDIDFromBytes(pubKeyBytes) - - signingMethod := NewMPCSigningMethod("MPC256", enclave) - - return &MPCTokenBuilder{ - enclave: enclave, - issuerDID: issuerDID, - address: address, - signingMethod: signingMethod, - }, nil -} - -// GetIssuerDID returns the issuer DID derived from the enclave -func (b *MPCTokenBuilder) GetIssuerDID() string { - return b.issuerDID -} - -// GetAddress returns the address derived from the enclave -func (b *MPCTokenBuilder) GetAddress() string { - return b.address -} - -// CreateOriginToken creates a new origin UCAN token using MPC signing -func (b *MPCTokenBuilder) CreateOriginToken( - audienceDID string, - attenuations []Attenuation, - facts []Fact, - notBefore, expiresAt time.Time, -) (*Token, error) { - return b.createToken(audienceDID, nil, attenuations, facts, notBefore, expiresAt) -} - -// CreateDelegatedToken creates a delegated UCAN token using MPC signing -func (b *MPCTokenBuilder) CreateDelegatedToken( - parent *Token, - audienceDID string, - attenuations []Attenuation, - facts []Fact, - notBefore, expiresAt time.Time, -) (*Token, error) { - proofs, err := prepareDelegationProofs(parent, attenuations) - if err != nil { - return nil, err - } - - return b.createToken(audienceDID, proofs, attenuations, facts, notBefore, expiresAt) -} - -// createToken creates a UCAN token with MPC signing -func (b *MPCTokenBuilder) createToken( - audienceDID string, - proofs []Proof, - attenuations []Attenuation, - facts []Fact, - notBefore, expiresAt time.Time, -) (*Token, error) { - // Validate inputs - if !isValidDID(audienceDID) { - return nil, fmt.Errorf("invalid audience DID format: %s", audienceDID) - } - if len(attenuations) == 0 { - return nil, fmt.Errorf("at least one attenuation is required") - } - - // Create JWT token with MPC signing method - token := jwt.New(b.signingMethod) - - // Set UCAN version in header - token.Header["ucv"] = "0.9.0" - - // Prepare time claims - var nbfUnix, expUnix int64 - if !notBefore.IsZero() { - nbfUnix = notBefore.Unix() - } - if !expiresAt.IsZero() { - expUnix = expiresAt.Unix() - } - - // Convert attenuations to claim format - attClaims := make([]map[string]any, len(attenuations)) - for i, att := range attenuations { - attClaims[i] = map[string]any{ - "can": att.Capability.GetActions(), - "with": att.Resource.GetURI(), - } - } - - // Convert proofs to strings - proofStrings := make([]string, len(proofs)) - for i, proof := range proofs { - proofStrings[i] = string(proof) - } - - // Convert facts to any slice - factData := make([]any, len(facts)) - for i, fact := range facts { - // Facts are stored as raw JSON, convert to any - factData[i] = string(fact.Data) - } - - // Set claims - claims := jwt.MapClaims{ - "iss": b.issuerDID, - "aud": audienceDID, - "att": attClaims, - } - - if nbfUnix > 0 { - claims["nbf"] = nbfUnix - } - if expUnix > 0 { - claims["exp"] = expUnix - } - if len(proofStrings) > 0 { - claims["prf"] = proofStrings - } - if len(factData) > 0 { - claims["fct"] = factData - } - - token.Claims = claims - - // Sign the token using MPC enclave (key parameter is ignored for MPC signing) - tokenString, err := token.SignedString(nil) - if err != nil { - return nil, fmt.Errorf("failed to sign token with MPC: %w", err) - } - - return &Token{ - Raw: tokenString, - Issuer: b.issuerDID, - Audience: audienceDID, - ExpiresAt: expUnix, - NotBefore: nbfUnix, - Attenuations: attenuations, - Proofs: proofs, - Facts: facts, - }, nil -} - -// CreateVaultCapabilityToken creates a vault-specific UCAN token -func (b *MPCTokenBuilder) CreateVaultCapabilityToken( - audienceDID string, - vaultAddress string, - enclaveDataCID string, - actions []string, - expiresAt time.Time, -) (*Token, error) { - // Create vault-specific attenuation - attenuation := CreateVaultAttenuation(actions, enclaveDataCID, vaultAddress) - - return b.CreateOriginToken( - audienceDID, - []Attenuation{attenuation}, - nil, - time.Time{}, // No not-before restriction - expiresAt, - ) -} - -// MPCDIDResolver resolves DIDs with special handling for MPC-derived DIDs -type MPCDIDResolver struct { - enclave mpc.Enclave - issuerDID string - fallback DIDResolver -} - -// NewMPCDIDResolver creates a new MPC DID resolver -func NewMPCDIDResolver(enclave mpc.Enclave, fallback DIDResolver) *MPCDIDResolver { - pubKeyBytes := enclave.PubKeyBytes() - issuerDID, _ := deriveIssuerDIDFromBytes(pubKeyBytes) - - return &MPCDIDResolver{ - enclave: enclave, - issuerDID: issuerDID, - fallback: fallback, - } -} - -// ResolveDIDKey resolves DID keys with MPC enclave support -func (r *MPCDIDResolver) ResolveDIDKey(ctx context.Context, didStr string) (keys.DID, error) { - // Check if this is the MPC-derived DID - if didStr == r.issuerDID { - return r.createDIDFromEnclave() - } - - // Fall back to standard DID resolution - if r.fallback != nil { - return r.fallback.ResolveDIDKey(ctx, didStr) - } - - // Default fallback to string parsing - return keys.Parse(didStr) -} - -// createDIDFromEnclave creates a DID from the MPC enclave's public key -func (r *MPCDIDResolver) createDIDFromEnclave() (keys.DID, error) { - // This would need to be implemented based on how MPC public keys - // are converted to the keys.DID format - // For now, parse from the derived DID string - return keys.Parse(r.issuerDID) -} - -// MPCVerifier provides UCAN verification with MPC support -type MPCVerifier struct { - *Verifier - enclave mpc.Enclave -} - -// NewMPCVerifier creates a UCAN verifier with MPC support -func NewMPCVerifier(enclave mpc.Enclave) *MPCVerifier { - resolver := NewMPCDIDResolver(enclave, StringDIDResolver{}) - verifier := NewVerifier(resolver) - - return &MPCVerifier{ - Verifier: verifier, - enclave: enclave, - } -} - -// VerifyMPCToken verifies a UCAN token that may be signed with MPC -func (v *MPCVerifier) VerifyMPCToken(ctx context.Context, tokenString string) (*Token, error) { - // Try standard verification first - token, err := v.VerifyToken(ctx, tokenString) - if err == nil { - return token, nil - } - - // If standard verification fails, try MPC-specific verification - return v.verifyWithMPC(ctx, tokenString) -} - -// verifyWithMPC attempts to verify using MPC signing method -func (v *MPCVerifier) verifyWithMPC(_ context.Context, tokenString string) (*Token, error) { - // Create MPC signing method for verification - mpcMethod := NewMPCSigningMethod("MPC256", v.enclave) - - // Parse with MPC method - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { - // Ensure the token uses MPC signing method - if token.Method.Alg() != mpcMethod.Alg() { - return nil, fmt.Errorf("unexpected signing method: %v", token.Method) - } - // For MPC verification, the key is not used - return nil, nil - }) - if err != nil { - return nil, fmt.Errorf("MPC token verification failed: %w", err) - } - - // Extract and parse claims - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid token claims type") - } - - ucanToken, err := v.parseUCANClaims(claims, tokenString) - if err != nil { - return nil, fmt.Errorf("failed to parse UCAN claims: %w", err) - } - - return ucanToken, nil -} - -// MPCTokenValidator provides comprehensive UCAN token validation with MPC support -type MPCTokenValidator struct { - *MPCVerifier - enclaveValidation bool -} - -// NewMPCTokenValidator creates a comprehensive UCAN token validator with MPC support -func NewMPCTokenValidator(enclave mpc.Enclave, enableEnclaveValidation bool) *MPCTokenValidator { - verifier := NewMPCVerifier(enclave) - return &MPCTokenValidator{ - MPCVerifier: verifier, - enclaveValidation: enableEnclaveValidation, - } -} - -// ValidateTokenForVaultOperation performs comprehensive validation for vault operations -func (v *MPCTokenValidator) ValidateTokenForVaultOperation( - ctx context.Context, - tokenString string, - enclaveDataCID string, - requiredAction string, - vaultAddress string, -) (*Token, error) { - // Step 1: Verify token signature and structure - token, err := v.VerifyMPCToken(ctx, tokenString) - if err != nil { - return nil, fmt.Errorf("token verification failed: %w", err) - } - - // Step 2: Validate vault-specific capability - if err := ValidateVaultTokenCapability(token, enclaveDataCID, requiredAction); err != nil { - return nil, fmt.Errorf("vault capability validation failed: %w", err) - } - - // Step 3: Validate enclave data CID if enabled - if v.enclaveValidation { - if err := v.validateEnclaveDataCID(token, enclaveDataCID); err != nil { - return nil, fmt.Errorf("enclave data validation failed: %w", err) - } - } - - // Step 4: Validate vault address if provided - if vaultAddress != "" { - if err := v.validateVaultAddress(token, vaultAddress); err != nil { - return nil, fmt.Errorf("vault address validation failed: %w", err) - } - } - - // Step 5: Verify delegation chain if proofs exist - if len(token.Proofs) > 0 { - if err := v.VerifyDelegationChain(ctx, tokenString); err != nil { - return nil, fmt.Errorf("delegation chain validation failed: %w", err) - } - } - - return token, nil -} - -// ValidateTokenForResource validates token capabilities for a specific resource -func (v *MPCTokenValidator) ValidateTokenForResource( - ctx context.Context, - tokenString string, - resourceURI string, - requiredAbilities []string, -) (*Token, error) { - token, err := v.VerifyCapability(ctx, tokenString, resourceURI, requiredAbilities) - if err != nil { - return nil, fmt.Errorf("capability verification failed: %w", err) - } - - // Additional MPC-specific validation - if v.enclaveValidation { - if err := v.validateMPCIssuer(token); err != nil { - return nil, fmt.Errorf("MPC issuer validation failed: %w", err) - } - } - - return token, nil -} - -// validateEnclaveDataCID validates that the token contains the expected enclave data CID -func (v *MPCTokenValidator) validateEnclaveDataCID(token *Token, expectedCID string) error { - tokenCID, err := GetEnclaveDataCID(token) - if err != nil { - return fmt.Errorf("failed to extract enclave data CID from token: %w", err) - } - - if tokenCID != expectedCID { - return fmt.Errorf("enclave data CID mismatch: token=%s, expected=%s", tokenCID, expectedCID) - } - - return nil -} - -// validateVaultAddress validates the vault address in token capabilities -func (v *MPCTokenValidator) validateVaultAddress(token *Token, expectedAddress string) error { - for _, att := range token.Attenuations { - if vaultCap, ok := att.Capability.(*VaultCapability); ok { - if vaultCap.VaultAddress != "" && vaultCap.VaultAddress != expectedAddress { - return fmt.Errorf("vault address mismatch: token=%s, expected=%s", - vaultCap.VaultAddress, expectedAddress) - } - } - } - return nil -} - -// validateMPCIssuer validates that the token issuer matches the MPC enclave -func (v *MPCTokenValidator) validateMPCIssuer(token *Token) error { - expectedIssuer, _ := deriveIssuerDIDFromBytes(v.enclave.PubKeyBytes()) - - if token.Issuer != expectedIssuer { - return fmt.Errorf("token issuer does not match MPC enclave: token=%s, expected=%s", - token.Issuer, expectedIssuer) - } - - return nil -} - -// createMPCVaultAttenuation creates MPC-specific vault attenuations -func createMPCVaultAttenuation(actions []string, enclaveDataCID, vaultAddress string) Attenuation { - // Use the existing CreateVaultAttenuation function but add MPC-specific validation - return CreateVaultAttenuation(actions, enclaveDataCID, vaultAddress) -} - -// containsAdminAction checks if actions contain admin-level permissions -func containsAdminAction(actions []string) bool { - adminActions := map[string]bool{ - "admin": true, "export": true, "import": true, "delete": true, - } - - for _, action := range actions { - if adminActions[action] { - return true - } - } - return false -} - -// ValidateEnclaveDataIntegrity validates enclave data against IPFS CID -func ValidateEnclaveDataIntegrity(enclaveData *mpc.EnclaveData, expectedCID string) error { - if enclaveData == nil { - return fmt.Errorf("enclave data cannot be nil") - } - - // Basic validation of enclave structure - if len(enclaveData.PubBytes) == 0 { - return fmt.Errorf("enclave public key bytes cannot be empty") - } - - if enclaveData.PubHex == "" { - return fmt.Errorf("enclave public key hex cannot be empty") - } - - // Implement IPFS CID validation against enclave data hash - // Serialize the enclave data for consistent hashing - enclaveDataBytes, err := enclaveData.Marshal() - if err != nil { - return fmt.Errorf("failed to marshal enclave data: %w", err) - } - - // 1. Hash the enclave data using SHA-256 - hasher := sha256.New() - hasher.Write(enclaveDataBytes) - digest := hasher.Sum(nil) - - // 2. Create multihash with SHA-256 prefix - mhash, err := multihash.EncodeName(digest, "sha2-256") - if err != nil { - return fmt.Errorf("failed to create multihash: %w", err) - } - - // 3. Create CID and compare with expected - parsedExpectedCID, err := cid.Parse(expectedCID) - if err != nil { - return fmt.Errorf("failed to parse expected CID: %w", err) - } - - // Create CID v1 with dag-pb codec (IPFS default) - calculatedCID := cid.NewCidV1(cid.DagProtobuf, mhash) - - // Compare CIDs - if !parsedExpectedCID.Equals(calculatedCID) { - return fmt.Errorf( - "CID verification failed: expected %s, calculated %s", - parsedExpectedCID.String(), - calculatedCID.String(), - ) - } - - return nil -} - -// MPCCapabilityBuilder helps build MPC-specific capabilities -type MPCCapabilityBuilder struct { - enclave mpc.Enclave - builder *MPCTokenBuilder -} - -// NewMPCCapabilityBuilder creates a new MPC capability builder -func NewMPCCapabilityBuilder(enclave mpc.Enclave) (*MPCCapabilityBuilder, error) { - builder, err := NewMPCTokenBuilder(enclave) - if err != nil { - return nil, fmt.Errorf("failed to create MPC token builder: %w", err) - } - - return &MPCCapabilityBuilder{ - enclave: enclave, - builder: builder, - }, nil -} - -// CreateVaultAdminCapability creates admin-level vault capabilities -func (b *MPCCapabilityBuilder) CreateVaultAdminCapability( - vaultAddress, enclaveDataCID string, -) Attenuation { - allActions := []string{"read", "write", "sign", "export", "import", "delete", "admin"} - return CreateVaultAttenuation(allActions, enclaveDataCID, vaultAddress) -} - -// CreateVaultReadOnlyCapability creates read-only vault capabilities -func (b *MPCCapabilityBuilder) CreateVaultReadOnlyCapability( - vaultAddress, enclaveDataCID string, -) Attenuation { - readActions := []string{"read"} - return CreateVaultAttenuation(readActions, enclaveDataCID, vaultAddress) -} - -// CreateVaultSigningCapability creates signing-specific vault capabilities -func (b *MPCCapabilityBuilder) CreateVaultSigningCapability( - vaultAddress, enclaveDataCID string, -) Attenuation { - signActions := []string{"read", "sign"} - return CreateVaultAttenuation(signActions, enclaveDataCID, vaultAddress) -} - -// CreateCustomCapability creates a custom capability with specified actions -func (b *MPCCapabilityBuilder) CreateCustomCapability( - actions []string, - vaultAddress, enclaveDataCID string, -) Attenuation { - return CreateVaultAttenuation(actions, enclaveDataCID, vaultAddress) -} - -// Utility functions - -// deriveIssuerDIDFromBytes creates issuer DID and address from public key bytes -// Enhanced version using the crypto/keys package -func deriveIssuerDIDFromBytes(pubKeyBytes []byte) (string, string) { - // Use the enhanced NewFromMPCPubKey method from crypto/keys - did, err := keys.NewFromMPCPubKey(pubKeyBytes) - if err != nil { - // Fallback to simplified implementation - address := fmt.Sprintf("addr_%x", pubKeyBytes[:8]) - issuerDID := fmt.Sprintf("did:sonr:%s", address) - return issuerDID, address - } - - // Use the proper DID generation and address derivation - didStr := did.String() - address, err := did.Address() - if err != nil { - // Fallback to simplified address - address = fmt.Sprintf("addr_%x", pubKeyBytes[:8]) - } - - return didStr, address -} diff --git a/crypto/ucan/source.go b/crypto/ucan/source.go deleted file mode 100644 index 35ae15959..000000000 --- a/crypto/ucan/source.go +++ /dev/null @@ -1,302 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "fmt" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/sonr-io/sonr/crypto/keys" - "github.com/sonr-io/sonr/crypto/mpc" - "lukechampine.com/blake3" -) - -// KeyshareSource provides MPC-based UCAN token creation and validation -type KeyshareSource interface { - Address() string - Issuer() string - ChainCode() ([]byte, error) - OriginToken() (*Token, error) - SignData(data []byte) ([]byte, error) - VerifyData(data []byte, sig []byte) (bool, error) - Enclave() mpc.Enclave - - // UCAN token creation methods - NewOriginToken( - audienceDID string, - att []Attenuation, - fct []Fact, - notBefore, expires time.Time, - ) (*Token, error) - NewAttenuatedToken( - parent *Token, - audienceDID string, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, - ) (*Token, error) -} - -// mpcKeyshareSource implements KeyshareSource using MPC enclave -type mpcKeyshareSource struct { - enclave mpc.Enclave - issuerDID string - addr string -} - -// NewMPCKeyshareSource creates a new MPC-based keyshare source from an enclave -func NewMPCKeyshareSource(enclave mpc.Enclave) (KeyshareSource, error) { - if !enclave.IsValid() { - return nil, fmt.Errorf("invalid MPC enclave provided") - } - - pubKeyBytes := enclave.PubKeyBytes() - issuerDID, addr, err := getIssuerDIDFromBytes(pubKeyBytes) - if err != nil { - return nil, fmt.Errorf("failed to derive issuer DID: %w", err) - } - - return &mpcKeyshareSource{ - enclave: enclave, - issuerDID: issuerDID, - addr: addr, - }, nil -} - -// Address returns the address derived from the enclave public key -func (k *mpcKeyshareSource) Address() string { - return k.addr -} - -// Issuer returns the DID of the issuer derived from the enclave public key -func (k *mpcKeyshareSource) Issuer() string { - return k.issuerDID -} - -// Enclave returns the underlying MPC enclave -func (k *mpcKeyshareSource) Enclave() mpc.Enclave { - return k.enclave -} - -// ChainCode derives a deterministic chain code from the enclave -func (k *mpcKeyshareSource) ChainCode() ([]byte, error) { - // Sign the address to create a deterministic chain code - sig, err := k.SignData([]byte(k.addr)) - if err != nil { - return nil, fmt.Errorf("failed to sign address for chain code: %w", err) - } - - // Hash the signature to create a 32-byte chain code - hash := blake3.Sum256(sig) - return hash[:32], nil -} - -// OriginToken creates a default origin token with basic capabilities -func (k *mpcKeyshareSource) OriginToken() (*Token, error) { - // Create basic capability for the MPC keyshare - resource := &SimpleResource{ - Scheme: "mpc", - Value: k.addr, - URI: fmt.Sprintf("mpc://%s", k.addr), - } - - capability := &SimpleCapability{Action: "sign"} - - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - // Create token with no expiration for origin token - zero := time.Time{} - return k.NewOriginToken(k.issuerDID, []Attenuation{attenuation}, nil, zero, zero) -} - -// SignData signs data using the MPC enclave -func (k *mpcKeyshareSource) SignData(data []byte) ([]byte, error) { - if !k.enclave.IsValid() { - return nil, fmt.Errorf("enclave is not valid") - } - - return k.enclave.Sign(data) -} - -// VerifyData verifies a signature using the MPC enclave -func (k *mpcKeyshareSource) VerifyData(data []byte, sig []byte) (bool, error) { - if !k.enclave.IsValid() { - return false, fmt.Errorf("enclave is not valid") - } - - return k.enclave.Verify(data, sig) -} - -// NewOriginToken creates a new UCAN origin token using MPC signing -func (k *mpcKeyshareSource) NewOriginToken( - audienceDID string, - att []Attenuation, - fct []Fact, - notBefore, expires time.Time, -) (*Token, error) { - return k.newToken(audienceDID, nil, att, fct, notBefore, expires) -} - -// NewAttenuatedToken creates a new attenuated UCAN token using MPC signing -func (k *mpcKeyshareSource) NewAttenuatedToken( - parent *Token, - audienceDID string, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, -) (*Token, error) { - // Validate that new attenuations are more restrictive than parent - if !isAttenuationSubset(att, parent.Attenuations) { - return nil, fmt.Errorf("scope of ucan attenuations must be less than its parent") - } - - // Add parent as proof - proofs := []Proof{} - if parent.Raw != "" { - proofs = append(proofs, Proof(parent.Raw)) - } - proofs = append(proofs, parent.Proofs...) - - return k.newToken(audienceDID, proofs, att, fct, nbf, exp) -} - -// newToken creates a new UCAN token with MPC signing -func (k *mpcKeyshareSource) newToken( - audienceDID string, - proofs []Proof, - att []Attenuation, - fct []Fact, - nbf, exp time.Time, -) (*Token, error) { - // Validate audience DID - if !isValidDID(audienceDID) { - return nil, fmt.Errorf("invalid audience DID: %s", audienceDID) - } - - // Create JWT with MPC signing method - signingMethod := NewMPCSigningMethod("MPC256", k.enclave) - t := jwt.New(signingMethod) - - // Set UCAN version header - t.Header["ucv"] = "0.9.0" - - var ( - nbfUnix int64 - expUnix int64 - ) - - if !nbf.IsZero() { - nbfUnix = nbf.Unix() - } - if !exp.IsZero() { - expUnix = exp.Unix() - } - - // Convert attenuations to claim format - attClaims := make([]map[string]any, len(att)) - for i, a := range att { - attClaims[i] = map[string]any{ - "can": a.Capability.GetActions(), - "with": a.Resource.GetURI(), - } - } - - // Convert proofs to strings - proofStrings := make([]string, len(proofs)) - for i, proof := range proofs { - proofStrings[i] = string(proof) - } - - // Convert facts to any slice - factData := make([]any, len(fct)) - for i, fact := range fct { - factData[i] = string(fact.Data) - } - - // Set claims - claims := jwt.MapClaims{ - "iss": k.issuerDID, - "aud": audienceDID, - "att": attClaims, - } - - if nbfUnix > 0 { - claims["nbf"] = nbfUnix - } - if expUnix > 0 { - claims["exp"] = expUnix - } - if len(proofStrings) > 0 { - claims["prf"] = proofStrings - } - if len(factData) > 0 { - claims["fct"] = factData - } - - t.Claims = claims - - // Sign the token using MPC enclave - tokenString, err := t.SignedString(nil) - if err != nil { - return nil, fmt.Errorf("failed to sign token: %w", err) - } - - return &Token{ - Raw: tokenString, - Issuer: k.issuerDID, - Audience: audienceDID, - ExpiresAt: expUnix, - NotBefore: nbfUnix, - Attenuations: att, - Proofs: proofs, - Facts: fct, - }, nil -} - -// getIssuerDIDFromBytes creates an issuer DID and address from public key bytes -func getIssuerDIDFromBytes(pubKeyBytes []byte) (string, string, error) { - // Use the enhanced NewFromMPCPubKey method for proper MPC integration - did, err := keys.NewFromMPCPubKey(pubKeyBytes) - if err != nil { - return "", "", fmt.Errorf("failed to create DID from MPC public key: %w", err) - } - - didStr := did.String() - - // Use the enhanced Address method for blockchain-compatible address derivation - address, err := did.Address() - if err != nil { - return "", "", fmt.Errorf("failed to derive address from DID: %w", err) - } - - return didStr, address, nil -} - -// isAttenuationSubset checks if child attenuations are a subset of parent attenuations -func isAttenuationSubset(child, parent []Attenuation) bool { - for _, childAtt := range child { - if !containsAttenuation(parent, childAtt) { - return false - } - } - return true -} - -// containsAttenuation checks if the parent list contains an equivalent attenuation -func containsAttenuation(parent []Attenuation, att Attenuation) bool { - for _, parentAtt := range parent { - if parentAtt.Resource.Matches(att.Resource) && - parentAtt.Capability.Contains(att.Capability) { - return true - } - } - return false -} - -// Note: MPC signing methods are already implemented in mpc.go -// Note: isValidDID is already implemented in stubs.go diff --git a/crypto/ucan/stubs.go b/crypto/ucan/stubs.go deleted file mode 100644 index c50600d08..000000000 --- a/crypto/ucan/stubs.go +++ /dev/null @@ -1,87 +0,0 @@ -package ucan - -import ( - "time" -) - -// TokenBuilderInterface defines token building methods -type TokenBuilderInterface interface { - CreateOriginToken( - issuer string, - capabilities []Attenuation, - facts []Fact, - start, expiry time.Time, - ) (*Token, error) - CreateDelegatedToken( - parentToken *Token, - issuer string, - capabilities []Attenuation, - facts []Fact, - start, expiry time.Time, - ) (*Token, error) -} - -// TokenBuilder implements token builder functionality -type TokenBuilder struct { - Capability Attenuation -} - -// CreateOriginToken creates a new origin token -func (tb *TokenBuilder) CreateOriginToken( - issuer string, - capabilities []Attenuation, - facts []Fact, - start, expiry time.Time, -) (*Token, error) { - return &Token{ - Raw: "", - Issuer: issuer, - Audience: "", - ExpiresAt: expiry.Unix(), - NotBefore: start.Unix(), - Attenuations: capabilities, - Proofs: []Proof{}, - Facts: facts, - }, nil -} - -// CreateDelegatedToken creates a delegated token -func (tb *TokenBuilder) CreateDelegatedToken( - parentToken *Token, - issuer string, - capabilities []Attenuation, - facts []Fact, - start, expiry time.Time, -) (*Token, error) { - proofs := []Proof{} - if parentToken.Raw != "" { - proofs = append(proofs, Proof(parentToken.Raw)) - } - - return &Token{ - Raw: "", - Issuer: issuer, - Audience: parentToken.Issuer, - ExpiresAt: expiry.Unix(), - NotBefore: start.Unix(), - Attenuations: capabilities, - Proofs: proofs, - Facts: facts, - }, nil -} - -// Stub for DID validation -func isValidDID(did string) bool { - // Basic DID validation stub - return did != "" && len(did) > 5 && did[:4] == "did:" -} - -// Stub for preparing delegation proofs -func prepareDelegationProofs(token *Token, capabilities []Attenuation) ([]Proof, error) { - // Minimal stub implementation - proofs := []Proof{} - if token.Raw != "" { - proofs = append(proofs, Proof(token.Raw)) - } - return proofs, nil -} diff --git a/crypto/ucan/ucan_test.go b/crypto/ucan/ucan_test.go deleted file mode 100644 index 3a38d4ff5..000000000 --- a/crypto/ucan/ucan_test.go +++ /dev/null @@ -1,313 +0,0 @@ -package ucan - -import ( - "crypto/sha256" - "testing" - "time" - - "github.com/ipfs/go-cid" - "github.com/multiformats/go-multihash" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCapabilityCreation(t *testing.T) { - testCases := []struct { - name string - actions []string - expected bool - }{ - { - name: "Basic Capability Creation", - actions: []string{"read", "write"}, - expected: true, - }, - { - name: "Empty Actions", - actions: []string{}, - expected: true, - }, - { - name: "Complex Actions", - actions: []string{"create", "update", "delete", "admin"}, - expected: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - capability := &MultiCapability{Actions: tc.actions} - - assert.NotNil(t, capability) - assert.Equal(t, len(tc.actions), len(capability.Actions)) - - for _, action := range tc.actions { - assert.Contains(t, capability.Actions, action) - } - }) - } -} - -func TestCapabilityValidation(t *testing.T) { - testCases := []struct { - name string - actions []string - resourceScheme string - shouldPass bool - }{ - { - name: "Valid Standard Actions", - actions: []string{"read", "write"}, - resourceScheme: "example", - shouldPass: true, - }, - { - name: "Invalid Actions", - actions: []string{"delete", "admin"}, - resourceScheme: "restricted", - shouldPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - capability := &MultiCapability{Actions: tc.actions} - resource := &SimpleResource{ - Scheme: tc.resourceScheme, - Value: "test", - URI: tc.resourceScheme + "://test", - } - - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - StandardTemplate.AddAllowedActions(tc.resourceScheme, []string{"read", "write"}) - err := StandardTemplate.ValidateAttenuation(attenuation) - - if tc.shouldPass { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestJWTTokenLifecycle(t *testing.T) { - testCases := []struct { - name string - actions []string - resourceScheme string - duration time.Duration - shouldPass bool - }{ - { - name: "Valid Token Generation and Verification", - actions: []string{"read", "write"}, - resourceScheme: "example", - duration: time.Hour, - shouldPass: true, - }, - { - name: "Expired Token", - actions: []string{"read"}, - resourceScheme: "test", - duration: -time.Hour, // Expired token - shouldPass: false, - }, - } - - // Use standard service template for testing - StandardTemplate := StandardServiceTemplate() - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - capability := &MultiCapability{Actions: tc.actions} - resource := &SimpleResource{ - Scheme: tc.resourceScheme, - Value: "test", - URI: tc.resourceScheme + "://test", - } - - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - // Validate attenuation against template - err := StandardTemplate.ValidateAttenuation(attenuation) - require.NoError(t, err) - - // Simulate JWT token generation and verification - token := "test_token_" + time.Now().String() - - if tc.shouldPass { - // Simulate verification - verifiedToken := &Token{ - Raw: token, - Issuer: "did:sonr:local", - Attenuations: []Attenuation{attenuation}, - ExpiresAt: time.Now().Add(tc.duration).Unix(), - } - - assert.NotNil(t, verifiedToken) - assert.Equal(t, "did:sonr:local", verifiedToken.Issuer) - assert.Len(t, verifiedToken.Attenuations, 1) - assert.Equal( - t, - tc.resourceScheme+"://test", - verifiedToken.Attenuations[0].Resource.GetURI(), - ) - } else { - // Simulate expired token verification - assert.True(t, time.Now().Unix() > time.Now().Add(tc.duration).Unix()) - } - }) - } -} - -func TestCapabilityRevocation(t *testing.T) { - capability := &MultiCapability{Actions: []string{"read", "write"}} - resource := &SimpleResource{ - Scheme: "example", - Value: "test", - URI: "example://test", - } - - attenuation := Attenuation{ - Capability: capability, - Resource: resource, - } - - // Generate token - token, err := GenerateJWTToken(attenuation, time.Hour) - require.NoError(t, err) - - // Revoke capability - err = RevokeCapability(attenuation) - assert.NoError(t, err) - - // Attempt to verify revoked token should fail - _, err = VerifyJWTToken(token) - assert.Error(t, err) - assert.Contains(t, err.Error(), "token has been revoked") -} - -func TestResourceValidation(t *testing.T) { - testCases := []struct { - name string - resourceScheme string - resourceValue string - resourceURI string - expectValid bool - }{ - { - name: "Valid Resource", - resourceScheme: "sonr", - resourceValue: "test-resource", - resourceURI: "sonr://test-resource", - expectValid: true, - }, - { - name: "Invalid Resource URI", - resourceScheme: "invalid", - resourceValue: "test-resource", - resourceURI: "invalid-malformed-uri", - expectValid: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - resource := &SimpleResource{ - Scheme: tc.resourceScheme, - Value: tc.resourceValue, - URI: tc.resourceURI, - } - - // Simplified resource validation - if tc.expectValid { - assert.Regexp(t, `^[a-z]+://[a-z-]+$`, resource.URI) - } else { - assert.NotRegexp(t, `^[a-z]+://[a-z-]+$`, resource.URI) - } - }) - } -} - -func TestValidateEnclaveDataCIDIntegrity(t *testing.T) { - testCases := []struct { - name string - data []byte - expectedCID string - expectError bool - errorContains string - }{ - { - name: "Empty CID", - data: []byte("test data"), - expectedCID: "", - expectError: true, - errorContains: "enclave data CID cannot be empty", - }, - { - name: "Empty data", - data: []byte{}, - expectedCID: "QmTest", - expectError: true, - errorContains: "enclave data cannot be empty", - }, - { - name: "Invalid CID format", - data: []byte("test data"), - expectedCID: "invalid-cid", - expectError: true, - errorContains: "invalid IPFS CID format", - }, - { - name: "Valid CID verification - should pass", - data: []byte("test data"), - expectedCID: generateValidCIDForData([]byte("test data")), - expectError: false, - }, - { - name: "Mismatched CID - should fail", - data: []byte("test data"), - expectedCID: generateValidCIDForData([]byte("different data")), - expectError: true, - errorContains: "CID verification failed", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := ValidateEnclaveDataCIDIntegrity(tc.expectedCID, tc.data) - - if tc.expectError { - assert.Error(t, err) - if tc.errorContains != "" { - assert.Contains(t, err.Error(), tc.errorContains) - } - } else { - assert.NoError(t, err) - } - }) - } -} - -// Helper function to generate a valid CID for test data -func generateValidCIDForData(data []byte) string { - hasher := sha256.New() - hasher.Write(data) - digest := hasher.Sum(nil) - - mhash, err := multihash.EncodeName(digest, "sha2-256") - if err != nil { - panic(err) - } - - calculatedCID := cid.NewCidV1(cid.DagProtobuf, mhash) - return calculatedCID.String() -} diff --git a/crypto/ucan/vault.go b/crypto/ucan/vault.go deleted file mode 100644 index 579f533fd..000000000 --- a/crypto/ucan/vault.go +++ /dev/null @@ -1,485 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "crypto/sha256" - "fmt" - "slices" - "strings" - "time" - - z "github.com/Oudwins/zog" - "github.com/ipfs/go-cid" - "github.com/multiformats/go-multihash" -) - -// Constants for vault capability actions -const ( - VaultAdminAction = "vault/admin" -) - -// VaultCapabilitySchema defines validation specifically for vault capabilities -var VaultCapabilitySchema = z.Struct(z.Shape{ - "can": z.String().Required().OneOf( - []string{ - VaultAdminAction, - "vault/read", - "vault/write", - "vault/sign", - "vault/export", - "vault/import", - "vault/delete", - }, - z.Message("Invalid vault capability"), - ), - "with": z.String(). - Required(). - TestFunc(ValidateIPFSCID, z.Message("Vault resource must be IPFS CID in format 'ipfs://CID'")), - "actions": z.Slice(z.String().OneOf( - []string{"read", "write", "sign", "export", "import", "delete"}, - z.Message("Invalid vault action"), - )).Optional(), - "vault": z.String().Required().Min(1, z.Message("Vault address cannot be empty")), - "cavs": z.Slice(z.String()).Optional(), // Caveats as string array for vault capabilities -}) - -// VaultCapability implements Capability for vault-specific operations -// with support for admin permissions, actions, and enclave data management. -type VaultCapability struct { - Action string `json:"can"` - Actions []string `json:"actions,omitempty"` - VaultAddress string `json:"vault,omitempty"` - Caveats []string `json:"cavs,omitempty"` - EnclaveDataCID string `json:"enclave_data_cid,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// GetActions returns the actions this vault capability grants -func (c *VaultCapability) GetActions() []string { - if c.Action == VaultAdminAction { - // Admin capability grants all vault actions - return []string{"read", "write", "sign", "export", "import", "delete", VaultAdminAction} - } - - if len(c.Actions) > 0 { - return c.Actions - } - - // Extract action from the main capability string - if strings.HasPrefix(c.Action, "vault/") { - return []string{c.Action[6:]} // Remove "vault/" prefix - } - - return []string{c.Action} -} - -// Grants checks if this capability grants the required abilities -func (c *VaultCapability) Grants(abilities []string) bool { - if c.Action == VaultAdminAction { - // Admin capability grants everything - return true - } - - grantedActions := make(map[string]bool) - for _, action := range c.GetActions() { - grantedActions[action] = true - grantedActions["vault/"+action] = true // Support both formats - } - - // Check each required ability - for _, ability := range abilities { - if !grantedActions[ability] { - return false - } - } - - return true -} - -// Contains checks if this capability contains another capability -func (c *VaultCapability) Contains(other Capability) bool { - if c.Action == VaultAdminAction { - // Admin contains all vault capabilities - if otherVault, ok := other.(*VaultCapability); ok { - return strings.HasPrefix(otherVault.Action, "vault/") - } - // Admin contains any action that starts with vault-related actions - for _, action := range other.GetActions() { - if strings.HasPrefix(action, "vault/") || - action == "read" || action == "write" || action == "sign" || - action == "export" || action == "import" || action == "delete" { - return true - } - } - return false - } - - // Check if our actions contain all of the other capability's actions - ourActions := make(map[string]bool) - for _, action := range c.GetActions() { - ourActions[action] = true - ourActions["vault/"+action] = true - } - - for _, otherAction := range other.GetActions() { - if !ourActions[otherAction] { - return false - } - } - - return true -} - -// String returns string representation -func (c *VaultCapability) String() string { - return c.Action -} - -// VaultResourceExt represents an extended IPFS-based vault resource (to avoid redeclaration) -type VaultResourceExt struct { - SimpleResource - VaultAddress string `json:"vault_address"` - EnclaveDataCID string `json:"enclave_data_cid"` -} - -// ValidateIPFSCID validates IPFS CID format for vault resources -func ValidateIPFSCID(value *string, ctx z.Ctx) bool { - if !strings.HasPrefix(*value, "ipfs://") { - return false - } - cidStr := (*value)[7:] // Remove "ipfs://" prefix - - // Enhanced CID validation - return validateCIDFormat(cidStr) -} - -// validateCIDFormat performs comprehensive IPFS CID format validation -func validateCIDFormat(cidStr string) bool { - if len(cidStr) == 0 { - return false - } - - // CIDv0: Base58-encoded SHA-256 multihash (starts with 'Qm' and is 46 characters) - if strings.HasPrefix(cidStr, "Qm") && len(cidStr) == 46 { - return isValidBase58(cidStr) - } - - // CIDv1: Base32 or Base58 encoded (starts with 'b' for base32 or other prefixes) - if len(cidStr) >= 59 { - // CIDv1 in base32 typically starts with 'b' and is longer - if strings.HasPrefix(cidStr, "b") { - return isValidBase32(cidStr[1:]) // Remove 'b' prefix - } - // CIDv1 in base58 or other encodings - return isValidBase58(cidStr) - } - - return false -} - -// isValidBase58 checks if string contains valid base58 characters -func isValidBase58(s string) bool { - base58Chars := "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - for _, char := range s { - if !strings.Contains(base58Chars, string(char)) { - return false - } - } - return true -} - -// isValidBase32 checks if string contains valid base32 characters -func isValidBase32(s string) bool { - base32Chars := "abcdefghijklmnopqrstuvwxyz234567" - for _, char := range s { - if !strings.Contains(base32Chars, string(char)) { - return false - } - } - return true -} - -// ValidateEnclaveDataCIDIntegrity validates enclave data against expected CID -func ValidateEnclaveDataCIDIntegrity(enclaveDataCID string, enclaveData []byte) error { - if enclaveDataCID == "" { - return fmt.Errorf("enclave data CID cannot be empty") - } - - if len(enclaveData) == 0 { - return fmt.Errorf("enclave data cannot be empty") - } - - // Validate CID format first - if !validateCIDFormat(enclaveDataCID) { - return fmt.Errorf("invalid IPFS CID format: %s", enclaveDataCID) - } - - // Implement actual CID verification by hashing enclave data - // 1. Hash the enclave data using SHA-256 - hasher := sha256.New() - hasher.Write(enclaveData) - digest := hasher.Sum(nil) - - // 2. Create multihash with SHA-256 prefix - mhash, err := multihash.EncodeName(digest, "sha2-256") - if err != nil { - return fmt.Errorf("failed to create multihash: %w", err) - } - - // 3. Create CID and compare with expected - expectedCID, err := cid.Parse(enclaveDataCID) - if err != nil { - return fmt.Errorf("failed to parse expected CID: %w", err) - } - - // Create CID v1 with dag-pb codec (IPFS default) - calculatedCID := cid.NewCidV1(cid.DagProtobuf, mhash) - - // Compare CIDs - if !expectedCID.Equals(calculatedCID) { - return fmt.Errorf( - "CID verification failed: expected %s, calculated %s", - expectedCID.String(), - calculatedCID.String(), - ) - } - - return nil -} - -// ValidateVaultCapability validates vault-specific capabilities -func ValidateVaultCapability(att map[string]any) error { - var validated struct { - Can string `json:"can"` - With string `json:"with"` - Actions []string `json:"actions,omitempty"` - Vault string `json:"vault"` - Cavs []string `json:"cavs,omitempty"` - } - - errs := VaultCapabilitySchema.Parse(att, &validated) - if errs != nil { - return fmt.Errorf("vault capability validation failed: %v", errs) - } - - return nil -} - -// VaultAttenuationConstructor creates vault-specific attenuations with enhanced validation -func VaultAttenuationConstructor(m map[string]any) (Attenuation, error) { - // First validate using vault-specific schema - if err := ValidateVaultCapability(m); err != nil { - return Attenuation{}, fmt.Errorf("vault attenuation validation failed: %w", err) - } - - capStr, withStr, err := extractRequiredFields(m) - if err != nil { - return Attenuation{}, err - } - - vaultCap := createVaultCapability(capStr, m) - resource := createVaultResource(withStr, vaultCap.VaultAddress) - - // Set enclave data CID if using IPFS resource - if vaultRes, ok := resource.(*VaultResource); ok { - vaultCap.EnclaveDataCID = vaultRes.EnclaveDataCID - } - - return Attenuation{ - Capability: vaultCap, - Resource: resource, - }, nil -} - -// extractRequiredFields extracts and validates required 'can' and 'with' fields -func extractRequiredFields(m map[string]any) (string, string, error) { - capValue, exists := m["can"] - if !exists { - return "", "", fmt.Errorf("missing 'can' field in attenuation") - } - capStr, ok := capValue.(string) - if !ok { - return "", "", fmt.Errorf("'can' field must be a string") - } - - withValue, exists := m["with"] - if !exists { - return "", "", fmt.Errorf("missing 'with' field in attenuation") - } - withStr, ok := withValue.(string) - if !ok { - return "", "", fmt.Errorf("'with' field must be a string") - } - - return capStr, withStr, nil -} - -// createVaultCapability creates and populates a VaultCapability from the input map -func createVaultCapability(action string, m map[string]any) *VaultCapability { - vaultCap := &VaultCapability{Action: action} - - if actions, exists := m["actions"]; exists { - vaultCap.Actions = extractStringSlice(actions) - } - - if vault, exists := m["vault"]; exists { - if vaultStr, ok := vault.(string); ok { - vaultCap.VaultAddress = vaultStr - } - } - - if cavs, exists := m["cavs"]; exists { - vaultCap.Caveats = extractStringSlice(cavs) - } - - return vaultCap -} - -// extractStringSlice safely extracts a string slice from an any -func extractStringSlice(value any) []string { - if slice, ok := value.([]any); ok { - result := make([]string, 0, len(slice)) - for _, item := range slice { - if str, ok := item.(string); ok { - result = append(result, str) - } - } - return result - } - return nil -} - -// createVaultResource creates appropriate Resource based on the URI scheme -func createVaultResource(withStr, vaultAddress string) Resource { - parts := strings.SplitN(withStr, "://", 2) - if len(parts) == 2 && parts[0] == "ipfs" { - return &VaultResource{ - SimpleResource: SimpleResource{ - Scheme: "ipfs", - Value: parts[1], - URI: withStr, - }, - VaultAddress: vaultAddress, - EnclaveDataCID: parts[1], - } - } - - return &SimpleResource{ - Scheme: "ipfs", - Value: withStr, - URI: withStr, - } -} - -// NewVaultAdminToken creates a new UCAN token with vault admin capabilities -func NewVaultAdminToken( - builder TokenBuilderInterface, - vaultOwnerDID string, - vaultAddress string, - enclaveDataCID string, - exp time.Time, -) (*Token, error) { - // Validate input parameters - if !isValidDID(vaultOwnerDID) { - return nil, fmt.Errorf("invalid vault owner DID: %s", vaultOwnerDID) - } - - // Create vault admin attenuation with full permissions - vaultResource := &VaultResource{ - SimpleResource: SimpleResource{ - Scheme: "ipfs", - Value: enclaveDataCID, - URI: fmt.Sprintf("ipfs://%s", enclaveDataCID), - }, - VaultAddress: vaultAddress, - EnclaveDataCID: enclaveDataCID, - } - - vaultCap := &VaultCapability{ - Action: VaultAdminAction, - Actions: []string{"read", "write", "sign", "export", "import", "delete"}, - VaultAddress: vaultAddress, - EnclaveDataCID: enclaveDataCID, - } - - // Validate the vault capability using vault-specific schema - capMap := map[string]any{ - "can": vaultCap.Action, - "with": vaultResource.URI, - "actions": vaultCap.Actions, - "vault": vaultCap.VaultAddress, - } - if err := ValidateVaultCapability(capMap); err != nil { - return nil, fmt.Errorf("invalid vault capability: %w", err) - } - - attenuation := Attenuation{ - Capability: vaultCap, - Resource: vaultResource, - } - - // Create token with vault admin capabilities - return builder.CreateOriginToken( - vaultOwnerDID, - []Attenuation{attenuation}, - nil, - time.Now(), - exp, - ) -} - -// ValidateVaultTokenCapability validates a UCAN token for vault operations -func ValidateVaultTokenCapability(token *Token, enclaveDataCID, requiredAction string) error { - expectedResource := fmt.Sprintf("ipfs://%s", enclaveDataCID) - - // Validate the required action parameter - validActions := []string{"read", "write", "sign", "export", "import", "delete"} - actionValid := slices.Contains(validActions, requiredAction) - if !actionValid { - return fmt.Errorf("invalid required action: %s", requiredAction) - } - - // Check if token contains the required vault capability - for _, att := range token.Attenuations { - if att.Resource.GetURI() == expectedResource { - // Check if this is a vault capability - if vaultCap, ok := att.Capability.(*VaultCapability); ok { - // Validate using vault-specific schema - validationMap := map[string]any{ - "can": vaultCap.Action, - "with": att.Resource.GetURI(), - "actions": vaultCap.Actions, - "vault": vaultCap.VaultAddress, - } - - if err := ValidateVaultCapability(validationMap); err != nil { - continue // Skip invalid capabilities - } - - // Check if capability grants the required action - if vaultCap.Grants([]string{requiredAction}) { - return nil - } - } - } - } - - return fmt.Errorf( - "insufficient vault capability: required action '%s' for enclave '%s'", - requiredAction, - enclaveDataCID, - ) -} - -// GetEnclaveDataCID extracts the enclave data CID from vault capabilities -func GetEnclaveDataCID(token *Token) (string, error) { - for _, att := range token.Attenuations { - resource := att.Resource.GetURI() - if strings.HasPrefix(resource, "ipfs://") { - return resource[7:], nil - } - } - return "", fmt.Errorf("no enclave data CID found in token") -} diff --git a/crypto/ucan/verifier.go b/crypto/ucan/verifier.go deleted file mode 100644 index 1e0ec584a..000000000 --- a/crypto/ucan/verifier.go +++ /dev/null @@ -1,984 +0,0 @@ -// Package ucan provides User-Controlled Authorization Networks (UCAN) implementation -// for decentralized authorization and capability delegation in the Sonr network. -// This package handles JWT-based tokens, cryptographic verification, and resource capabilities. -package ucan - -import ( - "context" - "crypto/ed25519" - "crypto/rsa" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/golang-jwt/jwt/v5" - "github.com/libp2p/go-libp2p/core/crypto" - "github.com/sonr-io/sonr/crypto/keys" -) - -// Verifier provides UCAN token verification and validation functionality -type Verifier struct { - didResolver DIDResolver -} - -// DIDResolver resolves DID keys to public keys for signature verification -type DIDResolver interface { - ResolveDIDKey(ctx context.Context, did string) (keys.DID, error) -} - -// NewVerifier creates a new UCAN token verifier -func NewVerifier(didResolver DIDResolver) *Verifier { - return &Verifier{ - didResolver: didResolver, - } -} - -// VerifyToken parses and verifies a UCAN JWT token -func (v *Verifier) VerifyToken(ctx context.Context, tokenString string) (*Token, error) { - if tokenString == "" { - return nil, fmt.Errorf("token string cannot be empty") - } - - // Parse the JWT token - token, err := jwt.Parse(tokenString, v.keyFunc(ctx)) - if err != nil { - return nil, fmt.Errorf("failed to parse JWT token: %w", err) - } - - // Extract claims - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid token claims type") - } - - // Parse UCAN-specific fields - ucanToken, err := v.parseUCANClaims(claims, tokenString) - if err != nil { - return nil, fmt.Errorf("failed to parse UCAN claims: %w", err) - } - - // Validate token structure - if err := v.validateToken(ctx, ucanToken); err != nil { - return nil, fmt.Errorf("token validation failed: %w", err) - } - - return ucanToken, nil -} - -// VerifyCapability validates that a UCAN token grants specific capabilities -func (v *Verifier) VerifyCapability( - ctx context.Context, - tokenString string, - resource string, - abilities []string, -) (*Token, error) { - token, err := v.VerifyToken(ctx, tokenString) - if err != nil { - return nil, fmt.Errorf("token verification failed: %w", err) - } - - // Check if token grants required capabilities - if err := v.checkCapabilities(token, resource, abilities); err != nil { - return nil, fmt.Errorf("capability check failed: %w", err) - } - - return token, nil -} - -// VerifyDelegationChain validates the complete delegation chain of a UCAN token -func (v *Verifier) VerifyDelegationChain(ctx context.Context, tokenString string) error { - token, err := v.VerifyToken(ctx, tokenString) - if err != nil { - return fmt.Errorf("failed to verify root token: %w", err) - } - - // Verify each proof in the delegation chain - for i, proof := range token.Proofs { - proofToken, err := v.VerifyToken(ctx, string(proof)) - if err != nil { - return fmt.Errorf("failed to verify proof[%d] in delegation chain: %w", i, err) - } - - // Validate delegation relationship - if err := v.validateDelegation(token, proofToken); err != nil { - return fmt.Errorf("invalid delegation at proof[%d]: %w", i, err) - } - } - - return nil -} - -// keyFunc returns a function that resolves the signing key for JWT verification -func (v *Verifier) keyFunc(ctx context.Context) jwt.Keyfunc { - return func(token *jwt.Token) (any, error) { - // Extract issuer from claims - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("invalid claims type") - } - - issuer, ok := claims["iss"].(string) - if !ok { - return nil, fmt.Errorf("missing or invalid issuer claim") - } - - // Resolve the issuer's DID to get public key - did, err := v.didResolver.ResolveDIDKey(ctx, issuer) - if err != nil { - return nil, fmt.Errorf("failed to resolve issuer DID: %w", err) - } - - // Get verification key based on signing method - switch token.Method { - case jwt.SigningMethodRS256, jwt.SigningMethodRS384, jwt.SigningMethodRS512: - return v.getRSAPublicKey(did) - case jwt.SigningMethodEdDSA: - return v.getEd25519PublicKey(did) - default: - return nil, fmt.Errorf("unsupported signing method: %v", token.Method) - } - } -} - -// parseUCANClaims extracts UCAN-specific fields from JWT claims -func (v *Verifier) parseUCANClaims(claims jwt.MapClaims, raw string) (*Token, error) { - issuer, audience := extractStandardClaims(claims) - expiresAt, notBefore := extractTimeClaims(claims) - - attenuations, err := v.parseAttenuationsClaims(claims) - if err != nil { - return nil, err - } - - proofs := parseProofsClaims(claims) - facts := parseFactsClaims(claims) - - return &Token{ - Raw: raw, - Issuer: issuer, - Audience: audience, - ExpiresAt: expiresAt, - NotBefore: notBefore, - Attenuations: attenuations, - Proofs: proofs, - Facts: facts, - }, nil -} - -// extractStandardClaims extracts standard JWT claims (issuer and audience) -func extractStandardClaims(claims jwt.MapClaims) (string, string) { - issuer, _ := claims["iss"].(string) - audience, _ := claims["aud"].(string) - return issuer, audience -} - -// extractTimeClaims extracts time-related claims (exp and nbf) -func extractTimeClaims(claims jwt.MapClaims) (int64, int64) { - var expiresAt, notBefore int64 - - if exp, ok := claims["exp"]; ok { - if expFloat, ok := exp.(float64); ok { - expiresAt = int64(expFloat) - } - } - - if nbf, ok := claims["nbf"]; ok { - if nbfFloat, ok := nbf.(float64); ok { - notBefore = int64(nbfFloat) - } - } - - return expiresAt, notBefore -} - -// parseAttenuationsClaims parses the attenuations from claims -func (v *Verifier) parseAttenuationsClaims(claims jwt.MapClaims) ([]Attenuation, error) { - attClaims, ok := claims["att"] - if !ok { - return nil, nil - } - - attSlice, ok := attClaims.([]any) - if !ok { - return nil, nil - } - - // Pre-allocate slice with known capacity - attenuations := make([]Attenuation, 0, len(attSlice)) - - for _, attItem := range attSlice { - attMap, ok := attItem.(map[string]any) - if !ok { - continue - } - - att, err := v.parseAttenuation(attMap) - if err != nil { - return nil, fmt.Errorf("failed to parse attenuation: %w", err) - } - attenuations = append(attenuations, att) - } - - return attenuations, nil -} - -// parseProofsClaims parses the proofs from claims -func parseProofsClaims(claims jwt.MapClaims) []Proof { - var proofs []Proof - - prfClaims, ok := claims["prf"] - if !ok { - return proofs - } - - prfSlice, ok := prfClaims.([]any) - if !ok { - return proofs - } - - for _, prfItem := range prfSlice { - if prfStr, ok := prfItem.(string); ok { - proofs = append(proofs, Proof(prfStr)) - } - } - - return proofs -} - -// parseFactsClaims parses the facts from claims -func parseFactsClaims(claims jwt.MapClaims) []Fact { - fctClaims, ok := claims["fct"] - if !ok { - return nil - } - - fctSlice, ok := fctClaims.([]any) - if !ok { - return nil - } - - // Pre-allocate slice with known capacity - facts := make([]Fact, 0, len(fctSlice)) - - for _, fctItem := range fctSlice { - factData, _ := json.Marshal(fctItem) - facts = append(facts, Fact{Data: factData}) - } - - return facts -} - -// parseAttenuation converts a map to an Attenuation struct with enhanced module-specific support -func (v *Verifier) parseAttenuation(attMap map[string]any) (Attenuation, error) { - // Extract capability - canValue, ok := attMap["can"] - if !ok { - return Attenuation{}, fmt.Errorf("missing 'can' field in attenuation") - } - - // Extract resource - withValue, ok := attMap["with"] - if !ok { - return Attenuation{}, fmt.Errorf("missing 'with' field in attenuation") - } - - withStr, ok := withValue.(string) - if !ok { - return Attenuation{}, fmt.Errorf("'with' field must be a string") - } - - // Parse resource first to determine module type - resource, err := v.parseResource(withStr) - if err != nil { - return Attenuation{}, fmt.Errorf("failed to parse resource: %w", err) - } - - // Create module-specific capability based on resource scheme - cap, err := v.createModuleSpecificCapability(resource.GetScheme(), canValue, attMap) - if err != nil { - return Attenuation{}, fmt.Errorf("failed to create capability: %w", err) - } - - return Attenuation{ - Capability: cap, - Resource: resource, - }, nil -} - -// createModuleSpecificCapability creates appropriate capability type based on module -func (v *Verifier) createModuleSpecificCapability(scheme string, canValue any, attMap map[string]any) (Capability, error) { - // Extract common fields - caveats := extractStringSliceFromMap(attMap, "caveats") - metadata := extractStringMapFromMap(attMap, "metadata") - - switch scheme { - case "did": - return v.createDIDCapability(canValue, caveats, metadata) - case "dwn": - return v.createDWNCapability(canValue, caveats, metadata) - case "service", "svc": - return v.createServiceCapability(canValue, caveats, metadata) - case "dex", "pool": - return v.createDEXCapability(canValue, caveats, metadata, attMap) - case "ipfs", "vault": - // Handle existing vault capabilities - return v.createVaultCapabilityFromMap(canValue, attMap) - default: - // Fallback to simple/multi capability for unknown schemes - return v.createGenericCapability(canValue) - } -} - -// createDIDCapability creates a DID-specific capability -func (v *Verifier) createDIDCapability(canValue any, caveats []string, metadata map[string]string) (Capability, error) { - switch canVal := canValue.(type) { - case string: - return &DIDCapability{ - Action: canVal, - Caveats: caveats, - Metadata: metadata, - }, nil - case []any: - actions := extractStringSlice(canVal) - return &DIDCapability{ - Actions: actions, - Caveats: caveats, - Metadata: metadata, - }, nil - default: - return nil, fmt.Errorf("unsupported DID capability type") - } -} - -// createDWNCapability creates a DWN-specific capability -func (v *Verifier) createDWNCapability(canValue any, caveats []string, metadata map[string]string) (Capability, error) { - switch canVal := canValue.(type) { - case string: - return &DWNCapability{ - Action: canVal, - Caveats: caveats, - Metadata: metadata, - }, nil - case []any: - actions := extractStringSlice(canVal) - return &DWNCapability{ - Actions: actions, - Caveats: caveats, - Metadata: metadata, - }, nil - default: - return nil, fmt.Errorf("unsupported DWN capability type") - } -} - -// createServiceCapability creates a Service-specific capability -func (v *Verifier) createServiceCapability(canValue any, caveats []string, metadata map[string]string) (Capability, error) { - // Service capabilities can still use MultiCapability for now - switch canVal := canValue.(type) { - case string: - return &MultiCapability{Actions: []string{canVal}}, nil - case []any: - actions := extractStringSlice(canVal) - return &MultiCapability{Actions: actions}, nil - default: - return nil, fmt.Errorf("unsupported Service capability type") - } -} - -// createDEXCapability creates a DEX-specific capability -func (v *Verifier) createDEXCapability(canValue any, caveats []string, metadata map[string]string, attMap map[string]any) (Capability, error) { - maxAmount, _ := attMap["max_amount"].(string) - - switch canVal := canValue.(type) { - case string: - return &DEXCapability{ - Action: canVal, - Caveats: caveats, - MaxAmount: maxAmount, - Metadata: metadata, - }, nil - case []any: - actions := extractStringSlice(canVal) - return &DEXCapability{ - Actions: actions, - Caveats: caveats, - MaxAmount: maxAmount, - Metadata: metadata, - }, nil - default: - return nil, fmt.Errorf("unsupported DEX capability type") - } -} - -// createVaultCapabilityFromMap creates vault capability from existing logic -func (v *Verifier) createVaultCapabilityFromMap(canValue any, attMap map[string]any) (Capability, error) { - // Use existing vault capability creation logic - vaultAddress, _ := attMap["vault"].(string) - caveats := extractStringSliceFromMap(attMap, "caveats") - - switch canVal := canValue.(type) { - case string: - return &VaultCapability{ - Action: canVal, - VaultAddress: vaultAddress, - Caveats: caveats, - }, nil - case []any: - actions := extractStringSlice(canVal) - return &VaultCapability{ - Actions: actions, - VaultAddress: vaultAddress, - Caveats: caveats, - }, nil - default: - return nil, fmt.Errorf("unsupported vault capability type") - } -} - -// createGenericCapability creates fallback capability for unknown schemes -func (v *Verifier) createGenericCapability(canValue any) (Capability, error) { - switch canVal := canValue.(type) { - case string: - return &SimpleCapability{Action: canVal}, nil - case []any: - actions := extractStringSlice(canVal) - return &MultiCapability{Actions: actions}, nil - default: - return nil, fmt.Errorf("unsupported capability type") - } -} - -// Helper functions for extracting data from maps -func extractStringSliceFromMap(m map[string]any, key string) []string { - if value, exists := m[key]; exists { - return extractStringSlice(value) - } - return nil -} - -func extractStringMapFromMap(m map[string]any, key string) map[string]string { - result := make(map[string]string) - if value, exists := m[key]; exists { - if mapValue, ok := value.(map[string]any); ok { - for k, v := range mapValue { - if strValue, ok := v.(string); ok { - result[k] = strValue - } - } - } - } - return result -} - -// parseResource creates a Resource from a URI string -func (v *Verifier) parseResource(uri string) (Resource, error) { - if uri == "" { - return nil, fmt.Errorf("resource URI cannot be empty") - } - - // Parse URI scheme and value - support both "scheme://value" and "scheme:value" formats - var scheme, value string - if strings.Contains(uri, "://") { - parts := strings.SplitN(uri, "://", 2) - if len(parts) == 2 { - scheme = parts[0] - value = parts[1] - } - } else if strings.Contains(uri, ":") { - parts := strings.SplitN(uri, ":", 2) - if len(parts) == 2 { - scheme = parts[0] - value = parts[1] - } - } - - if scheme == "" || value == "" { - return nil, fmt.Errorf("invalid resource URI format: %s", uri) - } - - return &SimpleResource{ - Scheme: scheme, - Value: value, - URI: uri, - }, nil -} - -// validateToken performs structural and temporal validation -func (v *Verifier) validateToken(_ context.Context, token *Token) error { - // Check required fields - if token.Issuer == "" { - return fmt.Errorf("issuer is required") - } - if token.Audience == "" { - return fmt.Errorf("audience is required") - } - if len(token.Attenuations) == 0 { - return fmt.Errorf("at least one attenuation is required") - } - - // Check temporal validity - now := time.Now().Unix() - - if token.NotBefore > 0 && now < token.NotBefore { - return fmt.Errorf("token is not yet valid (nbf: %d, now: %d)", token.NotBefore, now) - } - - if token.ExpiresAt > 0 && now >= token.ExpiresAt { - return fmt.Errorf("token has expired (exp: %d, now: %d)", token.ExpiresAt, now) - } - - return nil -} - -// checkCapabilities verifies that the token grants the required capabilities with enhanced module-specific validation -func (v *Verifier) checkCapabilities(token *Token, resource string, abilities []string) error { - for _, att := range token.Attenuations { - if att.Resource.GetURI() == resource { - if att.Capability.Grants(abilities) { - // Validate caveats for module-specific capabilities - if err := v.validateCaveats(att.Capability, att.Resource); err != nil { - return fmt.Errorf("caveat validation failed: %w", err) - } - return nil - } - } - } - return fmt.Errorf("required capabilities not granted for resource %s", resource) -} - -// validateCaveats validates constraints (caveats) for module-specific capabilities -func (v *Verifier) validateCaveats(cap Capability, resource Resource) error { - scheme := resource.GetScheme() - - switch scheme { - case "did": - return v.validateDIDCaveats(cap, resource) - case "dwn": - return v.validateDWNCaveats(cap, resource) - case "dex", "pool": - return v.validateDEXCaveats(cap, resource) - case "service", "svc": - return v.validateServiceCaveats(cap, resource) - case "vault", "ipfs": - return v.validateVaultCaveats(cap, resource) - default: - return nil // No caveat validation for unknown schemes - } -} - -// validateDIDCaveats validates DID-specific constraints -func (v *Verifier) validateDIDCaveats(cap Capability, resource Resource) error { - didCap, ok := cap.(*DIDCapability) - if !ok { - return nil // Not a DID capability - } - - for _, caveat := range didCap.Caveats { - switch caveat { - case "owner": - // Validate that the capability is for the owner's DID - if err := v.validateOwnerCaveat(resource); err != nil { - return fmt.Errorf("owner caveat validation failed: %w", err) - } - case "controller": - // Validate controller permissions - if err := v.validateControllerCaveat(resource); err != nil { - return fmt.Errorf("controller caveat validation failed: %w", err) - } - } - } - return nil -} - -// validateDWNCaveats validates DWN-specific constraints -func (v *Verifier) validateDWNCaveats(cap Capability, resource Resource) error { - dwnCap, ok := cap.(*DWNCapability) - if !ok { - return nil // Not a DWN capability - } - - for _, caveat := range dwnCap.Caveats { - switch caveat { - case "owner": - // Validate record ownership - if err := v.validateRecordOwnership(resource); err != nil { - return fmt.Errorf("record ownership validation failed: %w", err) - } - case "protocol": - // Validate protocol compliance - if err := v.validateProtocolCaveat(resource); err != nil { - return fmt.Errorf("protocol caveat validation failed: %w", err) - } - } - } - return nil -} - -// validateDEXCaveats validates DEX-specific constraints -func (v *Verifier) validateDEXCaveats(cap Capability, resource Resource) error { - dexCap, ok := cap.(*DEXCapability) - if !ok { - return nil // Not a DEX capability - } - - for _, caveat := range dexCap.Caveats { - switch caveat { - case "max-amount": - // Validate maximum swap amount - if dexCap.MaxAmount != "" { - if err := v.validateMaxAmountCaveat(dexCap.MaxAmount); err != nil { - return fmt.Errorf("max amount caveat validation failed: %w", err) - } - } - case "pool-member": - // Validate pool membership - if err := v.validatePoolMembershipCaveat(resource); err != nil { - return fmt.Errorf("pool membership validation failed: %w", err) - } - } - } - return nil -} - -// validateServiceCaveats validates Service-specific constraints -func (v *Verifier) validateServiceCaveats(cap Capability, resource Resource) error { - // Service capabilities use MultiCapability for now - // Add service-specific caveat validation if needed - return nil -} - -// validateVaultCaveats validates Vault-specific constraints -func (v *Verifier) validateVaultCaveats(cap Capability, resource Resource) error { - vaultCap, ok := cap.(*VaultCapability) - if !ok { - return nil // Not a vault capability - } - - for _, caveat := range vaultCap.Caveats { - switch caveat { - case "vault-owner": - // Validate vault ownership - if err := v.validateVaultOwnership(vaultCap.VaultAddress); err != nil { - return fmt.Errorf("vault ownership validation failed: %w", err) - } - case "enclave-integrity": - // Validate enclave data integrity - if err := v.validateEnclaveIntegrity(vaultCap.EnclaveDataCID); err != nil { - return fmt.Errorf("enclave integrity validation failed: %w", err) - } - } - } - return nil -} - -// Caveat validation helper methods (placeholders for actual implementation) - -// validateOwnerCaveat validates DID ownership constraint -func (v *Verifier) validateOwnerCaveat(resource Resource) error { - // Placeholder: Implement actual DID ownership validation - return nil -} - -// validateControllerCaveat validates DID controller constraint -func (v *Verifier) validateControllerCaveat(resource Resource) error { - // Placeholder: Implement actual controller validation - return nil -} - -// validateRecordOwnership validates DWN record ownership -func (v *Verifier) validateRecordOwnership(resource Resource) error { - // Placeholder: Implement actual record ownership validation - return nil -} - -// validateProtocolCaveat validates DWN protocol constraint -func (v *Verifier) validateProtocolCaveat(resource Resource) error { - // Placeholder: Implement actual protocol validation - return nil -} - -// validateMaxAmountCaveat validates DEX maximum amount constraint -func (v *Verifier) validateMaxAmountCaveat(maxAmount string) error { - // Placeholder: Implement actual amount validation - return nil -} - -// validatePoolMembershipCaveat validates DEX pool membership -func (v *Verifier) validatePoolMembershipCaveat(resource Resource) error { - // Placeholder: Implement actual pool membership validation - return nil -} - -// validateVaultOwnership validates vault ownership -func (v *Verifier) validateVaultOwnership(vaultAddress string) error { - // Placeholder: Implement actual vault ownership validation - return nil -} - -// validateEnclaveIntegrity validates enclave data integrity -func (v *Verifier) validateEnclaveIntegrity(enclaveDataCID string) error { - // Placeholder: Implement actual enclave integrity validation - return nil -} - -// validateDelegation checks that child token is properly attenuated from parent with enhanced module-specific validation -func (v *Verifier) validateDelegation(child, parent *Token) error { - // Child's issuer must be parent's audience - if child.Issuer != parent.Audience { - return fmt.Errorf("delegation chain broken: child issuer must be parent audience") - } - - // Child capabilities must be subset of parent with module-specific validation - for _, childAtt := range child.Attenuations { - if !v.isModuleCapabilitySubset(childAtt, parent.Attenuations) { - return fmt.Errorf("child capability exceeds parent capabilities") - } - } - - // Child expiration must not exceed parent - if parent.ExpiresAt > 0 && (child.ExpiresAt == 0 || child.ExpiresAt > parent.ExpiresAt) { - return fmt.Errorf("child token expires after parent token") - } - - // Validate cross-module delegation constraints - if err := v.validateCrossModuleDelegation(child, parent); err != nil { - return fmt.Errorf("cross-module delegation validation failed: %w", err) - } - - return nil -} - -// isModuleCapabilitySubset checks if a capability is a subset with module-specific logic -func (v *Verifier) isModuleCapabilitySubset(childAtt Attenuation, parentAtts []Attenuation) bool { - for _, parentAtt := range parentAtts { - if childAtt.Resource.GetURI() == parentAtt.Resource.GetURI() { - if v.isModuleCapabilityContained(childAtt.Capability, parentAtt.Capability, childAtt.Resource.GetScheme()) { - return true - } - } - } - return false -} - -// isModuleCapabilityContained checks containment with module-specific logic -func (v *Verifier) isModuleCapabilityContained(child, parent Capability, scheme string) bool { - // First check basic containment - if parent.Contains(child) { - // Additional module-specific containment validation - switch scheme { - case "did": - return v.validateDIDContainment(child, parent) - case "dwn": - return v.validateDWNContainment(child, parent) - case "dex", "pool": - return v.validateDEXContainment(child, parent) - case "vault", "ipfs": - return v.validateVaultContainment(child, parent) - default: - return true // Basic containment is sufficient for unknown schemes - } - } - return false -} - -// validateCrossModuleDelegation validates constraints across different modules -func (v *Verifier) validateCrossModuleDelegation(child, parent *Token) error { - childModules := v.extractModulesFromToken(child) - parentModules := v.extractModulesFromToken(parent) - - // Check if child uses modules not present in parent - for module := range childModules { - if _, exists := parentModules[module]; !exists { - return fmt.Errorf("child token uses module '%s' not delegated by parent", module) - } - } - - // Validate specific cross-module constraints - return v.validateSpecificCrossModuleConstraints(child, parent) -} - -// extractModulesFromToken extracts the modules used by a token -func (v *Verifier) extractModulesFromToken(token *Token) map[string]bool { - modules := make(map[string]bool) - for _, att := range token.Attenuations { - scheme := att.Resource.GetScheme() - modules[scheme] = true - } - return modules -} - -// validateSpecificCrossModuleConstraints validates specific cross-module business logic -func (v *Verifier) validateSpecificCrossModuleConstraints(child, parent *Token) error { - // Example: If DID operations require vault access, ensure both are present - childHasDID := v.tokenHasModule(child, "did") - childHasVault := v.tokenHasModule(child, "vault") || v.tokenHasModule(child, "ipfs") - - if childHasDID && !childHasVault { - // Check if parent has vault capability that can be inherited - parentHasVault := v.tokenHasModule(parent, "vault") || v.tokenHasModule(parent, "ipfs") - if !parentHasVault { - return fmt.Errorf("DID operations require vault access which is not available in delegation chain") - } - } - - // Add more cross-module constraints as needed - return nil -} - -// tokenHasModule checks if a token has capabilities for a specific module -func (v *Verifier) tokenHasModule(token *Token, module string) bool { - for _, att := range token.Attenuations { - if att.Resource.GetScheme() == module { - return true - } - } - return false -} - -// Module-specific containment validation methods - -// validateDIDContainment validates DID capability containment -func (v *Verifier) validateDIDContainment(child, parent Capability) bool { - childDID, childOk := child.(*DIDCapability) - parentDID, parentOk := parent.(*DIDCapability) - - if !childOk || !parentOk { - return true // Not both DID capabilities, basic containment applies - } - - // Validate that child caveats are more restrictive or equal - return v.areCaveatsMoreRestrictive(childDID.Caveats, parentDID.Caveats) -} - -// validateDWNContainment validates DWN capability containment -func (v *Verifier) validateDWNContainment(child, parent Capability) bool { - childDWN, childOk := child.(*DWNCapability) - parentDWN, parentOk := parent.(*DWNCapability) - - if !childOk || !parentOk { - return true // Not both DWN capabilities, basic containment applies - } - - // Validate that child caveats are more restrictive or equal - return v.areCaveatsMoreRestrictive(childDWN.Caveats, parentDWN.Caveats) -} - -// validateDEXContainment validates DEX capability containment -func (v *Verifier) validateDEXContainment(child, parent Capability) bool { - childDEX, childOk := child.(*DEXCapability) - parentDEX, parentOk := parent.(*DEXCapability) - - if !childOk || !parentOk { - return true // Not both DEX capabilities, basic containment applies - } - - // Validate max amount restriction - if parentDEX.MaxAmount != "" && childDEX.MaxAmount != "" { - // Child max amount should be less than or equal to parent - if !v.isAmountLessOrEqual(childDEX.MaxAmount, parentDEX.MaxAmount) { - return false - } - } else if parentDEX.MaxAmount != "" && childDEX.MaxAmount == "" { - // Child must have max amount if parent does - return false - } - - // Validate that child caveats are more restrictive or equal - return v.areCaveatsMoreRestrictive(childDEX.Caveats, parentDEX.Caveats) -} - -// validateVaultContainment validates Vault capability containment -func (v *Verifier) validateVaultContainment(child, parent Capability) bool { - childVault, childOk := child.(*VaultCapability) - parentVault, parentOk := parent.(*VaultCapability) - - if !childOk || !parentOk { - return true // Not both Vault capabilities, basic containment applies - } - - // Vault address must match - if childVault.VaultAddress != parentVault.VaultAddress { - return false - } - - // Validate that child caveats are more restrictive or equal - return v.areCaveatsMoreRestrictive(childVault.Caveats, parentVault.Caveats) -} - -// Helper methods for containment validation - -// areCaveatsMoreRestrictive checks if child caveats are more restrictive than parent -func (v *Verifier) areCaveatsMoreRestrictive(childCaveats, parentCaveats []string) bool { - parentCaveatSet := make(map[string]bool) - for _, caveat := range parentCaveats { - parentCaveatSet[caveat] = true - } - - // All child caveats must be present in parent caveats (or child can have additional restrictions) - for _, childCaveat := range childCaveats { - if !parentCaveatSet[childCaveat] { - // Child has additional restrictions, which is allowed - continue - } - } - - return true -} - -// isAmountLessOrEqual compares two amount strings (placeholder implementation) -func (v *Verifier) isAmountLessOrEqual(childAmount, parentAmount string) bool { - // Placeholder: Implement actual amount comparison - // This would parse the amounts and compare them numerically - return true -} - -// isCapabilitySubset checks if a capability is a subset of any parent capabilities -func (v *Verifier) isCapabilitySubset(childAtt Attenuation, parentAtts []Attenuation) bool { - for _, parentAtt := range parentAtts { - if childAtt.Resource.GetURI() == parentAtt.Resource.GetURI() { - if parentAtt.Capability.Contains(childAtt.Capability) { - return true - } - } - } - return false -} - -// getRSAPublicKey extracts RSA public key from DID -func (v *Verifier) getRSAPublicKey(did keys.DID) (*rsa.PublicKey, error) { - verifyKey, err := did.VerifyKey() - if err != nil { - return nil, fmt.Errorf("failed to get verify key: %w", err) - } - - rsaKey, ok := verifyKey.(*rsa.PublicKey) - if !ok { - return nil, fmt.Errorf("DID does not contain RSA public key") - } - - return rsaKey, nil -} - -// getEd25519PublicKey extracts Ed25519 public key from DID -func (v *Verifier) getEd25519PublicKey(did keys.DID) (ed25519.PublicKey, error) { - pubKey := did.PublicKey() - rawBytes, err := pubKey.Raw() - if err != nil { - return nil, fmt.Errorf("failed to get raw public key: %w", err) - } - - if pubKey.Type() != crypto.Ed25519 { - return nil, fmt.Errorf("DID does not contain Ed25519 public key") - } - - return ed25519.PublicKey(rawBytes), nil -} - -// StringDIDResolver implements DIDResolver for did:key strings -type StringDIDResolver struct{} - -// ResolveDIDKey extracts a public key from a did:key string -func (StringDIDResolver) ResolveDIDKey(ctx context.Context, didStr string) (keys.DID, error) { - return keys.Parse(didStr) -} diff --git a/crypto/vrf/vrf.go b/crypto/vrf/vrf.go deleted file mode 100644 index 46e2e97c0..000000000 --- a/crypto/vrf/vrf.go +++ /dev/null @@ -1,231 +0,0 @@ -// Package vrf implements a verifiable random function using the Edwards form -// of Curve25519, SHA3 and the Elligator map. -// -// E is Curve25519 (in Edwards coordinates), h is SHA3. -// f is the elligator map (bytes->E) that covers half of E. -// 8 is the cofactor of E, the group order is 8*l for prime l. -// Setup : the prover publicly commits to a public key (P : E) -// H : names -> E -// H(n) = f(h(n))^8 -// VRF : keys -> names -> vrfs -// VRF_x(n) = h(n, H(n)^x)) -// Prove : keys -> names -> proofs -// Prove_x(n) = tuple(c=h(n, g^r, H(n)^r), t=r-c*x, ii=H(n)^x) -// where r = h(x, n) is used as a source of randomness -// Check : E -> names -> vrfs -> proofs -> bool -// Check(P, n, vrf, (c,t,ii)) = vrf == h(n, ii) -// && c == h(n, g^t*P^c, H(n)^t*ii^c) -package vrf - -import ( - "bytes" - "crypto/rand" - "errors" - "io" - - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/internal/ed25519/edwards25519" - "github.com/sonr-io/sonr/crypto/internal/ed25519/extra25519" - "golang.org/x/crypto/ed25519" -) - -const ( - PublicKeySize = 32 - PrivateKeySize = 64 - Size = 32 - intermediateSize = 32 - ProofSize = 32 + 32 + intermediateSize -) - -var ErrGetPubKey = errors.New("[vrf] Couldn't get corresponding public-key from private-key") - -type ( - PrivateKey []byte - PublicKey []byte -) - -// GenerateKey creates a public/private key pair using rnd for randomness. -// If rnd is nil, crypto/rand is used. -func GenerateKey(rnd io.Reader) (sk PrivateKey, err error) { - if rnd == nil { - rnd = rand.Reader - } - sk = make([]byte, 64) - _, err = io.ReadFull(rnd, sk[:32]) - if err != nil { - return sk, err - } - x, _ := sk.expandSecret() - - var pkP edwards25519.ExtendedGroupElement - edwards25519.GeScalarMultBase(&pkP, x) - var pkBytes [PublicKeySize]byte - pkP.ToBytes(&pkBytes) - - copy(sk[32:], pkBytes[:]) - return sk, err -} - -// Public extracts the public VRF key from the underlying private-key -// and returns a boolean indicating if the operation was successful. -func (sk PrivateKey) Public() (PublicKey, bool) { - pk, ok := ed25519.PrivateKey(sk).Public().(ed25519.PublicKey) - return PublicKey(pk), ok -} - -func (sk PrivateKey) expandSecret() (x, skhr *[32]byte) { - x, skhr = new([32]byte), new([32]byte) - hash := sha3.NewShake256() - hash.Write(sk[:32]) - hash.Read(x[:]) - hash.Read(skhr[:]) - x[0] &= 248 - x[31] &= 127 - x[31] |= 64 - return x, skhr -} - -// Compute generates the vrf value for the byte slice m using the -// underlying private key sk. -func (sk PrivateKey) Compute(m []byte) []byte { - x, _ := sk.expandSecret() - var ii edwards25519.ExtendedGroupElement - var iiB [32]byte - edwards25519.GeScalarMult(&ii, x, hashToCurve(m)) - ii.ToBytes(&iiB) - - hash := sha3.NewShake256() - hash.Write(iiB[:]) // const length: Size - hash.Write(m) - var vrf [Size]byte - hash.Read(vrf[:]) - return vrf[:] -} - -func hashToCurve(m []byte) *edwards25519.ExtendedGroupElement { - // H(n) = (f(h(n))^8) - var hmb [32]byte - sha3.ShakeSum256(hmb[:], m) - var hm edwards25519.ExtendedGroupElement - extra25519.HashToEdwards(&hm, &hmb) - edwards25519.GeDouble(&hm, &hm) - edwards25519.GeDouble(&hm, &hm) - edwards25519.GeDouble(&hm, &hm) - return &hm -} - -// Prove returns the vrf value and a proof such that -// Verify(m, vrf, proof) == true. The vrf value is the -// same as returned by Compute(m). -func (sk PrivateKey) Prove(m []byte) (vrf, proof []byte) { - x, skhr := sk.expandSecret() - var sH, rH [64]byte - var r, s, minusS, t, gB, grB, hrB, hxB, hB [32]byte - var ii, gr, hr edwards25519.ExtendedGroupElement - - h := hashToCurve(m) - h.ToBytes(&hB) - edwards25519.GeScalarMult(&ii, x, h) - ii.ToBytes(&hxB) - - // use hash of private-, public-key and msg as randomness source: - hash := sha3.NewShake256() - hash.Write(skhr[:]) - hash.Write(sk[32:]) // public key, as in ed25519 - hash.Write(m) - hash.Read(rH[:]) - hash.Reset() - edwards25519.ScReduce(&r, &rH) - - edwards25519.GeScalarMultBase(&gr, &r) - edwards25519.GeScalarMult(&hr, &r, h) - gr.ToBytes(&grB) - hr.ToBytes(&hrB) - gB = edwards25519.BaseBytes - - // H2(g, h, g^x, h^x, g^r, h^r, m) - hash.Write(gB[:]) - hash.Write(hB[:]) - hash.Write(sk[32:]) // ed25519 public-key - hash.Write(hxB[:]) - hash.Write(grB[:]) - hash.Write(hrB[:]) - hash.Write(m) - hash.Read(sH[:]) - hash.Reset() - edwards25519.ScReduce(&s, &sH) - - edwards25519.ScNeg(&minusS, &s) - edwards25519.ScMulAdd(&t, x, &minusS, &r) - - proof = make([]byte, ProofSize) - copy(proof[:32], s[:]) - copy(proof[32:64], t[:]) - copy(proof[64:96], hxB[:]) - - hash.Write(hxB[:]) - hash.Write(m) - vrf = make([]byte, Size) - hash.Read(vrf[:]) - return vrf, proof -} - -// Verify returns true iff vrf=Compute(m) for the sk that -// corresponds to pk. -func (pkBytes PublicKey) Verify(m, vrfBytes, proof []byte) bool { - if len(proof) != ProofSize || len(vrfBytes) != Size || len(pkBytes) != PublicKeySize { - return false - } - var pk, s, sRef, t, vrf, hxB, hB, gB, ABytes, BBytes [32]byte - copy(vrf[:], vrfBytes) - copy(pk[:], pkBytes[:]) - copy(s[:32], proof[:32]) - copy(t[:32], proof[32:64]) - copy(hxB[:], proof[64:96]) - - hash := sha3.NewShake256() - hash.Write(hxB[:]) // const length - hash.Write(m) - var hCheck [Size]byte - hash.Read(hCheck[:]) - if !bytes.Equal(hCheck[:], vrf[:]) { - return false - } - hash.Reset() - - var P, B, ii, iic edwards25519.ExtendedGroupElement - var A, hmtP, iicP edwards25519.ProjectiveGroupElement - if !P.FromBytesBaseGroup(&pk) { - return false - } - if !ii.FromBytesBaseGroup(&hxB) { - return false - } - edwards25519.GeDoubleScalarMultVartime(&A, &s, &P, &t) - A.ToBytes(&ABytes) - gB = edwards25519.BaseBytes - - h := hashToCurve(m) // h = H1(m) - h.ToBytes(&hB) - edwards25519.GeDoubleScalarMultVartime(&hmtP, &t, h, &[32]byte{}) - edwards25519.GeDoubleScalarMultVartime(&iicP, &s, &ii, &[32]byte{}) - iicP.ToExtended(&iic) - hmtP.ToExtended(&B) - edwards25519.GeAdd(&B, &B, &iic) - B.ToBytes(&BBytes) - - var sH [64]byte - // sRef = H2(g, h, g^x, v, g^t·G^s,H1(m)^t·v^s, m), with v=H1(m)^x=h^x - hash.Write(gB[:]) - hash.Write(hB[:]) - hash.Write(pkBytes) - hash.Write(hxB[:]) - hash.Write(ABytes[:]) // const length (g^t*G^s) - hash.Write(BBytes[:]) // const length (H1(m)^t*v^s) - hash.Write(m) - hash.Read(sH[:]) - - edwards25519.ScReduce(&sRef, &sH) - return sRef == s -} diff --git a/crypto/vrf/vrf_test.go b/crypto/vrf/vrf_test.go deleted file mode 100644 index 5752a6667..000000000 --- a/crypto/vrf/vrf_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package vrf - -import ( - "bytes" - "testing" - // "fmt" -) - -func TestHonestComplete(t *testing.T) { - sk, err := GenerateKey(nil) - if err != nil { - t.Fatal(err) - } - pk, _ := sk.Public() - alice := []byte("alice") - aliceVRF := sk.Compute(alice) - aliceVRFFromProof, aliceProof := sk.Prove(alice) - - // fmt.Printf("pk: %X\n", pk) - // fmt.Printf("sk: %X\n", *sk) - // fmt.Printf("alice(bytes): %X\n", alice) - // fmt.Printf("aliceVRF: %X\n", aliceVRF) - // fmt.Printf("aliceProof: %X\n", aliceProof) - - if !pk.Verify(alice, aliceVRF, aliceProof) { - t.Error("Gen -> Compute -> Prove -> Verify -> FALSE") - } - if !bytes.Equal(aliceVRF, aliceVRFFromProof) { - t.Error("Compute != Prove") - } -} - -func TestConvertPrivateKeyToPublicKey(t *testing.T) { - sk, err := GenerateKey(nil) - if err != nil { - t.Fatal(err) - } - - pk, ok := sk.Public() - if !ok { - t.Fatal("Couldn't obtain public key.") - } - if !bytes.Equal(sk[32:], pk) { - t.Fatal("Raw byte respresentation doesn't match public key.") - } -} - -func TestFlipBitForgery(t *testing.T) { - sk, err := GenerateKey(nil) - if err != nil { - t.Fatal(err) - } - pk, _ := sk.Public() - alice := []byte("alice") - for i := 0; i < 32; i++ { - for j := uint(0); j < 8; j++ { - aliceVRF := sk.Compute(alice) - aliceVRF[i] ^= 1 << j - _, aliceProof := sk.Prove(alice) - if pk.Verify(alice, aliceVRF, aliceProof) { - t.Fatalf("forged by using aliceVRF[%d]^=%d:\n (sk=%x)", i, j, sk) - } - } - } -} - -func BenchmarkHashToGE(b *testing.B) { - alice := []byte("alice") - b.ResetTimer() - for n := 0; n < b.N; n++ { - hashToCurve(alice) - } -} - -func BenchmarkCompute(b *testing.B) { - sk, err := GenerateKey(nil) - if err != nil { - b.Fatal(err) - } - alice := []byte("alice") - b.ResetTimer() - for n := 0; n < b.N; n++ { - sk.Compute(alice) - } -} - -func BenchmarkProve(b *testing.B) { - sk, err := GenerateKey(nil) - if err != nil { - b.Fatal(err) - } - alice := []byte("alice") - b.ResetTimer() - for n := 0; n < b.N; n++ { - sk.Prove(alice) - } -} - -func BenchmarkVerify(b *testing.B) { - sk, err := GenerateKey(nil) - if err != nil { - b.Fatal(err) - } - alice := []byte("alice") - aliceVRF := sk.Compute(alice) - _, aliceProof := sk.Prove(alice) - pk, _ := sk.Public() - b.ResetTimer() - for n := 0; n < b.N; n++ { - pk.Verify(alice, aliceVRF, aliceProof) - } -} diff --git a/crypto/wasm/signer.go b/crypto/wasm/signer.go deleted file mode 100644 index e27e1130c..000000000 --- a/crypto/wasm/signer.go +++ /dev/null @@ -1,336 +0,0 @@ -// Package wasm provides cryptographic signing and verification for WebAssembly modules -package wasm - -import ( - "crypto/ed25519" - "crypto/rand" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "sync" - "time" -) - -// Signer provides Ed25519 digital signature operations for WASM modules -type Signer struct { - privateKey ed25519.PrivateKey - publicKey ed25519.PublicKey -} - -// NewSigner creates a new signer with a generated Ed25519 key pair -func NewSigner() (*Signer, error) { - pub, priv, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - return nil, fmt.Errorf("failed to generate Ed25519 key pair: %w", err) - } - - return &Signer{ - privateKey: priv, - publicKey: pub, - }, nil -} - -// NewSignerFromPrivateKey creates a signer from an existing private key -func NewSignerFromPrivateKey(privateKey ed25519.PrivateKey) (*Signer, error) { - if len(privateKey) != ed25519.PrivateKeySize { - return nil, fmt.Errorf("invalid private key size: expected %d, got %d", - ed25519.PrivateKeySize, len(privateKey)) - } - - publicKey := privateKey.Public().(ed25519.PublicKey) - - return &Signer{ - privateKey: privateKey, - publicKey: publicKey, - }, nil -} - -// Sign creates an Ed25519 signature for the given WASM bytecode -func (s *Signer) Sign(wasmBytes []byte) ([]byte, error) { - if s.privateKey == nil { - return nil, fmt.Errorf("private key not initialized") - } - - signature := ed25519.Sign(s.privateKey, wasmBytes) - return signature, nil -} - -// GetPublicKey returns the public key bytes -func (s *Signer) GetPublicKey() []byte { - return s.publicKey -} - -// GetPublicKeyHex returns the public key as hex string -func (s *Signer) GetPublicKeyHex() string { - return hex.EncodeToString(s.publicKey) -} - -// ExportPrivateKey exports the private key (handle with care) -func (s *Signer) ExportPrivateKey() []byte { - return s.privateKey -} - -// SignatureVerifier verifies Ed25519 signatures on WASM modules -type SignatureVerifier struct { - trustedKeys map[string]ed25519.PublicKey - mu sync.RWMutex -} - -// NewSignatureVerifier creates a new signature verifier -func NewSignatureVerifier() *SignatureVerifier { - return &SignatureVerifier{ - trustedKeys: make(map[string]ed25519.PublicKey), - } -} - -// AddTrustedKey adds a trusted public key for signature verification -func (v *SignatureVerifier) AddTrustedKey(keyID string, publicKey ed25519.PublicKey) error { - if len(publicKey) != ed25519.PublicKeySize { - return fmt.Errorf("invalid public key size: expected %d, got %d", - ed25519.PublicKeySize, len(publicKey)) - } - - v.mu.Lock() - defer v.mu.Unlock() - v.trustedKeys[keyID] = publicKey - return nil -} - -// AddTrustedKeyFromHex adds a trusted public key from hex string -func (v *SignatureVerifier) AddTrustedKeyFromHex(keyID string, publicKeyHex string) error { - publicKey, err := hex.DecodeString(publicKeyHex) - if err != nil { - return fmt.Errorf("failed to decode public key hex: %w", err) - } - - return v.AddTrustedKey(keyID, ed25519.PublicKey(publicKey)) -} - -// Verify verifies a signature against trusted public keys -func (v *SignatureVerifier) Verify(wasmBytes []byte, signature []byte) error { - v.mu.RLock() - defer v.mu.RUnlock() - - if len(v.trustedKeys) == 0 { - return fmt.Errorf("no trusted keys configured") - } - - // Try to verify with any trusted key - for keyID, publicKey := range v.trustedKeys { - if ed25519.Verify(publicKey, wasmBytes, signature) { - // Signature valid with this key - return nil - } - _ = keyID // Key ID available for logging if needed - } - - return fmt.Errorf("signature verification failed: no matching trusted key") -} - -// VerifyWithKey verifies a signature with a specific key -func (v *SignatureVerifier) VerifyWithKey(keyID string, wasmBytes []byte, signature []byte) error { - v.mu.RLock() - publicKey, exists := v.trustedKeys[keyID] - v.mu.RUnlock() - - if !exists { - return fmt.Errorf("trusted key not found: %s", keyID) - } - - if !ed25519.Verify(publicKey, wasmBytes, signature) { - return fmt.Errorf("signature verification failed for key: %s", keyID) - } - - return nil -} - -// RemoveTrustedKey removes a trusted key -func (v *SignatureVerifier) RemoveTrustedKey(keyID string) { - v.mu.Lock() - defer v.mu.Unlock() - delete(v.trustedKeys, keyID) -} - -// GetTrustedKeyIDs returns all trusted key IDs -func (v *SignatureVerifier) GetTrustedKeyIDs() []string { - v.mu.RLock() - defer v.mu.RUnlock() - - ids := make([]string, 0, len(v.trustedKeys)) - for id := range v.trustedKeys { - ids = append(ids, id) - } - return ids -} - -// SignedModule represents a WASM module with its signature -type SignedModule struct { - Module []byte `json:"-"` // WASM bytecode (excluded from JSON) - Hash string `json:"hash"` // SHA256 hash of module - Signature []byte `json:"signature"` // Ed25519 signature - SignerID string `json:"signer_id"` // ID of signing key - Timestamp time.Time `json:"timestamp"` // Signing timestamp - Version string `json:"version"` // Module version -} - -// SignModule creates a signed module package -func SignModule(signer *Signer, module []byte, signerID string, version string) (*SignedModule, error) { - // Compute hash - hashVerifier := NewHashVerifier() - hash := hashVerifier.ComputeHash(module) - - // Sign the module - signature, err := signer.Sign(module) - if err != nil { - return nil, fmt.Errorf("failed to sign module: %w", err) - } - - return &SignedModule{ - Module: module, - Hash: hash, - Signature: signature, - SignerID: signerID, - Timestamp: time.Now(), - Version: version, - }, nil -} - -// VerifySignedModule verifies a signed module -func VerifySignedModule(verifier *SignatureVerifier, module *SignedModule) error { - // Verify hash matches - hashVerifier := NewHashVerifier() - computedHash := hashVerifier.ComputeHash(module.Module) - if computedHash != module.Hash { - return fmt.Errorf("hash mismatch: expected %s, got %s", module.Hash, computedHash) - } - - // Verify signature - if module.SignerID != "" { - return verifier.VerifyWithKey(module.SignerID, module.Module, module.Signature) - } - - return verifier.Verify(module.Module, module.Signature) -} - -// SignatureManifest contains signature metadata for a WASM module -type SignatureManifest struct { - ModuleHash string `json:"module_hash"` - Signatures []SignatureEntry `json:"signatures"` - TrustedKeys []TrustedKeyEntry `json:"trusted_keys"` - CreatedAt time.Time `json:"created_at"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// SignatureEntry represents a single signature in the manifest -type SignatureEntry struct { - Signature string `json:"signature"` // Base64 encoded - SignerID string `json:"signer_id"` - Timestamp time.Time `json:"timestamp"` - Algorithm string `json:"algorithm"` // Always "Ed25519" -} - -// TrustedKeyEntry represents a trusted public key -type TrustedKeyEntry struct { - KeyID string `json:"key_id"` - PublicKey string `json:"public_key"` // Base64 encoded - AddedAt time.Time `json:"added_at"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` - Purpose string `json:"purpose"` // e.g., "code-signing" -} - -// CreateSignatureManifest creates a manifest for module signatures -func CreateSignatureManifest(module []byte, signer *Signer, signerID string) (*SignatureManifest, error) { - hashVerifier := NewHashVerifier() - moduleHash := hashVerifier.ComputeHash(module) - - signature, err := signer.Sign(module) - if err != nil { - return nil, fmt.Errorf("failed to sign module: %w", err) - } - - manifest := &SignatureManifest{ - ModuleHash: moduleHash, - Signatures: []SignatureEntry{ - { - Signature: base64.StdEncoding.EncodeToString(signature), - SignerID: signerID, - Timestamp: time.Now(), - Algorithm: "Ed25519", - }, - }, - TrustedKeys: []TrustedKeyEntry{ - { - KeyID: signerID, - PublicKey: base64.StdEncoding.EncodeToString(signer.GetPublicKey()), - AddedAt: time.Now(), - Purpose: "code-signing", - }, - }, - CreatedAt: time.Now(), - } - - return manifest, nil -} - -// VerifyWithManifest verifies a module using a signature manifest -func VerifyWithManifest(module []byte, manifest *SignatureManifest) error { - // Verify hash - hashVerifier := NewHashVerifier() - computedHash := hashVerifier.ComputeHash(module) - if computedHash != manifest.ModuleHash { - return fmt.Errorf("module hash mismatch") - } - - // Check expiration - if manifest.ExpiresAt != nil && time.Now().After(*manifest.ExpiresAt) { - return fmt.Errorf("signature manifest has expired") - } - - // Create verifier with trusted keys from manifest - verifier := NewSignatureVerifier() - for _, key := range manifest.TrustedKeys { - // Check key expiration - if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) { - continue // Skip expired keys - } - - publicKey, err := base64.StdEncoding.DecodeString(key.PublicKey) - if err != nil { - return fmt.Errorf("failed to decode public key: %w", err) - } - - if err := verifier.AddTrustedKey(key.KeyID, ed25519.PublicKey(publicKey)); err != nil { - return fmt.Errorf("failed to add trusted key: %w", err) - } - } - - // Verify at least one signature - for _, sig := range manifest.Signatures { - signature, err := base64.StdEncoding.DecodeString(sig.Signature) - if err != nil { - continue // Skip invalid signatures - } - - if err := verifier.VerifyWithKey(sig.SignerID, module, signature); err == nil { - // At least one valid signature found - return nil - } - } - - return fmt.Errorf("no valid signatures found in manifest") -} - -// ExportManifest exports a signature manifest as JSON -func ExportManifest(manifest *SignatureManifest) ([]byte, error) { - return json.MarshalIndent(manifest, "", " ") -} - -// ImportManifest imports a signature manifest from JSON -func ImportManifest(data []byte) (*SignatureManifest, error) { - var manifest SignatureManifest - if err := json.Unmarshal(data, &manifest); err != nil { - return nil, fmt.Errorf("failed to parse manifest: %w", err) - } - return &manifest, nil -} diff --git a/crypto/wasm/signer_test.go b/crypto/wasm/signer_test.go deleted file mode 100644 index e8e16fe6a..000000000 --- a/crypto/wasm/signer_test.go +++ /dev/null @@ -1,361 +0,0 @@ -package wasm - -import ( - "crypto/ed25519" - "crypto/rand" - "encoding/base64" - "encoding/hex" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestSigner_NewSigner(t *testing.T) { - signer, err := NewSigner() - require.NoError(t, err) - require.NotNil(t, signer) - - assert.NotNil(t, signer.privateKey) - assert.NotNil(t, signer.publicKey) - assert.Equal(t, ed25519.PrivateKeySize, len(signer.privateKey)) - assert.Equal(t, ed25519.PublicKeySize, len(signer.publicKey)) -} - -func TestSigner_NewSignerFromPrivateKey(t *testing.T) { - // Generate a key pair - pub, priv, err := ed25519.GenerateKey(rand.Reader) - require.NoError(t, err) - - // Create signer from private key - signer, err := NewSignerFromPrivateKey(priv) - require.NoError(t, err) - - assert.Equal(t, priv, signer.privateKey) - assert.Equal(t, pub, signer.publicKey) - - // Test invalid key size - invalidKey := []byte("too short") - _, err = NewSignerFromPrivateKey(ed25519.PrivateKey(invalidKey)) - assert.Error(t, err) - assert.Contains(t, err.Error(), "invalid private key size") -} - -func TestSigner_Sign(t *testing.T) { - signer, err := NewSigner() - require.NoError(t, err) - - // Test data - wasmBytes := []byte("test wasm module content") - - // Sign the data - signature, err := signer.Sign(wasmBytes) - require.NoError(t, err) - assert.Equal(t, ed25519.SignatureSize, len(signature)) - - // Verify the signature - valid := ed25519.Verify(signer.publicKey, wasmBytes, signature) - assert.True(t, valid) - - // Test signing different data produces different signature - differentData := []byte("different content") - signature2, err := signer.Sign(differentData) - require.NoError(t, err) - assert.NotEqual(t, signature, signature2) -} - -func TestSignatureVerifier_AddTrustedKey(t *testing.T) { - verifier := NewSignatureVerifier() - - // Generate a key pair - pub, _, err := ed25519.GenerateKey(rand.Reader) - require.NoError(t, err) - - // Add trusted key - err = verifier.AddTrustedKey("test-key", pub) - assert.NoError(t, err) - - // Test invalid key size - invalidKey := []byte("invalid") - err = verifier.AddTrustedKey("invalid-key", ed25519.PublicKey(invalidKey)) - assert.Error(t, err) - assert.Contains(t, err.Error(), "invalid public key size") -} - -func TestSignatureVerifier_AddTrustedKeyFromHex(t *testing.T) { - verifier := NewSignatureVerifier() - - // Generate a key pair - pub, _, err := ed25519.GenerateKey(rand.Reader) - require.NoError(t, err) - - // Add key from hex - hexKey := hex.EncodeToString(pub) - err = verifier.AddTrustedKeyFromHex("hex-key", hexKey) - assert.NoError(t, err) - - // Test invalid hex - err = verifier.AddTrustedKeyFromHex("bad-hex", "not-hex") - assert.Error(t, err) -} - -func TestSignatureVerifier_Verify(t *testing.T) { - // Create signer and verifier - signer, err := NewSigner() - require.NoError(t, err) - - verifier := NewSignatureVerifier() - - // Test data - wasmBytes := []byte("test wasm module") - - // Sign the data - signature, err := signer.Sign(wasmBytes) - require.NoError(t, err) - - // Test verification without trusted keys - err = verifier.Verify(wasmBytes, signature) - assert.Error(t, err) - assert.Contains(t, err.Error(), "no trusted keys") - - // Add trusted key - err = verifier.AddTrustedKey("signer1", signer.publicKey) - require.NoError(t, err) - - // Test successful verification - err = verifier.Verify(wasmBytes, signature) - assert.NoError(t, err) - - // Test verification with wrong data - wrongData := []byte("wrong data") - err = verifier.Verify(wrongData, signature) - assert.Error(t, err) - assert.Contains(t, err.Error(), "signature verification failed") - - // Test verification with wrong signature - wrongSignature := make([]byte, ed25519.SignatureSize) - err = verifier.Verify(wasmBytes, wrongSignature) - assert.Error(t, err) -} - -func TestSignatureVerifier_VerifyWithKey(t *testing.T) { - signer1, err := NewSigner() - require.NoError(t, err) - - signer2, err := NewSigner() - require.NoError(t, err) - - verifier := NewSignatureVerifier() - verifier.AddTrustedKey("key1", signer1.publicKey) - verifier.AddTrustedKey("key2", signer2.publicKey) - - wasmBytes := []byte("test module") - signature1, _ := signer1.Sign(wasmBytes) - signature2, _ := signer2.Sign(wasmBytes) - - // Verify with correct key - err = verifier.VerifyWithKey("key1", wasmBytes, signature1) - assert.NoError(t, err) - - err = verifier.VerifyWithKey("key2", wasmBytes, signature2) - assert.NoError(t, err) - - // Verify with wrong key - err = verifier.VerifyWithKey("key1", wasmBytes, signature2) - assert.Error(t, err) - - // Verify with non-existent key - err = verifier.VerifyWithKey("key3", wasmBytes, signature1) - assert.Error(t, err) - assert.Contains(t, err.Error(), "trusted key not found") -} - -func TestSignatureVerifier_Management(t *testing.T) { - verifier := NewSignatureVerifier() - - // Generate keys - pub1, _, _ := ed25519.GenerateKey(rand.Reader) - pub2, _, _ := ed25519.GenerateKey(rand.Reader) - - // Add keys - verifier.AddTrustedKey("key1", pub1) - verifier.AddTrustedKey("key2", pub2) - - // Get key IDs - ids := verifier.GetTrustedKeyIDs() - assert.Len(t, ids, 2) - assert.Contains(t, ids, "key1") - assert.Contains(t, ids, "key2") - - // Remove key - verifier.RemoveTrustedKey("key1") - ids = verifier.GetTrustedKeyIDs() - assert.Len(t, ids, 1) - assert.NotContains(t, ids, "key1") - assert.Contains(t, ids, "key2") -} - -func TestSignedModule(t *testing.T) { - signer, err := NewSigner() - require.NoError(t, err) - - module := []byte("test wasm module") - signerID := "test-signer" - version := "v1.0.0" - - // Create signed module - signed, err := SignModule(signer, module, signerID, version) - require.NoError(t, err) - - assert.Equal(t, module, signed.Module) - assert.NotEmpty(t, signed.Hash) - assert.NotEmpty(t, signed.Signature) - assert.Equal(t, signerID, signed.SignerID) - assert.Equal(t, version, signed.Version) - assert.False(t, signed.Timestamp.IsZero()) - - // Verify signed module - verifier := NewSignatureVerifier() - verifier.AddTrustedKey(signerID, signer.publicKey) - - err = VerifySignedModule(verifier, signed) - assert.NoError(t, err) - - // Test with tampered module - signed.Module = []byte("tampered") - err = VerifySignedModule(verifier, signed) - assert.Error(t, err) - assert.Contains(t, err.Error(), "hash mismatch") -} - -func TestSignatureManifest(t *testing.T) { - signer, err := NewSigner() - require.NoError(t, err) - - module := []byte("test wasm module") - signerID := "manifest-signer" - - // Create manifest - manifest, err := CreateSignatureManifest(module, signer, signerID) - require.NoError(t, err) - - assert.NotEmpty(t, manifest.ModuleHash) - assert.Len(t, manifest.Signatures, 1) - assert.Len(t, manifest.TrustedKeys, 1) - assert.Equal(t, signerID, manifest.Signatures[0].SignerID) - assert.Equal(t, "Ed25519", manifest.Signatures[0].Algorithm) - assert.Equal(t, signerID, manifest.TrustedKeys[0].KeyID) - assert.Equal(t, "code-signing", manifest.TrustedKeys[0].Purpose) - - // Verify with manifest - err = VerifyWithManifest(module, manifest) - assert.NoError(t, err) - - // Test with wrong module - wrongModule := []byte("wrong module") - err = VerifyWithManifest(wrongModule, manifest) - assert.Error(t, err) - assert.Contains(t, err.Error(), "hash mismatch") - - // Test with expired manifest - expired := time.Now().Add(-1 * time.Hour) - manifest.ExpiresAt = &expired - err = VerifyWithManifest(module, manifest) - assert.Error(t, err) - assert.Contains(t, err.Error(), "expired") -} - -func TestManifestSerialization(t *testing.T) { - signer, err := NewSigner() - require.NoError(t, err) - - module := []byte("test module") - manifest, err := CreateSignatureManifest(module, signer, "test-key") - require.NoError(t, err) - - // Export manifest - data, err := ExportManifest(manifest) - require.NoError(t, err) - assert.NotEmpty(t, data) - - // Import manifest - imported, err := ImportManifest(data) - require.NoError(t, err) - - assert.Equal(t, manifest.ModuleHash, imported.ModuleHash) - assert.Len(t, imported.Signatures, 1) - assert.Len(t, imported.TrustedKeys, 1) - - // Verify imported manifest - err = VerifyWithManifest(module, imported) - assert.NoError(t, err) - - // Test invalid JSON - _, err = ImportManifest([]byte("invalid json")) - assert.Error(t, err) -} - -func TestMultipleSignatures(t *testing.T) { - // Create multiple signers - signer1, _ := NewSigner() - signer2, _ := NewSigner() - - module := []byte("multi-signed module") - - // Create manifest with first signature - manifest, err := CreateSignatureManifest(module, signer1, "signer1") - require.NoError(t, err) - - // Add second signature - signature2, _ := signer2.Sign(module) - manifest.Signatures = append(manifest.Signatures, SignatureEntry{ - Signature: base64.StdEncoding.EncodeToString(signature2), - SignerID: "signer2", - Timestamp: time.Now(), - Algorithm: "Ed25519", - }) - - manifest.TrustedKeys = append(manifest.TrustedKeys, TrustedKeyEntry{ - KeyID: "signer2", - PublicKey: base64.StdEncoding.EncodeToString(signer2.GetPublicKey()), - AddedAt: time.Now(), - Purpose: "code-signing", - }) - - // Verify with either signature - err = VerifyWithManifest(module, manifest) - assert.NoError(t, err) - - // Remove first signature and key - manifest.Signatures = manifest.Signatures[1:] - manifest.TrustedKeys = manifest.TrustedKeys[1:] - - // Should still verify with second signature - err = VerifyWithManifest(module, manifest) - assert.NoError(t, err) -} - -func BenchmarkSign(b *testing.B) { - signer, _ := NewSigner() - data := make([]byte, 1024*1024) // 1MB - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = signer.Sign(data) - } -} - -func BenchmarkVerify(b *testing.B) { - signer, _ := NewSigner() - verifier := NewSignatureVerifier() - verifier.AddTrustedKey("bench", signer.publicKey) - - data := make([]byte, 1024*1024) // 1MB - signature, _ := signer.Sign(data) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = verifier.Verify(data, signature) - } -} diff --git a/crypto/wasm/verifier.go b/crypto/wasm/verifier.go deleted file mode 100644 index b5ff26af2..000000000 --- a/crypto/wasm/verifier.go +++ /dev/null @@ -1,224 +0,0 @@ -// Package wasm provides cryptographic verification for WebAssembly modules -package wasm - -import ( - "crypto/sha256" - "encoding/hex" - "fmt" - "sync" -) - -// HashVerifier provides SHA256 hash verification for WASM modules -type HashVerifier struct { - // trustedHashes stores SHA256 hashes of trusted WASM modules - trustedHashes map[string]string - mu sync.RWMutex -} - -// NewHashVerifier creates a new WASM hash verifier -func NewHashVerifier() *HashVerifier { - return &HashVerifier{ - trustedHashes: make(map[string]string), - } -} - -// ComputeHash calculates SHA256 hash of WASM bytecode -func (v *HashVerifier) ComputeHash(wasmBytes []byte) string { - hash := sha256.Sum256(wasmBytes) - return hex.EncodeToString(hash[:]) -} - -// AddTrustedHash adds a trusted hash for a named WASM module -func (v *HashVerifier) AddTrustedHash(name, hash string) { - v.mu.Lock() - defer v.mu.Unlock() - v.trustedHashes[name] = hash -} - -// VerifyHash verifies WASM bytecode against trusted hash -func (v *HashVerifier) VerifyHash(name string, wasmBytes []byte) error { - v.mu.RLock() - trustedHash, exists := v.trustedHashes[name] - v.mu.RUnlock() - - if !exists { - return fmt.Errorf("no trusted hash found for WASM module: %s", name) - } - - computedHash := v.ComputeHash(wasmBytes) - if computedHash != trustedHash { - return fmt.Errorf( - "WASM hash verification failed for %s: expected %s, got %s", - name, trustedHash, computedHash, - ) - } - - return nil -} - -// VerifyHashWithFallback verifies against primary hash or fallback list -func (v *HashVerifier) VerifyHashWithFallback(name string, wasmBytes []byte, fallbackHashes []string) error { - // Try primary verification first - if err := v.VerifyHash(name, wasmBytes); err == nil { - return nil - } - - // Check against fallback hashes - computedHash := v.ComputeHash(wasmBytes) - for _, fallbackHash := range fallbackHashes { - if computedHash == fallbackHash { - // Update trusted hash for future use - v.AddTrustedHash(name, computedHash) - return nil - } - } - - return fmt.Errorf( - "WASM hash verification failed: computed hash %s not in trusted set", - computedHash, - ) -} - -// GetTrustedHash retrieves the trusted hash for a module -func (v *HashVerifier) GetTrustedHash(name string) (string, bool) { - v.mu.RLock() - defer v.mu.RUnlock() - hash, exists := v.trustedHashes[name] - return hash, exists -} - -// ClearTrustedHashes removes all trusted hashes -func (v *HashVerifier) ClearTrustedHashes() { - v.mu.Lock() - defer v.mu.Unlock() - v.trustedHashes = make(map[string]string) -} - -// HashChain provides hash chain verification for plugin updates -type HashChain struct { - chain []HashEntry - mu sync.RWMutex -} - -// HashEntry represents a single entry in the hash chain -type HashEntry struct { - Version string `json:"version"` - Hash string `json:"hash"` - PreviousHash string `json:"previous_hash"` - Timestamp int64 `json:"timestamp"` -} - -// NewHashChain creates a new hash chain -func NewHashChain() *HashChain { - return &HashChain{ - chain: make([]HashEntry, 0), - } -} - -// AddEntry adds a new entry to the hash chain -func (hc *HashChain) AddEntry(version, hash string, timestamp int64) error { - hc.mu.Lock() - defer hc.mu.Unlock() - - previousHash := "" - if len(hc.chain) > 0 { - previousHash = hc.chain[len(hc.chain)-1].Hash - } - - entry := HashEntry{ - Version: version, - Hash: hash, - PreviousHash: previousHash, - Timestamp: timestamp, - } - - hc.chain = append(hc.chain, entry) - return nil -} - -// VerifyChain verifies the integrity of the hash chain -func (hc *HashChain) VerifyChain() error { - hc.mu.RLock() - defer hc.mu.RUnlock() - - if len(hc.chain) == 0 { - return nil - } - - // First entry should have empty previous hash - if hc.chain[0].PreviousHash != "" { - return fmt.Errorf("invalid hash chain: first entry has non-empty previous hash") - } - - // Verify chain continuity - for i := 1; i < len(hc.chain); i++ { - if hc.chain[i].PreviousHash != hc.chain[i-1].Hash { - return fmt.Errorf( - "hash chain broken at version %s: expected previous hash %s, got %s", - hc.chain[i].Version, - hc.chain[i-1].Hash, - hc.chain[i].PreviousHash, - ) - } - } - - return nil -} - -// GetLatestEntry returns the most recent hash chain entry -func (hc *HashChain) GetLatestEntry() (*HashEntry, error) { - hc.mu.RLock() - defer hc.mu.RUnlock() - - if len(hc.chain) == 0 { - return nil, fmt.Errorf("hash chain is empty") - } - - latest := hc.chain[len(hc.chain)-1] - return &latest, nil -} - -// VerificationError represents a WASM verification failure -type VerificationError struct { - Module string - ExpectedHash string - ActualHash string - Reason string -} - -// Error implements the error interface -func (e *VerificationError) Error() string { - return fmt.Sprintf( - "WASM verification failed for %s: %s (expected: %s, actual: %s)", - e.Module, e.Reason, e.ExpectedHash, e.ActualHash, - ) -} - -// SecurityPolicy defines verification requirements -type SecurityPolicy struct { - RequireHashVerification bool - RequireSignature bool - AllowedHashes []string - MaxModuleSize int64 -} - -// DefaultSecurityPolicy returns a secure default policy -func DefaultSecurityPolicy() *SecurityPolicy { - return &SecurityPolicy{ - RequireHashVerification: true, - RequireSignature: false, // Will be enabled in next phase - AllowedHashes: []string{}, - MaxModuleSize: 10 * 1024 * 1024, // 10MB max - } -} - -// Validate checks if WASM module meets security policy -func (p *SecurityPolicy) Validate(wasmBytes []byte) error { - if p.MaxModuleSize > 0 && int64(len(wasmBytes)) > p.MaxModuleSize { - return fmt.Errorf( - "WASM module size %d exceeds maximum allowed size %d", - len(wasmBytes), p.MaxModuleSize, - ) - } - return nil -} diff --git a/crypto/wasm/verifier_test.go b/crypto/wasm/verifier_test.go deleted file mode 100644 index 2734685cf..000000000 --- a/crypto/wasm/verifier_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package wasm - -import ( - "crypto/sha256" - "encoding/hex" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestHashVerifier_ComputeHash(t *testing.T) { - verifier := NewHashVerifier() - - testCases := []struct { - name string - input []byte - expected string - }{ - { - name: "empty input", - input: []byte{}, - expected: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - }, - { - name: "simple wasm header", - input: []byte{0x00, 0x61, 0x73, 0x6d}, // \0asm - expected: "cd5d4935a48c0672cb06407bb443bc0087aff947c6b864bac886982c73b3027f", - }, - { - name: "test module", - input: []byte("test wasm module content"), - expected: "945acabcfc93e347e8c08ea44afd3122670f04a89f9a0a0a5ce16ab849bbac06", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - hash := verifier.ComputeHash(tc.input) - assert.Equal(t, tc.expected, hash) - }) - } -} - -func TestHashVerifier_TrustedHashes(t *testing.T) { - verifier := NewHashVerifier() - - // Add trusted hash - moduleName := "test-module" - trustedHash := "abc123def456" - verifier.AddTrustedHash(moduleName, trustedHash) - - // Retrieve trusted hash - hash, exists := verifier.GetTrustedHash(moduleName) - assert.True(t, exists) - assert.Equal(t, trustedHash, hash) - - // Non-existent module - _, exists = verifier.GetTrustedHash("non-existent") - assert.False(t, exists) - - // Clear hashes - verifier.ClearTrustedHashes() - _, exists = verifier.GetTrustedHash(moduleName) - assert.False(t, exists) -} - -func TestHashVerifier_VerifyHash(t *testing.T) { - verifier := NewHashVerifier() - - // Test data - wasmBytes := []byte("test wasm module") - expectedHash := verifier.ComputeHash(wasmBytes) - moduleName := "test-module" - - // Test missing trusted hash - err := verifier.VerifyHash(moduleName, wasmBytes) - assert.Error(t, err) - assert.Contains(t, err.Error(), "no trusted hash found") - - // Add trusted hash - verifier.AddTrustedHash(moduleName, expectedHash) - - // Test successful verification - err = verifier.VerifyHash(moduleName, wasmBytes) - assert.NoError(t, err) - - // Test failed verification - verifier.AddTrustedHash(moduleName, "wrong-hash") - err = verifier.VerifyHash(moduleName, wasmBytes) - assert.Error(t, err) - assert.Contains(t, err.Error(), "hash verification failed") -} - -func TestHashVerifier_VerifyHashWithFallback(t *testing.T) { - verifier := NewHashVerifier() - - wasmBytes := []byte("test wasm module") - actualHash := verifier.ComputeHash(wasmBytes) - moduleName := "test-module" - - // Test with fallback hashes - fallbackHashes := []string{ - "wrong-hash-1", - actualHash, - "wrong-hash-2", - } - - err := verifier.VerifyHashWithFallback(moduleName, wasmBytes, fallbackHashes) - assert.NoError(t, err) - - // Verify that the hash was added as trusted - trustedHash, exists := verifier.GetTrustedHash(moduleName) - assert.True(t, exists) - assert.Equal(t, actualHash, trustedHash) - - // Test with no matching fallback - fallbackHashes = []string{"wrong-1", "wrong-2"} - verifier.ClearTrustedHashes() - - err = verifier.VerifyHashWithFallback(moduleName, wasmBytes, fallbackHashes) - assert.Error(t, err) - assert.Contains(t, err.Error(), "not in trusted set") -} - -func TestHashChain(t *testing.T) { - chain := NewHashChain() - - // Add entries - timestamp1 := time.Now().Unix() - err := chain.AddEntry("v1.0.0", "hash1", timestamp1) - require.NoError(t, err) - - timestamp2 := time.Now().Unix() - err = chain.AddEntry("v1.0.1", "hash2", timestamp2) - require.NoError(t, err) - - timestamp3 := time.Now().Unix() - err = chain.AddEntry("v1.0.2", "hash3", timestamp3) - require.NoError(t, err) - - // Verify chain integrity - err = chain.VerifyChain() - assert.NoError(t, err) - - // Get latest entry - latest, err := chain.GetLatestEntry() - require.NoError(t, err) - assert.Equal(t, "v1.0.2", latest.Version) - assert.Equal(t, "hash3", latest.Hash) - assert.Equal(t, "hash2", latest.PreviousHash) -} - -func TestHashChain_BrokenChain(t *testing.T) { - chain := NewHashChain() - - // Manually create a broken chain - chain.chain = []HashEntry{ - {Version: "v1", Hash: "hash1", PreviousHash: ""}, - {Version: "v2", Hash: "hash2", PreviousHash: "hash1"}, - {Version: "v3", Hash: "hash3", PreviousHash: "wrong-hash"}, // Broken link - } - - err := chain.VerifyChain() - assert.Error(t, err) - assert.Contains(t, err.Error(), "hash chain broken") -} - -func TestSecurityPolicy(t *testing.T) { - policy := DefaultSecurityPolicy() - - // Test size validation - smallModule := make([]byte, 1024) - err := policy.Validate(smallModule) - assert.NoError(t, err) - - // Test oversized module - largeModule := make([]byte, 11*1024*1024) - err = policy.Validate(largeModule) - assert.Error(t, err) - assert.Contains(t, err.Error(), "exceeds maximum allowed size") -} - -func TestVerificationError(t *testing.T) { - err := &VerificationError{ - Module: "test.wasm", - ExpectedHash: "expected123", - ActualHash: "actual456", - Reason: "hash mismatch", - } - - errStr := err.Error() - assert.Contains(t, errStr, "test.wasm") - assert.Contains(t, errStr, "hash mismatch") - assert.Contains(t, errStr, "expected123") - assert.Contains(t, errStr, "actual456") -} - -func BenchmarkComputeHash(b *testing.B) { - verifier := NewHashVerifier() - data := make([]byte, 1024*1024) // 1MB - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = verifier.ComputeHash(data) - } -} - -func BenchmarkVerifyHash(b *testing.B) { - verifier := NewHashVerifier() - data := make([]byte, 1024*1024) // 1MB - hash := verifier.ComputeHash(data) - verifier.AddTrustedHash("bench-module", hash) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = verifier.VerifyHash("bench-module", data) - } -} - -// Helper function to compute SHA256 hash for testing -func computeSHA256(data []byte) string { - hash := sha256.Sum256(data) - return hex.EncodeToString(hash[:]) -} diff --git a/crypto/zkp/schnorr/schnorr.go b/crypto/zkp/schnorr/schnorr.go deleted file mode 100644 index 5d2f92ecc..000000000 --- a/crypto/zkp/schnorr/schnorr.go +++ /dev/null @@ -1,157 +0,0 @@ -// -// Copyright Coinbase, Inc. All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -// Package schnorr implements a Schnorr proof, as described and used in Doerner, et al. https://eprint.iacr.org/2018/499.pdf -// see Functionalities 6. it also implements a "committed" version, as described in Functionality 7. -package schnorr - -import ( - "crypto/rand" - "crypto/subtle" - "fmt" - - "github.com/pkg/errors" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -type Commitment = []byte - -type Prover struct { - curve *curves.Curve - basePoint curves.Point - uniqueSessionId []byte -} - -// Proof contains the (c, s) schnorr proof. `Statement` is the curve point you're proving knowledge of discrete log of, -// with respect to the base point. -type Proof struct { - C curves.Scalar - S curves.Scalar - Statement curves.Point -} - -// NewProver generates a `Prover` object, ready to generate Schnorr proofs on any given point. -// We allow the option `basePoint == nil`, in which case `basePoint` is auto-assigned to be the "default" generator for the group. -func NewProver(curve *curves.Curve, basepoint curves.Point, uniqueSessionId []byte) *Prover { - if basepoint == nil { - basepoint = curve.NewGeneratorPoint() - } - return &Prover{ - curve: curve, - basePoint: basepoint, - uniqueSessionId: uniqueSessionId, - } -} - -// Prove generates and returns a Schnorr proof, given the scalar witness `x`. -// in the process, it will actually also construct the statement (just one curve mult in this case) -func (p *Prover) Prove(x curves.Scalar) (*Proof, error) { - // assumes that params, and pub are already populated. populates the fields c and s... - var err error - result := &Proof{} - result.Statement = p.basePoint.Mul(x) - k := p.curve.Scalar.Random(rand.Reader) - random := p.basePoint.Mul(k) - hash := sha3.New256() - if _, err = hash.Write(p.uniqueSessionId); err != nil { - return nil, errors.Wrap(err, "writing salt to hash in schnorr prove") - } - if _, err = hash.Write(p.basePoint.ToAffineCompressed()); err != nil { - return nil, errors.Wrap(err, "writing basePoint to hash in schnorr prove") - } - if _, err = hash.Write(result.Statement.ToAffineCompressed()); err != nil { - return nil, errors.Wrap(err, "writing statement to hash in schnorr prove") - } - if _, err = hash.Write(random.ToAffineCompressed()); err != nil { - return nil, errors.Wrap(err, "writing point K to hash in schnorr prove") - } - hashBytes := hash.Sum(nil) - result.C, err = p.curve.Scalar.SetBytesWide(append(hashBytes, make([]byte, 32)...)) - if err != nil { - return nil, errors.Wrap(err, "creating challenge scalar in schnorr prove") - } - result.S = result.C.Mul(x).Add(k) - return result, nil -} - -// Verify verifies the `proof`, given the prover parameters `scalar` and `curve`. -// As for the prover, we allow `basePoint == nil`, in this case, it's auto-assigned to be the group's default generator. -func Verify( - proof *Proof, - curve *curves.Curve, - basepoint curves.Point, - uniqueSessionId []byte, -) error { - if basepoint == nil { - basepoint = curve.NewGeneratorPoint() - } - gs := basepoint.Mul(proof.S) - xc := proof.Statement.Mul(proof.C.Neg()) - random := gs.Add(xc) - hash := sha3.New256() - if _, err := hash.Write(uniqueSessionId); err != nil { - return errors.Wrap(err, "writing salt to hash in schnorr verify") - } - if _, err := hash.Write(basepoint.ToAffineCompressed()); err != nil { - return errors.Wrap(err, "writing basePoint to hash in schnorr verify") - } - if _, err := hash.Write(proof.Statement.ToAffineCompressed()); err != nil { - return errors.Wrap(err, "writing statement to hash in schnorr verify") - } - if _, err := hash.Write(random.ToAffineCompressed()); err != nil { - return errors.Wrap(err, "writing point K to hash in schnorr verify") - } - hashBytes := hash.Sum(nil) - expectedC, err := curve.Scalar.SetBytesWide(append(hashBytes, make([]byte, 32)...)) - if err != nil { - return errors.Wrap(err, "creating expected challenge scalar in schnorr verify") - } - if subtle.ConstantTimeCompare(proof.C.Bytes(), expectedC.Bytes()) != 1 { - return fmt.Errorf("schnorr verification failed") - } - return nil -} - -// ProveCommit generates _and_ commits to a schnorr proof which is later revealed; see Functionality 7. -// returns the Proof and Commitment. -func (p *Prover) ProveCommit(x curves.Scalar) (*Proof, Commitment, error) { - proof, err := p.Prove(x) - if err != nil { - return nil, nil, err - } - hash := sha3.New256() - if _, err = hash.Write(proof.C.Bytes()); err != nil { - return nil, nil, err - } - if _, err = hash.Write(proof.S.Bytes()); err != nil { - return nil, nil, err - } - return proof, hash.Sum(nil), nil -} - -// DecommitVerify receives a `Proof` and a `Commitment`; it first checks that the proof actually opens the commitment; -// then it verifies the proof. returns and error if either on eof thse fail. -func DecommitVerify( - proof *Proof, - commitment Commitment, - curve *curves.Curve, - basepoint curves.Point, - uniqueSessionId []byte, -) error { - hash := sha3.New256() - if _, err := hash.Write(proof.C.Bytes()); err != nil { - return err - } - if _, err := hash.Write(proof.S.Bytes()); err != nil { - return err - } - if subtle.ConstantTimeCompare(hash.Sum(nil), commitment) != 1 { - return fmt.Errorf("initial hash decommitment failed") - } - return Verify(proof, curve, basepoint, uniqueSessionId) -} diff --git a/crypto/zkp/schnorr/schnorr_test.go b/crypto/zkp/schnorr/schnorr_test.go deleted file mode 100644 index 0474ba394..000000000 --- a/crypto/zkp/schnorr/schnorr_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package schnorr - -import ( - "crypto/rand" - "fmt" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/crypto/sha3" - - "github.com/sonr-io/sonr/crypto/core/curves" -) - -func TestZKPOverMultipleCurves(t *testing.T) { - curveInstances := []*curves.Curve{ - curves.K256(), - curves.P256(), - curves.PALLAS(), - curves.BLS12377G1(), - curves.BLS12377G2(), - curves.BLS12381G1(), - curves.BLS12381G2(), - curves.ED25519(), - } - for i, curve := range curveInstances { - uniqueSessionId := sha3.New256().Sum([]byte("random seed")) - prover := NewProver(curve, nil, uniqueSessionId) - - secret := curve.Scalar.Random(rand.Reader) - proof, err := prover.Prove(secret) - require.NoError(t, err, fmt.Sprintf("failed in curve %d", i)) - - err = Verify(proof, curve, nil, uniqueSessionId) - require.NoError(t, err, fmt.Sprintf("failed in curve %d", i)) - } -} diff --git a/devbox.json b/devbox.json index c822b202d..a3146c53c 100644 --- a/devbox.json +++ b/devbox.json @@ -45,55 +45,21 @@ "sh ./scripts/devbox-env.sh install" ], "scripts": { - "build": "./scripts/devbox-env.sh build-all", - "test": "./scripts/devbox-env.sh test-all", - "snapshot": "./scripts/devbox-env.sh snapshot-all", - "release": "./scripts/devbox-env.sh release-all", - "build:auth": "pnpm --filter '@sonr.io/com' build && pnpm --filter '@sonr.io/es' build && pnpm --filter '@sonr.io/sdk' build && pnpm --filter '@sonr.io/ui' build && pnpm --filter '@sonr.io/auth' build", + "build": "make build-all", + "test": "make test-all", + "snapshot": "make snapshot", + "release": "make release", "build:client": "make build-client", - "build:com": "pnpm --filter '@sonr.io/com' build", "build:core": "make -C cmd/snrd build", - "build:dash": "pnpm --filter '@sonr.io/com' build && pnpm --filter '@sonr.io/es' build && pnpm --filter '@sonr.io/sdk' build && pnpm --filter '@sonr.io/ui' build && pnpm --filter '@sonr.io/dash' build", - "build:es": "pnpm --filter '@sonr.io/es' build", - "build:hway": "make -C cmd/hway build", - "build:motr": "make -C cmd/motr build", - "build:pkl": "pnpm --filter '@sonr.io/pkl' build", - "build:sdk": "pnpm --filter '@sonr.io/es' build && pnpm --filter '@sonr.io/sdk' build", - "build:ui": "pnpm --filter '@sonr.io/com' build && pnpm --filter '@sonr.io/ui' build", - "build:vault": "make -C cmd/vault build", - "test:auth": "pnpm --filter '@sonr.io/auth' test", "test:client": "make test-client", - "test:com": "pnpm --filter '@sonr.io/com' test", "test:core": "make test-app", - "test:crypto": "make test-crypto", - "test:dash": "pnpm --filter '@sonr.io/dash' test", "test:dex": "make test-module MODULE=dex", "test:devops": "make test-devops", "test:did": "make test-module MODULE=did", "test:dwn": "make test-dwn-ci", - "test:es": "pnpm --filter '@sonr.io/es' test", - "test:hway": "make test-hway", - "test:motr": "make test-motr", - "test:pkl": "pnpm --filter '@sonr.io/pkl' test", - "test:sdk": "pnpm --filter '@sonr.io/sdk' test", "test:svc": "make test-module MODULE=svc", - "test:ui": "pnpm --filter '@sonr.io/ui' test", - "test:vault": "make test-vault", "snapshot:core": "make -C cmd/snrd snapshot", - "snapshot:hway": "make -C cmd/hway snapshot", - "snapshot:motr": "make -C cmd/motr snapshot", - "snapshot:vault": "make -C cmd/vault snapshot", - "release:auth": "pnpm --filter '@sonr.io/auth' release", - "release:com": "pnpm --filter '@sonr.io/com' release", - "release:core": "make -C cmd/snrd release", - "release:dash": "pnpm --filter '@sonr.io/dash' release", - "release:es": "pnpm --filter '@sonr.io/es' release", - "release:hway": "make -C cmd/hway release", - "release:motr": "make -C cmd/motr release", - "release:pkl": "pnpm --filter '@sonr.io/pkl' release", - "release:sdk": "pnpm --filter '@sonr.io/sdk' release", - "release:ui": "pnpm --filter '@sonr.io/ui' release", - "release:vault": "make -C cmd/vault release" + "release:core": "make -C cmd/snrd release" } } } diff --git a/docker-compose.yml b/docker-compose.yml index 20559fc18..6a85cdedb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,47 +1,6 @@ name: sonr-core services: - # Redis service for Highway task queue - redis: - container_name: redis - image: redis:7-alpine - restart: unless-stopped - ports: - - "127.0.0.1:6379:6379" - volumes: - - redis-data:/data - command: redis-server --appendonly yes --appendfsync everysec - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 5s - timeout: 3s - retries: 5 - start_period: 10s - networks: - - sonr-network - - postgres: - image: ghcr.io/sonr-io/postgres:latest - restart: unless-stopped - environment: - POSTGRES_HOST_AUTH_METHOD: trust - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: hway - POSTGRES_INITDB_ARGS: "--encoding=UTF8 --locale=C" - volumes: - - postgres-data:/var/lib/postgresql/data - ports: - - "127.0.0.1:5432:5432" - healthcheck: - test: ["CMD-SHELL", "pg_isready -U postgres -d hway"] - interval: 10s - timeout: 5s - retries: 5 - start_period: 10s - networks: - - sonr-network - ipfs: container_name: ipfs image: ipfs/kubo:release @@ -93,34 +52,6 @@ services: networks: - sonr-network - hway: - container_name: hway - image: onsonr/hway:latest - build: - context: . - dockerfile: cmd/hway/Dockerfile - restart: unless-stopped - depends_on: - redis: - condition: service_healthy - ipfs: - condition: service_started - environment: - REDIS_URL: redis://redis:6379 - IPFS_API_URL: http://ipfs:5001 - LOG_LEVEL: ${LOG_LEVEL:-debug} - HIGHWAY_PORT: 8090 - ports: - - "127.0.0.1:8090:8090" - healthcheck: - test: ["CMD", "wget", "--spider", "-q", "http://localhost:8090/health"] - interval: 10s - timeout: 5s - retries: 5 - start_period: 30s - networks: - - sonr-network - snrd: container_name: snrd image: onsonr/snrd:latest @@ -165,87 +96,6 @@ services: networks: - sonr-network - # Auth web application - auth: - container_name: auth - image: onsonr/auth:latest - build: - context: . - dockerfile: web/auth/Dockerfile - restart: unless-stopped - depends_on: - snrd: - condition: service_healthy - hway: - condition: service_healthy - environment: - NODE_ENV: ${NODE_ENV:-development} - PORT: 3100 - NEXT_PUBLIC_API_URL: ${AUTH_NEXT_PUBLIC_API_URL:-http://localhost:8080} - OIDC_ISSUER: ${AUTH_OIDC_ISSUER:-http://localhost:3000} - OIDC_PUBLIC_URL: ${AUTH_OIDC_PUBLIC_URL:-http://localhost:3000} - WEBAUTHN_RP_ID: ${AUTH_WEBAUTHN_RP_ID:-localhost} - WEBAUTHN_RP_NAME: ${AUTH_WEBAUTHN_RP_NAME:-Sonr Identity Platform} - WEBAUTHN_TIMEOUT: ${AUTH_WEBAUTHN_TIMEOUT:-60000} - JWT_SECRET: ${AUTH_JWT_SECRET:-highway-ucan-secret-key} - REDIS_ADDR: redis:6379 - OIDC_CLIENT_ID: ${AUTH_OIDC_CLIENT_ID:-sonr-auth} - LOG_LEVEL: ${AUTH_LOG_LEVEL:-info} - CORS_ENABLED: ${AUTH_CORS_ENABLED:-true} - ports: - - "127.0.0.1:3100:3100" - healthcheck: - test: ["CMD", "wget", "--spider", "-q", "http://localhost:3100/"] - interval: 10s - timeout: 5s - retries: 5 - start_period: 30s - networks: - - sonr-network - - # Dashboard web application - dash: - container_name: dash - image: onsonr/dash:latest - build: - context: . - dockerfile: web/dash/Dockerfile - restart: unless-stopped - depends_on: - snrd: - condition: service_healthy - hway: - condition: service_healthy - auth: - condition: service_healthy - environment: - NODE_ENV: ${NODE_ENV:-development} - PORT: 3200 - NEXT_PUBLIC_CHAIN_ID: ${DASH_NEXT_PUBLIC_CHAIN_ID:-sonrtest_1-1} - NEXT_PUBLIC_CHAIN_ENDPOINT: http://snrd:26657 - NEXT_PUBLIC_RPC_ENDPOINT: http://snrd:1317 - NEXT_PUBLIC_GRPC_ENDPOINT: http://snrd:9090 - NEXT_PUBLIC_WS_ENDPOINT: ws://snrd:26657/websocket - NEXT_PUBLIC_AUTH_URL: http://auth:3100 - NEXT_PUBLIC_AUTH_DOMAIN: ${DASH_NEXT_PUBLIC_AUTH_DOMAIN:-localhost} - NEXT_PUBLIC_API_URL: ${DASH_NEXT_PUBLIC_API_URL:-http://localhost:3000} - NEXT_PUBLIC_SERVICE_NAME: ${DASH_NEXT_PUBLIC_SERVICE_NAME:-Sonr Dashboard} - NEXT_PUBLIC_IPFS_GATEWAY: ${DASH_NEXT_PUBLIC_IPFS_GATEWAY:-https://ipfs.io/ipfs/} - NEXT_PUBLIC_IPFS_API: http://ipfs:5001 - NEXT_PUBLIC_WEBAUTHN_RP_NAME: ${DASH_NEXT_PUBLIC_WEBAUTHN_RP_NAME:-Sonr Dashboard} - NEXT_PUBLIC_WEBAUTHN_RP_ID: ${DASH_NEXT_PUBLIC_WEBAUTHN_RP_ID:-localhost} - NEXT_PUBLIC_LOG_LEVEL: ${DASH_NEXT_PUBLIC_LOG_LEVEL:-info} - ports: - - "127.0.0.1:3200:3200" - healthcheck: - test: ["CMD", "wget", "--spider", "-q", "http://localhost:3200/"] - interval: 10s - timeout: 5s - retries: 5 - start_period: 30s - networks: - - sonr-network - networks: sonr-network: driver: bridge @@ -253,6 +103,4 @@ networks: volumes: caddy-config: - redis-data: caddy-data: - postgres-data: diff --git a/docs/reference/architecture/decentralized-identity.mdx b/docs/reference/architecture/decentralized-identity.mdx index 5ff9d9b4f..56afd2a0b 100644 --- a/docs/reference/architecture/decentralized-identity.mdx +++ b/docs/reference/architecture/decentralized-identity.mdx @@ -24,7 +24,7 @@ The `didkey.go` interface supports the following key types: ```go import ( "github.com/libp2p/go-libp2p/core/crypto" - "github.com/sonr-io/sonr/crypto/keys" + "github.com/sonr-io/crypto/keys" ) // Generate a new key pair @@ -95,7 +95,7 @@ package main import ( "fmt" "github.com/libp2p/go-libp2p/core/crypto" - "github.com/sonr-io/sonr/crypto/keys" + "github.com/sonr-io/crypto/keys" ) func main() { diff --git a/docs/reference/contracts/DAO.mdx b/docs/reference/contracts/DAO.mdx deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/reference/contracts/wSNR.mdx b/docs/reference/contracts/wSNR.mdx deleted file mode 100644 index e69de29bb..000000000 diff --git a/go.mod b/go.mod index 61e202d51..704fcc54f 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sonr-io/sonr -go 1.24.7 +go 1.25 // overrides replace ( @@ -11,7 +11,6 @@ replace ( github.com/cosmos/cosmos-sdk => github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 github.com/cosmos/evm => github.com/strangelove-ventures/cosmos-evm v0.2.0 github.com/ethereum/go-ethereum => github.com/evmos/go-ethereum v1.10.26-evmos-rc2 - github.com/sonr-io/sonr/crypto => ./crypto github.com/spf13/viper => github.com/spf13/viper v1.17.0 // v1.18+ breaks app overrides nhooyr.io/websocket => nhooyr.io/websocket v1.8.17 ) @@ -48,6 +47,7 @@ require ( cosmossdk.io/math v1.5.0 cosmossdk.io/orm v1.0.0-beta.3 cosmossdk.io/store v1.1.1 + cosmossdk.io/tools/confix v0.1.2 cosmossdk.io/x/circuit v0.1.1 cosmossdk.io/x/evidence v0.1.1 cosmossdk.io/x/feegrant v0.1.1 @@ -56,13 +56,11 @@ require ( cosmossdk.io/x/upgrade v0.1.4 github.com/CosmWasm/wasmvm v1.5.8 github.com/asynkron/protoactor-go v0.0.0-20240822202345-3c0e61ca19c9 - github.com/biter777/countries v1.7.5 github.com/cometbft/cometbft v0.38.17 github.com/cosmos/cosmos-db v1.1.1 github.com/cosmos/cosmos-proto v1.0.0-beta.5 github.com/cosmos/cosmos-sdk v0.53.4 github.com/cosmos/evm v0.1.0 - github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogoproto v1.7.0 github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v8 v8.1.1 github.com/cosmos/ibc-apps/modules/rate-limiting/v8 v8.0.0 @@ -72,25 +70,20 @@ require ( github.com/ethereum/go-ethereum v1.16.3 github.com/extism/go-sdk v1.7.1 github.com/fxamacker/cbor/v2 v2.9.0 - github.com/golang-jwt/jwt/v5 v5.3.0 github.com/golang/protobuf v1.5.4 - github.com/google/go-tpm v0.9.5 github.com/gorilla/mux v1.8.1 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/hibiken/asynq v0.25.1 - github.com/ipfs/boxo v0.32.0 - github.com/ipfs/kubo v0.35.0 - github.com/labstack/echo-jwt/v4 v4.3.1 github.com/labstack/echo/v4 v4.13.4 - github.com/sonr-io/sonr/crypto v0.0.0-00010101000000-000000000000 + github.com/sonr-io/common v0.0.0-20251010142707-ab6d2fe7e9c9 + github.com/sonr-io/crypto v1.0.1 github.com/spf13/cast v1.9.2 github.com/spf13/cobra v1.8.1 github.com/spf13/viper v1.19.0 github.com/strangelove-ventures/tokenfactory v0.50.3 - github.com/stretchr/testify v1.10.0 - google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 - google.golang.org/grpc v1.71.0 - google.golang.org/protobuf v1.36.6 + github.com/stretchr/testify v1.11.1 + google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 + google.golang.org/grpc v1.75.0 + google.golang.org/protobuf v1.36.9 gorm.io/driver/sqlite v1.6.0 gorm.io/gorm v1.30.1 ) @@ -98,17 +91,32 @@ require ( require ( github.com/Oudwins/zog v0.21.6 // indirect github.com/alexvec/go-bip39 v1.1.0 // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/biter777/countries v1.7.5 // indirect + github.com/cockroachdb/datadriven v1.0.3-0.20250407164829-2945557346d5 // indirect + github.com/cosmos/go-bip39 v1.0.0 // indirect + github.com/creachadair/atomicfile v0.3.1 // indirect + github.com/creachadair/tomledit v0.0.24 // indirect + github.com/dgraph-io/ristretto/v2 v2.1.0 // indirect + github.com/edsrzf/mmap-go v1.1.0 // indirect + github.com/gammazero/chanqueue v1.1.1 // indirect + github.com/golang-jwt/jwt/v5 v5.3.0 // indirect + github.com/google/go-tpm v0.9.6 // indirect + github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a // indirect + github.com/ipfs/boxo v0.35.0 // indirect + github.com/ipfs/go-cidutil v0.1.0 // indirect + github.com/ipfs/go-dsqueue v0.0.5 // indirect + github.com/ipfs/kubo v0.38.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/labstack/gommon v0.4.2 // indirect github.com/mattn/go-sqlite3 v1.14.22 // indirect github.com/nxadm/tail v1.4.11 // indirect - github.com/redis/go-redis/v9 v9.11.0 // indirect - github.com/robfig/cron/v3 v3.0.1 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/ginkgo/v2 v2.23.4 // indirect github.com/smartystreets/goconvey v1.8.1 // indirect github.com/tklauser/go-sysconf v0.3.11 // indirect github.com/tklauser/numcpus v0.6.1 // indirect + github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect github.com/x448/float16 v0.8.4 // indirect @@ -119,48 +127,42 @@ require ( cloud.google.com/go v0.115.0 // indirect cloud.google.com/go/auth v0.6.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect - cloud.google.com/go/compute/metadata v0.6.0 // indirect + cloud.google.com/go/compute/metadata v0.7.0 // indirect cloud.google.com/go/iam v1.1.9 // indirect cloud.google.com/go/storage v1.41.0 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect github.com/DataDog/datadog-go v3.2.0+incompatible // indirect - github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e // indirect + github.com/DataDog/zstd v1.5.7 // indirect github.com/StackExchange/wmi v1.2.1 // indirect github.com/VictoriaMetrics/fastcache v1.6.0 // indirect github.com/Workiva/go-datastructures v1.1.3 // indirect github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect github.com/aws/aws-sdk-go v1.55.6 // indirect - github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect github.com/bits-and-blooms/bitset v1.24.0 // indirect github.com/blang/semver/v4 v4.0.0 // indirect - github.com/btcsuite/btcd v0.24.2 + github.com/btcsuite/btcd v0.24.2 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect - github.com/btcsuite/btcd/btcutil v1.1.6 + github.com/btcsuite/btcd/btcutil v1.1.6 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect github.com/bwesterb/go-ristretto v1.2.3 // indirect github.com/bytedance/sonic v1.14.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect - github.com/caddyserver/certmagic v0.21.6 // indirect - github.com/caddyserver/zerossl v0.1.3 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/cloudwego/base64x v0.1.5 // indirect github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/cockroachdb/apd/v3 v3.2.1 // indirect - github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 // indirect github.com/cockroachdb/errors v1.11.3 // indirect github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/pebble v1.1.2 // indirect - github.com/cockroachdb/pebble/v2 v2.0.3 // indirect github.com/cockroachdb/redact v1.1.5 // indirect - github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 // indirect github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.14.1 // indirect github.com/consensys/gnark-crypto v0.19.0 // indirect @@ -172,12 +174,10 @@ require ( github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf // indirect github.com/danieljoos/wincred v1.1.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect - github.com/dgraph-io/badger/v4 v4.2.0 // indirect - github.com/dgraph-io/ristretto v0.1.1 // indirect + github.com/dgraph-io/badger/v4 v4.5.1 // indirect github.com/dlclark/regexp2 v1.11.0 // indirect github.com/dop251/goja v0.0.0-20220405120441-9037c2b61cbf // indirect github.com/dustin/go-humanize v1.0.1 // indirect @@ -186,18 +186,15 @@ require ( github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect github.com/emicklei/dot v1.6.2 // indirect github.com/emirpasic/gods v1.18.1 // indirect - github.com/facebookgo/atomicfile v0.0.0-20151019160806-2de1f203e7d5 // indirect github.com/fatih/color v1.16.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/flynn/noise v1.1.0 // indirect - github.com/francoispqt/gojay v1.2.13 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect - github.com/gammazero/deque v1.0.0 // indirect + github.com/gammazero/deque v1.1.0 // indirect github.com/getsentry/sentry-go v0.27.0 // indirect github.com/go-kit/kit v0.13.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect @@ -208,21 +205,20 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/gogo/status v1.1.0 // indirect github.com/golang-jwt/jwt/v4 v4.5.2 // indirect - github.com/golang/glog v1.2.4 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/mock v1.6.0 // indirect github.com/golang/snappy v0.0.5-0.20231225225746-43d5d4cd4e0e // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/flatbuffers v23.5.26+incompatible // indirect + github.com/google/flatbuffers v24.12.23+incompatible // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/gopacket v1.1.19 // indirect github.com/google/orderedcode v0.0.1 // indirect github.com/google/s2a-go v0.1.7 // indirect - github.com/google/uuid v1.6.0 + github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.5 // indirect github.com/gorilla/handlers v1.5.2 // indirect - github.com/gorilla/websocket v1.5.3 + github.com/gorilla/websocket v1.5.3 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect @@ -242,54 +238,40 @@ require ( github.com/holiman/bloomfilter/v2 v2.0.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect github.com/huandu/skiplist v1.2.0 // indirect - github.com/huin/goupnp v1.3.0 // indirect github.com/iancoleman/orderedmap v0.3.0 // indirect github.com/iancoleman/strcase v0.3.0 // indirect - github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect + github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/ipfs/bbloom v0.0.4 // indirect github.com/ipfs/go-bitfield v1.1.0 // indirect - github.com/ipfs/go-block-format v0.2.1 // indirect + github.com/ipfs/go-block-format v0.2.3 // indirect github.com/ipfs/go-cid v0.5.0 - github.com/ipfs/go-datastore v0.8.2 // indirect - github.com/ipfs/go-ds-measure v0.2.2 // indirect - github.com/ipfs/go-fs-lock v0.1.1 // indirect - github.com/ipfs/go-ipfs-cmds v0.14.1 // indirect - github.com/ipfs/go-ipld-cbor v0.2.0 // indirect - github.com/ipfs/go-ipld-format v0.6.1 // indirect - github.com/ipfs/go-ipld-legacy v0.2.1 // indirect - github.com/ipfs/go-log v1.0.5 // indirect - github.com/ipfs/go-log/v2 v2.6.0 // indirect + github.com/ipfs/go-datastore v0.9.0 // indirect + github.com/ipfs/go-ipfs-cmds v0.15.0 // indirect + github.com/ipfs/go-ipld-format v0.6.3 // indirect + github.com/ipfs/go-ipld-legacy v0.2.2 // indirect + github.com/ipfs/go-log/v2 v2.8.1 // indirect github.com/ipfs/go-metrics-interface v0.3.0 // indirect - github.com/ipfs/go-unixfsnode v1.10.1 // indirect - github.com/ipld/go-car/v2 v2.14.3 // indirect github.com/ipld/go-codec-dagpb v1.7.0 // indirect github.com/ipld/go-ipld-prime v0.21.0 // indirect - github.com/ipshipyard/p2p-forge v0.5.1 // indirect - github.com/jackpal/go-nat-pmp v1.0.2 // indirect - github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect github.com/klauspost/compress v1.18.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/koron/go-ssdp v0.0.6 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.9 // indirect - github.com/libdns/libdns v0.2.2 // 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.2.0 // indirect github.com/libp2p/go-libp2p v0.43.0 // indirect github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect - github.com/libp2p/go-libp2p-kad-dht v0.33.1 // indirect - github.com/libp2p/go-libp2p-kbucket v0.7.0 // indirect + github.com/libp2p/go-libp2p-kad-dht v0.35.0 // 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.2.2 // indirect - github.com/libp2p/go-reuseport v0.4.0 // indirect github.com/linxGnu/grocksdb v1.9.8 // indirect github.com/lithammer/shortuuid/v4 v4.0.0 // indirect github.com/lmittmann/tint v1.0.3 // indirect @@ -298,23 +280,21 @@ require ( github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/mholt/acmez/v3 v3.0.0 // indirect - github.com/miekg/dns v1.1.66 // indirect + github.com/miekg/dns v1.1.68 // indirect github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect github.com/minio/highwayhash v1.0.3 // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect - github.com/mitchellh/mapstructure v1.5.0 + github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mr-tron/base58 v1.2.0 // indirect github.com/mtibben/percent v0.2.1 // indirect github.com/multiformats/go-base32 v0.1.0 // indirect github.com/multiformats/go-base36 v0.2.0 // indirect - github.com/multiformats/go-multiaddr v0.16.0 // indirect + github.com/multiformats/go-multiaddr v0.16.1 // indirect github.com/multiformats/go-multiaddr-dns v0.4.1 // indirect - github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect github.com/multiformats/go-multibase v0.2.0 // indirect - github.com/multiformats/go-multicodec v0.9.1 // indirect + github.com/multiformats/go-multicodec v0.9.2 // 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 @@ -322,42 +302,17 @@ require ( github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect github.com/oklog/run v1.1.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/orcaman/concurrent-map v1.0.0 // indirect - github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect - github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 // indirect github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect - github.com/pion/datachannel v1.5.10 // indirect - github.com/pion/dtls/v2 v2.2.12 // indirect - github.com/pion/dtls/v3 v3.0.6 // indirect - github.com/pion/ice/v4 v4.0.10 // indirect - github.com/pion/interceptor v0.1.40 // indirect - github.com/pion/logging v0.2.3 // indirect - github.com/pion/mdns/v2 v2.0.7 // indirect - github.com/pion/randutil v0.1.0 // indirect - github.com/pion/rtcp v1.2.15 // indirect - github.com/pion/rtp v1.8.19 // indirect - github.com/pion/sctp v1.8.39 // indirect - github.com/pion/sdp/v3 v3.0.13 // indirect - github.com/pion/srtp/v3 v3.0.6 // indirect - github.com/pion/stun v0.6.1 // indirect - github.com/pion/stun/v3 v3.0.0 // indirect - github.com/pion/transport/v2 v2.2.10 // indirect - github.com/pion/transport/v3 v3.0.7 // indirect - github.com/pion/turn/v4 v4.0.2 // indirect - github.com/pion/webrtc/v4 v4.1.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/polydawn/refmt v0.89.0 // indirect - github.com/prometheus/client_golang v1.22.0 // indirect + github.com/prometheus/client_golang v1.23.2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.64.0 // indirect - github.com/prometheus/procfs v0.16.1 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.17.0 // indirect github.com/prometheus/tsdb v0.10.0 // indirect - github.com/quic-go/qpack v0.5.1 // indirect - github.com/quic-go/quic-go v0.54.0 // indirect - github.com/quic-go/webtransport-go v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rjeczalik/notify v0.9.3 // indirect @@ -366,7 +321,6 @@ require ( github.com/rs/zerolog v1.33.0 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect - github.com/samber/lo v1.47.0 // indirect github.com/sasha-s/go-deadlock v0.3.5 // indirect github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/sourcegraph/conc v0.3.0 // indirect @@ -388,51 +342,41 @@ require ( github.com/ulikunitz/xz v0.5.11 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc // indirect - github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 // indirect - github.com/whyrusleeping/cbor-gen v0.1.2 // indirect github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f // indirect github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1 // indirect - github.com/wlynxg/anet v0.0.5 // indirect - github.com/zeebo/blake3 v0.2.4 // indirect github.com/zondax/hid v0.9.2 // indirect github.com/zondax/ledger-go v0.14.3 // indirect go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 // indirect - go.opentelemetry.io/otel v1.35.0 // indirect - go.opentelemetry.io/otel/exporters/prometheus v0.44.0 // indirect - go.opentelemetry.io/otel/metric v1.35.0 // indirect - go.opentelemetry.io/otel/sdk v1.34.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.35.0 // indirect - go.opentelemetry.io/proto/otlp v1.3.1 // indirect - go.uber.org/dig v1.19.0 // indirect - go.uber.org/fx v1.24.0 // indirect - go.uber.org/mock v0.5.2 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect + go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel/exporters/prometheus v0.56.0 // indirect + go.opentelemetry.io/otel/metric v1.38.0 // indirect + go.opentelemetry.io/otel/sdk v1.38.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.38.0 // indirect + go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.opentelemetry.io/proto/otlp v1.7.1 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - go.uber.org/zap/exp v0.3.0 // indirect - go.yaml.in/yaml/v2 v2.4.2 // indirect - go4.org v0.0.0-20230225012048-214862532bf5 // indirect + go.yaml.in/yaml/v2 v2.4.3 // indirect golang.org/x/arch v0.3.0 // indirect golang.org/x/crypto v0.42.0 - golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect - golang.org/x/mod v0.27.0 // indirect - golang.org/x/net v0.43.0 // indirect - golang.org/x/oauth2 v0.30.0 // indirect + golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect + golang.org/x/mod v0.28.0 // indirect + golang.org/x/net v0.44.0 // indirect + golang.org/x/oauth2 v0.31.0 // indirect golang.org/x/sync v0.17.0 // indirect golang.org/x/sys v0.36.0 // indirect golang.org/x/term v0.35.0 // indirect golang.org/x/text v0.29.0 // indirect golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.36.0 // indirect - golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect + golang.org/x/tools v0.37.0 // indirect gonum.org/v1/gonum v0.16.0 // indirect google.golang.org/api v0.186.0 // indirect google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index bfb54f1da..4e69e910a 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,5 @@ -bazil.org/fuse v0.0.0-20200117225306-7b5117fecadc h1:utDghgcjE8u+EBjHOgYT+dJPcnDF05KqWMBcjuJy510= -bazil.org/fuse v0.0.0-20200117225306-7b5117fecadc/go.mod h1:FbcW6z/2VytnFDhZfumh8Ss8zxHE6qpMP5sHTRe0EaM= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.31.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.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo= 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= @@ -186,8 +182,8 @@ cloud.google.com/go/compute/metadata v0.1.0/go.mod h1:Z1VN+bulIf6bt4P/C37K4DyZYZ cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= cloud.google.com/go/compute/metadata v0.2.1/go.mod h1:jgHgmJd2RKBGzXqF5LR2EZMGxBkeanZ9wwa75XHJgOM= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= -cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= -cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= +cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= +cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= cloud.google.com/go/contactcenterinsights v1.3.0/go.mod h1:Eu2oemoePuEFc/xKFPjbTuPSj0fYJcPls9TFlPNnHHY= cloud.google.com/go/contactcenterinsights v1.4.0/go.mod h1:L2YzkGbPsv+vMQMCADxJoT9YiTTnSEd6fEvCeHTYVck= cloud.google.com/go/contactcenterinsights v1.6.0/go.mod h1:IIDlT6CLcDoyv79kDv8iWxMSTZhLxSCofVV5W6YFM/w= @@ -626,6 +622,8 @@ cosmossdk.io/math v1.5.0 h1:sbOASxee9Zxdjd6OkzogvBZ25/hP929vdcYcBJQbkLc= cosmossdk.io/math v1.5.0/go.mod h1:AAwwBmUhqtk2nlku174JwSll+/DepUXW3rWIXN5q+Nw= cosmossdk.io/orm v1.0.0-beta.3 h1:XmffCwsIZE+y0sS4kEfRUfIgvJfGGn3HFKntZ91sWcU= cosmossdk.io/orm v1.0.0-beta.3/go.mod h1:KSH9lKA+0K++2OKECWwPAasKbUIEtZ7xYG+0ikChiyU= +cosmossdk.io/tools/confix v0.1.2 h1:2hoM1oFCNisd0ltSAAZw2i4ponARPmlhuNu3yy0VwI4= +cosmossdk.io/tools/confix v0.1.2/go.mod h1:7XfcbK9sC/KNgVGxgLM0BrFbVcR/+6Dg7MFfpx7duYo= cosmossdk.io/x/circuit v0.1.1 h1:KPJCnLChWrxD4jLwUiuQaf5mFD/1m7Omyo7oooefBVQ= cosmossdk.io/x/circuit v0.1.1/go.mod h1:B6f/urRuQH8gjt4eLIXfZJucrbreuYrKh5CSjaOxr+Q= cosmossdk.io/x/evidence v0.1.1 h1:Ks+BLTa3uftFpElLTDp9L76t2b58htjVbSZ86aoK/E4= @@ -638,20 +636,13 @@ cosmossdk.io/x/tx v0.13.7 h1:8WSk6B/OHJLYjiZeMKhq7DK7lHDMyK0UfDbBMxVmeOI= cosmossdk.io/x/tx v0.13.7/go.mod h1:V6DImnwJMTq5qFjeGWpXNiT/fjgE4HtmclRmTqRVM3w= cosmossdk.io/x/upgrade v0.1.4 h1:/BWJim24QHoXde8Bc64/2BSEB6W4eTydq0X/2f8+g38= cosmossdk.io/x/upgrade v0.1.4/go.mod h1:9v0Aj+fs97O+Ztw+tG3/tp5JSlrmT7IcFhAebQHmOPo= -dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= -dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= -dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= -git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= -github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 h1:cTp8I5+VIoKjsnZuH8vjyaysT/ses3EvZeaV/1UkF2M= -github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -660,8 +651,8 @@ github.com/CosmWasm/wasmvm v1.5.8 h1:vrmAvDuXcNqw7XqDiVDIyopo9gNdkcvRLFTC8+wBb/A github.com/CosmWasm/wasmvm v1.5.8/go.mod h1:2qaMB5ISmYXtpkJR2jy8xxx5Ti8sntOEf1cUgolb4QI= github.com/DataDog/datadog-go v3.2.0+incompatible h1:qSG2N4FghB1He/r2mFrWKCaL7dXCilEuNEeAn20fdD4= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e h1:ZIWapoIRN1VqT8GR8jAwb1Ie9GyehWjVcGh32Y2MznE= -github.com/DataDog/zstd v1.5.6-0.20230824185856-869dae002e5e/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= +github.com/DataDog/zstd v1.5.7 h1:ybO8RBeh29qrxIhCA9E8gKY6xfONU9T6G6aP9DTKfLE= +github.com/DataDog/zstd v1.5.7/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk= github.com/Jorropo/jsync v1.0.1 h1:6HgRolFZnsdfzRUj+ImB9og1JYOxQoReSywkHOGSaUU= github.com/Jorropo/jsync v1.0.1/go.mod h1:jCOZj3vrBCri3bSU3ErUYvevKlnbssrXeCivybS5ABQ= @@ -673,6 +664,10 @@ github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8 github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/Oudwins/zog v0.21.6 h1:3JVJA66fr59k2x72RojCB7v5XkVmtVsnp1YO/np595k= github.com/Oudwins/zog v0.21.6/go.mod h1:c4ADJ2zNkJp37ZViNy1o3ZZoeMvO7UQVO7BaPtRoocg= +github.com/RaduBerinde/axisds v0.0.0-20250419182453-5135a0650657 h1:8XBWWQD+vFF+JqOsm16t0Kab1a7YWV8+GISVEP8AuZ8= +github.com/RaduBerinde/axisds v0.0.0-20250419182453-5135a0650657/go.mod h1:UHGJonU9z4YYGKJxSaC6/TNcLOBptpmM5m2Cksbnw0Y= +github.com/RaduBerinde/btreemap v0.0.0-20250419174037-3d62b7205d54 h1:bsU8Tzxr/PNz75ayvCnxKZWEYdLMPDkUgticP4a4Bvk= +github.com/RaduBerinde/btreemap v0.0.0-20250419174037-3d62b7205d54/go.mod h1:0tr7FllbE9gJkHq7CVeeDDFAFKQVy5RnCSSNBOvdqbc= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA= @@ -683,8 +678,6 @@ github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrd github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/Workiva/go-datastructures v1.1.3 h1:LRdRrug9tEuKk7TGfz/sct5gjVj44G9pfqDt4qm7ghw= github.com/Workiva/go-datastructures v1.1.3/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= -github.com/aclements/go-perfevent v0.0.0-20240301234650-f7843625020f h1:JjxwchlOepwsUWcQwD2mLUAGE9aCp0/ehy6yCHFBOvo= -github.com/aclements/go-perfevent v0.0.0-20240301234650-f7843625020f/go.mod h1:tMDTce/yLLN/SK8gMOxQfnyeMeCg8KGzp0D1cbECEeo= github.com/adlio/schema v1.3.6 h1:k1/zc2jNfeiZBA5aFTRy37jlBIuCkXCm0XmvpzCKI9I= github.com/adlio/schema v1.3.6/go.mod h1:qkxwLgPBd1FgLRHYVCmQT/rrBr3JH38J9LjmVzWNudg= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= @@ -702,14 +695,11 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b h1:mimo19zliBX/vSQ6PWWSL9lK8qwHozUj03+zLoEB8O0= github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b/go.mod h1:fvzegU4vN3H1qMT+8wDmzjAcDONcgo2/SZ/TyfdUOFs= -github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5 h1:iW0a5ljuFxkLGPNem5Ui+KBjFJzKg4Fv2fnxe4dvzpM= -github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5/go.mod h1:Y2QMoi1vgtOIfc+6DhrMOGkLoGzqSV2rKp4Sm+opsyA= github.com/alexvec/go-bip39 v1.1.0 h1:NIIGUK5upunOmun1ud6wuLmgGOlyNJisOvaM+zPoWic= github.com/alexvec/go-bip39 v1.1.0/go.mod h1:krOrXeBrNpaizxUULtpLeQ64bm/+0vPMHk11kXwb9lY= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apache/arrow/go/v10 v10.0.1/go.mod h1:YvhnlEePVnBS4+0z3fhPfUy7W1Ikj0Ih0vcRo/gZ1M0= github.com/apache/arrow/go/v11 v11.0.0/go.mod h1:Eg5OsL5H+e299f7u5ssuXsuHQVEGC4xei5aX110hRiI= @@ -748,11 +738,6 @@ github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= -github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= -github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= github.com/btcsuite/btcd v0.23.5-0.20231215221805-96c9fd8078fd/go.mod h1:nm3Bko6zh6bWP60UxwoT5LzdGJsQJaPo6HjduXq9p6A= @@ -779,7 +764,6 @@ github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtE github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/bufbuild/protocompile v0.6.0 h1:Uu7WiSQ6Yj9DbkdnOe7U4mNKp58y9WDMKDn28/ZlunY= github.com/bufbuild/protocompile v0.6.0/go.mod h1:YNP35qEYoYGme7QMtz5SBCoN4kL4g12jTtjuzRNdjpE= -github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw= github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= @@ -787,8 +771,8 @@ github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxl github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= -github.com/caddyserver/certmagic v0.21.6 h1:1th6GfprVfsAtFNOu4StNMF5IxK5XiaI0yZhAHlZFPE= -github.com/caddyserver/certmagic v0.21.6/go.mod h1:n1sCo7zV1Ez2j+89wrzDxo4N/T1Ws/Vx8u5NvuBFabw= +github.com/caddyserver/certmagic v0.23.0 h1:CfpZ/50jMfG4+1J/u2LV6piJq4HOfO6ppOnOf7DkFEU= +github.com/caddyserver/certmagic v0.23.0/go.mod h1:9mEZIWqqWoI+Gf+4Trh04MOVPD0tGSxtqsxg87hAIH4= github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA= github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= @@ -800,8 +784,6 @@ github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyY github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= -github.com/ceramicnetwork/go-dag-jose v0.1.1 h1:7pObs22egc14vSS3AfCFfS1VmaL4lQUsAK7OGC3PlKk= -github.com/ceramicnetwork/go-dag-jose v0.1.1/go.mod h1:8ptnYwY2Z2y/s5oJnNBn/UCxLg6CpramNJ2ZXF/5aNY= github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= @@ -843,23 +825,21 @@ github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b80 github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= github.com/cockroachdb/apd/v3 v3.2.1 h1:U+8j7t0axsIgvQUqthuNm82HIrYXodOV2iWLWtEaIwg= github.com/cockroachdb/apd/v3 v3.2.1/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc= -github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94 h1:bvJv505UUfjzbaIPdNS4AEkHreDqQk6yuNpsdRHpwFA= -github.com/cockroachdb/crlib v0.0.0-20241015224233-894974b3ad94/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= +github.com/cockroachdb/crlib v0.0.0-20241112164430-1264a2edc35b h1:SHlYZ/bMx7frnmeqCu+xm0TCxXLzX3jQIVuFbnFGtFU= +github.com/cockroachdb/crlib v0.0.0-20241112164430-1264a2edc35b/go.mod h1:Gq51ZeKaFCXk6QwuGM0w1dnaOqc/F5zKT2zA9D6Xeac= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/cockroachdb/datadriven v1.0.3-0.20240530155848-7682d40af056 h1:slXychO2uDM6hYRu4c0pD0udNI8uObfeKN6UInWViS8= -github.com/cockroachdb/datadriven v1.0.3-0.20240530155848-7682d40af056/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= +github.com/cockroachdb/datadriven v1.0.3-0.20250407164829-2945557346d5 h1:UycK/E0TkisVrQbSoxvU827FwgBBcZ95nRRmpj/12QI= +github.com/cockroachdb/datadriven v1.0.3-0.20250407164829-2945557346d5/go.mod h1:jsaKMvD3RBCATk1/jbUZM8C9idWBJME9+VRZ5+Liq1g= github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= -github.com/cockroachdb/metamorphic v0.0.0-20231108215700-4ba948b56895 h1:XANOgPYtvELQ/h4IrmPAohXqe2pWA8Bwhejr3VQoZsA= -github.com/cockroachdb/metamorphic v0.0.0-20231108215700-4ba948b56895/go.mod h1:aPd7gM9ov9M8v32Yy5NJrDyOcD8z642dqs+F0CeNXfA= github.com/cockroachdb/pebble v1.1.2 h1:CUh2IPtR4swHlEj48Rhfzw6l/d0qA31fItcIszQVIsA= github.com/cockroachdb/pebble v1.1.2/go.mod h1:4exszw1r40423ZsmkG/09AFEG83I0uDgfujJdbL6kYU= -github.com/cockroachdb/pebble/v2 v2.0.3 h1:YJ3Sc9jRN/q6OOCNyRHPbcpenbxL1DdgdpUqPlPus6o= -github.com/cockroachdb/pebble/v2 v2.0.3/go.mod h1:NgxgNcWwyG/uxkLUZGM2aelshaLIZvc0hCX7SCfaO8s= +github.com/cockroachdb/pebble/v2 v2.1.0 h1:6KZvjSpWcEXZUvlLzTRC7T1A2G7r+bFskIzggklxixo= +github.com/cockroachdb/pebble/v2 v2.1.0/go.mod h1:Aza05DCCc05ghIJZkB4Q/axv/JK9wx5cFwWcnhG0eGw= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/swiss v0.0.0-20250624142022-d6e517c1d961 h1:Nua446ru3juLHLZd4AwKNzClZgL1co3pUPGv3o8FlcA= @@ -877,7 +857,6 @@ github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvA github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= @@ -917,6 +896,10 @@ github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3 github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf h1:dwGgBWn84wUS1pVikGiruW+x5XM4amhjaZO20vCjay4= github.com/crackcomm/go-gitignore v0.0.0-20241020182519-7843d2ba8fdf/go.mod h1:p1d6YEZWvFzEh4KLyvBcVSnrfNDDvK2zfK/4x2v/4pE= +github.com/creachadair/atomicfile v0.3.1 h1:yQORkHjSYySh/tv5th1dkKcn02NEW5JleB84sjt+W4Q= +github.com/creachadair/atomicfile v0.3.1/go.mod h1:mwfrkRxFKwpNAflYZzytbSwxvbK6fdGRRlp0KEQc0qU= +github.com/creachadair/tomledit v0.0.24 h1:5Xjr25R2esu1rKCbQEmjZYlrhFkDspoAbAKb6QKQDhQ= +github.com/creachadair/tomledit v0.0.24/go.mod h1:9qHbShRWQzSCcn617cMzg4eab1vbLCOjOshAWSzWr8U= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cskr/pubsub v1.0.2 h1:vlOzMhl6PFn60gRlTQQsIfVwaPB/B/8MziK8FhEPt/0= @@ -945,17 +928,12 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjY github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= -github.com/dgraph-io/badger v1.6.2 h1:mNw0qs90GVgGGWylh0umH5iag1j6n/PeJtNvL6KY/x8= -github.com/dgraph-io/badger v1.6.2/go.mod h1:JW2yswe3V058sS0kZ2h/AXeDSqFjxnZcRrVH//y2UQE= -github.com/dgraph-io/badger/v4 v4.2.0 h1:kJrlajbXXL9DFTNuhhu9yCx7JJa4qpYWxtE8BzuWsEs= -github.com/dgraph-io/badger/v4 v4.2.0/go.mod h1:qfCqhPoWDFJRx1gp5QwwyGo8xk1lbHUxvK9nK0OGAak= -github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= -github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgraph-io/badger/v4 v4.5.1 h1:7DCIXrQjo1LKmM96YD+hLVJ2EEsyyoWxJfpdd56HLps= +github.com/dgraph-io/badger/v4 v4.5.1/go.mod h1:qn3Be0j3TfV4kPbVoK0arXCD1/nr1ftth6sbL5jxdoA= +github.com/dgraph-io/ristretto/v2 v2.1.0 h1:59LjpOJLNDULHh8MC4UaegN52lC4JnO2dITsie/Pa8I= +github.com/dgraph-io/ristretto/v2 v2.1.0/go.mod h1:uejeqfYXpUomfse0+lO+13ATz4TypQYLJZzBSAemuB4= github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0= github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= @@ -1025,7 +1003,6 @@ github.com/filecoin-project/go-clock v0.1.0 h1:SFbYIM75M8NnFm1yMHhN9Ahy3W5bEZV9g github.com/filecoin-project/go-clock v0.1.0/go.mod h1:4uB/O4PvOjlx1VCMdZ9MyDZXRm//gkj1ELEbxfI1AZs= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5 h1:FtmdgXiUlNeRsoNMFlKLDt+S+6hbjVMEW6RGQ7aUf7c= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= 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/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= @@ -1045,21 +1022,15 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/gabriel-vasile/mimetype v1.4.6 h1:3+PzJTKLkvgjeTbts6msPJt4DixhT4YtFNf1gtGe3zc= -github.com/gabriel-vasile/mimetype v1.4.6/go.mod h1:JX1qVKqZd40hUPpAfiNTe0Sne7hdfKSbOqqmkq8GCXc= -github.com/gammazero/chanqueue v1.1.0 h1:yiwtloc1azhgGLFo2gMloJtQvkYD936Ai7tBfa+rYJw= -github.com/gammazero/chanqueue v1.1.0/go.mod h1:fMwpwEiuUgpab0sH4VHiVcEoji1pSi+EIzeG4TPeKPc= -github.com/gammazero/deque v1.0.0 h1:LTmimT8H7bXkkCy6gZX7zNLtkbz4NdS2z8LZuor3j34= -github.com/gammazero/deque v1.0.0/go.mod h1:iflpYvtGfM3U8S8j+sZEKIak3SAKYpA5/SQewgfXDKo= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0= +github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gammazero/chanqueue v1.1.1 h1:n9Y+zbBxw2f7uUE9wpgs0rOSkP/I/yhDLiNuhyVjojQ= +github.com/gammazero/chanqueue v1.1.1/go.mod h1:fMwpwEiuUgpab0sH4VHiVcEoji1pSi+EIzeG4TPeKPc= +github.com/gammazero/deque v1.1.0 h1:OyiyReBbnEG2PP0Bnv1AASLIYvyKqIFN5xfl1t8oGLo= +github.com/gammazero/deque v1.1.0/go.mod h1:JVrR+Bj1NMQbPnYclvDlvSX0nVGReLrQZ0aUMuWLctg= github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= -github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9 h1:r5GgOLGbza2wVHRzK7aAj6lWZjfbAwiu/RDCVOKjRyM= -github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9/go.mod h1:106OIgooyS7OzLDOpUGgm9fA3bQENb/cFSyyBmMoJDs= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-fonts/dejavu v0.1.0/go.mod h1:4Wt4I4OU2Nq9asgDCteaAaWZOV24E+0/Pwo0gppep4g= @@ -1070,8 +1041,6 @@ github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmn 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-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= -github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= @@ -1088,8 +1057,8 @@ github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= @@ -1105,6 +1074,8 @@ github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0= @@ -1138,15 +1109,12 @@ github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGw github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= -github.com/golang/glog v1.2.4 h1:CNNw5U8lSiiBk7druxtSHHTsRWcxKoac6kZKm2peBBc= -github.com/golang/glog v1.2.4/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= 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/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= 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= @@ -1189,8 +1157,8 @@ github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/flatbuffers v2.0.8+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= -github.com/google/flatbuffers v23.5.26+incompatible h1:M9dgRyhJemaM4Sw8+66GHBu8ioaQmyPLg1b8VwK5WJg= -github.com/google/flatbuffers v23.5.26+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/flatbuffers v24.12.23+incompatible h1:ubBKR94NR4pXUCY/MUsRVzd9umNW7ht7EG9hHfS9FX8= +github.com/google/flatbuffers v24.12.23+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= 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= @@ -1209,10 +1177,8 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 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/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= -github.com/google/go-tpm v0.9.5 h1:ocUmnDebX54dnW+MQWGQRbdaAcJELsa6PqZhJ48KwVU= -github.com/google/go-tpm v0.9.5/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= +github.com/google/go-tpm v0.9.6 h1:Ku42PT4LmjDu1H5C5ISWLlpI1mj+Zq7sPGKoRw2XROA= +github.com/google/go-tpm v0.9.6/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= @@ -1244,8 +1210,8 @@ github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20250208200701-d0013a598941 h1:43XjGa6toxLpeksjcxs1jIoIyr+vUfOqY2c6HB4bpoc= -github.com/google/pprof v0.0.0-20250208200701-d0013a598941/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= +github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a h1://KbezygeMJZCSHH+HgUZiTeSoiuFspbMg1ge+eFj18= +github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= @@ -1261,8 +1227,6 @@ github.com/googleapis/enterprise-certificate-proxy v0.2.1/go.mod h1:AwSRAtLfXpU5 github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= -github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= -github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= 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/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= @@ -1292,20 +1256,16 @@ github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 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/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= 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/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3/go.mod h1:o//XUCC/F+yRGJoPO/VU0GSB0f8Nhgmxx0VIRUvaC0w= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= @@ -1363,8 +1323,6 @@ github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= github.com/hdevalence/ed25519consensus v0.1.0 h1:jtBwzzcHuTmFrQN6xQZn6CQEO/V9f7HsjsjeEZ6auqU= github.com/hdevalence/ed25519consensus v0.1.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= -github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw= -github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg= github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA= github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA= @@ -1384,100 +1342,70 @@ github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSAS 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/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw= -github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b h1:ogbOPx86mIhFy764gGkqnkFC8m5PJA7sPzlk9ppLVQA= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= 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/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= -github.com/ipfs-shipyard/nopfs v0.0.14 h1:HFepJt/MxhZ3/GsLZkkAPzIPdNYKaLO1Qb7YmPbWIKk= -github.com/ipfs-shipyard/nopfs v0.0.14/go.mod h1:mQyd0BElYI2gB/kq/Oue97obP4B3os4eBmgfPZ+hnrE= -github.com/ipfs-shipyard/nopfs/ipfs v0.25.0 h1:OqNqsGZPX8zh3eFMO8Lf8EHRRnSGBMqcdHUd7SDsUOY= -github.com/ipfs-shipyard/nopfs/ipfs v0.25.0/go.mod h1:BxhUdtBgOXg1B+gAPEplkg/GpyTZY+kCMSfsJvvydqU= github.com/ipfs/bbloom v0.0.4 h1:Gi+8EGJ2y5qiD5FbsbpX/TMNcJw8gSqr7eyjHa4Fhvs= github.com/ipfs/bbloom v0.0.4/go.mod h1:cS9YprKXpoZ9lT0n/Mw/a6/aFV6DTjTLYHeA+gyqMG0= -github.com/ipfs/boxo v0.32.0 h1:rBs3P53Wt9bFW9WJwVdkzLtzYCXAj2bMjM7+1nrazZw= -github.com/ipfs/boxo v0.32.0/go.mod h1:VEtO3gOmr+sXGodalaTV9Vvsp3qVYegc4Rcu08Iw+wM= +github.com/ipfs/boxo v0.35.0 h1:3Mku5arSbAZz0dvb4goXRsQuZkFkPrGr5yYdu0YM1pY= +github.com/ipfs/boxo v0.35.0/go.mod h1:uhaF0DGnbgEiXDTmD249jCGbxVkMm6+Ew85q6Uub7lo= github.com/ipfs/go-bitfield v1.1.0 h1:fh7FIo8bSwaJEh6DdTWbCeZ1eqOaOkKFI74SCnsWbGA= github.com/ipfs/go-bitfield v1.1.0/go.mod h1:paqf1wjq/D2BBmzfTVFlJQ9IlFOZpg422HL0HqsGWHU= -github.com/ipfs/go-block-format v0.2.1 h1:96kW71XGNNa+mZw/MTzJrCpMhBWCrd9kBLoKm9Iip/Q= -github.com/ipfs/go-block-format v0.2.1/go.mod h1:frtvXHMQhM6zn7HvEQu+Qz5wSTj+04oEH/I+NjDgEjk= +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.5.0 h1:goEKKhaGm0ul11IHA7I6p1GmKz8kEYniqFopaB5Otwg= github.com/ipfs/go-cid v0.5.0/go.mod h1:0L7vmeNXpQpUS9vt+yEARkJ8rOg43DF3iPgn4GIN0mk= github.com/ipfs/go-cidutil v0.1.0 h1:RW5hO7Vcf16dplUU60Hs0AKDkQAVPVplr7lk97CFL+Q= github.com/ipfs/go-cidutil v0.1.0/go.mod h1:e7OEVBMIv9JaOxt9zaGEmAoSlXW9jdFZ5lP/0PwcfpA= -github.com/ipfs/go-datastore v0.8.2 h1:Jy3wjqQR6sg/LhyY0NIePZC3Vux19nLtg7dx0TVqr6U= -github.com/ipfs/go-datastore v0.8.2/go.mod h1:W+pI1NsUsz3tcsAACMtfC+IZdnQTnC/7VfPoJBQuts0= +github.com/ipfs/go-datastore v0.9.0 h1:WocriPOayqalEsueHv6SdD4nPVl4rYMfYGLD4bqCZ+w= +github.com/ipfs/go-datastore v0.9.0/go.mod h1:uT77w/XEGrvJWwHgdrMr8bqCN6ZTW9gzmi+3uK+ouHg= 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-ds-badger v0.3.4 h1:MmqFicftE0KrwMC77WjXTrPuoUxhwyFsjKONSeWrlOo= -github.com/ipfs/go-ds-badger v0.3.4/go.mod h1:HfqsKJcNnIr9ZhZ+rkwS1J5PpaWjJjg6Ipmxd7KPfZ8= -github.com/ipfs/go-ds-flatfs v0.5.5 h1:lkx5C99pFBMI7T1sYF7y3v7xIYekNVNMp/95Gm9Y3tY= -github.com/ipfs/go-ds-flatfs v0.5.5/go.mod h1:bM7+m7KFUyv5dp3RBKTr3+OHgZ6h8ydCQkO7tjeO9Z4= -github.com/ipfs/go-ds-leveldb v0.5.2 h1:6nmxlQ2zbp4LCNdJVsmHfs9GP0eylfBNxpmY1csp0x0= -github.com/ipfs/go-ds-leveldb v0.5.2/go.mod h1:2fAwmcvD3WoRT72PzEekHBkQmBDhc39DJGoREiuGmYo= -github.com/ipfs/go-ds-measure v0.2.2 h1:4kwvBGbbSXNYe4ANlg7qTIYoZU6mNlqzQHdVqICkqGI= -github.com/ipfs/go-ds-measure v0.2.2/go.mod h1:b/87ak0jMgH9Ylt7oH0+XGy4P8jHx9KG09Qz+pOeTIs= -github.com/ipfs/go-ds-pebble v0.5.0 h1:lXffYCAKVD7nLLPqwJ9D8IxgO7Kz8woiX021tezdsIM= -github.com/ipfs/go-ds-pebble v0.5.0/go.mod h1:aiCRVcj3K60sxc6k5C+HO9C6rouqiSkjR/WKnbTcMfQ= -github.com/ipfs/go-fs-lock v0.1.1 h1:TecsP/Uc7WqYYatasreZQiP9EGRy4ZnKoG4yXxR33nw= -github.com/ipfs/go-fs-lock v0.1.1/go.mod h1:2goSXMCw7QfscHmSe09oXiR34DQeUdm+ei+dhonqly0= -github.com/ipfs/go-ipfs-blockstore v1.3.1 h1:cEI9ci7V0sRNivqaOr0elDsamxXFxJMMMy7PTTDQNsQ= -github.com/ipfs/go-ipfs-blockstore v1.3.1/go.mod h1:KgtZyc9fq+P2xJUiCAzbRdhhqJHvsw8u2Dlqy2MyRTE= -github.com/ipfs/go-ipfs-cmds v0.14.1 h1:TA8vBixPwXL3k7VtcbX3r4FQgw2m+jMOWlslUOlM9Rs= -github.com/ipfs/go-ipfs-cmds v0.14.1/go.mod h1:SCYxNUVPeVR05cE8DJ6wyH2+aQ8vPgjxxkxQWOXobzo= +github.com/ipfs/go-dsqueue v0.0.5 h1:TUOk15TlCJ/NKV8Yk2W5wgkEjDa44Nem7a7FGIjsMNU= +github.com/ipfs/go-dsqueue v0.0.5/go.mod h1:i/jAlpZjBbQJLioN+XKbFgnd+u9eAhGZs9IrqIzTd9g= +github.com/ipfs/go-ipfs-cmds v0.15.0 h1:nQDgKadrzyiFyYoZMARMIoVoSwe3gGTAfGvrWLeAQbQ= +github.com/ipfs/go-ipfs-cmds v0.15.0/go.mod h1:VABf/mv/wqvYX6hLG6Z+40eNAEw3FQO0bSm370Or3Wk= github.com/ipfs/go-ipfs-delay v0.0.1 h1:r/UXYyRcddO6thwOnhiznIAiSvxMECGgtv35Xs1IeRQ= github.com/ipfs/go-ipfs-delay v0.0.1/go.mod h1:8SP1YXK1M1kXuc4KJZINY3TQQ03J2rwBG9QfXmbRPrw= -github.com/ipfs/go-ipfs-ds-help v1.1.1 h1:B5UJOH52IbcfS56+Ul+sv8jnIV10lbjLF5eOO0C66Nw= -github.com/ipfs/go-ipfs-ds-help v1.1.1/go.mod h1:75vrVCkSdSFidJscs8n4W+77AtTpCIAdDGAwjitJMIo= github.com/ipfs/go-ipfs-pq v0.0.3 h1:YpoHVJB+jzK15mr/xsWC574tyDLkezVrDNeaalQBsTE= github.com/ipfs/go-ipfs-pq v0.0.3/go.mod h1:btNw5hsHBpRcSSgZtiNm/SLj5gYIZ18AKtv3kERkRb4= github.com/ipfs/go-ipfs-redirects-file v0.1.2 h1:QCK7VtL91FH17KROVVy5KrzDx2hu68QvB2FTWk08ZQk= github.com/ipfs/go-ipfs-redirects-file v0.1.2/go.mod h1:yIiTlLcDEM/8lS6T3FlCEXZktPPqSOyuY6dEzVqw7Fw= -github.com/ipfs/go-ipfs-util v0.0.3 h1:2RFdGez6bu2ZlZdI+rWfIdbQb1KudQp3VGwPtdNCmE0= -github.com/ipfs/go-ipfs-util v0.0.3/go.mod h1:LHzG1a0Ig4G+iZ26UUOMjHd+lfM84LZCrn17xAKWBvs= -github.com/ipfs/go-ipld-cbor v0.2.0 h1:VHIW3HVIjcMd8m4ZLZbrYpwjzqlVUfjLM7oK4T5/YF0= -github.com/ipfs/go-ipld-cbor v0.2.0/go.mod h1:Cp8T7w1NKcu4AQJLqK0tWpd1nkgTxEVB5C6kVpLW6/0= -github.com/ipfs/go-ipld-format v0.6.1 h1:lQLmBM/HHbrXvjIkrydRXkn+gc0DE5xO5fqelsCKYOQ= -github.com/ipfs/go-ipld-format v0.6.1/go.mod h1:8TOH1Hj+LFyqM2PjSqI2/ZnyO0KlfhHbJLkbxFa61hs= -github.com/ipfs/go-ipld-git v0.1.1 h1:TWGnZjS0htmEmlMFEkA3ogrNCqWjIxwr16x1OsdhG+Y= -github.com/ipfs/go-ipld-git v0.1.1/go.mod h1:+VyMqF5lMcJh4rwEppV0e6g4nCCHXThLYYDpKUkJubI= -github.com/ipfs/go-ipld-legacy v0.2.1 h1:mDFtrBpmU7b//LzLSypVrXsD8QxkEWxu5qVxN99/+tk= -github.com/ipfs/go-ipld-legacy v0.2.1/go.mod h1:782MOUghNzMO2DER0FlBR94mllfdCJCkTtDtPM51otM= -github.com/ipfs/go-log v1.0.5 h1:2dOuUCB1Z7uoczMWgAyDck5JLb72zHzrMnGnCNNbvY8= -github.com/ipfs/go-log v1.0.5/go.mod h1:j0b8ZoR+7+R99LD9jZ6+AJsrzkPbSXbZfGakb5JPtIo= -github.com/ipfs/go-log/v2 v2.1.3/go.mod h1:/8d0SH3Su5Ooc31QlL1WysJhvyOTDCjcCZ9Axpmri6g= -github.com/ipfs/go-log/v2 v2.6.0 h1:2Nu1KKQQ2ayonKp4MPo6pXCjqw1ULc9iohRqWV5EYqg= -github.com/ipfs/go-log/v2 v2.6.0/go.mod h1:p+Efr3qaY5YXpx9TX7MoLCSEZX5boSWj9wh86P5HJa8= +github.com/ipfs/go-ipld-cbor v0.2.1 h1:H05yEJbK/hxg0uf2AJhyerBDbjOuHX4yi+1U/ogRa7E= +github.com/ipfs/go-ipld-cbor v0.2.1/go.mod h1:x9Zbeq8CoE5R2WicYgBMcr/9mnkQ0lHddYWJP2sMV3A= +github.com/ipfs/go-ipld-format v0.6.3 h1:9/lurLDTotJpZSuL++gh3sTdmcFhVkCwsgx2+rAh4j8= +github.com/ipfs/go-ipld-format v0.6.3/go.mod h1:74ilVN12NXVMIV+SrBAyC05UJRk0jVvGqdmrcYZvCBk= +github.com/ipfs/go-ipld-legacy v0.2.2 h1:DThbqCPVLpWBcGtU23KDLiY2YRZZnTkXQyfz8aOfBkQ= +github.com/ipfs/go-ipld-legacy v0.2.2/go.mod h1:hhkj+b3kG9b2BcUNw8IFYAsfeNo8E3U7eYlWeAOPyDU= +github.com/ipfs/go-log/v2 v2.8.1 h1:Y/X36z7ASoLJaYIJAL4xITXgwf7RVeqb1+/25aq/Xk0= +github.com/ipfs/go-log/v2 v2.8.1/go.mod h1:NyhTBcZmh2Y55eWVjOeKf8M7e4pnJYM3yDZNxQBWEEY= github.com/ipfs/go-metrics-interface v0.3.0 h1:YwG7/Cy4R94mYDUuwsBfeziJCVm9pBMJ6q/JR9V40TU= github.com/ipfs/go-metrics-interface v0.3.0/go.mod h1:OxxQjZDGocXVdyTPocns6cOLwHieqej/jos7H4POwoY= github.com/ipfs/go-peertaskqueue v0.8.2 h1:PaHFRaVFdxQk1Qo3OKiHPYjmmusQy7gKQUaL8JDszAU= github.com/ipfs/go-peertaskqueue v0.8.2/go.mod h1:L6QPvou0346c2qPJNiJa6BvOibxDfaiPlqHInmzg0FA= -github.com/ipfs/go-test v0.2.2 h1:1yjYyfbdt1w93lVzde6JZ2einh3DIV40at4rVoyEcE8= -github.com/ipfs/go-test v0.2.2/go.mod h1:cmLisgVwkdRCnKu/CFZOk2DdhOcwghr5GsHeqwexoRA= -github.com/ipfs/go-unixfsnode v1.10.1 h1:hGKhzuH6NSzZ4y621wGuDspkjXRNG3B+HqhlyTjSwSM= -github.com/ipfs/go-unixfsnode v1.10.1/go.mod h1:eguv/otvacjmfSbYvmamc9ssNAzLvRk0+YN30EYeOOY= -github.com/ipfs/kubo v0.35.0 h1:gSL9deP/W5Vmyz/lZ37KeX4mIaXoPQ/97xxZpqlUr00= -github.com/ipfs/kubo v0.35.0/go.mod h1:wAZKTT0wbblEWvysWo7MBC3/NlzK2jkNrX/JcjqR6q8= -github.com/ipld/go-car/v2 v2.14.3 h1:1Mhl82/ny8MVP+w1M4LXbj4j99oK3gnuZG2GmG1IhC8= -github.com/ipld/go-car/v2 v2.14.3/go.mod h1:/vpSvPngOX8UnvmdFJ3o/mDgXa9LuyXsn7wxOzHDYQE= +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/ipfs/go-unixfsnode v1.10.2 h1:TREegX1J4X+k1w4AhoDuxxFvVcS9SegMRvrmxF6Tca8= +github.com/ipfs/go-unixfsnode v1.10.2/go.mod h1:ImDPTSiKZ+2h4UVdkSDITJHk87bUAp7kX/lgifjRicg= +github.com/ipfs/kubo v0.38.1 h1:y8GYMY8R4nFYzQfchPmYrVdC2F7RvK1YTpmqhZNlSF4= +github.com/ipfs/kubo v0.38.1/go.mod h1:lTCedbpplztHA/spUWG2E1F5eQSITwPVC4zT1MiB/eI= +github.com/ipld/go-car/v2 v2.15.0 h1:RxtZcGXFx72zFESl+UUsCNQV2YMcy3gEMYx9M3uio24= +github.com/ipld/go-car/v2 v2.15.0/go.mod h1:ovlq/n3xlVJDmoiN3Kd/Z7kIzQbdTIFSwltfOP+qIgk= github.com/ipld/go-codec-dagpb v1.7.0 h1:hpuvQjCSVSLnTnHXn+QAMR0mLmb1gA6wl10LExo2Ts0= github.com/ipld/go-codec-dagpb v1.7.0/go.mod h1:rD3Zg+zub9ZnxcLwfol/OTQRVjaLzXypgy4UqHQvilM= github.com/ipld/go-ipld-prime v0.21.0 h1:n4JmcpOlPDIxBcY037SVfpd1G+Sj1nKZah0m6QH9C2E= github.com/ipld/go-ipld-prime v0.21.0/go.mod h1:3RLqy//ERg/y5oShXXdx5YIp50cFGOanyMctpPjsvxQ= -github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20230102063945-1a409dc236dd h1:gMlw/MhNr2Wtp5RwGdsW23cs+yCuj9k2ON7i9MiJlRo= -github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20230102063945-1a409dc236dd/go.mod h1:wZ8hH8UxeryOs4kJEJaiui/s00hDSbE37OKsL47g+Sw= -github.com/ipshipyard/p2p-forge v0.5.1 h1:9MCpAlk+wNhy7W/yOYKgi9KlXPnyb0abmDpsRPHUDxQ= -github.com/ipshipyard/p2p-forge v0.5.1/go.mod h1:GNDXM2CR8KRS8mJGw7ARIRVlrG9NH8MdewgNVfIIByA= +github.com/ipshipyard/p2p-forge v0.6.1 h1:987/hUC1YxI56CcMX6iTB+9BLjFV0d2SJnig9Z1pf8A= +github.com/ipshipyard/p2p-forge v0.6.1/go.mod h1:pj8Zcs+ex5OMq5a1bFLHqW0oL3qYO0v5eGLZmit0l7U= 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/jbenet/goprocess v0.1.4 h1:DRGOFReOMqqDNXwW70QkacFW0YN9QnwLV0Vqk+3oU0o= -github.com/jbenet/goprocess v0.1.4/go.mod h1:5yspPrukOVuOLORacaBi858NqyClJPQxYZlqdZVfqY4= -github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jhump/protoreflect v1.15.3 h1:6SFRuqU45u9hIZPJAoZ8c28T3nK64BNdp9w6jFonzls= @@ -1522,8 +1450,8 @@ github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrD 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.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= -github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +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/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -1537,14 +1465,11 @@ github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NB 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/pty v1.1.3/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/labstack/echo-jwt/v4 v4.3.1 h1:d8+/qf8nx7RxeL46LtoIwHJsH2PNN8xXCQ/jDianycE= -github.com/labstack/echo-jwt/v4 v4.3.1/go.mod h1:yJi83kN8S/5vePVPd+7ID75P4PqPNVRs2HVeuvYJH00= github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA= github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ= github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0= @@ -1553,36 +1478,30 @@ github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzW github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/libdns/libdns v0.2.2 h1:O6ws7bAfRPaBsgAYt8MDe2HcNBGC29hkZ9MX2eUSX3s= -github.com/libdns/libdns v0.2.2/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= +github.com/libdns/libdns v1.0.0-beta.1 h1:KIf4wLfsrEpXpZ3vmc/poM8zCATXT2klbdPe6hyOBjQ= +github.com/libdns/libdns v1.0.0-beta.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= 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-doh-resolver v0.5.0 h1:4h7plVVW+XTS+oUBw2+8KfoM1jF6w8XmO7+skhePFdE= github.com/libp2p/go-doh-resolver v0.5.0/go.mod h1:aPDxfiD2hNURgd13+hfo29z9IC22fv30ee5iM31RzxU= -github.com/libp2p/go-flow-metrics v0.2.0 h1:EIZzjmeOE6c8Dav0sNv35vhZxATIXWZg6j/C08XmmDw= -github.com/libp2p/go-flow-metrics v0.2.0/go.mod h1:st3qqfu8+pMfh+9Mzqb2GTiwrAGjIPszEjZmtksN8Jc= +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.43.0 h1:b2bg2cRNmY4HpLK8VHYQXLX2d3iND95OjodLFymvqXU= github.com/libp2p/go-libp2p v0.43.0/go.mod h1:IiSqAXDyP2sWH+J2gs43pNmB/y4FOi2XQPbsb+8qvzc= 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.33.1 h1:hKFhHMf7WH69LDjaxsJUWOU6qZm71uO47M/a5ijkiP0= -github.com/libp2p/go-libp2p-kad-dht v0.33.1/go.mod h1:CdmNk4VeGJa9EXM9SLNyNVySEvduKvb+5rSC/H4pLAo= -github.com/libp2p/go-libp2p-kbucket v0.7.0 h1:vYDvRjkyJPeWunQXqcW2Z6E93Ywx7fX0jgzb/dGOKCs= -github.com/libp2p/go-libp2p-kbucket v0.7.0/go.mod h1:blOINGIj1yiPYlVEX0Rj9QwEkmVnz3EP8LK1dRKBC6g= -github.com/libp2p/go-libp2p-pubsub v0.13.1 h1:tV3ttzzZSCk0EtEXnxVmWIXgjVxXx+20Jwjbs/Ctzjo= -github.com/libp2p/go-libp2p-pubsub v0.13.1/go.mod h1:MKPU5vMI8RRFyTP0HfdsF9cLmL1nHAeJm44AxJGJx44= -github.com/libp2p/go-libp2p-pubsub-router v0.6.0 h1:D30iKdlqDt5ZmLEYhHELCMRj8b4sFAqrUcshIUvVP/s= -github.com/libp2p/go-libp2p-pubsub-router v0.6.0/go.mod h1:FY/q0/RBTKsLA7l4vqC2cbRbOvyDotg8PJQ7j8FDudE= +github.com/libp2p/go-libp2p-kad-dht v0.35.0 h1:pWRC4FKR9ptQjA9DuMSrAn2D3vABE8r58iAeoLoK1Ig= +github.com/libp2p/go-libp2p-kad-dht v0.35.0/go.mod h1:s70f017NjhsBx+SVl0/w+x//uyglrFpKLfvuQJj4QAU= +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-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-libp2p-xor v0.1.0 h1:hhQwT4uGrBcuAkUGXADuPltalOdpf9aag9kaYNT2tLA= -github.com/libp2p/go-libp2p-xor v0.1.0/go.mod h1:LSTM5yRnjGZbWNTA/hRwq2gGFrvRIbQJscoIL/u6InY= 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.2.2 h1:Dejd8cQ47Qx2kRABg6lPwknU7+nBnFRpko45/fFPuZ8= @@ -1591,8 +1510,6 @@ github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQsc github.com/libp2p/go-reuseport v0.4.0/go.mod h1:ZtI03j/wO5hZVDFo2jKywN6bYKWLOy8Se6DrI2E1cLU= github.com/libp2p/go-yamux/v5 v5.0.1 h1:f0WoX/bEF2E8SbE4c/k1Mo+/9z0O4oC/hWEA+nfYRSg= github.com/libp2p/go-yamux/v5 v5.0.1/go.mod h1:en+3cdX51U0ZslwRdRLrvQsdayFt3TSUKvBGErzpWbU= -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/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/linxGnu/grocksdb v1.9.8 h1:vOIKv9/+HKiqJAElJIEYv3ZLcihRxyP7Suu/Mu8Dxjs= @@ -1601,14 +1518,12 @@ github.com/lithammer/shortuuid/v4 v4.0.0 h1:QRbbVkfgNippHOS8PXDkti4NaWeyYfcBTHtw github.com/lithammer/shortuuid/v4 v4.0.0/go.mod h1:Zs8puNcrvf2rV9rTH51ZLLcj7ZXqQI3lv67aw4KiB1Y= github.com/lmittmann/tint v1.0.3 h1:W5PHeA2D8bBJVvabNfQD/XW9HPLZK1XoPZH0cq8NouQ= github.com/lmittmann/tint v1.0.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE= -github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= github.com/lyft/protoc-gen-star v0.6.0/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/lyft/protoc-gen-star v0.6.1/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/lyft/protoc-gen-star/v2 v2.0.1/go.mod h1:RcCdONR2ScXaYnQC5tUzxzlpA3WVYF7/opLeUgcQs/o= github.com/lyft/protoc-gen-star/v2 v2.0.3/go.mod h1:amey7yeodaJhXSbf/TlLvWiqQfLOSpEk//mLlc+axEk= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= -github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd h1:br0buuQ854V8u83wA0rVZ8ttrq5CpaPZdvrK0LP2lOk= @@ -1636,12 +1551,11 @@ github.com/mattn/go-sqlite3 v1.14.14/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4 github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/mholt/acmez/v3 v3.0.0 h1:r1NcjuWR0VaKP2BTjDK9LRFBw/WvURx3jlaEUl9Ht8E= -github.com/mholt/acmez/v3 v3.0.0/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= -github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/mholt/acmez/v3 v3.1.2 h1:auob8J/0FhmdClQicvJvuDavgd5ezwLBfKuYmynhYzc= +github.com/mholt/acmez/v3 v3.1.2/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/miekg/dns v1.1.66 h1:FeZXOS3VCVsKnEAd+wBkjMC3D2K+ww66Cq3VnCINuJE= -github.com/miekg/dns v1.1.66/go.mod h1:jGFzBsSNbJw6z1HYut1RKBKHA9PBdxeHrZG8J+gC2WE= +github.com/miekg/dns v1.1.68 h1:jsSRkNozw7G/mnmXULynzMNIsgY2dHC8LO6U6Ij2JEA= +github.com/miekg/dns v1.1.68/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps= 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= @@ -1649,11 +1563,11 @@ github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc/go.mod h1:cGKTAVKx4S github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= -github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= github.com/minio/highwayhash v1.0.3 h1:kbnuUMoHYyVl7szWjSxJnxw11k2U709jqFPPmIUyD6Q= github.com/minio/highwayhash v1.0.3/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= -github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM= +github.com/minio/minlz v1.0.1-0.20250507153514-87eb42fe8882 h1:0lgqHvJWHLGW5TuObJrfyEi6+ASTKDBWikGvPqy9Yiw= +github.com/minio/minlz v1.0.1-0.20250507153514-87eb42fe8882/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec= 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= @@ -1675,7 +1589,6 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/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.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= @@ -1684,18 +1597,16 @@ github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aG 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.0 h1:oGWEVKioVQcdIOBlYM8BH1rZDWOGJSqr9/BKl6zQ4qc= -github.com/multiformats/go-multiaddr v0.16.0/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0= +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.4.1 h1:whi/uCLbDS3mSEUMb1MsoT4uzUeZB0N32yzufqS0i5M= github.com/multiformats/go-multiaddr-dns v0.4.1/go.mod h1:7hfthtB4E4pQwirrz+J0CcDUfbWzTqEzVyYKKIKpgkc= 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.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g= github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk= -github.com/multiformats/go-multicodec v0.9.1 h1:x/Fuxr7ZuR4jJV4Os5g444F7xC4XmyUaT/FWtE+9Zjo= -github.com/multiformats/go-multicodec v0.9.1/go.mod h1:LLWNMtyV5ithSBUo3vFIMaeDy+h3EbkMTek1m+Fybbo= -github.com/multiformats/go-multihash v0.0.8/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew= +github.com/multiformats/go-multicodec v0.9.2 h1:YrlXCuqxjqm3bXl+vBq5LKz5pz4mvAsugdqy78k0pXQ= +github.com/multiformats/go-multicodec v0.9.2/go.mod h1:LLWNMtyV5ithSBUo3vFIMaeDy+h3EbkMTek1m+Fybbo= 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= @@ -1715,10 +1626,9 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= -github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc= github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a h1:dlRvE5fWabOchtH7znfiFCcOvmIYgOeAS5ifBXBlh9Q= @@ -1737,14 +1647,14 @@ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108 github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= 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.22.2 h1:/3X8Panh8/WwhU/3Ssa6rCKqPLuAkVY2I0RoyDLySlU= -github.com/onsi/ginkgo/v2 v2.22.2/go.mod h1:oeMosUL+8LtarXBHu/c0bx2D/K9zyQ6uX3cTyztHwsk= +github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= +github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 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.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8= -github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY= +github.com/onsi/gomega v1.36.3 h1:hID7cr8t3Wp26+cYnfcjR6HpJ00fdogN6dqZ1t6IylU= +github.com/onsi/gomega v1.36.3/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= @@ -1756,15 +1666,10 @@ github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= -github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/openzipkin/zipkin-go v0.4.3 h1:9EGwpqkgnwdEIJ+Od7QVSEIH+ocmm5nPat0G7sjsSdg= -github.com/openzipkin/zipkin-go v0.4.3/go.mod h1:M9wCJZFWCo2RiY+o1eBCEMe0Dp2S5LDHcMZmk3RmK7c= github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY= github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI= github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= @@ -1794,7 +1699,6 @@ github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4 github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pion/datachannel v1.5.10 h1:ly0Q26K1i6ZkGf42W7D4hQYR90pZwzFOjTq5AuCKk4o= github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oLo8Rs4Py/M= -github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= github.com/pion/dtls/v2 v2.2.12 h1:KP7H5/c1EiVAAKUmXyCzPiQe5+bCJrpOeKg/L05dunk= github.com/pion/dtls/v2 v2.2.12/go.mod h1:d9SYc9fch0CqK90mRk1dC7AkzzpwJj6u2GU3u+9pqFE= github.com/pion/dtls/v3 v3.0.6 h1:7Hkd8WhAJNbRgq9RgdNh1aaWlZlGpYTzdqjy9x9sK2E= @@ -1803,7 +1707,6 @@ github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4= github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw= github.com/pion/interceptor v0.1.40 h1:e0BjnPcGpr2CFQgKhrQisBU7V3GXK6wrfYrGYaU6Jq4= github.com/pion/interceptor v0.1.40/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic= -github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI= github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90= github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM= @@ -1824,8 +1727,6 @@ github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4= github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8= github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw= github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU= -github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= -github.com/pion/transport/v2 v2.2.4/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= github.com/pion/transport/v2 v2.2.10 h1:ucLBLE8nuxiHfvkFKnkDQRYWYfp8ejf4YBOPfaQpw6Q= github.com/pion/transport/v2 v2.2.10/go.mod h1:sq1kSLWs+cHW9E+2fJP95QudkzbK7wscs8yYgQToO5E= github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0= @@ -1848,15 +1749,14 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH github.com/polydawn/refmt v0.89.0 h1:ADJTApkvkeBZsN0tBTx8QjpD9JkmxbKp0cxfr9qszm4= github.com/polydawn/refmt v0.89.0/go.mod h1:/zvteZs/GwLtCgZ4BL6CBsk9IKIlexP43ObX9AxTqTw= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +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-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -1866,24 +1766,22 @@ github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6T github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= 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.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= -github.com/prometheus/common v0.64.0 h1:pdZeA+g617P7oGv1CzdTzyeShxAGrTBsolKNOLQPGO4= -github.com/prometheus/common v0.64.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= -github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= -github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= +github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= github.com/prometheus/tsdb v0.10.0 h1:If5rVCMTp6W2SiRAQFlbpJNgVlgMEd+U2GZckwK38ic= github.com/prometheus/tsdb v0.10.0/go.mod h1:oi49uRhEe9dPUTlS3JRZOwJuVi6tmh10QSgwXEyGCt4= github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= @@ -1897,8 +1795,6 @@ github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Ung github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= -github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M= github.com/regen-network/gocuke v0.6.2/go.mod h1:zYaqIHZobHyd0xOrHGPQjbhGJsuZ1oElx150u2o1xuk= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= @@ -1907,8 +1803,6 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rjeczalik/notify v0.9.3 h1:6rJAzHTGKXGj76sbRgDiDcYj/HniypXmSJo1SWakZeY= github.com/rjeczalik/notify v0.9.3/go.mod h1:gF3zSOrafR9DQEWSE8TjfI9NkooDxbyT4UgRGKZA0lc= -github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= -github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= 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= @@ -1924,51 +1818,23 @@ github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= -github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk= -github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= -github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= -github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= -github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= -github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= -github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= -github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= -github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= -github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= -github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= -github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= -github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= -github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= -github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= -github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= -github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= -github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= -github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= -github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= -github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= -github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= -github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= @@ -1984,11 +1850,13 @@ github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3 github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/sonr-io/common v0.0.0-20251010142707-ab6d2fe7e9c9 h1:2Tu6piK6EKWKcJP5pvu4IPd88q/oUD1dIKl/8GpHQAA= +github.com/sonr-io/common v0.0.0-20251010142707-ab6d2fe7e9c9/go.mod h1:Tu5ij87FPhPCVe8jfNc8CLJHbzZ8YEjuhxNZfmPp1r0= +github.com/sonr-io/crypto v1.0.1 h1:pTsWbdvs8I8zTMalfCK7/ecCvFkBw9VIb/bKKGwMWGw= +github.com/sonr-io/crypto v1.0.1/go.mod h1:f6YZo/FfbUQEEN8TMPAeFI8BOljbDNrui3IXuIzCa/E= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= -github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= @@ -2008,8 +1876,6 @@ github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.17.0 h1:I5txKw7MJasPL/BrfkbA0Jyo/oELqVmux4pR/UxOMfI= github.com/spf13/viper v1.17.0/go.mod h1:BmMMMLQXSbcHK6KAOiFLz0l5JHrU89OdIRHvsk0+yVI= -github.com/status-im/keycard-go v0.2.0 h1:QDLFswOQu1r5jsycloeQh3bVU8n/NatHHaZobtDnDzA= -github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9+mHxBEeo3Hbg= github.com/strangelove-ventures/cosmos-evm v0.2.0 h1:Abua+Wsvna9njxTuRLX/d0QmQnKIpImf/VbKrxBuHlU= github.com/strangelove-ventures/cosmos-evm v0.2.0/go.mod h1:5sAR9ETde0vSs4b/FUE1MXA9cWZ4aPsDCm9zVb49/As= github.com/strangelove-ventures/cosmos-sdk v0.0.0-20250317212103-0767f8c5b1e5 h1:5v7j5P2QTOiV3Uftja+1bwwuyaGe/lpnsC7dZNgoo/U= @@ -2038,13 +1904,12 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +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.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= -github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q= @@ -2090,8 +1955,6 @@ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6Kllzaw github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU= -github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM= github.com/warpfork/go-testmark v0.12.1 h1:rMgCpJfwy1sJ50x0M0NgyphxYYPMOODIJHhsXyEHU0s= github.com/warpfork/go-testmark v0.12.1/go.mod h1:kHwy7wfvGSPh1rQJYKayD4AbtNaeyZdcGi9tNJTaa5Y= github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ= @@ -2100,15 +1963,12 @@ github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc h1:BCPnHtcboa github.com/whyrusleeping/base32 v0.0.0-20170828182744-c30ac30633cc/go.mod h1:r45hJU7yEoA81k6MWNhpMj/kms0n14dkzkxYHoB96UM= github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 h1:5HZfQkwe0mIfyDmc1Em5GqlNRzcdtlv4HTNmdpt7XH0= github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11/go.mod h1:Wlo/SzPmxVp6vXpGt/zaXhHH0fn4IxgqZc82aKg6bpQ= -github.com/whyrusleeping/cbor-gen v0.1.2 h1:WQFlrPhpcQl+M2/3dP5cvlTLWPVsL6LGBb9jJt6l/cA= -github.com/whyrusleeping/cbor-gen v0.1.2/go.mod h1:pM99HXyEbSQHcosHc0iW7YFmwnscr+t9Te4ibko05so= +github.com/whyrusleeping/cbor-gen v0.3.1 h1:82ioxmhEYut7LBVGhGq8xoRkXPLElVuh5mV67AFfdv0= +github.com/whyrusleeping/cbor-gen v0.3.1/go.mod h1:pM99HXyEbSQHcosHc0iW7YFmwnscr+t9Te4ibko05so= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f h1:jQa4QT2UP9WYv2nzyawpKMOCl+Z/jW7djv2/J50lj9E= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f/go.mod h1:p9UJB6dDgdPgMJZs7UjUOdulKyRr9fqkS+6JKAInPy8= 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/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7 h1:E9S12nwJwEOXe2d6gT6qxdvqMnNq+VnSsKPgm2ZZNds= -github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= -github.com/wlynxg/anet v0.0.3/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= 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= @@ -2123,12 +1983,9 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= -github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= -github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= github.com/zondax/hid v0.9.2 h1:WCJFnEDMiqGF64nlZz28E9qLVZ0KSJ7xpc5DLEyma2U= github.com/zondax/hid v0.9.2/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= @@ -2138,7 +1995,6 @@ go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 h1:qxen9oVGzDdIRP6ejyAJc760RwW4SnVDiTYTzwnXuxo= go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5/go.mod h1:eW0HG9/oHQhvRCvb1/pIXW4cOvtDqeQK+XSi3TnwaXY= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= -go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -2150,46 +2006,35 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +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/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 h1:UP6IpuHFkUgOQL9FFQFrZ+5LiwhhYRbi7VZSIx6Nj5s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0/go.mod h1:qxuZLtbq5QDtdeSHsS7bcf6EH6uO6jUAgk764zd3rhM= -go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= -go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0 h1:FFeLy03iVTXP6ffeN2iXrxfGsZGCjVx0/4KlizjyBwU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.31.0/go.mod h1:TMu73/k1CP8nBUpDLc71Wj/Kf7ZS9FK5b53VapRsP9o= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0 h1:lUsI2TYsQw2r1IASwoROaCnjdj2cvC2+Jbxvk6nHnWU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0/go.mod h1:2HpZxxQurfGxJlJDblybejHB6RX6pmExPNe517hREw4= -go.opentelemetry.io/otel/exporters/prometheus v0.44.0 h1:08qeJgaPC0YEBu2PQMbqU3rogTlyzpjhCI2b58Yn00w= -go.opentelemetry.io/otel/exporters/prometheus v0.44.0/go.mod h1:ERL2uIeBtg4TxZdojHUwzZfIFlUIjZtxubT5p4h1Gjg= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0 h1:UGZ1QwZWY67Z6BmckTU+9Rxn04m2bD3gD6Mk0OIOCPk= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0/go.mod h1:fcwWuDuaObkkChiDlhEpSq9+X1C0omv+s5mBtToAQ64= -go.opentelemetry.io/otel/exporters/zipkin v1.31.0 h1:CgucL0tj3717DJnni7HVVB2wExzi8c2zJNEA2BhLMvI= -go.opentelemetry.io/otel/exporters/zipkin v1.31.0/go.mod h1:rfzOVNiSwIcWtEC2J8epwG26fiaXlYvLySJ7bwsrtAE= -go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= -go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= -go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= -go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= -go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/exporters/prometheus v0.56.0 h1:GnCIi0QyG0yy2MrJLzVrIM7laaJstj//flf1zEJCG+E= +go.opentelemetry.io/otel/exporters/prometheus v0.56.0/go.mod h1:JQcVZtbIIPM+7SWBB+T6FK+xunlyidwLp++fN0sUaOk= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.15.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= -go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= -go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= +go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= +go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= 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= @@ -2201,52 +2046,38 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= 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/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= -go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= -go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= -go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= +go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= +go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE= go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI= -go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= -go4.org v0.0.0-20230225012048-214862532bf5 h1:nifaUDeh+rPaBCMPMQHZmvJf+QdpLFnuQPwx+LxVmtc= -go4.org v0.0.0-20230225012048-214862532bf5/go.mod h1:F57wTi5Lrj6WLyswp5EYV1ncrEbFGHD4hhz6S1ZYeaU= golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/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-20190313024323-a1f597ede03a/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-20190701094942-4def268fd1a4/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-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= -golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= @@ -2268,8 +2099,8 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EH golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/exp v0.0.0-20220827204233-334a2380cb91/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= +golang.org/x/exp v0.0.0-20250911091902-df9299821621 h1:2id6c1/gto0kaHYyrixvknJ8tUK/Qs5IsmBtrc+FtgU= +golang.org/x/exp v0.0.0-20250911091902-df9299821621/go.mod h1:TwQYMMnGpvZyc+JpB/UAuTNIsVJifOlSkrZkhcvpVUk= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= 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= @@ -2283,7 +2114,6 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= -golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 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= @@ -2317,15 +2147,13 @@ golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= -golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= +golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= +golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 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-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/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-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -2333,7 +2161,6 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/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-20190313220215-9f648a60d977/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= @@ -2393,17 +2220,13 @@ golang.org/x/net v0.7.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.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= -golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= -golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= -golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= +golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/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= @@ -2432,9 +2255,8 @@ golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw= golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= -golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= +golang.org/x/oauth2 v0.31.0 h1:8Fq0yVZLh4j4YA47vHKFTa9Ew5XIrCP8LC6UeNZnLxo= +golang.org/x/oauth2 v0.31.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= 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= @@ -2463,13 +2285,11 @@ golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7/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-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/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-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/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= @@ -2503,7 +2323,6 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/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-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -2513,6 +2332,7 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w 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-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -2561,7 +2381,6 @@ golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -2569,9 +2388,7 @@ 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.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -2579,6 +2396,8 @@ golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053 h1:dHQOQddU4YHS5gY33/6klKjq7Gp3WwMyOXGNp5nzRj8= +golang.org/x/telemetry v0.0.0-20250908211612-aef8a434d053/go.mod h1:+nZKN+XVh4LCiA9DV3ywrzN4gumyCnKjau3NGb9SGoE= 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.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= @@ -2588,9 +2407,7 @@ 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.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= @@ -2612,7 +2429,6 @@ golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 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.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= @@ -2632,7 +2448,6 @@ golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/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-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -2687,6 +2502,7 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/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.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -2704,8 +2520,8 @@ golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= -golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= -golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= +golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= +golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= 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= @@ -2726,9 +2542,6 @@ gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6d gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= gonum.org/v1/plot v0.9.0/go.mod h1:3Pcqqmp6RHvJI72kgb8fThyUnav364FOsdDo2aGW5lY= gonum.org/v1/plot v0.10.1/go.mod h1:VZW5OlhkL1mysU9vaqNHnsy86inf6Ot+jB3r+BczCEo= -google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= 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= @@ -2791,7 +2604,6 @@ google.golang.org/api v0.186.0 h1:n2OPp+PPXX0Axh4GuSsL5QL8xQCTb2oDwyzPnQvqUug= google.golang.org/api v0.186.0/go.mod h1:hvRbBmgoje49RV3xqVXrmP6w93n6ehGgIVPYrGtBFFc= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 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= @@ -2801,9 +2613,6 @@ google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCID google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= -google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 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= @@ -2941,13 +2750,11 @@ google.golang.org/genproto v0.0.0-20230331144136-dcfb400f0633/go.mod h1:UUQDJDOl google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094 h1:6whtk83KtD3FkGrVb2hFXuQ+ZMbCNdakARIn/aHMmG8= google.golang.org/genproto v0.0.0-20240701130421-f6361c86f094/go.mod h1:Zs4wYw8z1zr6RNF4cwYb31mvN/EGaKAdQjNCF3DW6K4= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 h1:e0AIkUUhxyBKh6ssZNrAMeqhA7RKUj42346d1y02i2g= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY= +google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 h1:eaY8u2EuxbRv7c3NiGK0/NedzVsCcV6hDuU5qPX5EGE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5/go.mod h1:M4/wBTSeyLxupu3W3tJtOgB14jILAS/XWPSSa3TAlJc= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -2995,8 +2802,8 @@ google.golang.org/grpc v1.52.3/go.mod h1:pu6fVzoFb+NBYNAvQL08ic+lvB2IojljRYuun5v google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= google.golang.org/grpc v1.54.0/go.mod h1:PUSEXI6iWghWaB6lXM4knEgpJNu2qUcKfDtNci3EC2g= google.golang.org/grpc v1.56.3/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= -google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= -google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4= +google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= 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= @@ -3016,8 +2823,8 @@ google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw google.golang.org/protobuf v1.29.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw= +google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 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= @@ -3030,7 +2837,6 @@ gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qS 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/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= @@ -3059,7 +2865,6 @@ gorm.io/gorm v1.30.1 h1:lSHg33jJTBxs2mgJRfRZeLDG+WZaHYCk3Wtfl6Ngzo4= gorm.io/gorm v1.30.1/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE= gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= -grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 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= @@ -3118,5 +2923,3 @@ sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.5.0 h1:M10b2U7aEUY6hRtU870n2VTPgR5RZiL/I6Lcc2F4NUQ= sigs.k8s.io/yaml v1.5.0/go.mod h1:wZs27Rbxoai4C0f8/9urLZtZtF3avA3gKvGyPdDqTO4= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= -sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= -sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/scripts/install.sh b/install.sh similarity index 100% rename from scripts/install.sh rename to install.sh diff --git a/internal/migrations/001_accounts_table.sql b/internal/migrations/001_accounts_table.sql deleted file mode 100644 index 6b2aa36c9..000000000 --- a/internal/migrations/001_accounts_table.sql +++ /dev/null @@ -1,44 +0,0 @@ --- +goose Up --- +goose StatementBegin -CREATE TABLE accounts ( - id TEXT PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - deleted_at TIMESTAMP WITH TIME ZONE, - number INTEGER NOT NULL, - sequence INTEGER NOT NULL DEFAULT 0, - address TEXT NOT NULL, - public_key JSONB NOT NULL, - chain_id TEXT NOT NULL, - block_created INTEGER NOT NULL, - controller TEXT NOT NULL, - label TEXT NOT NULL, - handle TEXT NOT NULL, - is_subsidiary BOOLEAN NOT NULL DEFAULT FALSE, - is_validator BOOLEAN NOT NULL DEFAULT FALSE, - is_delegator BOOLEAN NOT NULL DEFAULT FALSE, - is_accountable BOOLEAN NOT NULL DEFAULT TRUE -); - - --- Unique constraints -CREATE UNIQUE INDEX idx_accounts_address_unique ON accounts(address) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX idx_accounts_handle_controller_unique ON accounts(handle, controller) WHERE deleted_at IS NULL; - --- Regular indexes for query performance -CREATE INDEX idx_accounts_chain_id ON accounts(chain_id); -CREATE INDEX idx_accounts_block_created ON accounts(block_created); -CREATE INDEX idx_accounts_label ON accounts(label); -CREATE INDEX idx_accounts_controller ON accounts(controller); -CREATE INDEX idx_accounts_number ON accounts(number); -CREATE INDEX idx_accounts_is_subsidiary ON accounts(is_subsidiary) WHERE is_subsidiary = TRUE; -CREATE INDEX idx_accounts_is_validator ON accounts(is_validator) WHERE is_validator = TRUE; -CREATE INDEX idx_accounts_is_delegator ON accounts(is_delegator) WHERE is_delegator = TRUE; -CREATE INDEX idx_accounts_deleted_at ON accounts(deleted_at) WHERE deleted_at IS NOT NULL; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TABLE accounts; --- +goose StatementEnd - diff --git a/internal/migrations/002_credentials_table.sql b/internal/migrations/002_credentials_table.sql deleted file mode 100644 index e8468362f..000000000 --- a/internal/migrations/002_credentials_table.sql +++ /dev/null @@ -1,36 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Credentials store WebAuthn credentials -CREATE TABLE credentials ( - id TEXT PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - deleted_at TIMESTAMP WITH TIME ZONE, - handle TEXT NOT NULL, - raw_id TEXT NOT NULL, - type TEXT NOT NULL DEFAULT 'public-key', - authenticator_attachment TEXT, - transports TEXT[], -- Array of transport strings - client_extension_results JSONB, - attestation_object TEXT NOT NULL, -- Base64URL encoded - client_data_json TEXT NOT NULL, -- Base64URL encoded - public_key_alg INTEGER, - public_key BYTEA -); - --- Unique constraints -CREATE UNIQUE INDEX idx_credentials_id_unique ON credentials(id) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX idx_credentials_raw_id_unique ON credentials(raw_id) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX idx_credentials_handle_unique ON credentials(handle) WHERE deleted_at IS NULL; - --- Regular indexes for query performance -CREATE INDEX idx_credentials_handle ON credentials(handle); -CREATE INDEX idx_credentials_type ON credentials(type); -CREATE INDEX idx_credentials_authenticator_attachment ON credentials(authenticator_attachment); -CREATE INDEX idx_credentials_deleted_at ON credentials(deleted_at) WHERE deleted_at IS NULL; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TABLE credentials; --- +goose StatementEnd diff --git a/internal/migrations/003_profiles_table.sql b/internal/migrations/003_profiles_table.sql deleted file mode 100644 index e8ee32f75..000000000 --- a/internal/migrations/003_profiles_table.sql +++ /dev/null @@ -1,30 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Profiles represent user identities -CREATE TABLE profiles ( - id TEXT PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - deleted_at TIMESTAMP WITH TIME ZONE, - address TEXT NOT NULL, - handle TEXT NOT NULL, - origin TEXT NOT NULL, - name TEXT NOT NULL -); - --- Unique constraints -CREATE UNIQUE INDEX idx_profiles_handle_unique ON profiles(handle) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX idx_profiles_address_origin_unique ON profiles(address, origin) WHERE deleted_at IS NULL; - --- Regular indexes for query performance -CREATE INDEX idx_profiles_address ON profiles(address); -CREATE INDEX idx_profiles_origin ON profiles(origin); -CREATE INDEX idx_profiles_name ON profiles(name); -CREATE INDEX idx_profiles_deleted_at ON profiles(deleted_at) WHERE deleted_at IS NOT NULL; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TABLE profiles; --- +goose StatementEnd - diff --git a/internal/migrations/004_vaults_table.sql b/internal/migrations/004_vaults_table.sql deleted file mode 100644 index 72d89ea9f..000000000 --- a/internal/migrations/004_vaults_table.sql +++ /dev/null @@ -1,33 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Vaults store encrypted data -CREATE TABLE vaults ( - id TEXT PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - deleted_at TIMESTAMP WITH TIME ZONE, - handle TEXT NOT NULL, - origin TEXT NOT NULL, - address TEXT NOT NULL, - cid TEXT NOT NULL, - config JSONB NOT NULL, - session_id TEXT NOT NULL, - redirect_uri TEXT NOT NULL -); - --- Unique constraints -CREATE UNIQUE INDEX idx_vaults_cid_unique ON vaults(cid) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX idx_vaults_handle_origin_address_unique ON vaults(handle, origin, address) WHERE deleted_at IS NULL; - --- Regular indexes for query performance -CREATE INDEX idx_vaults_handle ON vaults(handle); -CREATE INDEX idx_vaults_origin ON vaults(origin); -CREATE INDEX idx_vaults_address ON vaults(address); -CREATE INDEX idx_vaults_session_id ON vaults(session_id); -CREATE INDEX idx_vaults_deleted_at ON vaults(deleted_at) WHERE deleted_at IS NOT NULL; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TABLE vaults; --- +goose StatementEnd diff --git a/internal/migrations/005_create_cosmos_registry.sql b/internal/migrations/005_create_cosmos_registry.sql deleted file mode 100644 index 333963936..000000000 --- a/internal/migrations/005_create_cosmos_registry.sql +++ /dev/null @@ -1,368 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Create the http extension required for making HTTP requests -CREATE EXTENSION IF NOT EXISTS http; - -CREATE TABLE IF NOT EXISTS chains ( - chain_id VARCHAR(100) PRIMARY KEY, - name VARCHAR(100), - path VARCHAR(100), - chain_name VARCHAR(100), - network_type VARCHAR(50), - pretty_name VARCHAR(200), - status VARCHAR(50), - bech32_prefix VARCHAR(20), - slip44 INTEGER, - symbol VARCHAR(20), - display VARCHAR(20), - denom VARCHAR(50), - decimals INTEGER, - image VARCHAR(500), - website VARCHAR(500), - height BIGINT, - proxy_status JSONB, - keywords TEXT[], - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS chain_apis ( - id SERIAL PRIMARY KEY, - chain_id VARCHAR(100) REFERENCES chains(chain_id) ON DELETE CASCADE, - api_type VARCHAR(20), -- 'rest', 'rpc', 'grpc' - address VARCHAR(500), - provider VARCHAR(200), - archive BOOLEAN DEFAULT FALSE, - is_best_api BOOLEAN DEFAULT FALSE, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS chain_explorers ( - id SERIAL PRIMARY KEY, - chain_id VARCHAR(100) REFERENCES chains(chain_id) ON DELETE CASCADE, - kind VARCHAR(50), - url VARCHAR(500), - tx_page VARCHAR(500), - account_page VARCHAR(500), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - --- 4. Create versions table -CREATE TABLE IF NOT EXISTS chain_versions ( - id SERIAL PRIMARY KEY, - chain_id VARCHAR(100) REFERENCES chains(chain_id) ON DELETE CASCADE, - application_name VARCHAR(100), - application_version VARCHAR(50), - consensus_name VARCHAR(100), - consensus_version VARCHAR(50), - cosmos_sdk_version VARCHAR(50), - tendermint_version VARCHAR(50), - ibc_go_version VARCHAR(50), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - --- 5. Create assets table -CREATE TABLE IF NOT EXISTS chain_assets ( - id SERIAL PRIMARY KEY, - chain_id VARCHAR(100) REFERENCES chains(chain_id) ON DELETE CASCADE, - asset_name VARCHAR(100), - description VARCHAR(1000), - denom_units JSONB, - base VARCHAR(100), - display VARCHAR(100), - symbol VARCHAR(20), - logo_uri VARCHAR(500), - keywords TEXT[], - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - --- 6. Create parameters table -CREATE TABLE IF NOT EXISTS chain_params ( - id SERIAL PRIMARY KEY, - chain_id VARCHAR(100) REFERENCES chains(chain_id) ON DELETE CASCADE, - actual_block_time NUMERIC, - actual_blocks_per_year NUMERIC, - bonded_ratio NUMERIC, - inflation JSONB, - staking_apr NUMERIC, - unbonding_time INTEGER, - max_validators INTEGER, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - --- 7. Create indexes for better performance -CREATE INDEX IF NOT EXISTS idx_chains_status ON chains(status); -CREATE INDEX IF NOT EXISTS idx_chains_network_type ON chains(network_type); -CREATE INDEX IF NOT EXISTS idx_chain_apis_type ON chain_apis(api_type); -CREATE INDEX IF NOT EXISTS idx_chain_apis_chain_id ON chain_apis(chain_id); -CREATE INDEX IF NOT EXISTS idx_chain_explorers_chain_id ON chain_explorers(chain_id); -CREATE INDEX IF NOT EXISTS idx_chain_versions_chain_id ON chain_versions(chain_id); -CREATE INDEX IF NOT EXISTS idx_chain_assets_chain_id ON chain_assets(chain_id); -CREATE INDEX IF NOT EXISTS idx_chain_params_chain_id ON chain_params(chain_id); --- +goose StatementEnd - --- +goose StatementBegin --- 8. Main function to fetch and parse Cosmos chain data -CREATE OR REPLACE FUNCTION fetch_and_parse_cosmos_chains() -RETURNS TABLE( - operation VARCHAR, - chains_inserted INTEGER, - apis_inserted INTEGER, - explorers_inserted INTEGER, - versions_inserted INTEGER, - assets_inserted INTEGER, - params_inserted INTEGER, - total_processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - cosmos_data JSONB; - chains_count INTEGER := 0; - apis_count INTEGER := 0; - explorers_count INTEGER := 0; - versions_count INTEGER := 0; - assets_count INTEGER := 0; - params_count INTEGER := 0; -BEGIN - start_time := clock_timestamp(); - - -- Fetch data from the Cosmos chain directory - SELECT content::JSONB INTO cosmos_data - FROM http_get('https://chains.cosmos.directory'); - - -- Clear existing data (optional - comment out if you want to preserve data) - DELETE FROM chain_params; - DELETE FROM chain_assets; - DELETE FROM chain_versions; - DELETE FROM chain_explorers; - DELETE FROM chain_apis; - DELETE FROM chains; - - -- Insert chains data - INSERT INTO chains ( - chain_id, name, path, chain_name, network_type, pretty_name, - status, bech32_prefix, slip44, symbol, display, denom, - decimals, image, website, height, proxy_status, keywords - ) - SELECT - (chain->>'chain_id')::VARCHAR(100), - (chain->>'name')::VARCHAR(100), - (chain->>'path')::VARCHAR(100), - (chain->>'chain_name')::VARCHAR(100), - (chain->>'network_type')::VARCHAR(50), - (chain->>'pretty_name')::VARCHAR(200), - (chain->>'status')::VARCHAR(50), - (chain->>'bech32_prefix')::VARCHAR(20), - (chain->>'slip44')::INTEGER, - (chain->>'symbol')::VARCHAR(20), - (chain->>'display')::VARCHAR(20), - (chain->>'denom')::VARCHAR(50), - (chain->>'decimals')::INTEGER, - (chain->>'image')::VARCHAR(500), - (chain->>'website')::VARCHAR(500), - (chain->>'height')::BIGINT, - chain->'proxy_status', - CASE - WHEN chain->'keywords' IS NOT NULL - THEN ARRAY(SELECT jsonb_array_elements_text(chain->'keywords')) - ELSE NULL - END - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain; - - GET DIAGNOSTICS chains_count = ROW_COUNT; - - -- Insert REST API endpoints - INSERT INTO chain_apis (chain_id, api_type, address, provider, archive, is_best_api) - SELECT - (chain->>'chain_id')::VARCHAR(100), - 'rest'::VARCHAR(20), - (api->>'address')::VARCHAR(500), - (api->>'provider')::VARCHAR(200), - COALESCE((api->>'archive')::BOOLEAN, false), - true - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain, - JSONB_ARRAY_ELEMENTS(chain->'best_apis'->'rest') AS api - WHERE chain->'best_apis'->'rest' IS NOT NULL; - - -- Insert RPC API endpoints - INSERT INTO chain_apis (chain_id, api_type, address, provider, archive, is_best_api) - SELECT - (chain->>'chain_id')::VARCHAR(100), - 'rpc'::VARCHAR(20), - (api->>'address')::VARCHAR(500), - (api->>'provider')::VARCHAR(200), - COALESCE((api->>'archive')::BOOLEAN, false), - true - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain, - JSONB_ARRAY_ELEMENTS(chain->'best_apis'->'rpc') AS api - WHERE chain->'best_apis'->'rpc' IS NOT NULL; - - -- Insert GRPC API endpoints - INSERT INTO chain_apis (chain_id, api_type, address, provider, archive, is_best_api) - SELECT - (chain->>'chain_id')::VARCHAR(100), - 'grpc'::VARCHAR(20), - (api->>'address')::VARCHAR(500), - (api->>'provider')::VARCHAR(200), - COALESCE((api->>'archive')::BOOLEAN, false), - true - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain, - JSONB_ARRAY_ELEMENTS(chain->'best_apis'->'grpc') AS api - WHERE chain->'best_apis'->'grpc' IS NOT NULL; - - GET DIAGNOSTICS apis_count = ROW_COUNT; - - -- Insert explorers - INSERT INTO chain_explorers (chain_id, kind, url, tx_page, account_page) - SELECT - (chain->>'chain_id')::VARCHAR(100), - (explorer->>'kind')::VARCHAR(50), - (explorer->>'url')::VARCHAR(500), - (explorer->>'tx_page')::VARCHAR(500), - (explorer->>'account_page')::VARCHAR(500) - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain, - JSONB_ARRAY_ELEMENTS(chain->'explorers') AS explorer - WHERE chain->'explorers' IS NOT NULL; - - GET DIAGNOSTICS explorers_count = ROW_COUNT; - - -- Insert version information - INSERT INTO chain_versions ( - chain_id, application_name, application_version, - consensus_name, consensus_version, cosmos_sdk_version, - tendermint_version, ibc_go_version - ) - SELECT - (chain->>'chain_id')::VARCHAR(100), - (chain->'versions'->>'name')::VARCHAR(100), - (chain->'versions'->>'version')::VARCHAR(50), - (chain->'versions'->'consensus'->>'name')::VARCHAR(100), - (chain->'versions'->'consensus'->>'version')::VARCHAR(50), - (chain->'versions'->>'cosmos_sdk_version')::VARCHAR(50), - (chain->'versions'->>'tendermint_version')::VARCHAR(50), - (chain->'versions'->>'ibc_go_version')::VARCHAR(50) - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain - WHERE chain->'versions' IS NOT NULL; - - GET DIAGNOSTICS versions_count = ROW_COUNT; - - -- Insert assets - INSERT INTO chain_assets ( - chain_id, asset_name, description, denom_units, - base, display, symbol, logo_uri, keywords - ) - SELECT - (chain->>'chain_id')::VARCHAR(100), - (asset->>'name')::VARCHAR(100), - (asset->>'description')::VARCHAR(1000), - asset->'denom_units', - (asset->>'base')::VARCHAR(100), - (asset->>'display')::VARCHAR(100), - (asset->>'symbol')::VARCHAR(20), - (asset->'logo_URIs'->>'png')::VARCHAR(500), - CASE - WHEN asset->'keywords' IS NOT NULL - THEN ARRAY(SELECT jsonb_array_elements_text(asset->'keywords')) - ELSE NULL - END - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain, - JSONB_ARRAY_ELEMENTS(chain->'assets') AS asset - WHERE chain->'assets' IS NOT NULL; - - GET DIAGNOSTICS assets_count = ROW_COUNT; - - -- Insert parameters - INSERT INTO chain_params ( - chain_id, actual_block_time, actual_blocks_per_year, - bonded_ratio, inflation, staking_apr, unbonding_time, max_validators - ) - SELECT - (chain->>'chain_id')::VARCHAR(100), - (chain->'params'->>'actual_block_time')::NUMERIC, - (chain->'params'->>'actual_blocks_per_year')::NUMERIC, - (chain->'params'->>'bonded_ratio')::NUMERIC, - chain->'params'->'inflation', - (chain->'params'->>'staking_apr')::NUMERIC, - (chain->'params'->>'unbonding_time')::INTEGER, - (chain->'params'->>'max_validators')::INTEGER - FROM JSONB_ARRAY_ELEMENTS(cosmos_data->'chains') AS chain - WHERE chain->'params' IS NOT NULL; - - GET DIAGNOSTICS params_count = ROW_COUNT; - - -- Return summary - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - chains_count, - apis_count, - explorers_count, - versions_count, - assets_count, - params_count, - clock_timestamp() - start_time as total_processing_time; - -EXCEPTION - WHEN OTHERS THEN - -- Return error information - RETURN QUERY SELECT - 'ERROR'::VARCHAR as operation, - 0::INTEGER, - 0::INTEGER, - 0::INTEGER, - 0::INTEGER, - 0::INTEGER, - 0::INTEGER, - clock_timestamp() - start_time as total_processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin --- 9. Convenience function to refresh data -CREATE OR REPLACE FUNCTION refresh_cosmos_data() -RETURNS VOID AS $$ -BEGIN - PERFORM fetch_and_parse_cosmos_chains(); -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin --- 10. Function to get chain summary statistics -CREATE OR REPLACE FUNCTION get_cosmos_chain_stats() -RETURNS TABLE( - total_chains INTEGER, - live_chains INTEGER, - testnet_chains INTEGER, - total_apis INTEGER, - total_explorers INTEGER, - chains_with_staking_info INTEGER, - avg_staking_apr NUMERIC -) AS $$ -BEGIN - RETURN QUERY - SELECT - (SELECT COUNT(*)::INTEGER FROM chains) as total_chains, - (SELECT COUNT(*)::INTEGER FROM chains WHERE status = 'live') as live_chains, - (SELECT COUNT(*)::INTEGER FROM chains WHERE network_type = 'testnet') as testnet_chains, - (SELECT COUNT(*)::INTEGER FROM chain_apis) as total_apis, - (SELECT COUNT(*)::INTEGER FROM chain_explorers) as total_explorers, - (SELECT COUNT(*)::INTEGER FROM chain_params WHERE staking_apr IS NOT NULL) as chains_with_staking_info, - (SELECT AVG(staking_apr) FROM chain_params WHERE staking_apr IS NOT NULL) as avg_staking_apr; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP FUNCTION IF EXISTS get_cosmos_chain_stats(); -DROP FUNCTION IF EXISTS refresh_cosmos_data(); -DROP FUNCTION IF EXISTS fetch_and_parse_cosmos_chains(); -DROP TABLE IF EXISTS chain_params CASCADE; -DROP TABLE IF EXISTS chain_assets CASCADE; -DROP TABLE IF EXISTS chain_versions CASCADE; -DROP TABLE IF EXISTS chain_explorers CASCADE; -DROP TABLE IF EXISTS chain_apis CASCADE; -DROP TABLE IF EXISTS chains CASCADE; --- +goose StatementEnd diff --git a/internal/migrations/006_execute_cosmos_registry.sql b/internal/migrations/006_execute_cosmos_registry.sql deleted file mode 100644 index 2411348ac..000000000 --- a/internal/migrations/006_execute_cosmos_registry.sql +++ /dev/null @@ -1,16 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Step 1: Execute the main function to fetch and parse data -SELECT * FROM fetch_and_parse_cosmos_chains(); --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin --- Clean up data from all tables -DELETE FROM chain_params; -DELETE FROM chain_assets; -DELETE FROM chain_versions; -DELETE FROM chain_explorers; -DELETE FROM chain_apis; -DELETE FROM chains; --- +goose StatementEnd \ No newline at end of file diff --git a/internal/migrations/007_webauthn_to_vc_func.sql b/internal/migrations/007_webauthn_to_vc_func.sql deleted file mode 100644 index 91f96dd65..000000000 --- a/internal/migrations/007_webauthn_to_vc_func.sql +++ /dev/null @@ -1,29 +0,0 @@ --- +goose Up --- +goose StatementBegin -CREATE OR REPLACE FUNCTION convert_webauthn_to_vc( - webauthn_credential JSONB -) RETURNS JSONB AS $$ -DECLARE - vc_result JSONB; -BEGIN - -- Create the Verifiable Credential structure based on W3C standard - vc_result = jsonb_build_object( - '@context', jsonb_build_array('https://www.w3.org/2018/credentials/v1'), - 'type', jsonb_build_array('VerifiableCredential', 'WebAuthnCredential'), - 'issuer', jsonb_build_object( - 'id', 'did:example:' || encode(digest(webauthn_credential->>'rpId', 'sha256'), 'hex') - ), - 'issuanceDate', to_char(now() at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'), - 'credentialSubject', jsonb_build_object( - 'id', 'did:key:' || encode(digest(webauthn_credential->>'id', 'sha256'), 'hex'), - 'webauthn', webauthn_credential - ) - ); - - RETURN vc_result; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose Down -DROP FUNCTION convert_webauthn_to_vc; diff --git a/internal/migrations/008_create_coinpaprika_market_data.sql b/internal/migrations/008_create_coinpaprika_market_data.sql deleted file mode 100644 index e42805c9d..000000000 --- a/internal/migrations/008_create_coinpaprika_market_data.sql +++ /dev/null @@ -1,486 +0,0 @@ --- +goose Up --- +goose StatementBegin -CREATE TABLE IF NOT EXISTS crypto_global_market_data ( - id SERIAL PRIMARY KEY, - market_cap_usd NUMERIC(20, 2), - volume_24h_usd NUMERIC(20, 2), - bitcoin_dominance_percentage NUMERIC(5, 2), - cryptocurrencies_number INTEGER, - market_cap_ath_value NUMERIC(20, 2), - market_cap_ath_date TIMESTAMP WITH TIME ZONE, - volume_24h_ath_value NUMERIC(20, 2), - volume_24h_ath_date TIMESTAMP WITH TIME ZONE, - market_cap_change_24h NUMERIC(10, 2), - volume_24h_change_24h NUMERIC(10, 2), - last_updated INTEGER, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_crypto_global_market_data_last_updated ON crypto_global_market_data(last_updated DESC); -CREATE INDEX IF NOT EXISTS idx_crypto_global_market_data_created_at ON crypto_global_market_data(created_at DESC); - -CREATE TABLE IF NOT EXISTS crypto_coins ( - id VARCHAR(100) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - symbol VARCHAR(20) NOT NULL, - rank INTEGER, - is_new BOOLEAN DEFAULT FALSE, - is_active BOOLEAN DEFAULT TRUE, - type VARCHAR(50), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_crypto_coins_symbol ON crypto_coins(symbol); -CREATE INDEX IF NOT EXISTS idx_crypto_coins_rank ON crypto_coins(rank); -CREATE INDEX IF NOT EXISTS idx_crypto_coins_is_active ON crypto_coins(is_active); -CREATE INDEX IF NOT EXISTS idx_crypto_coins_type ON crypto_coins(type); - -CREATE TABLE IF NOT EXISTS crypto_coin_details ( - id VARCHAR(100) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - symbol VARCHAR(20) NOT NULL, - parent_id VARCHAR(100), - parent_name VARCHAR(255), - parent_symbol VARCHAR(20), - rank INTEGER, - is_new BOOLEAN DEFAULT FALSE, - is_active BOOLEAN DEFAULT TRUE, - type VARCHAR(50), - logo VARCHAR(500), - tags JSONB, - team JSONB, - description TEXT, - message TEXT, - open_source BOOLEAN, - hardware_wallet BOOLEAN, - started_at TIMESTAMP WITH TIME ZONE, - development_status VARCHAR(100), - proof_type VARCHAR(100), - org_structure VARCHAR(100), - hash_algorithm VARCHAR(100), - contract VARCHAR(255), - platform VARCHAR(255), - contracts JSONB, - links JSONB, - links_extended JSONB, - whitepaper JSONB, - first_data_at TIMESTAMP WITH TIME ZONE, - last_data_at TIMESTAMP WITH TIME ZONE, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_crypto_coin_details_symbol ON crypto_coin_details(symbol); -CREATE INDEX IF NOT EXISTS idx_crypto_coin_details_rank ON crypto_coin_details(rank); -CREATE INDEX IF NOT EXISTS idx_crypto_coin_details_type ON crypto_coin_details(type); -CREATE INDEX IF NOT EXISTS idx_crypto_coin_details_started_at ON crypto_coin_details(started_at); --- +goose StatementEnd - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION fetch_coinpaprika_global_market_data() -RETURNS TABLE( - operation VARCHAR, - records_inserted INTEGER, - last_market_cap NUMERIC, - last_volume NUMERIC, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - market_data JSONB; - insert_count INTEGER := 0; - last_cap NUMERIC; - last_vol NUMERIC; -BEGIN - start_time := clock_timestamp(); - SELECT content::JSONB INTO market_data - FROM http_get('https://api.coinpaprika.com/v1/global'); - INSERT INTO crypto_global_market_data ( - market_cap_usd, - volume_24h_usd, - bitcoin_dominance_percentage, - cryptocurrencies_number, - market_cap_ath_value, - market_cap_ath_date, - volume_24h_ath_value, - volume_24h_ath_date, - market_cap_change_24h, - volume_24h_change_24h, - last_updated - ) - SELECT - (market_data->>'market_cap_usd')::NUMERIC, - (market_data->>'volume_24h_usd')::NUMERIC, - (market_data->>'bitcoin_dominance_percentage')::NUMERIC, - (market_data->>'cryptocurrencies_number')::INTEGER, - (market_data->>'market_cap_ath_value')::NUMERIC, - (market_data->>'market_cap_ath_date')::TIMESTAMP WITH TIME ZONE, - (market_data->>'volume_24h_ath_value')::NUMERIC, - (market_data->>'volume_24h_ath_date')::TIMESTAMP WITH TIME ZONE, - (market_data->>'market_cap_change_24h')::NUMERIC, - (market_data->>'volume_24h_change_24h')::NUMERIC, - (market_data->>'last_updated')::INTEGER - RETURNING market_cap_usd, volume_24h_usd INTO last_cap, last_vol; - - GET DIAGNOSTICS insert_count = ROW_COUNT; - - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - insert_count as records_inserted, - last_cap as last_market_cap, - last_vol as last_volume, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - 0::INTEGER as records_inserted, - 0::NUMERIC as last_market_cap, - 0::NUMERIC as last_volume, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION refresh_market_data() -RETURNS VOID AS $$ -BEGIN - PERFORM fetch_coinpaprika_global_market_data(); -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION fetch_coinpaprika_coins() -RETURNS TABLE( - operation VARCHAR, - records_upserted INTEGER, - new_coins INTEGER, - updated_coins INTEGER, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - coins_data JSONB; - coin_record JSONB; - upsert_count INTEGER := 0; - new_count INTEGER := 0; - update_count INTEGER := 0; - existing_id VARCHAR; -BEGIN - start_time := clock_timestamp(); - SELECT content::JSONB INTO coins_data - FROM http_get('https://api.coinpaprika.com/v1/coins'); - FOR coin_record IN SELECT * FROM jsonb_array_elements(coins_data) - LOOP - SELECT id INTO existing_id FROM crypto_coins WHERE id = coin_record->>'id'; - INSERT INTO crypto_coins ( - id, - name, - symbol, - rank, - is_new, - is_active, - type, - updated_at - ) - VALUES ( - coin_record->>'id', - coin_record->>'name', - coin_record->>'symbol', - (coin_record->>'rank')::INTEGER, - (coin_record->>'is_new')::BOOLEAN, - (coin_record->>'is_active')::BOOLEAN, - coin_record->>'type', - CURRENT_TIMESTAMP - ) - ON CONFLICT (id) DO UPDATE SET - name = EXCLUDED.name, - symbol = EXCLUDED.symbol, - rank = EXCLUDED.rank, - is_new = EXCLUDED.is_new, - is_active = EXCLUDED.is_active, - type = EXCLUDED.type, - updated_at = CURRENT_TIMESTAMP; - - upsert_count := upsert_count + 1; - - IF existing_id IS NULL THEN - new_count := new_count + 1; - ELSE - update_count := update_count + 1; - END IF; - END LOOP; - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - upsert_count as records_upserted, - new_count as new_coins, - update_count as updated_coins, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - 0::INTEGER as records_upserted, - 0::INTEGER as new_coins, - 0::INTEGER as updated_coins, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION refresh_all_coinpaprika_data() -RETURNS TABLE( - operation VARCHAR, - market_data_result VARCHAR, - coins_result VARCHAR, - total_processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - market_result RECORD; - coins_result RECORD; -BEGIN - start_time := clock_timestamp(); - - -- Fetch market data - SELECT * INTO market_result FROM fetch_coinpaprika_global_market_data(); - - -- Fetch coins data - SELECT * INTO coins_result FROM fetch_coinpaprika_coins(); - - -- Return combined results - RETURN QUERY SELECT - 'COMPLETE'::VARCHAR as operation, - market_result.operation as market_data_result, - coins_result.operation as coins_result, - clock_timestamp() - start_time as total_processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR'::VARCHAR as operation, - 'ERROR: ' || SQLERRM::VARCHAR as market_data_result, - 'ERROR: ' || SQLERRM::VARCHAR as coins_result, - clock_timestamp() - start_time as total_processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin --- Function to fetch and store detailed coin information -CREATE OR REPLACE FUNCTION fetch_coinpaprika_coin_details(coin_id VARCHAR) -RETURNS TABLE( - operation VARCHAR, - coin_name VARCHAR, - coin_symbol VARCHAR, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - coin_data JSONB; - parent_data JSONB; -BEGIN - start_time := clock_timestamp(); - - -- Fetch data from CoinPaprika coin details endpoint - SELECT content::JSONB INTO coin_data - FROM http_get('https://api.coinpaprika.com/v1/coins/' || coin_id); - - -- Extract parent data if exists - parent_data := coin_data->'parent'; - - -- Insert or update the coin details - INSERT INTO crypto_coin_details ( - id, - name, - symbol, - parent_id, - parent_name, - parent_symbol, - rank, - is_new, - is_active, - type, - logo, - tags, - team, - description, - message, - open_source, - hardware_wallet, - started_at, - development_status, - proof_type, - org_structure, - hash_algorithm, - contract, - platform, - contracts, - links, - links_extended, - whitepaper, - first_data_at, - last_data_at, - updated_at - ) - VALUES ( - coin_data->>'id', - coin_data->>'name', - coin_data->>'symbol', - CASE WHEN parent_data IS NOT NULL THEN parent_data->>'id' ELSE NULL END, - CASE WHEN parent_data IS NOT NULL THEN parent_data->>'name' ELSE NULL END, - CASE WHEN parent_data IS NOT NULL THEN parent_data->>'symbol' ELSE NULL END, - (coin_data->>'rank')::INTEGER, - (coin_data->>'is_new')::BOOLEAN, - (coin_data->>'is_active')::BOOLEAN, - coin_data->>'type', - coin_data->>'logo', - coin_data->'tags', - coin_data->'team', - coin_data->>'description', - coin_data->>'message', - (coin_data->>'open_source')::BOOLEAN, - (coin_data->>'hardware_wallet')::BOOLEAN, - (coin_data->>'started_at')::TIMESTAMP WITH TIME ZONE, - coin_data->>'development_status', - coin_data->>'proof_type', - coin_data->>'org_structure', - coin_data->>'hash_algorithm', - coin_data->>'contract', - coin_data->>'platform', - coin_data->'contracts', - coin_data->'links', - coin_data->'links_extended', - coin_data->'whitepaper', - (coin_data->>'first_data_at')::TIMESTAMP WITH TIME ZONE, - (coin_data->>'last_data_at')::TIMESTAMP WITH TIME ZONE, - CURRENT_TIMESTAMP - ) - ON CONFLICT (id) DO UPDATE SET - name = EXCLUDED.name, - symbol = EXCLUDED.symbol, - parent_id = EXCLUDED.parent_id, - parent_name = EXCLUDED.parent_name, - parent_symbol = EXCLUDED.parent_symbol, - rank = EXCLUDED.rank, - is_new = EXCLUDED.is_new, - is_active = EXCLUDED.is_active, - type = EXCLUDED.type, - logo = EXCLUDED.logo, - tags = EXCLUDED.tags, - team = EXCLUDED.team, - description = EXCLUDED.description, - message = EXCLUDED.message, - open_source = EXCLUDED.open_source, - hardware_wallet = EXCLUDED.hardware_wallet, - started_at = EXCLUDED.started_at, - development_status = EXCLUDED.development_status, - proof_type = EXCLUDED.proof_type, - org_structure = EXCLUDED.org_structure, - hash_algorithm = EXCLUDED.hash_algorithm, - contract = EXCLUDED.contract, - platform = EXCLUDED.platform, - contracts = EXCLUDED.contracts, - links = EXCLUDED.links, - links_extended = EXCLUDED.links_extended, - whitepaper = EXCLUDED.whitepaper, - first_data_at = EXCLUDED.first_data_at, - last_data_at = EXCLUDED.last_data_at, - updated_at = CURRENT_TIMESTAMP; - - -- Return summary - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - coin_data->>'name' as coin_name, - coin_data->>'symbol' as coin_symbol, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - -- Return error information - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - NULL::VARCHAR as coin_name, - NULL::VARCHAR as coin_symbol, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose StatementBegin --- Function to fetch details for top N coins -CREATE OR REPLACE FUNCTION fetch_top_coins_details(limit_count INTEGER DEFAULT 10) -RETURNS TABLE( - operation VARCHAR, - coins_processed INTEGER, - successful_fetches INTEGER, - failed_fetches INTEGER, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - coin_rec RECORD; - success_count INTEGER := 0; - fail_count INTEGER := 0; - total_count INTEGER := 0; - fetch_result RECORD; -BEGIN - start_time := clock_timestamp(); - - -- Fetch details for each top coin - FOR coin_rec IN - SELECT id FROM crypto_coins - WHERE is_active = TRUE AND rank IS NOT NULL - ORDER BY rank - LIMIT limit_count - LOOP - total_count := total_count + 1; - - -- Try to fetch coin details - BEGIN - SELECT * INTO fetch_result FROM fetch_coinpaprika_coin_details(coin_rec.id); - IF fetch_result.operation = 'SUCCESS' THEN - success_count := success_count + 1; - ELSE - fail_count := fail_count + 1; - END IF; - EXCEPTION - WHEN OTHERS THEN - fail_count := fail_count + 1; - END; - END LOOP; - - -- Return summary - RETURN QUERY SELECT - 'COMPLETE'::VARCHAR as operation, - total_count as coins_processed, - success_count as successful_fetches, - fail_count as failed_fetches, - clock_timestamp() - start_time as processing_time; -END; -$$ LANGUAGE plpgsql; --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP FUNCTION IF EXISTS fetch_top_coins_details(INTEGER); -DROP FUNCTION IF EXISTS fetch_coinpaprika_coin_details(VARCHAR); -DROP FUNCTION IF EXISTS refresh_all_coinpaprika_data(); -DROP FUNCTION IF EXISTS fetch_coinpaprika_coins(); -DROP FUNCTION IF EXISTS refresh_market_data(); -DROP FUNCTION IF EXISTS fetch_coinpaprika_global_market_data(); -DROP TABLE IF EXISTS crypto_coin_details CASCADE; -DROP TABLE IF EXISTS crypto_coins CASCADE; -DROP TABLE IF EXISTS crypto_global_market_data CASCADE; --- +goose StatementEnd diff --git a/internal/migrations/009_webauthn_options_functions.sql b/internal/migrations/009_webauthn_options_functions.sql deleted file mode 100644 index 79e592479..000000000 --- a/internal/migrations/009_webauthn_options_functions.sql +++ /dev/null @@ -1,139 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- Enable pgcrypto extension for gen_random_bytes if not already enabled -CREATE EXTENSION IF NOT EXISTS pgcrypto; - --- Function to generate WebAuthn registration options with largeBlob and payment extensions -CREATE OR REPLACE FUNCTION generate_webauthn_register_options( - session_id UUID, - vault_id UUID -) RETURNS JSONB AS $$ -DECLARE - challenge_bytes BYTEA; - challenge_base64 TEXT; - rp_id TEXT; - rp_name TEXT; - user_name TEXT; - user_display_name TEXT; -BEGIN - -- Generate a random challenge based on session_id - challenge_bytes = gen_random_bytes(32); - challenge_base64 = encode(challenge_bytes, 'base64'); - - -- Set default user information - user_name = 'user@' || session_id::TEXT; - user_display_name = 'User'; - - -- Set relying party information - rp_id = 'localhost'; -- This should be configurable - rp_name = 'Sonr Highway'; - - -- Build and return the registration options - RETURN jsonb_build_object( - 'challenge', challenge_base64, - 'rp', jsonb_build_object( - 'id', rp_id, - 'name', rp_name - ), - 'user', jsonb_build_object( - 'id', encode(session_id::TEXT::BYTEA, 'base64'), - 'name', user_name, - 'displayName', user_display_name - ), - 'pubKeyCredParams', jsonb_build_array( - jsonb_build_object('type', 'public-key', 'alg', -7), -- ES256 - jsonb_build_object('type', 'public-key', 'alg', -257) -- RS256 - ), - 'timeout', 60000, - 'attestation', 'direct', - 'authenticatorSelection', jsonb_build_object( - 'authenticatorAttachment', 'platform', - 'userVerification', 'required', - 'residentKey', 'required', - 'requireResidentKey', true - ), - 'extensions', jsonb_build_object( - 'largeBlob', jsonb_build_object( - 'support', 'required' - ), - 'payment', jsonb_build_object( - 'isPayment', true - ) - ) - ); -END; -$$ LANGUAGE plpgsql; - --- Function to generate WebAuthn login options with largeBlob and payment extensions -CREATE OR REPLACE FUNCTION generate_webauthn_login_options( - session_id UUID, - vault_id UUID -) RETURNS JSONB AS $$ -DECLARE - challenge_bytes BYTEA; - challenge_base64 TEXT; - allow_credentials JSONB; - rp_id TEXT; -BEGIN - -- Generate a random challenge based on session_id - challenge_bytes = gen_random_bytes(32); - challenge_base64 = encode(challenge_bytes, 'base64'); - - -- Set relying party information - rp_id = 'localhost'; -- This should be configurable - - -- Set empty allowed credentials (no vault_id column exists) - allow_credentials = '[]'::JSONB; - - -- Build and return the login options - RETURN jsonb_build_object( - 'challenge', challenge_base64, - 'timeout', 60000, - 'rpId', rp_id, - 'allowCredentials', allow_credentials, - 'userVerification', 'required', - 'extensions', jsonb_build_object( - 'largeBlob', jsonb_build_object( - 'support', 'required', - 'read', true, - 'write', true - ), - 'payment', jsonb_build_object( - 'isPayment', true, - 'payeeName', 'Sonr Network', - 'payeeOrigin', 'https://sonr.io', - 'total', jsonb_build_object( - 'currency', 'USD', - 'value', '0.00' - ), - 'instrument', jsonb_build_object( - 'displayName', 'Sonr Wallet', - 'icon', 'https://sonr.io/icon.png' - ) - ) - ) - ); -END; -$$ LANGUAGE plpgsql; - --- Add comments for documentation -COMMENT ON FUNCTION generate_webauthn_register_options(UUID, UUID) IS -'Generates WebAuthn registration options with largeBlob and payment extensions. -Parameters: - - session_id: UUID for generating unique challenge - - vault_id: UUID to associate with user information -Returns: JSONB object with WebAuthn registration options including required extensions'; - -COMMENT ON FUNCTION generate_webauthn_login_options(UUID, UUID) IS -'Generates WebAuthn login options with largeBlob and payment extensions. -Parameters: - - session_id: UUID for generating unique challenge - - vault_id: UUID to lookup allowed credentials -Returns: JSONB object with WebAuthn login options including read/write largeBlob and SPC payment extensions'; - --- +goose StatementEnd - --- +goose Down -DROP FUNCTION IF EXISTS generate_webauthn_login_options(UUID, UUID); -DROP FUNCTION IF EXISTS generate_webauthn_register_options(UUID, UUID); diff --git a/internal/migrations/010_crypto_asset_symbol_linking.sql b/internal/migrations/010_crypto_asset_symbol_linking.sql deleted file mode 100644 index 5d5e1dd9f..000000000 --- a/internal/migrations/010_crypto_asset_symbol_linking.sql +++ /dev/null @@ -1,176 +0,0 @@ --- +goose Up --- +goose StatementBegin --- Create a junction table to link chain assets with crypto coins by symbol -CREATE TABLE IF NOT EXISTS asset_symbol_links ( - id SERIAL PRIMARY KEY, - chain_asset_id INTEGER REFERENCES chain_assets(id) ON DELETE CASCADE, - crypto_coin_id VARCHAR(100) REFERENCES crypto_coins(id) ON DELETE CASCADE, - symbol VARCHAR(20) NOT NULL, - match_confidence VARCHAR(20) DEFAULT 'exact', -- 'exact', 'case_insensitive', 'manual' - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - UNIQUE(chain_asset_id, crypto_coin_id) -); - --- Create indexes for efficient lookups -CREATE INDEX IF NOT EXISTS idx_asset_symbol_links_symbol ON asset_symbol_links(symbol); -CREATE INDEX IF NOT EXISTS idx_asset_symbol_links_chain_asset ON asset_symbol_links(chain_asset_id); -CREATE INDEX IF NOT EXISTS idx_asset_symbol_links_crypto_coin ON asset_symbol_links(crypto_coin_id); -CREATE INDEX IF NOT EXISTS idx_asset_symbol_links_confidence ON asset_symbol_links(match_confidence); - --- Create a composite index on both tables' symbol columns for faster joins -CREATE INDEX IF NOT EXISTS idx_chain_assets_symbol_lower ON chain_assets(LOWER(symbol)); -CREATE INDEX IF NOT EXISTS idx_crypto_coins_symbol_lower ON crypto_coins(LOWER(symbol)); - --- Function to populate asset symbol links based on matching symbols -CREATE OR REPLACE FUNCTION populate_asset_symbol_links() -RETURNS TABLE( - operation VARCHAR, - exact_matches INTEGER, - case_insensitive_matches INTEGER, - total_links_created INTEGER, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - exact_count INTEGER := 0; - case_count INTEGER := 0; -BEGIN - start_time := clock_timestamp(); - - -- First, clear existing automatic matches (preserve manual matches) - DELETE FROM asset_symbol_links WHERE match_confidence IN ('exact', 'case_insensitive'); - - -- Insert exact symbol matches - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - ca.symbol, - 'exact' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON ca.symbol = cc.symbol - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS exact_count = ROW_COUNT; - - -- Insert case-insensitive matches (excluding already matched) - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - UPPER(ca.symbol), - 'case_insensitive' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON LOWER(ca.symbol) = LOWER(cc.symbol) - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - AND NOT EXISTS ( - SELECT 1 FROM asset_symbol_links asl - WHERE asl.chain_asset_id = ca.id - AND asl.crypto_coin_id = cc.id - ) - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS case_count = ROW_COUNT; - - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - exact_count as exact_matches, - case_count as case_insensitive_matches, - exact_count + case_count as total_links_created, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - 0::INTEGER as exact_matches, - 0::INTEGER as case_insensitive_matches, - 0::INTEGER as total_links_created, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; - --- View to easily query linked assets with their market data -CREATE OR REPLACE VIEW v_linked_crypto_assets AS -SELECT - ca.chain_id, - ca.asset_name, - ca.symbol AS chain_symbol, - ca.description AS chain_description, - ca.logo_uri AS chain_logo, - cc.id AS crypto_coin_id, - cc.name AS crypto_coin_name, - cc.symbol AS crypto_symbol, - cc.rank AS market_rank, - cc.type AS crypto_type, - asl.match_confidence, - asl.created_at AS link_created_at -FROM asset_symbol_links asl -INNER JOIN chain_assets ca ON asl.chain_asset_id = ca.id -INNER JOIN crypto_coins cc ON asl.crypto_coin_id = cc.id -ORDER BY cc.rank; - --- Function to get market data for a specific chain asset -CREATE OR REPLACE FUNCTION get_chain_asset_market_data(p_chain_id VARCHAR, p_symbol VARCHAR) -RETURNS TABLE( - chain_id VARCHAR, - asset_name VARCHAR, - symbol VARCHAR, - crypto_coin_id VARCHAR, - crypto_coin_name VARCHAR, - market_rank INTEGER, - coin_type VARCHAR, - match_confidence VARCHAR -) AS $$ -BEGIN - RETURN QUERY - SELECT - ca.chain_id, - ca.asset_name, - ca.symbol, - cc.id AS crypto_coin_id, - cc.name AS crypto_coin_name, - cc.rank AS market_rank, - cc.type AS coin_type, - asl.match_confidence - FROM chain_assets ca - INNER JOIN asset_symbol_links asl ON ca.id = asl.chain_asset_id - INNER JOIN crypto_coins cc ON asl.crypto_coin_id = cc.id - WHERE ca.chain_id = p_chain_id - AND ca.symbol = p_symbol; -END; -$$ LANGUAGE plpgsql; - --- Trigger to update the updated_at timestamp -CREATE OR REPLACE FUNCTION update_asset_symbol_links_updated_at() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = CURRENT_TIMESTAMP; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER trigger_update_asset_symbol_links_updated_at - BEFORE UPDATE ON asset_symbol_links - FOR EACH ROW - EXECUTE FUNCTION update_asset_symbol_links_updated_at(); --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TRIGGER IF EXISTS trigger_update_asset_symbol_links_updated_at ON asset_symbol_links; -DROP FUNCTION IF EXISTS update_asset_symbol_links_updated_at(); -DROP FUNCTION IF EXISTS get_chain_asset_market_data(VARCHAR, VARCHAR); -DROP VIEW IF EXISTS v_linked_crypto_assets; -DROP FUNCTION IF EXISTS populate_asset_symbol_links(); -DROP INDEX IF EXISTS idx_crypto_coins_symbol_lower; -DROP INDEX IF EXISTS idx_chain_assets_symbol_lower; -DROP TABLE IF EXISTS asset_symbol_links CASCADE; --- +goose StatementEnd \ No newline at end of file diff --git a/internal/migrations/011_common_functions.sql b/internal/migrations/011_common_functions.sql deleted file mode 100644 index ae6fe55e6..000000000 --- a/internal/migrations/011_common_functions.sql +++ /dev/null @@ -1,21 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- Create a common function to update the updated_at column -CREATE OR REPLACE FUNCTION update_updated_at_column() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin - --- Drop the function -DROP FUNCTION IF EXISTS update_updated_at_column(); - --- +goose StatementEnd \ No newline at end of file diff --git a/internal/migrations/012_crypto_coin_price_data.sql b/internal/migrations/012_crypto_coin_price_data.sql deleted file mode 100644 index 1390b6a0c..000000000 --- a/internal/migrations/012_crypto_coin_price_data.sql +++ /dev/null @@ -1,507 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- Enable TimescaleDB extension -CREATE EXTENSION IF NOT EXISTS timescaledb; - --- Enable pg_cron extension for scheduled jobs -CREATE EXTENSION IF NOT EXISTS pg_cron; - --- Grant usage on pg_cron schema to postgres user -GRANT USAGE ON SCHEMA cron TO postgres; - --- Create crypto_coin_price table for storing historical price data -CREATE TABLE IF NOT EXISTS crypto_coin_price ( - id SERIAL, - coin_id VARCHAR(255) NOT NULL REFERENCES crypto_coins(id) ON DELETE CASCADE, - time_open TIMESTAMPTZ NOT NULL, - time_close TIMESTAMPTZ NOT NULL, - open DECIMAL(20, 8), - high DECIMAL(20, 8), - low DECIMAL(20, 8), - close DECIMAL(20, 8), - volume DECIMAL(30, 2), - market_cap DECIMAL(30, 2), - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW(), - UNIQUE(coin_id, time_open, time_close) -); - --- Convert to hypertable partitioned by time_close -SELECT create_hypertable('crypto_coin_price', 'time_close', - chunk_time_interval => INTERVAL '7 days', - if_not_exists => TRUE -); - --- Create indexes optimized for TimescaleDB -CREATE INDEX idx_crypto_coin_price_time_close_coin_id -ON crypto_coin_price (time_close DESC, coin_id) -WHERE time_close IS NOT NULL; - -CREATE INDEX idx_crypto_coin_price_coin_id_time_close -ON crypto_coin_price (coin_id, time_close DESC) -WHERE coin_id IS NOT NULL; - --- Enable compression on older chunks -ALTER TABLE crypto_coin_price SET ( - timescaledb.compress, - timescaledb.compress_segmentby = 'coin_id', - timescaledb.compress_orderby = 'time_close DESC' -); - --- Create a policy to automatically compress chunks older than specified interval --- Default is 30 days, but can be configured via app.timescaledb_compress_after_days -DO $$ -DECLARE - compress_days INTEGER; - compress_interval INTERVAL; -BEGIN - -- Try to get compression days from config, default to 30 days - compress_days := COALESCE( - current_setting('app.timescaledb_compress_after_days', true)::INTEGER, - 30 - ); - - compress_interval := compress_days || ' days'; - - PERFORM add_compression_policy('crypto_coin_price', compress_interval); - - RAISE NOTICE 'Compression policy set to compress chunks older than % days', compress_days; -END $$; - --- Add retention policy to drop chunks older than specified interval --- Default is 1 year, but can be configured via app.timescaledb_retention_days -DO $$ -DECLARE - retention_days INTEGER; - retention_interval INTERVAL; -BEGIN - -- Try to get retention days from config, default to 365 days (1 year) - retention_days := COALESCE( - current_setting('app.timescaledb_retention_days', true)::INTEGER, - 365 - ); - - retention_interval := retention_days || ' days'; - - PERFORM add_retention_policy('crypto_coin_price', retention_interval); - - RAISE NOTICE 'Retention policy set to % days', retention_days; -END $$; - --- Create update trigger for updated_at -CREATE TRIGGER update_crypto_coin_price_updated_at - BEFORE UPDATE ON crypto_coin_price - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - --- Create HTTP function to fetch OHLCV data from CoinPaprika -CREATE OR REPLACE FUNCTION http_get_coinpaprika_ohlcv(coin_id TEXT, start_date TEXT DEFAULT NULL, end_date TEXT DEFAULT NULL) -RETURNS TABLE ( - time_open TIMESTAMPTZ, - time_close TIMESTAMPTZ, - open NUMERIC, - high NUMERIC, - low NUMERIC, - close NUMERIC, - volume NUMERIC, - market_cap NUMERIC -) AS $$ -DECLARE - api_url TEXT; - response JSON; - api_key TEXT; -BEGIN - -- Get API key from environment or use default - api_key := COALESCE(current_setting('app.coinpaprika_api_key', true), 'dummy-key-for-free-tier'); - - -- Build URL based on parameters - IF start_date IS NULL AND end_date IS NULL THEN - -- Get today's data - api_url := 'https://api.coinpaprika.com/v1/coins/' || coin_id || '/ohlcv/today'; - ELSIF start_date IS NOT NULL AND end_date IS NOT NULL THEN - -- Get historical data for date range - api_url := 'https://api.coinpaprika.com/v1/coins/' || coin_id || '/ohlcv/historical?start=' || start_date || '&end=' || end_date; - ELSE - -- Get latest data (last 24 hours) - api_url := 'https://api.coinpaprika.com/v1/coins/' || coin_id || '/ohlcv/latest'; - END IF; - - -- Make HTTP request - response := http_get( - api_url, - JSONB_BUILD_OBJECT( - 'User-Agent', 'PostgreSQL/HTTP', - 'Accept', 'application/json' - ) - )::JSON; - - -- Parse and return the response - RETURN QUERY - SELECT - (item->>'time_open')::TIMESTAMPTZ, - (item->>'time_close')::TIMESTAMPTZ, - (item->>'open')::NUMERIC, - (item->>'high')::NUMERIC, - (item->>'low')::NUMERIC, - (item->>'close')::NUMERIC, - (item->>'volume')::NUMERIC, - (item->>'market_cap')::NUMERIC - FROM json_array_elements(response) AS item; -END; -$$ LANGUAGE plpgsql; - --- Function to fetch and store today's price data for a coin -CREATE OR REPLACE FUNCTION refresh_coin_price_today(p_coin_id TEXT) -RETURNS VOID AS $$ -BEGIN - -- Insert or update today's price data - INSERT INTO crypto_coin_price ( - coin_id, time_open, time_close, open, high, low, close, volume, market_cap - ) - SELECT - p_coin_id, time_open, time_close, open, high, low, close, volume, market_cap - FROM http_get_coinpaprika_ohlcv(p_coin_id) - ON CONFLICT (coin_id, time_open, time_close) - DO UPDATE SET - open = EXCLUDED.open, - high = EXCLUDED.high, - low = EXCLUDED.low, - close = EXCLUDED.close, - volume = EXCLUDED.volume, - market_cap = EXCLUDED.market_cap, - updated_at = NOW(); -END; -$$ LANGUAGE plpgsql; - --- Create continuous aggregates for different time intervals --- 1 hour aggregates -CREATE MATERIALIZED VIEW crypto_coin_price_1h -WITH (timescaledb.continuous) AS -SELECT - coin_id, - time_bucket('1 hour', time_close) AS bucket, - FIRST(open, time_open) AS open, - MAX(high) AS high, - MIN(low) AS low, - LAST(close, time_close) AS close, - SUM(volume) AS volume, - AVG(market_cap) AS market_cap, - COUNT(*) AS num_records -FROM crypto_coin_price -GROUP BY coin_id, bucket -WITH NO DATA; - --- 4 hour aggregates -CREATE MATERIALIZED VIEW crypto_coin_price_4h -WITH (timescaledb.continuous) AS -SELECT - coin_id, - time_bucket('4 hours', time_close) AS bucket, - FIRST(open, time_open) AS open, - MAX(high) AS high, - MIN(low) AS low, - LAST(close, time_close) AS close, - SUM(volume) AS volume, - AVG(market_cap) AS market_cap, - COUNT(*) AS num_records -FROM crypto_coin_price -GROUP BY coin_id, bucket -WITH NO DATA; - --- 1 day aggregates -CREATE MATERIALIZED VIEW crypto_coin_price_1d -WITH (timescaledb.continuous) AS -SELECT - coin_id, - time_bucket('1 day', time_close) AS bucket, - FIRST(open, time_open) AS open, - MAX(high) AS high, - MIN(low) AS low, - LAST(close, time_close) AS close, - SUM(volume) AS volume, - AVG(market_cap) AS market_cap, - COUNT(*) AS num_records -FROM crypto_coin_price -GROUP BY coin_id, bucket -WITH NO DATA; - --- 1 week aggregates -CREATE MATERIALIZED VIEW crypto_coin_price_1w -WITH (timescaledb.continuous) AS -SELECT - coin_id, - time_bucket('1 week', time_close) AS bucket, - FIRST(open, time_open) AS open, - MAX(high) AS high, - MIN(low) AS low, - LAST(close, time_close) AS close, - SUM(volume) AS volume, - AVG(market_cap) AS market_cap, - COUNT(*) AS num_records -FROM crypto_coin_price -GROUP BY coin_id, bucket -WITH NO DATA; - --- Create refresh policies for continuous aggregates --- The refresh window must be larger than the bucket interval --- For 1h buckets: window must be > 1 hour -SELECT add_continuous_aggregate_policy('crypto_coin_price_1h', - start_offset => INTERVAL '4 hours', - end_offset => INTERVAL '1 hour', - schedule_interval => INTERVAL '30 minutes'); - --- For 4h buckets: window must be > 4 hours -SELECT add_continuous_aggregate_policy('crypto_coin_price_4h', - start_offset => INTERVAL '24 hours', - end_offset => INTERVAL '4 hours', - schedule_interval => INTERVAL '2 hours'); - --- For 1d buckets: window must be > 1 day -SELECT add_continuous_aggregate_policy('crypto_coin_price_1d', - start_offset => INTERVAL '7 days', - end_offset => INTERVAL '1 day', - schedule_interval => INTERVAL '6 hours'); - --- For 1w buckets: window must be > 1 week -SELECT add_continuous_aggregate_policy('crypto_coin_price_1w', - start_offset => INTERVAL '4 weeks', - end_offset => INTERVAL '1 week', - schedule_interval => INTERVAL '1 day'); - --- Create indexes on continuous aggregates -CREATE INDEX idx_crypto_coin_price_1h_coin_bucket ON crypto_coin_price_1h(coin_id, bucket DESC); -CREATE INDEX idx_crypto_coin_price_4h_coin_bucket ON crypto_coin_price_4h(coin_id, bucket DESC); -CREATE INDEX idx_crypto_coin_price_1d_coin_bucket ON crypto_coin_price_1d(coin_id, bucket DESC); -CREATE INDEX idx_crypto_coin_price_1w_coin_bucket ON crypto_coin_price_1w(coin_id, bucket DESC); - --- Function to get latest price for a coin -CREATE OR REPLACE FUNCTION get_latest_coin_price(p_coin_id TEXT) -RETURNS TABLE ( - coin_id VARCHAR(255), - price DECIMAL(20, 8), - volume DECIMAL(30, 2), - market_cap DECIMAL(30, 2), - high_24h DECIMAL(20, 8), - low_24h DECIMAL(20, 8), - change_24h DECIMAL(20, 8), - last_updated TIMESTAMPTZ -) AS $$ -BEGIN - RETURN QUERY - SELECT - cp.coin_id, - cp.close as price, - cp.volume, - cp.market_cap, - cp.high as high_24h, - cp.low as low_24h, - CASE - WHEN cp.open > 0 THEN ((cp.close - cp.open) / cp.open * 100) - ELSE 0 - END as change_24h, - cp.time_close as last_updated - FROM crypto_coin_price cp - WHERE cp.coin_id = p_coin_id - ORDER BY cp.time_close DESC - LIMIT 1; -END; -$$ LANGUAGE plpgsql; - --- Function to update TimescaleDB policies dynamically -CREATE OR REPLACE FUNCTION update_timescaledb_policies( - p_retention_days INTEGER DEFAULT NULL, - p_compress_after_days INTEGER DEFAULT NULL -) -RETURNS TABLE ( - policy_type TEXT, - old_value TEXT, - new_value TEXT, - status TEXT -) AS $$ -DECLARE - current_retention INTERVAL; - current_compression INTERVAL; - new_retention INTERVAL; - new_compression INTERVAL; -BEGIN - -- Update retention policy if provided - IF p_retention_days IS NOT NULL THEN - -- Get current retention policy - SELECT schedule_interval INTO current_retention - FROM timescaledb_information.policies - WHERE hypertable = 'crypto_coin_price'::regclass - AND policy_name LIKE '%retention%' - LIMIT 1; - - new_retention := p_retention_days || ' days'; - - -- Remove old policy and add new one - PERFORM remove_retention_policy('crypto_coin_price', if_exists => TRUE); - PERFORM add_retention_policy('crypto_coin_price', new_retention); - - RETURN QUERY SELECT - 'retention'::TEXT, - COALESCE(current_retention::TEXT, 'none'), - new_retention::TEXT, - 'updated'::TEXT; - END IF; - - -- Update compression policy if provided - IF p_compress_after_days IS NOT NULL THEN - -- Get current compression policy - SELECT schedule_interval INTO current_compression - FROM timescaledb_information.policies - WHERE hypertable = 'crypto_coin_price'::regclass - AND policy_name LIKE '%compress%' - LIMIT 1; - - new_compression := p_compress_after_days || ' days'; - - -- Remove old policy and add new one - PERFORM remove_compression_policy('crypto_coin_price', if_exists => TRUE); - PERFORM add_compression_policy('crypto_coin_price', new_compression); - - RETURN QUERY SELECT - 'compression'::TEXT, - COALESCE(current_compression::TEXT, 'none'), - new_compression::TEXT, - 'updated'::TEXT; - END IF; - - -- Save configuration to database settings - IF p_retention_days IS NOT NULL THEN - PERFORM set_config('app.timescaledb_retention_days', p_retention_days::TEXT, FALSE); - END IF; - - IF p_compress_after_days IS NOT NULL THEN - PERFORM set_config('app.timescaledb_compress_after_days', p_compress_after_days::TEXT, FALSE); - END IF; -END; -$$ LANGUAGE plpgsql; - --- Create function to refresh price data for all active coins -CREATE OR REPLACE FUNCTION refresh_all_coin_prices() -RETURNS VOID AS $$ -DECLARE - coin RECORD; - success_count INT := 0; - error_count INT := 0; -BEGIN - -- Iterate through all coins that have been linked to Cosmos assets - FOR coin IN - SELECT DISTINCT cc.id as coin_id - FROM crypto_coins cc - JOIN asset_symbol_links asl ON asl.crypto_coin_id = cc.id - WHERE cc.is_active = TRUE - LIMIT 100 -- Process in batches to avoid overwhelming the API - LOOP - BEGIN - PERFORM refresh_coin_price_today(coin.coin_id); - success_count := success_count + 1; - EXCEPTION WHEN OTHERS THEN - error_count := error_count + 1; - RAISE NOTICE 'Error refreshing price for coin %: %', coin.coin_id, SQLERRM; - END; - END LOOP; - - RAISE NOTICE 'Price refresh completed. Success: %, Errors: %', success_count, error_count; -END; -$$ LANGUAGE plpgsql; - --- Create pg_cron jobs for automated data fetching --- Refresh prices every 5 minutes during market hours -SELECT cron.schedule( - 'refresh-coin-prices-frequent', - '*/5 * * * *', -- Every 5 minutes - $$SELECT refresh_all_coin_prices();$$ -); - --- Refresh continuous aggregates every hour -SELECT cron.schedule( - 'refresh-continuous-aggregates-1h', - '0 * * * *', -- Every hour at minute 0 - $$CALL refresh_continuous_aggregate('crypto_coin_price_1h', NULL, NULL);$$ -); - --- Function to get cosmos asset price through symbol linking -CREATE OR REPLACE FUNCTION get_cosmos_asset_price(p_chain_name TEXT, p_base_denom TEXT) -RETURNS TABLE ( - chain_name TEXT, - base_denom TEXT, - symbol TEXT, - coin_id VARCHAR(255), - price DECIMAL(20, 8), - volume DECIMAL(30, 2), - market_cap DECIMAL(30, 2), - high_24h DECIMAL(20, 8), - low_24h DECIMAL(20, 8), - change_24h DECIMAL(20, 8), - last_updated TIMESTAMPTZ -) AS $$ -BEGIN - RETURN QUERY - SELECT - ca.chain_id as chain_name, - ca.base as base_denom, - asl.symbol, - lcp.coin_id, - lcp.price, - lcp.volume, - lcp.market_cap, - lcp.high_24h, - lcp.low_24h, - lcp.change_24h, - lcp.last_updated - FROM asset_symbol_links asl - JOIN chain_assets ca ON asl.chain_asset_id = ca.id - JOIN LATERAL get_latest_coin_price(asl.crypto_coin_id) lcp ON TRUE - WHERE ca.chain_id = p_chain_name - AND ca.base = p_base_denom; -END; -$$ LANGUAGE plpgsql; - --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin - --- Drop cron jobs -SELECT cron.unschedule('refresh-coin-prices-frequent'); -SELECT cron.unschedule('refresh-continuous-aggregates-1h'); - --- Drop functions -DROP FUNCTION IF EXISTS get_cosmos_asset_price(TEXT, TEXT); -DROP FUNCTION IF EXISTS get_latest_coin_price(TEXT); -DROP FUNCTION IF EXISTS update_timescaledb_policies(INTEGER, INTEGER); -DROP FUNCTION IF EXISTS refresh_all_coin_prices(); -DROP FUNCTION IF EXISTS refresh_coin_price_today(TEXT); -DROP FUNCTION IF EXISTS http_get_coinpaprika_ohlcv(TEXT, TEXT, TEXT); - --- Drop continuous aggregate policies -SELECT remove_continuous_aggregate_policy('crypto_coin_price_1h', if_exists => TRUE); -SELECT remove_continuous_aggregate_policy('crypto_coin_price_4h', if_exists => TRUE); -SELECT remove_continuous_aggregate_policy('crypto_coin_price_1d', if_exists => TRUE); -SELECT remove_continuous_aggregate_policy('crypto_coin_price_1w', if_exists => TRUE); - --- Drop continuous aggregates -DROP MATERIALIZED VIEW IF EXISTS crypto_coin_price_1h CASCADE; -DROP MATERIALIZED VIEW IF EXISTS crypto_coin_price_4h CASCADE; -DROP MATERIALIZED VIEW IF EXISTS crypto_coin_price_1d CASCADE; -DROP MATERIALIZED VIEW IF EXISTS crypto_coin_price_1w CASCADE; - --- Drop TimescaleDB policies -SELECT remove_retention_policy('crypto_coin_price', if_exists => TRUE); -SELECT remove_compression_policy('crypto_coin_price', if_exists => TRUE); - --- Drop triggers -DROP TRIGGER IF EXISTS update_crypto_coin_price_updated_at ON crypto_coin_price; - --- Drop hypertable (this will drop all associated objects) -DROP TABLE IF EXISTS crypto_coin_price CASCADE; - --- Drop extensions -DROP EXTENSION IF EXISTS pg_cron CASCADE; -DROP EXTENSION IF EXISTS timescaledb CASCADE; - --- +goose StatementEnd \ No newline at end of file diff --git a/internal/migrations/013_add_asset_quality_filters.sql b/internal/migrations/013_add_asset_quality_filters.sql deleted file mode 100644 index 4e6b60d65..000000000 --- a/internal/migrations/013_add_asset_quality_filters.sql +++ /dev/null @@ -1,420 +0,0 @@ --- +goose Up --- +goose StatementBegin - --- Add status and quality fields to chain_assets table -ALTER TABLE chain_assets -ADD COLUMN IF NOT EXISTS is_active BOOLEAN DEFAULT true, -ADD COLUMN IF NOT EXISTS is_verified BOOLEAN DEFAULT false, -ADD COLUMN IF NOT EXISTS verification_score INTEGER DEFAULT 0, -ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); - --- Create trigger to update updated_at -CREATE TRIGGER update_chain_assets_updated_at - BEFORE UPDATE ON chain_assets - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - --- Create indexes for efficient filtering -CREATE INDEX IF NOT EXISTS idx_chain_assets_active ON chain_assets(is_active) WHERE is_active = true; -CREATE INDEX IF NOT EXISTS idx_chain_assets_verified ON chain_assets(is_verified) WHERE is_verified = true; -CREATE INDEX IF NOT EXISTS idx_chain_assets_score ON chain_assets(verification_score) WHERE verification_score > 0; - --- Function to calculate verification score for assets -CREATE OR REPLACE FUNCTION calculate_asset_verification_score(p_asset_id INTEGER) -RETURNS INTEGER AS $$ -DECLARE - v_score INTEGER := 0; - v_chain_status VARCHAR(50); - v_has_symbol BOOLEAN; - v_has_logo BOOLEAN; - v_has_description BOOLEAN; - v_linked_coin_rank INTEGER; - v_linked_coin_active BOOLEAN; - v_match_confidence VARCHAR(20); -BEGIN - -- Get asset details - SELECT - c.status, - ca.symbol IS NOT NULL AND ca.symbol != '', - ca.logo_uri IS NOT NULL AND ca.logo_uri != '', - ca.description IS NOT NULL AND ca.description != '' - INTO v_chain_status, v_has_symbol, v_has_logo, v_has_description - FROM chain_assets ca - JOIN chains c ON ca.chain_id = c.chain_id - WHERE ca.id = p_asset_id; - - -- Base scoring - IF v_chain_status = 'live' THEN - v_score := v_score + 30; - ELSIF v_chain_status = 'upcoming' THEN - v_score := v_score + 10; - END IF; - - IF v_has_symbol THEN - v_score := v_score + 20; - END IF; - - IF v_has_logo THEN - v_score := v_score + 10; - END IF; - - IF v_has_description THEN - v_score := v_score + 10; - END IF; - - -- Check for linked market data - SELECT - cc.rank, - cc.is_active, - asl.match_confidence - INTO v_linked_coin_rank, v_linked_coin_active, v_match_confidence - FROM asset_symbol_links asl - JOIN crypto_coins cc ON asl.crypto_coin_id = cc.id - WHERE asl.chain_asset_id = p_asset_id - LIMIT 1; - - IF v_linked_coin_rank IS NOT NULL THEN - -- Has market data - v_score := v_score + 30; - - -- Bonus for high rank coins - IF v_linked_coin_rank <= 100 THEN - v_score := v_score + 20; - ELSIF v_linked_coin_rank <= 500 THEN - v_score := v_score + 10; - END IF; - - -- Match confidence bonus - IF v_match_confidence = 'exact' THEN - v_score := v_score + 10; - ELSIF v_match_confidence = 'manual' THEN - v_score := v_score + 15; -- Manual verification is most trusted - END IF; - - IF v_linked_coin_active THEN - v_score := v_score + 10; - END IF; - END IF; - - RETURN v_score; -END; -$$ LANGUAGE plpgsql; - --- Function to update asset quality flags -CREATE OR REPLACE FUNCTION update_asset_quality_flags() -RETURNS TABLE( - total_assets INTEGER, - deactivated_count INTEGER, - verified_count INTEGER, - high_quality_count INTEGER -) AS $$ -DECLARE - v_total INTEGER; - v_deactivated INTEGER := 0; - v_verified INTEGER := 0; - v_high_quality INTEGER := 0; -BEGIN - -- Count total assets - SELECT COUNT(*) INTO v_total FROM chain_assets; - - -- Update verification scores - UPDATE chain_assets - SET verification_score = calculate_asset_verification_score(id); - - -- Mark as inactive: assets with very low scores or from non-live chains - UPDATE chain_assets ca - SET is_active = false - WHERE ca.verification_score < 20 - OR EXISTS ( - SELECT 1 FROM chains c - WHERE c.chain_id = ca.chain_id - AND c.status NOT IN ('live', 'upcoming') - ); - - GET DIAGNOSTICS v_deactivated = ROW_COUNT; - - -- Mark as verified: high quality assets with market data - UPDATE chain_assets ca - SET is_verified = true - WHERE ca.verification_score >= 70 - AND EXISTS ( - SELECT 1 FROM asset_symbol_links asl - JOIN crypto_coins cc ON asl.crypto_coin_id = cc.id - WHERE asl.chain_asset_id = ca.id - AND cc.is_active = true - AND cc.rank IS NOT NULL - ); - - GET DIAGNOSTICS v_verified = ROW_COUNT; - - -- Count high quality assets - SELECT COUNT(*) INTO v_high_quality - FROM chain_assets - WHERE verification_score >= 50; - - RETURN QUERY SELECT v_total, v_deactivated, v_verified, v_high_quality; -END; -$$ LANGUAGE plpgsql; - --- Update the populate_asset_symbol_links function to respect filters -CREATE OR REPLACE FUNCTION populate_asset_symbol_links() -RETURNS TABLE( - operation VARCHAR, - exact_matches INTEGER, - case_insensitive_matches INTEGER, - total_links_created INTEGER, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - exact_count INTEGER := 0; - case_count INTEGER := 0; -BEGIN - start_time := clock_timestamp(); - - -- First, update asset quality flags - PERFORM update_asset_quality_flags(); - - -- Clear existing automatic matches (preserve manual matches) - DELETE FROM asset_symbol_links WHERE match_confidence IN ('exact', 'case_insensitive'); - - -- Insert exact symbol matches (only for active assets) - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - ca.symbol, - 'exact' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON ca.symbol = cc.symbol - INNER JOIN chains c ON ca.chain_id = c.chain_id - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - AND ca.is_active = TRUE - AND c.status IN ('live', 'upcoming') - AND ca.verification_score >= 30 - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS exact_count = ROW_COUNT; - - -- Insert case-insensitive matches (excluding already matched, only for quality assets) - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - UPPER(ca.symbol), - 'case_insensitive' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON LOWER(ca.symbol) = LOWER(cc.symbol) - INNER JOIN chains c ON ca.chain_id = c.chain_id - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - AND ca.is_active = TRUE - AND c.status IN ('live', 'upcoming') - AND ca.verification_score >= 30 - AND NOT EXISTS ( - SELECT 1 FROM asset_symbol_links asl - WHERE asl.chain_asset_id = ca.id - AND asl.crypto_coin_id = cc.id - ) - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS case_count = ROW_COUNT; - - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - exact_count as exact_matches, - case_count as case_insensitive_matches, - exact_count + case_count as total_links_created, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - 0::INTEGER as exact_matches, - 0::INTEGER as case_insensitive_matches, - 0::INTEGER as total_links_created, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; - --- Create view for quality assets only -CREATE OR REPLACE VIEW v_quality_linked_assets AS -SELECT - ca.chain_id, - ca.asset_name, - ca.symbol, - ca.description, - ca.logo_uri, - ca.is_verified, - ca.verification_score, - cc.id as crypto_coin_id, - cc.name as crypto_coin_name, - cc.rank as market_rank, - cc.type as coin_type, - asl.match_confidence, - cp.close as current_price, - cp.volume as volume_24h, - cp.market_cap, - CASE - WHEN cp.open > 0 THEN ((cp.close - cp.open) / cp.open * 100) - ELSE 0 - END as change_24h -FROM chain_assets ca -INNER JOIN asset_symbol_links asl ON ca.id = asl.chain_asset_id -INNER JOIN crypto_coins cc ON asl.crypto_coin_id = cc.id -LEFT JOIN LATERAL ( - SELECT * FROM crypto_coin_price - WHERE coin_id = cc.id - ORDER BY time_close DESC - LIMIT 1 -) cp ON true -WHERE ca.is_active = true - AND ca.verification_score >= 50 - AND cc.is_active = true -ORDER BY cc.rank NULLS LAST; - --- Function to manually mark an asset as junk/inactive -CREATE OR REPLACE FUNCTION mark_asset_as_junk(p_chain_id TEXT, p_base_denom TEXT) -RETURNS VOID AS $$ -BEGIN - UPDATE chain_assets - SET - is_active = false, - is_verified = false, - verification_score = 0, - updated_at = NOW() - WHERE chain_id = p_chain_id AND base = p_base_denom; - - -- Remove any symbol links for this asset - DELETE FROM asset_symbol_links - WHERE chain_asset_id IN ( - SELECT id FROM chain_assets - WHERE chain_id = p_chain_id AND base = p_base_denom - ); -END; -$$ LANGUAGE plpgsql; - --- Function to manually verify an asset -CREATE OR REPLACE FUNCTION verify_asset(p_chain_id TEXT, p_base_denom TEXT) -RETURNS VOID AS $$ -BEGIN - UPDATE chain_assets - SET - is_active = true, - is_verified = true, - verification_score = GREATEST(verification_score, 80), - updated_at = NOW() - WHERE chain_id = p_chain_id AND base = p_base_denom; -END; -$$ LANGUAGE plpgsql; - --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin - --- Drop views -DROP VIEW IF EXISTS v_quality_linked_assets; - --- Drop functions -DROP FUNCTION IF EXISTS verify_asset(TEXT, TEXT); -DROP FUNCTION IF EXISTS mark_asset_as_junk(TEXT, TEXT); -DROP FUNCTION IF EXISTS update_asset_quality_flags(); -DROP FUNCTION IF EXISTS calculate_asset_verification_score(INTEGER); - --- Restore original populate_asset_symbol_links function -CREATE OR REPLACE FUNCTION populate_asset_symbol_links() -RETURNS TABLE( - operation VARCHAR, - exact_matches INTEGER, - case_insensitive_matches INTEGER, - total_links_created INTEGER, - processing_time INTERVAL -) AS $$ -DECLARE - start_time TIMESTAMP; - exact_count INTEGER := 0; - case_count INTEGER := 0; -BEGIN - start_time := clock_timestamp(); - - -- First, clear existing automatic matches (preserve manual matches) - DELETE FROM asset_symbol_links WHERE match_confidence IN ('exact', 'case_insensitive'); - - -- Insert exact symbol matches - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - ca.symbol, - 'exact' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON ca.symbol = cc.symbol - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS exact_count = ROW_COUNT; - - -- Insert case-insensitive matches (excluding already matched) - INSERT INTO asset_symbol_links (chain_asset_id, crypto_coin_id, symbol, match_confidence) - SELECT DISTINCT - ca.id, - cc.id, - UPPER(ca.symbol), - 'case_insensitive' - FROM chain_assets ca - INNER JOIN crypto_coins cc ON LOWER(ca.symbol) = LOWER(cc.symbol) - WHERE ca.symbol IS NOT NULL - AND cc.symbol IS NOT NULL - AND cc.is_active = TRUE - AND NOT EXISTS ( - SELECT 1 FROM asset_symbol_links asl - WHERE asl.chain_asset_id = ca.id - AND asl.crypto_coin_id = cc.id - ) - ON CONFLICT (chain_asset_id, crypto_coin_id) DO NOTHING; - - GET DIAGNOSTICS case_count = ROW_COUNT; - - RETURN QUERY SELECT - 'SUCCESS'::VARCHAR as operation, - exact_count as exact_matches, - case_count as case_insensitive_matches, - exact_count + case_count as total_links_created, - clock_timestamp() - start_time as processing_time; - -EXCEPTION - WHEN OTHERS THEN - RETURN QUERY SELECT - 'ERROR: ' || SQLERRM::VARCHAR as operation, - 0::INTEGER as exact_matches, - 0::INTEGER as case_insensitive_matches, - 0::INTEGER as total_links_created, - clock_timestamp() - start_time as processing_time; - RAISE; -END; -$$ LANGUAGE plpgsql; - --- Drop triggers -DROP TRIGGER IF EXISTS update_chain_assets_updated_at ON chain_assets; - --- Drop indexes -DROP INDEX IF EXISTS idx_chain_assets_score; -DROP INDEX IF EXISTS idx_chain_assets_verified; -DROP INDEX IF EXISTS idx_chain_assets_active; - --- Drop columns -ALTER TABLE chain_assets -DROP COLUMN IF EXISTS updated_at, -DROP COLUMN IF EXISTS verification_score, -DROP COLUMN IF EXISTS is_verified, -DROP COLUMN IF EXISTS is_active; - --- +goose StatementEnd \ No newline at end of file diff --git a/internal/migrations/014_sessions_table.sql b/internal/migrations/014_sessions_table.sql deleted file mode 100644 index eb4f2ed8d..000000000 --- a/internal/migrations/014_sessions_table.sql +++ /dev/null @@ -1,26 +0,0 @@ --- +goose Up --- +goose StatementBegin -CREATE TABLE sessions ( - id TEXT PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, - expires_at TIMESTAMP WITH TIME ZONE NOT NULL, - account_id TEXT NOT NULL, - user_agent TEXT, - ip_address TEXT, - is_active BOOLEAN NOT NULL DEFAULT TRUE, - session_data JSONB, - FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE -); - --- Indexes for performance -CREATE INDEX idx_sessions_account_id ON sessions(account_id); -CREATE INDEX idx_sessions_expires_at ON sessions(expires_at); -CREATE INDEX idx_sessions_is_active ON sessions(is_active) WHERE is_active = TRUE; -CREATE INDEX idx_sessions_created_at ON sessions(created_at); --- +goose StatementEnd - --- +goose Down --- +goose StatementBegin -DROP TABLE sessions; --- +goose StatementEnd \ No newline at end of file diff --git a/package.json b/package.json deleted file mode 100644 index 8021d8970..000000000 --- a/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "@sonr.io/monorepo", - "version": "0.1.0", - "private": true, - "description": "Sonr - Decentralized identity and asset management monorepo", - "author": "diDAO", - "license": "MIT", - "homepage": "https://github.com/sonr-io/sonr", - "repository": { - "type": "git", - "url": "git+https://github.com/sonr-io/sonr.git" - }, - "bugs": { - "url": "https://github.com/sonr-io/sonr/issues" - }, - "engines": { - "node": ">=20.0.0", - "pnpm": ">=10.0.0" - }, - "packageManager": "pnpm@10.14.0", - "scripts": { - "build": "turbo run build", - "preview": "turbo run preview", - "test": "turbo run test", - "lint": "biome check .", - "format": "biome format --write .", - "clean": "turbo run clean && rm -rf node_modules", - "build:cloudflare": "pnpm --filter ./web build:cloudflare", - "docs": "cd docs && npx -y mint dev", - "docs:convert-swagger": "node scripts/convert-swagger.js", - "typecheck": "turbo run typecheck", - "dev:auth": "cd web/auth && pnpm run dev", - "dev:dash": "cd web/dash && pnpm run dev", - "deploy:auth": "cd web/auth && pnpm run deploy", - "deploy:dash": "cd web/dash && pnpm run deploy" - }, - "devDependencies": { - "@biomejs/biome": "^2.2.3", - "@types/node": "^24.3.1", - "@vitest/ui": "^3.2.4", - "happy-dom": "^18.0.1", - "turbo": "^2.5.6", - "typescript": "^5.9.2", - "vitest": "^3.2.4", - "wrangler": "^4.34.0" - }, - "pnpm": { - "overrides": { - "esbuild": "0.20.0" - }, - "peerDependencyRules": { - "ignoreMissing": [] - }, - "onlyBuiltDependencies": [ - "@biomejs/biome", - "@bufbuild/buf", - "es5-ext", - "esbuild", - "sharp", - "workerd" - ] - }, - "dependencies": { - "glob": "^11.0.3", - "swagger2openapi": "^7.0.8", - "yaml": "^2.8.1" - } -} diff --git a/packages/com/.cz.toml b/packages/com/.cz.toml deleted file mode 100644 index 636165da5..000000000 --- a/packages/com/.cz.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "@sonr.io/com@v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "npm" -update_changelog_on_bump = true -major_version_zero = true -pre_bump_hooks = ["bash ../../scripts/hook-bump-pre.sh"] -post_bump_hooks = ["pnpm --filter '@sonr.io/com' publish --no-git-checks"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(pkg-com\\)(!)?:" diff --git a/packages/com/package.json b/packages/com/package.json deleted file mode 100644 index 073c5d942..000000000 --- a/packages/com/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "@sonr.io/com", - "version": "0.1.12", - "description": "Common types, utilities, and constants for Sonr ecosystem", - "type": "module", - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "exports": { - ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js", - "require": "./dist/index.cjs" - }, - "./types": { - "types": "./dist/types/index.d.ts", - "import": "./dist/types/index.js", - "require": "./dist/types/index.cjs" - }, - "./utils": { - "types": "./dist/utils/index.d.ts", - "import": "./dist/utils/index.js", - "require": "./dist/utils/index.cjs" - }, - "./constants": { - "types": "./dist/constants/index.d.ts", - "import": "./dist/constants/index.js", - "require": "./dist/constants/index.cjs" - } - }, - "files": [ - "dist", - "src" - ], - "scripts": { - "build": "tsup", - "dev": "tsup --watch", - "clean": "rm -rf dist", - "test": "echo 'No tests defined for @sonr.io/com'", - "typecheck": "tsc --noEmit", - "lint": "biome check .", - "format": "biome format --write .", - "release": "cz --no-raise 6,21 bump --yes --increment PATCH" - }, - "dependencies": { - "zod": "^3.24.1" - }, - "devDependencies": { - "@biomejs/biome": "^1.8.0", - "@types/node": "^22.5.5", - "tsup": "^8.0.0", - "typescript": "^5.7.2" - }, - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "https://github.com/sonr-io/sonr.git", - "directory": "packages/com" - }, - "license": "MIT", - "keywords": [ - "sonr", - "common", - "types", - "utilities", - "constants" - ] -} diff --git a/packages/com/src/constants/index.ts b/packages/com/src/constants/index.ts deleted file mode 100644 index 9b63ecb90..000000000 --- a/packages/com/src/constants/index.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * @sonr.io/com - Constants - * Shared constants and configurations - */ - -/** - * Status constants - */ -export const STATUS = { - ACTIVE: 'active', - INACTIVE: 'inactive', - PENDING: 'pending', - ERROR: 'error', - WARNING: 'warning', - SUCCESS: 'success', -} as const; - -/** - * HTTP methods - */ -export const HTTP_METHOD = { - GET: 'GET', - POST: 'POST', - PUT: 'PUT', - DELETE: 'DELETE', - PATCH: 'PATCH', -} as const; - -/** - * Time intervals in milliseconds - */ -export const TIME = { - SECOND: 1000, - MINUTE: 60 * 1000, - HOUR: 60 * 60 * 1000, - DAY: 24 * 60 * 60 * 1000, - WEEK: 7 * 24 * 60 * 60 * 1000, -} as const; - -/** - * Default pagination settings - */ -export const PAGINATION = { - DEFAULT_PAGE: 1, - DEFAULT_PAGE_SIZE: 20, - MAX_PAGE_SIZE: 100, -} as const; - -/** - * API error codes - */ -export const ERROR_CODE = { - NETWORK_ERROR: 'NETWORK_ERROR', - TIMEOUT: 'TIMEOUT', - UNAUTHORIZED: 'UNAUTHORIZED', - FORBIDDEN: 'FORBIDDEN', - NOT_FOUND: 'NOT_FOUND', - SERVER_ERROR: 'SERVER_ERROR', - VALIDATION_ERROR: 'VALIDATION_ERROR', - RATE_LIMIT: 'RATE_LIMIT', -} as const; - -/** - * User roles - */ -export const USER_ROLE = { - OWNER: 'owner', - ADMIN: 'admin', - DEVELOPER: 'developer', - VIEWER: 'viewer', -} as const; - -/** - * Permission effects - */ -export const PERMISSION_EFFECT = { - ALLOW: 'allow', - DENY: 'deny', -} as const; - -/** - * Domain verification methods - */ -export const VERIFICATION_METHOD = { - DNS: 'dns', - HTTP: 'http', -} as const; - -/** - * Chart types - */ -export const CHART_TYPE = { - LINE: 'line', - AREA: 'area', - BAR: 'bar', - PIE: 'pie', - DONUT: 'donut', - RADAR: 'radar', -} as const; - -/** - * Theme options - */ -export const THEME = { - LIGHT: 'light', - DARK: 'dark', - SYSTEM: 'system', -} as const; - -/** - * Notification frequency - */ -export const NOTIFICATION_FREQUENCY = { - REALTIME: 'realtime', - DAILY: 'daily', - WEEKLY: 'weekly', - NEVER: 'never', -} as const; - -/** - * Performance status thresholds - */ -export const PERFORMANCE_THRESHOLD = { - GOOD: 'good', - WARNING: 'warning', - CRITICAL: 'critical', -} as const; - -/** - * DNS record types - */ -export const DNS_RECORD_TYPE = { - TXT: 'TXT', - CNAME: 'CNAME', - A: 'A', - AAAA: 'AAAA', -} as const; - -/** - * Service categories - */ -export const SERVICE_CATEGORY = { - API: 'api', - WEBAPP: 'webapp', - MOBILE: 'mobile', - IOT: 'iot', - BLOCKCHAIN: 'blockchain', - OTHER: 'other', -} as const; - -/** - * Permission categories - */ -export const PERMISSION_CATEGORY = { - BASIC: 'basic', - STANDARD: 'standard', - ADVANCED: 'advanced', - CUSTOM: 'custom', -} as const; - -/** - * Time range presets - */ -export const TIME_PRESET = { - TODAY: 'today', - YESTERDAY: 'yesterday', - LAST_7_DAYS: 'last7days', - LAST_30_DAYS: 'last30days', - THIS_MONTH: 'thisMonth', - LAST_MONTH: 'lastMonth', - CUSTOM: 'custom', -} as const; - -/** - * Regular expressions for validation - */ -export const REGEX = { - EMAIL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, - URL: /^https?:\/\/.+/, - DOMAIN: /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i, - API_KEY: /^sk_(test|live)_[a-zA-Z0-9]{24,}$/, - DID: /^did:[a-z0-9]+:[a-zA-Z0-9:.-]+$/, - USERNAME: /^[a-zA-Z0-9_-]+$/, - PHONE: /^\+?[1-9]\d{1,14}$/, -} as const; - -/** - * Default chart colors - */ -export const CHART_COLORS = [ - '#3b82f6', // blue - '#10b981', // emerald - '#f59e0b', // amber - '#ef4444', // red - '#8b5cf6', // violet - '#ec4899', // pink - '#14b8a6', // teal - '#f97316', // orange -] as const; diff --git a/packages/com/src/index.ts b/packages/com/src/index.ts deleted file mode 100644 index 25fe281b4..000000000 --- a/packages/com/src/index.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @sonr.io/com - * Shared types, utilities, and constants for the Sonr ecosystem - */ - -// Export all types -export * from './types'; - -// Export all utilities -export * from './utils'; - -// Export all constants -export * from './constants'; - -// Re-export commonly used items at top level for convenience -export type { - // Core types - ID, - Timestamp, - Status, - Pagination, - Filter, - // Service types - Service, - ServiceMetrics, - ServiceRequest, - // Domain types - Domain, - DomainStatus, - DNSRecord, - // Permission types - Permission, - UCANToken, - UCANCapability, - // User types - User, - UserRole, - UserPreferences, - // API types - ApiResponse, - ApiError, - // Analytics types - TimeRange, - DataPoint, - Metric, -} from './types'; - -export { - // Date utilities - formatDate, - formatTime, - formatDateTime, - getRelativeTime, - // Format utilities - formatNumber, - formatCurrency, - formatPercentage, - formatBytes, - abbreviateNumber, - // Validation utilities - isValidEmail, - isValidUrl, - isValidDomain, - schemas, - // Array utilities - groupBy, - sortBy, - filterBy, - unique, -} from './utils'; - -export { - // Constants - STATUS, - HTTP_METHOD, - ERROR_CODE, - USER_ROLE, - THEME, -} from './constants'; diff --git a/packages/com/src/types/analytics.ts b/packages/com/src/types/analytics.ts deleted file mode 100644 index a53e7488b..000000000 --- a/packages/com/src/types/analytics.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Analytics & Metrics Types - * Types for charts, metrics, and data visualization - */ - -import type { Timestamp } from './common'; - -/** - * Time range for analytics - */ -export interface TimeRange { - start: Date; - end: Date; - preset?: - | 'today' - | 'yesterday' - | 'last7days' - | 'last30days' - | 'thisMonth' - | 'lastMonth' - | 'custom'; -} - -/** - * Analytics data point - */ -export interface DataPoint { - timestamp: Timestamp; - value: number; - label?: string; - metadata?: Record; -} - -/** - * Chart configuration - */ -export interface ChartConfig { - type: 'line' | 'area' | 'bar' | 'pie' | 'donut' | 'radar'; - colors?: string[]; - showLegend?: boolean; - showTooltip?: boolean; - showGrid?: boolean; - animated?: boolean; - stacked?: boolean; -} - -/** - * Metric with trend - */ -export interface Metric { - label: string; - value: number | string; - change?: number; - changeType?: 'increase' | 'decrease' | 'neutral'; - unit?: string; - icon?: string; -} - -/** - * Performance metric - */ -export interface PerformanceMetric { - name: string; - value: number; - unit: 'ms' | 's' | 'min' | '%' | 'rpm' | 'rps'; - status: 'good' | 'warning' | 'critical'; - threshold?: { - warning: number; - critical: number; - }; -} - -/** - * Activity data for charts - */ -export interface ActivityData { - date: string; - value: number; - category?: string; -} - -/** - * Request pattern data - */ -export interface RequestPatternData { - endpoint: string; - method: string; - count: number; - avgDuration: number; - errorRate: number; -} diff --git a/packages/com/src/types/api.ts b/packages/com/src/types/api.ts deleted file mode 100644 index 9caa5b8db..000000000 --- a/packages/com/src/types/api.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * API Types - * Types for API requests, responses, and errors - */ - -import type { Timestamp } from './common'; - -/** - * API response wrapper - */ -export interface ApiResponse { - data?: T; - error?: ApiError; - status: number; - timestamp: Timestamp; -} - -/** - * API error - */ -export interface ApiError { - code: string; - message: string; - details?: Record; - stack?: string; -} - -/** - * API request configuration - */ -export interface ApiRequestConfig { - method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; - headers?: Record; - params?: Record; - body?: any; - timeout?: number; - retry?: { - attempts: number; - delay: number; - backoff?: 'linear' | 'exponential'; - }; -} - -/** - * Paginated API response - */ -export interface PaginatedResponse { - items: T[]; - pagination: { - page: number; - pageSize: number; - total: number; - totalPages: number; - }; -} - -/** - * API endpoint metadata - */ -export interface ApiEndpoint { - path: string; - method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; - description?: string; - authenticated: boolean; - rateLimit?: { - requests: number; - window: number; - }; -} diff --git a/packages/com/src/types/common.ts b/packages/com/src/types/common.ts deleted file mode 100644 index a01488f8c..000000000 --- a/packages/com/src/types/common.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Core Common Types - * Fundamental types used across the Sonr ecosystem - */ - -/** - * Common ID type for entities - */ -export type ID = string; - -/** - * Timestamp in ISO 8601 format - */ -export type Timestamp = string; - -/** - * Status types used across components - */ -export type Status = 'active' | 'inactive' | 'pending' | 'error' | 'warning' | 'success'; - -/** - * Sort direction for tables and lists - */ -export type SortDirection = 'asc' | 'desc'; - -/** - * Common pagination props - */ -export interface Pagination { - page: number; - pageSize: number; - total: number; - totalPages: number; -} - -/** - * Common filter props - */ -export interface Filter { - field: string; - operator: 'equals' | 'contains' | 'startsWith' | 'endsWith' | 'gt' | 'lt' | 'gte' | 'lte'; - value: string | number | boolean; -} - -/** - * Navigation item - */ -export interface NavigationItem { - id: ID; - label: string; - href: string; - icon?: string; - badge?: string | number; - disabled?: boolean; - external?: boolean; - children?: NavigationItem[]; -} - -/** - * Breadcrumb item - */ -export interface BreadcrumbItem { - label: string; - href?: string; - current?: boolean; -} - -/** - * Notification - */ -export interface Notification { - id: ID; - type: 'info' | 'success' | 'warning' | 'error'; - title: string; - message?: string; - timestamp: Timestamp; - read?: boolean; - action?: { - label: string; - href?: string; - onClick?: () => void; - }; -} - -/** - * Activity event - */ -export interface ActivityEvent { - id: ID; - type: string; - actor: string; - action: string; - target?: string; - timestamp: Timestamp; - details?: Record; - icon?: string; -} diff --git a/packages/com/src/types/domain.ts b/packages/com/src/types/domain.ts deleted file mode 100644 index 7c4254f1e..000000000 --- a/packages/com/src/types/domain.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Domain & DNS Types - * Types for domain verification and DNS management - */ - -import type { ID, Timestamp } from './common'; - -/** - * Domain verification status - */ -export type DomainStatus = 'unverified' | 'pending' | 'verified' | 'failed' | 'expired'; - -/** - * Domain entity - */ -export interface Domain { - id: ID; - domain: string; - status: DomainStatus; - owner: string; - verificationMethod: 'dns' | 'http'; - verificationRecord?: DNSRecord; - verifiedAt?: Timestamp; - expiresAt?: Timestamp; - services?: ID[]; - createdAt: Timestamp; - updatedAt: Timestamp; -} - -/** - * DNS record for domain verification - */ -export interface DNSRecord { - type: 'TXT' | 'CNAME' | 'A' | 'AAAA'; - name: string; - value: string; - ttl?: number; -} - -/** - * Domain verification request - */ -export interface DomainVerificationRequest { - domain: string; - method: 'dns' | 'http'; - autoVerify?: boolean; -} - -/** - * Verification step - */ -export interface VerificationStep { - id: string; - label: string; - description?: string; - status: 'pending' | 'in-progress' | 'completed' | 'error'; - errorMessage?: string; -} - -/** - * Verification check result - */ -export interface VerificationCheck { - type: 'dns' | 'http'; - success: boolean; - message: string; - details?: Record; - timestamp: Timestamp; -} diff --git a/packages/com/src/types/index.ts b/packages/com/src/types/index.ts deleted file mode 100644 index 93a476bde..000000000 --- a/packages/com/src/types/index.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @sonr.io/com - Type Definitions - * Central export for all shared types - */ - -// Core common types -export * from './common'; - -// Service types -export * from './service'; - -// Domain & DNS types -export * from './domain'; - -// Permission & auth types -export * from './permission'; - -// User types -export * from './user'; - -// Analytics types -export * from './analytics'; - -// API types -export * from './api'; - -// Re-export commonly used types for convenience -export type { - ID, - Timestamp, - Status, - SortDirection, - Pagination, - Filter, -} from './common'; - -export type { - Service, - ServiceMetrics, - ServiceEndpoint, - ServiceRequest, -} from './service'; - -export type { - Domain, - DomainStatus, - DNSRecord, - DomainVerificationRequest, -} from './domain'; - -export type { - Permission, - UCANToken, - UCANCapability, - AuditLogEntry, -} from './permission'; - -export type { - User, - UserRole, - UserPreferences, -} from './user'; - -export type { - TimeRange, - DataPoint, - Metric, - PerformanceMetric, -} from './analytics'; - -export type { - ApiResponse, - ApiError, - ApiRequestConfig, -} from './api'; diff --git a/packages/com/src/types/permission.ts b/packages/com/src/types/permission.ts deleted file mode 100644 index 07cb10edc..000000000 --- a/packages/com/src/types/permission.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Auth & Permission Types - * Types for authentication, authorization, and UCAN tokens - */ - -import type { ID, Timestamp } from './common'; - -/** - * Permission entity - */ -export interface Permission { - id: ID; - resource: string; - action: string; - effect: 'allow' | 'deny'; - conditions?: PermissionCondition[]; - description?: string; -} - -/** - * Permission condition - */ -export interface PermissionCondition { - field: string; - operator: 'equals' | 'notEquals' | 'contains' | 'in' | 'notIn'; - value: any; -} - -/** - * Permission template for quick setup - */ -export interface PermissionTemplate { - id: ID; - name: string; - description: string; - permissions: Permission[]; - category: 'basic' | 'standard' | 'advanced' | 'custom'; -} - -/** - * UCAN token capability - */ -export interface UCANCapability { - with: string; - can: string; - nb?: Record; -} - -/** - * UCAN token structure - */ -export interface UCANToken { - iss: string; - aud: string; - exp?: number; - nbf?: number; - nnc?: string; - att: UCANCapability[]; - prf?: string[]; - fct?: Record; -} - -/** - * Audit log entry - */ -export interface AuditLogEntry { - id: ID; - timestamp: Timestamp; - actor: string; - action: string; - resource: string; - result: 'success' | 'failure'; - details?: Record; - ip?: string; - userAgent?: string; -} - -/** - * Permission request data - */ -export interface PermissionRequestData { - requester: string; - resource: string; - actions: string[]; - reason?: string; - duration?: number; - conditions?: PermissionCondition[]; -} diff --git a/packages/com/src/types/service.ts b/packages/com/src/types/service.ts deleted file mode 100644 index bc07a1eee..000000000 --- a/packages/com/src/types/service.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Service-related Types - * Types for Sonr Services (x/svc module) - */ - -import type { ID, Status, Timestamp } from './common'; -import type { Permission } from './permission'; - -/** - * Service entity - */ -export interface Service { - id: ID; - name: string; - description?: string; - domain: string; - status: 'active' | 'inactive' | 'pending'; - apiKey: string; - createdAt: Timestamp; - updatedAt: Timestamp; - permissions?: Permission[]; - metrics?: ServiceMetrics; - owner: string; - tags?: string[]; - endpoints?: ServiceEndpoint[]; - lastActive?: Timestamp; - domainVerificationStatus?: 'verified' | 'pending' | 'failed' | 'unverified'; -} - -/** - * Service endpoint configuration - */ -export interface ServiceEndpoint { - url: string; - method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; - description?: string; - authenticated: boolean; - rateLimit?: number; -} - -/** - * Service metrics - */ -export interface ServiceMetrics { - requests: number; - errors: number; - latencyP50: number; - latencyP95: number; - latencyP99: number; - uptime: number; - lastActivity?: Timestamp; -} - -/** - * Service creation/update request - */ -export interface ServiceRequest { - name: string; - description?: string; - domain?: string; - permissions?: string[]; - tags?: string[]; - endpoints?: ServiceEndpoint[]; -} - -/** - * Service status - */ -export type ServiceStatus = 'active' | 'inactive' | 'suspended' | 'pending'; - -/** - * Service category - */ -export type ServiceCategory = 'api' | 'webapp' | 'mobile' | 'iot' | 'blockchain' | 'other'; diff --git a/packages/com/src/types/user.ts b/packages/com/src/types/user.ts deleted file mode 100644 index 46a1407d0..000000000 --- a/packages/com/src/types/user.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * User Types - * Types for user profiles, roles, and preferences - */ - -import type { ID, Timestamp } from './common'; - -/** - * User profile - */ -export interface User { - id: ID; - did: string; - username?: string; - email?: string; - name?: string; - avatar?: string; - role?: UserRole; - createdAt: Timestamp; - lastLogin?: Timestamp; - preferences?: UserPreferences; -} - -/** - * User role - */ -export type UserRole = 'owner' | 'admin' | 'developer' | 'viewer'; - -/** - * User preferences - */ -export interface UserPreferences { - theme?: 'light' | 'dark' | 'system'; - language?: string; - timezone?: string; - notifications?: NotificationPreferences; -} - -/** - * Notification preferences - */ -export interface NotificationPreferences { - email?: boolean; - push?: boolean; - inApp?: boolean; - frequency?: 'realtime' | 'daily' | 'weekly' | 'never'; -} diff --git a/packages/com/src/utils/array.ts b/packages/com/src/utils/array.ts deleted file mode 100644 index cdb7c6e29..000000000 --- a/packages/com/src/utils/array.ts +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Array & Object Utilities - * Functions for manipulating arrays and objects - */ - -import type { Filter, SortDirection } from '../types'; - -/** - * Group an array of objects by a key - */ -export function groupBy(array: T[], key: keyof T): Record { - return array.reduce( - (result, item) => { - const group = String(item[key]); - if (!result[group]) result[group] = []; - result[group].push(item); - return result; - }, - {} as Record - ); -} - -/** - * Sort an array of objects by a key - */ -export function sortBy(array: T[], key: keyof T, direction: SortDirection = 'asc'): T[] { - return [...array].sort((a, b) => { - const aVal = a[key]; - const bVal = b[key]; - - if (aVal < bVal) return direction === 'asc' ? -1 : 1; - if (aVal > bVal) return direction === 'asc' ? 1 : -1; - return 0; - }); -} - -/** - * Filter an array of objects by multiple filters - */ -export function filterBy(array: T[], filters: Filter[]): T[] { - return array.filter((item) => { - return filters.every((filter) => { - const value = (item as any)[filter.field]; - const filterValue = filter.value; - - switch (filter.operator) { - case 'equals': - return value === filterValue; - case 'contains': - return String(value).toLowerCase().includes(String(filterValue).toLowerCase()); - case 'startsWith': - return String(value).toLowerCase().startsWith(String(filterValue).toLowerCase()); - case 'endsWith': - return String(value).toLowerCase().endsWith(String(filterValue).toLowerCase()); - case 'gt': - return value > filterValue; - case 'lt': - return value < filterValue; - case 'gte': - return value >= filterValue; - case 'lte': - return value <= filterValue; - default: - return true; - } - }); - }); -} - -/** - * Deep clone an object - */ -export function deepClone(obj: T): T { - return JSON.parse(JSON.stringify(obj)); -} - -/** - * Merge objects deeply - */ -export function deepMerge>(...objects: Partial[]): T { - const result = {} as any; - - for (const obj of objects) { - for (const key in obj) { - const val = obj[key]; - if (val !== null && typeof val === 'object' && !Array.isArray(val)) { - result[key] = deepMerge(result[key] || {}, val); - } else { - result[key] = val; - } - } - } - - return result; -} - -/** - * Remove duplicates from array - */ -export function unique(array: T[]): T[] { - return [...new Set(array)]; -} - -/** - * Remove duplicates from array of objects by key - */ -export function uniqueBy(array: T[], key: keyof T): T[] { - const seen = new Set(); - return array.filter((item) => { - const value = item[key]; - if (seen.has(value)) { - return false; - } - seen.add(value); - return true; - }); -} - -/** - * Chunk array into smaller arrays - */ -export function chunk(array: T[], size: number): T[][] { - const chunks: T[][] = []; - for (let i = 0; i < array.length; i += size) { - chunks.push(array.slice(i, i + size)); - } - return chunks; -} - -/** - * Flatten nested array - */ -export function flatten(array: (T | T[])[]): T[] { - return array.reduce((flat, item) => { - return flat.concat(Array.isArray(item) ? flatten(item) : item); - }, []); -} - -/** - * Pick specific keys from object - */ -export function pick, K extends keyof T>( - obj: T, - keys: K[] -): Pick { - const result = {} as Pick; - keys.forEach((key) => { - if (key in obj) { - result[key] = obj[key]; - } - }); - return result; -} - -/** - * Omit specific keys from object - */ -export function omit, K extends keyof T>( - obj: T, - keys: K[] -): Omit { - const result = { ...obj }; - keys.forEach((key) => { - delete result[key]; - }); - return result as Omit; -} diff --git a/packages/com/src/utils/chart.ts b/packages/com/src/utils/chart.ts deleted file mode 100644 index 2336d744f..000000000 --- a/packages/com/src/utils/chart.ts +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Chart & Analytics Utilities - * Functions for data visualization and analytics - */ - -import type { DataPoint } from '../types'; - -/** - * Generate chart colors - */ -export function generateChartColors(count: number): string[] { - const baseColors = [ - '#3b82f6', // blue - '#10b981', // emerald - '#f59e0b', // amber - '#ef4444', // red - '#8b5cf6', // violet - '#ec4899', // pink - '#14b8a6', // teal - '#f97316', // orange - ]; - - const colors: string[] = []; - for (let i = 0; i < count; i++) { - colors.push(baseColors[i % baseColors.length]); - } - - return colors; -} - -/** - * Calculate percentage change - */ -export function calculatePercentageChange(oldValue: number, newValue: number): number { - if (oldValue === 0) return newValue > 0 ? 100 : 0; - return ((newValue - oldValue) / Math.abs(oldValue)) * 100; -} - -/** - * Aggregate data points by interval - */ -export function aggregateDataPoints( - points: DataPoint[], - interval: 'hour' | 'day' | 'week' | 'month' -): DataPoint[] { - const grouped = new Map(); - - points.forEach((point) => { - const date = new Date(point.timestamp); - let key: string; - - switch (interval) { - case 'hour': - key = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-${date.getHours()}`; - break; - case 'day': - key = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`; - break; - case 'week': { - const weekNumber = Math.floor(date.getDate() / 7); - key = `${date.getFullYear()}-${date.getMonth()}-W${weekNumber}`; - break; - } - case 'month': - key = `${date.getFullYear()}-${date.getMonth()}`; - break; - } - - if (!grouped.has(key)) { - grouped.set(key, []); - } - grouped.get(key)?.push(point); - }); - - const aggregated: DataPoint[] = []; - grouped.forEach((group, key) => { - const sum = group.reduce((acc, point) => acc + point.value, 0); - const avg = sum / group.length; - - aggregated.push({ - timestamp: group[0].timestamp, - value: avg, - label: key, - metadata: { - count: group.length, - sum, - avg, - min: Math.min(...group.map((p) => p.value)), - max: Math.max(...group.map((p) => p.value)), - }, - }); - }); - - return aggregated.sort( - (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime() - ); -} - -/** - * Calculate statistics for data points - */ -export function calculateStatistics(values: number[]): { - min: number; - max: number; - mean: number; - median: number; - sum: number; - count: number; - stdDev: number; -} { - const sorted = [...values].sort((a, b) => a - b); - const sum = values.reduce((acc, val) => acc + val, 0); - const mean = sum / values.length; - - const median = - values.length % 2 === 0 - ? (sorted[values.length / 2 - 1] + sorted[values.length / 2]) / 2 - : sorted[Math.floor(values.length / 2)]; - - const variance = values.reduce((acc, val) => acc + (val - mean) ** 2, 0) / values.length; - const stdDev = Math.sqrt(variance); - - return { - min: Math.min(...values), - max: Math.max(...values), - mean, - median, - sum, - count: values.length, - stdDev, - }; -} - -/** - * Generate trend line data - */ -export function generateTrendLine(points: DataPoint[]): DataPoint[] { - if (points.length < 2) return points; - - // Simple linear regression - const n = points.length; - const sumX = points.reduce((acc, _, i) => acc + i, 0); - const sumY = points.reduce((acc, p) => acc + p.value, 0); - const sumXY = points.reduce((acc, p, i) => acc + i * p.value, 0); - const sumX2 = points.reduce((acc, _, i) => acc + i * i, 0); - - const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); - const intercept = (sumY - slope * sumX) / n; - - return points.map((point, i) => ({ - ...point, - value: slope * i + intercept, - metadata: { - ...point.metadata, - isTrendLine: true, - }, - })); -} - -/** - * Calculate moving average - */ -export function calculateMovingAverage(values: number[], window: number): number[] { - if (window > values.length) return values; - - const result: number[] = []; - for (let i = 0; i < values.length; i++) { - const start = Math.max(0, i - window + 1); - const windowValues = values.slice(start, i + 1); - const avg = windowValues.reduce((acc, val) => acc + val, 0) / windowValues.length; - result.push(avg); - } - - return result; -} diff --git a/packages/com/src/utils/date.ts b/packages/com/src/utils/date.ts deleted file mode 100644 index f32776cdb..000000000 --- a/packages/com/src/utils/date.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Date & Time Utilities - * Functions for date/time formatting and manipulation - */ - -import type { TimeRange, Timestamp } from '../types'; - -/** - * Format a timestamp to a human-readable date string - */ -export function formatDate(timestamp: Timestamp, options?: Intl.DateTimeFormatOptions): string { - const date = new Date(timestamp); - return date.toLocaleDateString( - undefined, - options || { - year: 'numeric', - month: 'short', - day: 'numeric', - } - ); -} - -/** - * Format a timestamp to a human-readable time string - */ -export function formatTime(timestamp: Timestamp, options?: Intl.DateTimeFormatOptions): string { - const date = new Date(timestamp); - return date.toLocaleTimeString( - undefined, - options || { - hour: '2-digit', - minute: '2-digit', - } - ); -} - -/** - * Format a timestamp to a human-readable date and time string - */ -export function formatDateTime(timestamp: Timestamp): string { - return `${formatDate(timestamp)} ${formatTime(timestamp)}`; -} - -/** - * Get a relative time string (e.g., "2 hours ago") - */ -export function getRelativeTime(timestamp: Timestamp): string { - const now = Date.now(); - const then = new Date(timestamp).getTime(); - const diff = now - then; - - const seconds = Math.floor(diff / 1000); - const minutes = Math.floor(seconds / 60); - const hours = Math.floor(minutes / 60); - const days = Math.floor(hours / 24); - const weeks = Math.floor(days / 7); - const months = Math.floor(days / 30); - const years = Math.floor(days / 365); - - if (seconds < 60) return `${seconds} second${seconds !== 1 ? 's' : ''} ago`; - if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`; - if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`; - if (days < 7) return `${days} day${days !== 1 ? 's' : ''} ago`; - if (weeks < 4) return `${weeks} week${weeks !== 1 ? 's' : ''} ago`; - if (months < 12) return `${months} month${months !== 1 ? 's' : ''} ago`; - return `${years} year${years !== 1 ? 's' : ''} ago`; -} - -/** - * Get date range from preset - */ -export function getDateRangeFromPreset(preset: TimeRange['preset']): TimeRange { - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); - - switch (preset) { - case 'today': - return { - start: today, - end: now, - preset, - }; - case 'yesterday': { - const yesterday = new Date(today); - yesterday.setDate(yesterday.getDate() - 1); - return { - start: yesterday, - end: today, - preset, - }; - } - case 'last7days': { - const weekAgo = new Date(today); - weekAgo.setDate(weekAgo.getDate() - 7); - return { - start: weekAgo, - end: now, - preset, - }; - } - case 'last30days': { - const monthAgo = new Date(today); - monthAgo.setDate(monthAgo.getDate() - 30); - return { - start: monthAgo, - end: now, - preset, - }; - } - case 'thisMonth': { - const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); - return { - start: startOfMonth, - end: now, - preset, - }; - } - case 'lastMonth': { - const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1); - const endOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0); - return { - start: startOfLastMonth, - end: endOfLastMonth, - preset, - }; - } - default: - return { - start: today, - end: now, - preset: 'today', - }; - } -} - -/** - * Format duration in milliseconds to human-readable string - */ -export function formatDuration(ms: number): string { - if (ms < 1000) return `${ms}ms`; - - const seconds = Math.floor(ms / 1000); - if (seconds < 60) return `${seconds}s`; - - const minutes = Math.floor(seconds / 60); - if (minutes < 60) return `${minutes}m ${seconds % 60}s`; - - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ${minutes % 60}m`; - - const days = Math.floor(hours / 24); - return `${days}d ${hours % 24}h`; -} diff --git a/packages/com/src/utils/format.ts b/packages/com/src/utils/format.ts deleted file mode 100644 index dae0c579c..000000000 --- a/packages/com/src/utils/format.ts +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Formatting Utilities - * Functions for number and string formatting - */ - -import type { Metric, Status } from '../types'; - -/** - * Format a number with commas - */ -export function formatNumber(value: number, decimals = 0): string { - return value.toLocaleString(undefined, { - minimumFractionDigits: decimals, - maximumFractionDigits: decimals, - }); -} - -/** - * Format a number as currency - */ -export function formatCurrency(value: number, currency = 'USD'): string { - return value.toLocaleString(undefined, { - style: 'currency', - currency, - }); -} - -/** - * Format a number as a percentage - */ -export function formatPercentage(value: number, decimals = 1): string { - return `${(value * 100).toFixed(decimals)}%`; -} - -/** - * Format bytes to human-readable size - */ -export function formatBytes(bytes: number, decimals = 2): string { - if (bytes === 0) return '0 Bytes'; - - const k = 1024; - const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - - return `${Number.parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`; -} - -/** - * Abbreviate large numbers (e.g., 1.2K, 3.4M) - */ -export function abbreviateNumber(value: number): string { - if (value < 1000) return value.toString(); - - const suffixes = ['', 'K', 'M', 'B', 'T']; - const suffixNum = Math.floor(`${value}`.length / 3); - const shortValue = Number.parseFloat( - (suffixNum !== 0 ? value / 1000 ** suffixNum : value).toPrecision(2) - ); - - if (shortValue % 1 !== 0) { - return shortValue.toFixed(1) + suffixes[suffixNum]; - } - - return shortValue + suffixes[suffixNum]; -} - -/** - * Truncate a string to a maximum length - */ -export function truncate(str: string, maxLength: number, suffix = '...'): string { - if (str.length <= maxLength) return str; - return str.slice(0, maxLength - suffix.length) + suffix; -} - -/** - * Convert a string to title case - */ -export function toTitleCase(str: string): string { - return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); -} - -/** - * Convert a string to slug format - */ -export function toSlug(str: string): string { - return str - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, '') - .replace(/[\s_-]+/g, '-') - .replace(/^-+|-+$/g, ''); -} - -/** - * Generate a random ID - */ -export function generateId(prefix = ''): string { - const random = Math.random().toString(36).substr(2, 9); - const timestamp = Date.now().toString(36); - return prefix ? `${prefix}_${timestamp}_${random}` : `${timestamp}_${random}`; -} - -/** - * Extract initials from a name - */ -export function getInitials(name: string): string { - return name - .split(' ') - .map((word) => word[0]) - .join('') - .toUpperCase() - .slice(0, 2); -} - -/** - * Get status color/variant - */ -export function getStatusColor(status: Status): string { - const colors: Record = { - active: 'green', - inactive: 'gray', - pending: 'yellow', - error: 'red', - warning: 'orange', - success: 'green', - }; - return colors[status] || 'gray'; -} - -/** - * Get status icon - */ -export function getStatusIcon(status: Status): string { - const icons: Record = { - active: 'check-circle', - inactive: 'x-circle', - pending: 'clock', - error: 'alert-circle', - warning: 'alert-triangle', - success: 'check-circle', - }; - return icons[status] || 'circle'; -} - -/** - * Format metric with trend - */ -export function formatMetricWithTrend(metric: Metric): string { - let result = String(metric.value); - - if (metric.unit) { - result += ` ${metric.unit}`; - } - - if (metric.change !== undefined) { - const symbol = metric.change > 0 ? '↑' : metric.change < 0 ? '↓' : '→'; - const changeStr = Math.abs(metric.change).toFixed(1); - result += ` ${symbol} ${changeStr}%`; - } - - return result; -} diff --git a/packages/com/src/utils/index.ts b/packages/com/src/utils/index.ts deleted file mode 100644 index 883e70864..000000000 --- a/packages/com/src/utils/index.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @sonr.io/com - Utility Functions - * Central export for all utility functions - */ - -// Date & time utilities -export * from './date'; - -// Formatting utilities -export * from './format'; - -// Validation utilities -export * from './validation'; - -// Array & object utilities -export * from './array'; - -// Chart & analytics utilities -export * from './chart'; - -// Export utility collections for convenience -export { - formatDate, - formatTime, - formatDateTime, - getRelativeTime, - getDateRangeFromPreset, - formatDuration, -} from './date'; - -export { - formatNumber, - formatCurrency, - formatPercentage, - formatBytes, - abbreviateNumber, - truncate, - toTitleCase, - toSlug, - generateId, - getInitials, - getStatusColor, - getStatusIcon, - formatMetricWithTrend, -} from './format'; - -export { - isValidEmail, - isValidUrl, - isValidDomain, - isValidApiKey, - isValidDID, - isValidPhoneNumber, - schemas, - createValidator, -} from './validation'; - -export { - groupBy, - sortBy, - filterBy, - deepClone, - deepMerge, - unique, - uniqueBy, - chunk, - flatten, - pick, - omit, -} from './array'; - -export { - generateChartColors, - calculatePercentageChange, - aggregateDataPoints, - calculateStatistics, - generateTrendLine, - calculateMovingAverage, -} from './chart'; diff --git a/packages/com/src/utils/validation.ts b/packages/com/src/utils/validation.ts deleted file mode 100644 index ade2170a1..000000000 --- a/packages/com/src/utils/validation.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Validation Utilities - * Functions for validating common formats and patterns - */ - -import { z } from 'zod'; - -/** - * Validate email address - */ -export function isValidEmail(email: string): boolean { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - return emailRegex.test(email); -} - -/** - * Validate URL - */ -export function isValidUrl(url: string): boolean { - try { - new URL(url); - return true; - } catch { - return false; - } -} - -/** - * Validate domain - */ -export function isValidDomain(domain: string): boolean { - const domainRegex = - /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i; - return domainRegex.test(domain); -} - -/** - * Validate API key format - */ -export function isValidApiKey(key: string): boolean { - const apiKeyRegex = /^sk_(test|live)_[a-zA-Z0-9]{24,}$/; - return apiKeyRegex.test(key); -} - -/** - * Validate DID format - */ -export function isValidDID(did: string): boolean { - // W3C DID format: did:method:method-specific-id - const didRegex = /^did:[a-z0-9]+:[a-zA-Z0-9:.-]+$/; - return didRegex.test(did); -} - -/** - * Validate phone number - */ -export function isValidPhoneNumber(phone: string): boolean { - // Basic international format - const phoneRegex = /^\+?[1-9]\d{1,14}$/; - return phoneRegex.test(phone.replace(/[\s-()]/g, '')); -} - -// ============================================================================ -// Zod Validation Schemas -// ============================================================================ - -/** - * Common validation schemas - */ -export const schemas = { - /** - * Email schema - */ - email: z.string().email('Invalid email address'), - - /** - * URL schema - */ - url: z.string().url('Invalid URL'), - - /** - * Domain schema - */ - domain: z.string().refine(isValidDomain, 'Invalid domain'), - - /** - * API key schema - */ - apiKey: z.string().refine(isValidApiKey, 'Invalid API key format'), - - /** - * DID schema - */ - did: z.string().refine(isValidDID, 'Invalid DID format'), - - /** - * Phone number schema - */ - phoneNumber: z.string().refine(isValidPhoneNumber, 'Invalid phone number'), - - /** - * Service registration schema - */ - serviceRegistration: z.object({ - name: z.string().min(3, 'Name must be at least 3 characters').max(50), - description: z.string().optional(), - domain: z.string().refine(isValidDomain, 'Invalid domain').optional(), - permissions: z.array(z.string()).optional(), - tags: z.array(z.string()).max(10, 'Maximum 10 tags allowed').optional(), - }), - - /** - * Domain verification schema - */ - domainVerification: z.object({ - domain: z.string().refine(isValidDomain, 'Invalid domain'), - method: z.enum(['dns', 'http']), - autoVerify: z.boolean().optional(), - }), - - /** - * User profile schema - */ - userProfile: z.object({ - username: z - .string() - .min(3) - .max(30) - .regex(/^[a-zA-Z0-9_-]+$/, 'Username can only contain letters, numbers, - and _'), - email: z.string().email().optional(), - name: z.string().max(100).optional(), - avatar: z.string().url().optional(), - }), - - /** - * Pagination schema - */ - pagination: z.object({ - page: z.number().int().positive(), - pageSize: z.number().int().positive().max(100), - }), - - /** - * Time range schema - */ - timeRange: z.object({ - start: z.date(), - end: z.date(), - preset: z - .enum(['today', 'yesterday', 'last7days', 'last30days', 'thisMonth', 'lastMonth', 'custom']) - .optional(), - }), - - /** - * Permission request schema - */ - permissionRequest: z.object({ - resource: z.string().min(1), - action: z.string().min(1), - effect: z.enum(['allow', 'deny']), - conditions: z - .array( - z.object({ - field: z.string(), - operator: z.enum(['equals', 'notEquals', 'contains', 'in', 'notIn']), - value: z.any(), - }) - ) - .optional(), - }), -}; - -/** - * Create a validator function from a Zod schema - */ -export function createValidator(schema: z.ZodSchema) { - return (data: unknown): { success: boolean; data?: T; errors?: z.ZodError } => { - const result = schema.safeParse(data); - if (result.success) { - return { success: true, data: result.data }; - } - return { success: false, errors: result.error }; - }; -} diff --git a/packages/com/tsconfig.json b/packages/com/tsconfig.json deleted file mode 100644 index dad17729e..000000000 --- a/packages/com/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "lib": ["ES2022"], - "declaration": true, - "declarationMap": true, - "outDir": "./dist", - "rootDir": "./src", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "types": ["node"] - }, - "include": ["src/**/*.ts", "src/**/*.tsx"], - "exclude": ["dist", "node_modules", "**/*.test.ts", "**/*.spec.ts"] -} diff --git a/packages/com/tsup.config.ts b/packages/com/tsup.config.ts deleted file mode 100644 index 967050eef..000000000 --- a/packages/com/tsup.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { defineConfig } from 'tsup'; - -export default defineConfig({ - entry: { - index: 'src/index.ts', - 'types/index': 'src/types/index.ts', - 'utils/index': 'src/utils/index.ts', - 'constants/index': 'src/constants/index.ts', - }, - format: ['esm', 'cjs'], - dts: true, - clean: true, - splitting: false, - sourcemap: true, - minify: false, - treeshake: true, - external: ['zod'], -}); diff --git a/packages/es/.cz.toml b/packages/es/.cz.toml deleted file mode 100644 index b7a12ec51..000000000 --- a/packages/es/.cz.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "@sonr.io/es@v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "npm" -update_changelog_on_bump = true -major_version_zero = true -pre_bump_hooks = ["bash ../../scripts/hook-bump-pre.sh"] -post_bump_hooks = ["pnpm --filter '@sonr.io/es' publish --no-git-checks"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(pkg-es\\)(!)?:" diff --git a/packages/es/.gitignore b/packages/es/.gitignore deleted file mode 100644 index ca460aae5..000000000 --- a/packages/es/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -node_modules -.pnp -.pnp.js - -# testing -coverage - -# build -dist/ - -# production -build - -# misc -.DS_Store -*.pem -.vscode -.tmp - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# local env files -.env -.env*.local - -# vercel -.vercel - -# typescript -*.tsbuildinfo - -# turbo -.turbo -.aider* diff --git a/packages/es/README.md b/packages/es/README.md deleted file mode 100644 index 380195a26..000000000 --- a/packages/es/README.md +++ /dev/null @@ -1,692 +0,0 @@ -# `@sonr.io/es` - -A tree-shakeable, framework agnostic, [pure ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) alternative of [CosmJS](https://github.com/cosmos/cosmjs) and [Cosmos Kit](https://cosmoskit.com) (**generate bundles up to 10x smaller than Cosmos Kit**). - -- [Features](#features) -- [Installing](#installing) - - [Using with TypeScript](#using-with-typescript) - - [Using with Vite](#using-with-vite) - - [Using Station wallet](#using-station-wallet) -- [Examples](#examples) -- [Modules](#modules) - - [`@sonr.io/es/client`](#@sonr.io/esclient) - - [`@sonr.io/es/codec`](#@sonr.io/escodec) - - [`@sonr.io/es/protobufs`](#@sonr.io/esprotobufs) - - [`@sonr.io/es/registry`](#@sonr.io/esregistry) - - [`@sonr.io/es/wallet`](#@sonr.io/eswallet) - - [`@sonr.io/es/ipfs`](#ipfs-integration) -- [Benchmarks](#benchmarks) - - [Results](#results) -- [See More](#see-more) - -## Features - -- **Fully tree-shakeable**: import and bundle only the modules you need -- **Framework agnostic**: integrate with any web framework (React, Vue, Svelte, Solid, etc.) -- **Lightweight and minimal**: 153 KB gzipped to connect a React app to Keplr via browser extension or WalletConnect, 10x smaller than Cosmos Kit V2 (see [benchmarks](#benchmarks)) -- **Uses modern web APIs**: no dependencies on Node.js and minimal dependencies on third-party libraries where possible -- **Supports modern bundlers**: works with Vite, SWC, Rollup, etc. -- **Fully typed**: written in TypeScript and ships with type definitions - -## Installing - -For Cosmos SDK v0.47 and below: - -```sh -npm install @sonr.io/es - -pnpm add @sonr.io/es - -yarn add @sonr.io/es -``` - -For Cosmos SDK v0.50, install using the `sdk50` tag: - -```sh -npm install @sonr.io/es@sdk50 - -pnpm add @sonr.io/es@sdk50 - -yarn add @sonr.io/es@sdk50 -``` - -> [!IMPORTANT] -> The bump from v0.47 to v0.50 introduces significant breaking changes and is not recommended to be used unless necessary. To reduce the impact on consumers, the `main` branch and the published package on npm with the `latest` tag will continue to target v0.47 until the majority of live chains have migrated to v0.50. -> -> The [`parallel/sdk50`](https://github.com/coinhall/@sonr.io/es/tree/parallel/sdk50) branch targetting v0.50 will be developed and maintained in parallel with the `main` branch, where the same patch version number should have feature parity (eg. `@sonr.io/es@0.0.69` should have the same features as `@sonr.io/es@0.0.69-sdk50.0`). - -### Using with TypeScript - -This library only exports ES modules. To ensure imports from this library work correctly, the following configuration is required in `tsconfig.json`: - -```ts -{ - "compilerOptions": { - "moduleResolution": "bundler", // recommended if using modern bundlers - // or "node16" - // or "nodenext" - // but NOT "node" - } -} -``` - -### Using with Vite - -If you are using Vite, the following configuration is required in `vite.config.ts`: - -```ts -export default defineConfig({ - define: { - global: "window", - }, -}); -``` - -> This can be removed once support for WalletConnect v1 is no longer required. - -### Using Station wallet - -The Station wallet currently relies on WalletConnect v1. If you want to import and use `StationController`, a polyfill for `Buffer` is required: - -```ts -// First, install the buffer package -npm install buffer - -// Then, create a new file 'polyfill.ts' -import { Buffer } from "buffer"; -(window as any).Buffer = Buffer; - -// Finally, import the above file in your entry file -import "./polyfill"; -``` - -See [`examples/solid-vite`](./examples/solid-vite) for a working example. - -> This can be removed once support for WalletConnect v1 is no longer required. - -## Examples - -### Using the ESM Autoloader (Browser/CDN) - -The library includes an autoloader that automatically initializes all modules and makes them available globally via `window.Sonr`. This is perfect for quick prototyping or when you want to use the library without a build system. - -#### Method 1: Load from CDN - -```html - - - - Sonr ES Example - - - - - - - - -``` - -#### Method 2: Import as ES Module - -```html - -``` - -#### Method 3: Using in Node.js/Build Systems - -```javascript -// Import specific modules (tree-shakeable) -import { registerWithPasskey, loginWithPasskey } from '@sonr.io/es/client/auth'; -import { createMotorPlugin } from '@sonr.io/es/plugins'; -import { bech32 } from '@sonr.io/es/codec'; - -// Or import the entire autoloader -import Sonr from '@sonr.io/es/autoloader'; - -// Initialize and use -async function main() { - // Initialize Sonr - await Sonr.init({ - enableMotor: true, - enableVault: false - }); - - // Use WebAuthn - if (await Sonr.webauthn.isAvailable()) { - const result = await Sonr.webauthn.register({ - username: 'bob', - displayName: 'Bob Smith', - rpId: 'example.com', - rpName: 'Example App' - }); - console.log('Registered:', result); - } - - // Access plugins - const motor = await Sonr.createMotorPlugin(); - console.log('Motor plugin ready:', motor); - - // Use codec utilities - const address = Sonr.codec.bech32.encode('sonr', [1, 2, 3, 4]); - console.log('Encoded address:', address); -} - -main(); -``` - -#### Autoloader API Reference - -The autoloader exposes the following on `window.Sonr`: - -```javascript -window.Sonr = { - // Core modules - auth: {...}, // Authentication utilities - client: {...}, // Blockchain client - codec: {...}, // Encoding/decoding utilities - wallet: {...}, // Wallet management - registry: {...}, // Chain registry - plugins: {...}, // WASM plugins (motor, vault) - - // WebAuthn shortcuts - webauthn: { - register: registerWithPasskey, - login: loginWithPasskey, - isSupported: isWebAuthnSupported, - isAvailable: isWebAuthnAvailable, - isConditionalAvailable: isConditionalMediationAvailable, - bufferToBase64url: bufferToBase64url, - base64urlToBuffer: base64urlToBuffer - }, - - // Plugin shortcuts - motor: {...}, // Motor plugin namespace - vault: {...}, // Vault plugin namespace - - // Factory functions - createMotorPlugin: Function, - createVaultClient: Function, - - // Utilities - init: async (config) => {...}, // Initialize with config - getEnvironment: () => {...}, // Get environment info - isBrowser: Boolean, // Check if running in browser - isNode: Boolean, // Check if running in Node.js - version: String // Library version -} -``` - -#### Events - -The autoloader dispatches the following events: - -- `sonr:ready` - Fired when the library is fully loaded and initialized - ```javascript - window.addEventListener('sonr:ready', (event) => { - const Sonr = event.detail; - console.log('Sonr is ready!', Sonr); - }); - ``` - -### Other Examples - -See the [`examples`](./examples) folder for more detailed examples: - -1. [How do I connect to third party wallets via browser extension or WalletConnect? How do I create, sign, and broadcast transactions?](./examples/solid-vite) -2. [How do I programmatically sign and broadcast transactions without relying on a third party wallet?](./examples/mnemonic-wallet) -3. [How do I verify signatures signed using the `signArbitrary` function?](./examples/verify-signatures) -4. [How do I batch queries to the blockchain?](./examples/batch-query) -5. [How do I use the ESM autoloader in a browser?](./examples/autoloader.html) - -## Modules - -This package is split into multiple subdirectories, with each subdirectory having their own set of functionalities. The root directory does not contain any exports, and all exports are exported from the subdirectories. Thus, imports must be done by referencing the subdirectories (ie. `import { ... } from "@sonr.io/es/client"`). - -### `@sonr.io/es/client` - -This directory contains models and helper functions to interact with Cosmos SDK via the [CometBFT RPC](https://docs.cosmos.network/v0.50/core/grpc_rest#cometbft-rpc). - -### `@sonr.io/es/codec` - -This directory contains various encoding and decoding functions that relies solely on [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) and has no dependencies on Node.js. For modern browsers and Node v16+, this should work out of the box. - -### `@sonr.io/es/protobufs` - -This directory contains the auto-generated code for various Cosmos SDK based protobufs. See `scripts/gen-protobufs.mjs` for the script that generates the code. - -### `@sonr.io/es/registry` - -This directory contains various APIs, data, and types needed for wallet interactions (ie. Keplr). Some types are auto-generated, see `scripts/gen-registry.mjs` for the script that generates the types. - -### `@sonr.io/es/wallet` - -This directory is a [Cosmos Kit](https://cosmoskit.com) alternative to interact with wallets across all Cosmos SDK based blockchains. See [`examples/solid-vite`](./examples/solid-vite) for a working example. - -**Wallets supported**: - -- [Station](https://docs.terra.money/learn/station/) -- [Keplr](https://www.keplr.app/) -- [Leap](https://www.leapwallet.io/) -- [Cosmostation](https://wallet.cosmostation.io/) -- [OWallet](https://owallet.dev/) -- [Compass](https://compasswallet.io/) (for Sei only) -- [MetaMask](https://metamask.io/) (for Injective only) -- [Ninji](https://ninji.xyz/) (for Injective only) - -**Features**: - -- Supports both browser extension (desktop) and WalletConnect (mobile) -- Unified interface for connecting, signing, broadcasting, and event handling -- Signing of arbitrary messages (for wallets that support it) -- Simultaneous connections to multiple WalletConnect wallets - -## Benchmarks - -See the [`benchmarks`](./benchmarks) folder, where the bundle size of SonrES is compared against Cosmos Kit. The following are adhered to: - -- Apps should only contain the minimal functionality of connecting to Osmosis via Keplr using both the browser extension and WalletConnect wallets -- Apps should be built using React 18 (as Cosmos Kit has a [hard dependency](https://docs.cosmoskit.com/get-started)) and Vite -- Use the total sum of all generated bundles as reported by Vite after running the `vite build` command, including the size of all other dependencies like React/HTML/CSS/etc. (note: this is crude and not 100% accurate, but is the simplest method) - -### Results - -> Last updated: 4th May 2024 - -| Package | Minified | Gzipped | -| ------------- | -------- | ------- | -| SonrES | 553 KB | 153 KB | -| Cosmos Kit v1 | 6010 KB | 1399 KB | -| Cosmos Kit v2 | 6780 KB | 1556 KB | - -## See More - -- [Changelog](./CHANGELOG.md) - for notable changes - -## IPFS Integration - -The `@sonr.io/es` package now includes comprehensive IPFS/Helia support for distributed MPC enclave data storage. This integration enables secure, decentralized storage of vault encryption keys and sensitive cryptographic material. - -### Features - -- 🌐 **Modern IPFS with Helia**: Built on the latest Helia implementation for JavaScript/TypeScript -- 🔐 **MPC Enclave Support**: Secure storage and retrieval of Multi-Party Computation enclave data -- ⚡ **Performance Optimized**: LRU caching, connection pooling, and retry logic with exponential backoff -- 🌍 **Browser & Node.js**: Full support for both environments with automatic transport selection -- 🔄 **Gateway Fallbacks**: Automatic fallback to IPFS gateways when direct connections fail -- 📦 **Batch Operations**: Efficient batch storage and retrieval of multiple enclaves -- 🔍 **DWN Integration**: Query service for backend IPFS operations through Decentralized Web Nodes - -### Quick Start - -```typescript -import { ipfs } from '@sonr.io/es'; - -// Create IPFS client -const client = await ipfs.createIPFSClient({ - gateways: ['https://gateway.pinata.cloud'], - enablePersistence: true, -}); - -// Store enclave data -const enclaveData = { - publicKey: 'ed25519:...', - privateKeyShares: ['share1', 'share2', 'share3'], - threshold: 2, - parties: 3, -}; - -const { cid } = await client.addEnclaveData( - new TextEncoder().encode(JSON.stringify(enclaveData)) -); - -// Retrieve data -const retrieved = await client.getEnclaveData(cid); -const data = JSON.parse(new TextDecoder().decode(retrieved)); - -// Clean up -await client.cleanup(); -``` - -### API Reference - -#### IPFSClient - -The main IPFS client for interacting with the network. - -```typescript -interface IPFSClient { - initialize(): Promise - addEnclaveData(data: Uint8Array): Promise - getEnclaveData(cid: string): Promise - pin(cid: string): Promise - unpin(cid: string): Promise - isPinned(cid: string): Promise - listPins(): Promise - getNodeStatus(): Promise - cleanup(): Promise -} -``` - -#### EnclaveIPFSManager - -Manages MPC enclave data with encryption and integrity verification. - -```typescript -interface EnclaveIPFSManager { - storeEnclaveData( - data: EnclaveDataWithCID, - payload: Uint8Array - ): Promise - - retrieveEnclaveData(cid: string): Promise - - verifyEnclaveDataIntegrity( - cid: string, - expectedData: Uint8Array - ): Promise - - batchStoreEnclaves( - enclaves: Array<{data: EnclaveDataWithCID, payload: Uint8Array}> - ): Promise -} -``` - -#### VaultClientWithIPFS - -Enhanced vault client with integrated IPFS support. - -```typescript -interface VaultClientWithIPFS extends VaultClient { - initializeWithIPFS( - wasmPath?: string, - accountAddress?: string, - ipfsConfig?: any - ): Promise - - storeEnclaveToIPFS( - data: EnclaveDataWithCID, - payload: Uint8Array - ): Promise - - retrieveEnclaveFromIPFS(cid: string): Promise - - listPinnedEnclaves(): Promise - - syncWithIPFS(): Promise -} -``` - -#### IPFSCache - -High-performance caching layer with LRU eviction and TTL support. - -```typescript -interface IPFSCache { - get(cid: string): Promise - set(cid: string, data: Uint8Array, metadata?: any): Promise - has(cid: string): Promise - remove(cid: string): Promise - clear(): Promise - preload( - cids: string[], - fetchFn: (cid: string) => Promise - ): Promise - getStats(): CacheStats -} -``` - -### Configuration - -#### IPFSClientConfig - -```typescript -interface IPFSClientConfig { - gatewayUrl?: string // Primary IPFS gateway URL for content retrieval - apiUrl?: string // IPFS API URL for node operations (e.g., pinning) - gateways?: string[] // List of fallback IPFS gateway URLs - enablePersistence?: boolean // Enable persistent storage - libp2pConfig?: any // Custom libp2p configuration - environment?: 'local' | 'testnet' | 'mainnet' // Auto-selects appropriate endpoints - timeout?: number // Request timeout in milliseconds (default: 30000) - maxRetries?: number // Max retries for failed requests (default: 3) -} -``` - -#### Default Configuration - -```typescript -const DEFAULT_IPFS_CONFIG = { - gatewayUrl: 'https://gateway.pinata.cloud', - apiUrl: 'http://localhost:5001', // Changes based on environment - gateways: [ - 'https://gateway.pinata.cloud', - 'https://ipfs.io', - 'https://cloudflare-ipfs.com', - 'https://dweb.link' - ], - apiEndpoints: { - local: 'http://localhost:5001', - testnet: 'https://ipfs.testnet.sonr.io', - mainnet: 'https://ipfs.sonr.io' - } -} -``` - -#### Environment Variables - -The IPFS client automatically detects and uses these environment variables: - -- `IPFS_GATEWAY_URL` - Primary gateway URL -- `IPFS_API_URL` - API endpoint URL -- `SONR_ENV` - Environment ('local', 'testnet', 'mainnet') - -```bash -# Example .env file -IPFS_GATEWAY_URL=https://my-custom-gateway.com -IPFS_API_URL=https://my-ipfs-api.com:5001 -SONR_ENV=testnet -``` - -#### EnclaveStorageConfig - -```typescript -interface EnclaveStorageConfig { - encryptionRequired: boolean // Require encryption for all data - pinningEnabled: boolean // Auto-pin stored data - redundancy: number // Number of redundant copies - maxRetries: number // Max retry attempts - operationTimeout?: number // Operation timeout in ms -} -``` - -### Usage Examples - -#### Basic Configuration - -```typescript -import { createIPFSClient, DEFAULT_IPFS_CONFIG } from '@sonr.io/es/ipfs' - -// Use defaults -const client = await createIPFSClient() - -// Custom configuration -const customClient = await createIPFSClient({ - gatewayUrl: 'https://my.gateway.com', - apiUrl: 'https://my.api.com:5001', - environment: 'testnet', - timeout: 60000, - maxRetries: 5 -}) - -// Update configuration dynamically -client.updateConfig({ - gatewayUrl: 'https://new.gateway.com', - timeout: 30000 -}) - -// Get current configuration -const config = client.getConfig() -console.log('Using gateway:', config.gatewayUrl) -``` - -#### Using the API Methods - -```typescript -// Add content via HTTP API (requires apiUrl configuration) -const data = new Uint8Array([1, 2, 3, 4]) -const cid = await client.addViaAPI(data) -console.log('Added via API:', cid) - -// Pin content to prevent garbage collection -await client.pinViaAPI(cid) - -// Get IPFS node information -const nodeInfo = await client.getNodeInfoViaAPI() -console.log('Node ID:', nodeInfo.ID) -console.log('Agent:', nodeInfo.AgentVersion) -``` - -See the [examples directory](./examples/ipfs-enclave-usage.ts) for comprehensive usage examples including: - -- Basic IPFS operations -- MPC enclave storage -- Vault integration -- Caching strategies -- Error handling -- Performance optimization - -### Performance Best Practices - -1. **Use Caching Aggressively**: Enable the cache layer for frequently accessed data -2. **Batch Operations**: Use batch methods when storing/retrieving multiple items -3. **Preload Critical Data**: Use cache preloading for known CIDs -4. **Configure Gateways**: Provide multiple gateway URLs for redundancy -5. **Set Appropriate Timeouts**: Configure timeouts based on your network conditions -6. **Monitor Cache Stats**: Use cache statistics to optimize hit rates - -### Troubleshooting - -#### Common Issues - -**Connection Failed** -```typescript -// Provide fallback gateways -const client = await createIPFSClient({ - gateways: [ - 'http://localhost:5001', // Local node - 'https://gateway.pinata.cloud', // Public gateway - 'https://ipfs.io' // Fallback - ] -}); -``` - -**Slow Retrieval** -```typescript -// Enable caching for better performance -const cache = createIPFSCache({ - maxSize: 200, - ttl: 300000, // 5 minutes - enablePersistence: true -}); - -// Preload frequently used CIDs -await cache.preload(cids, fetchFunction); -``` - -**Network Timeouts** -```typescript -// Configure retry logic -const manager = new EnclaveIPFSManager(client, { - maxRetries: 5, - operationTimeout: 30000 // 30 seconds -}); -``` - -### Security Considerations - -1. **Always Encrypt Sensitive Data**: Use consensus-based encryption for enclave data -2. **Verify CID Integrity**: Always verify retrieved data matches expected CID -3. **Use HTTPS Gateways**: Prefer HTTPS gateways over HTTP -4. **Validate Enclave Structure**: Validate threshold and parties before storage -5. **Implement Access Control**: Use UCAN tokens for authorization - -### Testing - -Run unit tests: -```bash -pnpm test -``` - -Run integration tests (requires Docker): -```bash -docker-compose up -d ipfs -pnpm test:integration -``` - -### Dependencies - -- `helia`: Core IPFS implementation -- `@helia/unixfs`: UnixFS for file operations -- `@helia/verified-fetch`: Verified content fetching -- `@libp2p/webrtc`: WebRTC transport -- `@libp2p/websockets`: WebSocket transport -- `multiformats`: CID and multiformat support -- `@tanstack/query-core`: Query caching for DWN service - diff --git a/packages/es/biome.json b/packages/es/biome.json deleted file mode 100644 index b5cad6ee2..000000000 --- a/packages/es/biome.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "https://biomejs.dev/schemas/2.1.4/schema.json", - "extends": ["../../biome.json"], - "linter": { - "rules": { - "suspicious": { - "noExplicitAny": "off" - }, - "correctness": { - "noUnusedVariables": "warn" - }, - "complexity": { - "noStaticOnlyClass": "off" - }, - "style": { - "useTemplate": "warn", - "noUnusedTemplateLiteral": "warn" - } - } - } -} diff --git a/packages/es/buf.gen.yaml b/packages/es/buf.gen.yaml deleted file mode 100644 index 1b6366be5..000000000 --- a/packages/es/buf.gen.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# see: https://docs.buf.build/configuration/v1/buf-gen-yaml -version: v1 -plugins: - - plugin: es - opt: target=ts - out: . - - plugin: cosmes - path: ./scripts/protoc-gen-cosmes.mjs - opt: target=ts - out: . diff --git a/packages/es/buf.lock b/packages/es/buf.lock deleted file mode 100644 index c91b5810c..000000000 --- a/packages/es/buf.lock +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by buf. DO NOT EDIT. -version: v1 diff --git a/packages/es/examples/autoloader.html b/packages/es/examples/autoloader.html deleted file mode 100644 index 2c4e6b58b..000000000 --- a/packages/es/examples/autoloader.html +++ /dev/null @@ -1,263 +0,0 @@ - - - - - - Sonr ES Autoloader Example - - - -

Sonr ES Autoloader Example

- -
-

Library Status

-
Loading Sonr ES library...
- -
- -
-

WebAuthn Demo

-
Checking WebAuthn availability...
- - -
- -
-

Available Modules

-
-
- -
-

Console Output

-

-    
- - - - - - - - - - - \ No newline at end of file diff --git a/packages/es/examples/ipfs-enclave-usage.ts b/packages/es/examples/ipfs-enclave-usage.ts deleted file mode 100644 index 5e87b0b17..000000000 --- a/packages/es/examples/ipfs-enclave-usage.ts +++ /dev/null @@ -1,489 +0,0 @@ -/** - * Usage examples for IPFS/Helia integration with MPC enclave data - * - * This file demonstrates how to use the IPFS integration for - * storing and retrieving MPC enclave data in the Sonr ecosystem. - */ - -import { - // IPFS client - IPFSClient, - createIPFSClient, - type IPFSClientConfig, - // Enclave manager - EnclaveIPFSManager, - createEnclaveIPFSManager, - type EnclaveDataWithCID, - // Enhanced vault client - VaultClientWithIPFS, - createVaultClientWithIPFS, - // Caching - IPFSCache, - createIPFSCache, - // DWN query service - DWNIPFSQueryService, - createDWNIPFSQueryService, -} from '@sonr.io/es'; - -// ============================================ -// Example 1: Basic IPFS Client Usage -// ============================================ -async function basicIPFSExample() { - console.log('🌐 Basic IPFS Client Example'); - - // Create and initialize IPFS client - const ipfsClient = await createIPFSClient({ - gateways: ['https://gateway.pinata.cloud', 'https://ipfs.io'], - enablePersistence: true, - }); - - try { - // Store data - const data = new TextEncoder().encode('Hello from Sonr!'); - const { cid, size, timestamp } = await ipfsClient.addEnclaveData(data); - console.log(`✅ Stored data with CID: ${cid} (${size} bytes)`); - - // Retrieve data - const retrieved = await ipfsClient.getEnclaveData(cid); - const text = new TextDecoder().decode(retrieved); - console.log(`✅ Retrieved: "${text}"`); - - // Get node status - const status = await ipfsClient.getNodeStatus(); - console.log(`📊 Node Status:`, status); - - // Pin important data - await ipfsClient.pin(cid); - console.log(`📌 Pinned CID: ${cid}`); - - // List all pins - const pins = await ipfsClient.listPins(); - console.log(`📋 Total pinned items: ${pins.length}`); - } finally { - await ipfsClient.cleanup(); - } -} - -// ============================================ -// Example 2: MPC Enclave Storage -// ============================================ -async function mpcEnclaveExample() { - console.log('🔐 MPC Enclave Storage Example'); - - const ipfsClient = await createIPFSClient(); - const enclaveManager = await createEnclaveIPFSManager(ipfsClient, { - encryptionRequired: true, - pinningEnabled: true, - maxRetries: 3, - }); - - try { - // Create MPC enclave data - const enclaveData: EnclaveDataWithCID = { - publicKey: 'ed25519:8FYH...publickey...ZKpQ', - privateKeyShares: [ - 'share1_encrypted_base64...', - 'share2_encrypted_base64...', - 'share3_encrypted_base64...', - ], - threshold: 2, // Need 2 out of 3 shares to reconstruct - parties: 3, - encryptionMetadata: { - algorithm: 'AES-256-GCM', - keyVersion: 1, - consensusHeight: 12345, - nonce: crypto.randomUUID(), - }, - }; - - // Encrypt the payload (in production, use consensus keys) - const payload = JSON.stringify({ - ...enclaveData, - timestamp: Date.now(), - chainId: 'sonr-mainnet-1', - }); - const encryptedPayload = new TextEncoder().encode(payload); - - // Store enclave data - const result = await enclaveManager.storeEnclaveData( - enclaveData, - encryptedPayload - ); - console.log(`✅ Stored enclave with CID: ${result.cid}`); - console.log(` - Size: ${result.size} bytes`); - console.log(` - Pinned: ${result.isPinned}`); - - // Retrieve and verify - const retrieved = await enclaveManager.retrieveEnclaveData(result.cid); - const isValid = await enclaveManager.verifyEnclaveDataIntegrity( - result.cid, - encryptedPayload - ); - console.log(`✅ Retrieved enclave data (integrity: ${isValid})`); - - // Check status - const status = await enclaveManager.getEnclaveStatus(result.cid); - console.log(`📊 Enclave Status:`, status); - } finally { - await ipfsClient.cleanup(); - } -} - -// ============================================ -// Example 3: Vault Client with IPFS -// ============================================ -async function vaultWithIPFSExample() { - console.log('🔒 Vault Client with IPFS Example'); - - const vaultClient = createVaultClientWithIPFS({ - chainId: 'sonr-testnet-1', - enableIPFSPersistence: true, - ipfsGateways: ['https://gateway.pinata.cloud'], - enclave: { - publicKey: 'test-public-key', - privateKeyShares: ['share1', 'share2', 'share3'], - threshold: 2, - parties: 3, - }, - }); - - try { - // Initialize vault with IPFS - await vaultClient.initializeWithIPFS( - '/path/to/vault.wasm', - 'sonr1abc...xyz' - ); - - // Store vault enclave - const cid = await vaultClient.storeVaultEnclave([ - 'encrypted_share1', - 'encrypted_share2', - 'encrypted_share3', - ]); - console.log(`✅ Stored vault enclave: ${cid}`); - - // Retrieve vault enclave - const enclave = await vaultClient.retrieveVaultEnclave(cid); - console.log(`✅ Retrieved enclave for ${enclave.parties} parties`); - - // List pinned enclaves - const pinnedEnclaves = await vaultClient.listPinnedEnclaves(); - console.log(`📌 Pinned enclaves: ${pinnedEnclaves.length}`); - - // Sync with IPFS network - await vaultClient.syncWithIPFS(); - console.log('✅ Synced with IPFS network'); - - // Get IPFS status - const ipfsStatus = await vaultClient.getIPFSStatus(); - console.log(`📊 IPFS Status:`, ipfsStatus); - } catch (error) { - // Handle WASM errors gracefully - if (error.message.includes('WASM')) { - console.log('⚠️ WASM not available, using IPFS features only'); - } else { - throw error; - } - } finally { - await vaultClient.cleanup(); - } -} - -// ============================================ -// Example 4: Caching Layer -// ============================================ -async function cachingExample() { - console.log('⚡ IPFS Caching Example'); - - const ipfsClient = await createIPFSClient(); - const cache = createIPFSCache({ - maxSize: 50, - ttl: 60000, // 1 minute TTL - enablePersistence: true, - }); - - try { - // Store some data in IPFS - const data1 = new TextEncoder().encode('Data item 1'); - const data2 = new TextEncoder().encode('Data item 2'); - const data3 = new TextEncoder().encode('Data item 3'); - - const { cid: cid1 } = await ipfsClient.addEnclaveData(data1); - const { cid: cid2 } = await ipfsClient.addEnclaveData(data2); - const { cid: cid3 } = await ipfsClient.addEnclaveData(data3); - - // Preload into cache - console.log('📥 Preloading data into cache...'); - await cache.preload( - [cid1, cid2, cid3], - async (cid) => await ipfsClient.getEnclaveData(cid) - ); - - // Measure cache performance - console.time('Cache retrieval'); - const cached1 = await cache.get(cid1); - const cached2 = await cache.get(cid2); - const cached3 = await cache.get(cid3); - console.timeEnd('Cache retrieval'); - - // Get cache statistics - const stats = cache.getStats(); - console.log('📊 Cache Statistics:'); - console.log(` - Size: ${stats.size} items`); - console.log(` - Total bytes: ${stats.totalBytes}`); - console.log(` - Hit rate: ${stats.hitRate.toFixed(2)}%`); - console.log(` - Avg access time: ${stats.avgAccessTime.toFixed(2)}ms`); - - // Clean up expired entries - const removed = await cache.cleanup(); - console.log(`🧹 Cleaned up ${removed} expired entries`); - } finally { - await cache.destroy(); - await ipfsClient.cleanup(); - } -} - -// ============================================ -// Example 5: DWN IPFS Query Service -// ============================================ -async function dwnQueryServiceExample() { - console.log('🔍 DWN IPFS Query Service Example'); - - const queryService = createDWNIPFSQueryService({ - rpcEndpoint: 'http://localhost:1317', - defaultStaleTime: 30000, - }); - - try { - // Query IPFS status from backend - const ipfsStatus = await queryService.queryIPFSStatus(); - console.log('📊 Backend IPFS Status:'); - console.log(` - Enabled: ${ipfsStatus.enabled}`); - console.log(` - Peer ID: ${ipfsStatus.peerId}`); - console.log(` - Connected peers: ${ipfsStatus.connectedPeers}`); - - // Query specific CID content - const cidResponse = await queryService.queryCIDContent( - 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG', - false // Don't decrypt - ); - if (cidResponse.error) { - console.log(`⚠️ CID not found: ${cidResponse.error}`); - } else { - console.log(`✅ Found CID content (${cidResponse.size} bytes)`); - } - - // Query enclave data for a vault - const enclaveResponse = await queryService.queryEnclaveData( - 'did:sonr:vault123', - false // Don't include private shares - ); - if (enclaveResponse.enclaveCid) { - console.log(`✅ Found enclave for vault: ${enclaveResponse.enclaveCid}`); - } - - // Store new enclave data via backend - const newEnclaveData = new TextEncoder().encode('New enclave data'); - const storeResult = await queryService.storeEnclaveData( - 'did:sonr:newvault', - newEnclaveData - ); - console.log(`✅ Stored via backend: ${storeResult.cid}`); - } finally { - await queryService.cleanup(); - } -} - -// ============================================ -// Example 6: Error Handling and Recovery -// ============================================ -async function errorHandlingExample() { - console.log('🛡️ Error Handling Example'); - - const ipfsClient = await createIPFSClient({ - gateways: [ - 'https://gateway.pinata.cloud', - 'https://ipfs.io', - 'http://localhost:8080', // Local fallback - ], - }); - - const enclaveManager = new EnclaveIPFSManager(ipfsClient, { - encryptionRequired: true, - pinningEnabled: true, - maxRetries: 3, - operationTimeout: 10000, - }); - - try { - // Handle invalid CID - try { - await ipfsClient.getEnclaveData('invalid-cid-format'); - } catch (error) { - console.log('✅ Caught invalid CID error:', error.message); - } - - // Handle missing encryption metadata - try { - const invalidEnclave: EnclaveDataWithCID = { - publicKey: 'test', - privateKeyShares: ['share1'], - threshold: 1, - parties: 1, - // Missing encryptionMetadata when encryptionRequired is true - }; - await enclaveManager.storeEnclaveData( - invalidEnclave, - new Uint8Array() - ); - } catch (error) { - console.log('✅ Caught missing encryption metadata:', error.message); - } - - // Handle network timeout with retry - console.log('🔄 Testing retry logic...'); - const enclaveData: EnclaveDataWithCID = { - publicKey: 'retry-test', - privateKeyShares: ['share1'], - threshold: 1, - parties: 1, - encryptionMetadata: { - algorithm: 'AES-256-GCM', - keyVersion: 1, - consensusHeight: 1, - nonce: 'test', - }, - }; - - const result = await enclaveManager.storeEnclaveData( - enclaveData, - new Uint8Array([1, 2, 3]) - ); - console.log('✅ Succeeded with retry logic'); - } finally { - await ipfsClient.cleanup(); - } -} - -// ============================================ -// Example 7: Performance Best Practices -// ============================================ -async function performanceExample() { - console.log('🚀 Performance Best Practices Example'); - - // 1. Use connection pooling - const ipfsClient = await createIPFSClient({ - gateways: ['https://gateway.pinata.cloud'], - libp2pConfig: { - connectionManager: { - maxConnections: 100, - minConnections: 10, - }, - }, - }); - - // 2. Use caching aggressively - const cache = createIPFSCache({ - maxSize: 200, - ttl: 300000, // 5 minutes - enablePersistence: true, - }); - - // 3. Batch operations - const enclaveManager = new EnclaveIPFSManager(ipfsClient, { - encryptionRequired: false, - pinningEnabled: true, - redundancy: 3, - maxRetries: 2, - }); - - try { - // Batch store multiple items - console.log('📦 Batch storing enclaves...'); - const enclaves = Array.from({ length: 10 }, (_, i) => ({ - data: { - publicKey: `key-${i}`, - privateKeyShares: [`share-${i}`], - threshold: 1, - parties: 1, - } as EnclaveDataWithCID, - payload: new Uint8Array([i, i, i]), - })); - - console.time('Batch store'); - const results = await enclaveManager.batchStoreEnclaves(enclaves); - console.timeEnd('Batch store'); - console.log(`✅ Stored ${results.length} enclaves in batch`); - - // Preload frequently accessed data - const cids = results.map((r) => r.cid); - console.time('Preload cache'); - await cache.preload(cids.slice(0, 5), async (cid) => - enclaveManager.retrieveEnclaveData(cid) - ); - console.timeEnd('Preload cache'); - - // Use cache for fast retrieval - console.time('Cached retrieval'); - for (const cid of cids.slice(0, 5)) { - await cache.get(cid); - } - console.timeEnd('Cached retrieval'); - - const stats = cache.getStats(); - console.log(`📊 Cache hit rate: ${stats.hitRate.toFixed(2)}%`); - } finally { - await cache.destroy(); - await ipfsClient.cleanup(); - } -} - -// ============================================ -// Main: Run all examples -// ============================================ -async function main() { - console.log('🌟 Sonr IPFS/Helia Integration Examples\n'); - - try { - await basicIPFSExample(); - console.log('\n---\n'); - - await mpcEnclaveExample(); - console.log('\n---\n'); - - await vaultWithIPFSExample(); - console.log('\n---\n'); - - await cachingExample(); - console.log('\n---\n'); - - await dwnQueryServiceExample(); - console.log('\n---\n'); - - await errorHandlingExample(); - console.log('\n---\n'); - - await performanceExample(); - - console.log('\n✅ All examples completed successfully!'); - } catch (error) { - console.error('❌ Example failed:', error); - process.exit(1); - } -} - -// Run if executed directly -if (require.main === module) { - main(); -} - -// Export examples for use in other modules -export { - basicIPFSExample, - mpcEnclaveExample, - vaultWithIPFSExample, - cachingExample, - dwnQueryServiceExample, - errorHandlingExample, - performanceExample, -}; \ No newline at end of file diff --git a/packages/es/examples/motor-browser-test.html b/packages/es/examples/motor-browser-test.html deleted file mode 100644 index b84574962..000000000 --- a/packages/es/examples/motor-browser-test.html +++ /dev/null @@ -1,442 +0,0 @@ - - - - - - Motor WASM Service Worker Test - - - -
-

🚀 Motor WASM Service Worker Test

- -
-

Service Worker Status

-
Checking service worker support...
- - -
- -
-

Plugin Initialization

-
Plugin not initialized
- -
- -
-

API Tests

-
- -

Identity Operations

- - -

UCAN Token Operations

- - - -

Cryptographic Operations

- - -

DWN Operations

- -
- -
-

Console Logs

-
- -
-
- - - - \ No newline at end of file diff --git a/packages/es/examples/motor-usage.ts b/packages/es/examples/motor-usage.ts deleted file mode 100644 index ff17c7e79..000000000 --- a/packages/es/examples/motor-usage.ts +++ /dev/null @@ -1,310 +0,0 @@ -/** - * Example usage of the Motor WASM service worker integration. - * This demonstrates how to use the Motor plugin for both DWN and Wallet operations. - */ - -import { - createMotorPlugin, - createMotorPluginForNode, - createMotorPluginForBrowser, - isMotorSupported, - getMotorEnvironment, - type MotorPlugin, - type NewOriginTokenRequest, - type CreateRecordRequest, -} from '@sonr.io/es/client/motor'; - -// ╭─────────────────────────────────────────────────────────╮ -// │ Environment Detection │ -// ╰─────────────────────────────────────────────────────────╯ - -async function detectEnvironment(): Promise { - console.log('🔍 Detecting environment capabilities...'); - - const env = getMotorEnvironment(); - console.log('Environment info:', { - browser: env.is_browser, - node: env.is_node, - serviceWorker: env.supports_service_worker, - wasm: env.supports_wasm, - }); - - const supported = isMotorSupported(); - console.log('Motor supported:', supported); -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Auto Plugin Creation │ -// ╰─────────────────────────────────────────────────────────╯ - -async function createPlugin(): Promise { - console.log('🚀 Creating Motor plugin...'); - - // Auto-detects environment and creates appropriate plugin - const plugin = await createMotorPlugin({ - debug: true, - timeout: 30000, - max_retries: 3, - }); - - console.log('✅ Plugin created successfully'); - return plugin; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Environment-Specific Creation │ -// ╰─────────────────────────────────────────────────────────╯ - -async function createBrowserPlugin(): Promise { - console.log('🌐 Creating browser-specific Motor plugin...'); - - const plugin = await createMotorPluginForBrowser('/motor-worker', { - auto_register_worker: true, - prefer_service_worker: true, - debug: true, - }); - - console.log('✅ Browser plugin created with service worker support'); - return plugin; -} - -async function createNodePlugin(): Promise { - console.log('🖥️ Creating Node.js-specific Motor plugin...'); - - const plugin = await createMotorPluginForNode('http://localhost:8080', { - timeout: 15000, - max_retries: 2, - debug: true, - }); - - console.log('✅ Node.js plugin created with HTTP fallback'); - return plugin; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Wallet Operations │ -// ╰─────────────────────────────────────────────────────────╯ - -async function demonstrateWalletOperations(plugin: MotorPlugin): Promise { - console.log('💼 Demonstrating wallet operations...'); - - try { - // Get issuer DID - console.log('📋 Getting issuer DID...'); - const issuerResponse = await plugin.getIssuerDID(); - console.log('Issuer DID:', issuerResponse.issuer_did); - console.log('Address:', issuerResponse.address); - - // Create origin token - console.log('🎫 Creating UCAN origin token...'); - const tokenRequest: NewOriginTokenRequest = { - audience_did: 'did:sonr:example-audience', - attenuations: [ - { - can: ['sign', 'encrypt'], - with: 'vault://example-vault', - }, - ], - facts: ['motor-wasm-demo'], - expires_at: Date.now() + (24 * 60 * 60 * 1000), // 24 hours - }; - - const tokenResponse = await plugin.newOriginToken(tokenRequest); - console.log('✅ Origin token created:', tokenResponse.token.substring(0, 50) + '...'); - - // Create attenuated token - console.log('🔗 Creating attenuated token...'); - const attenuatedResponse = await plugin.newAttenuatedToken({ - parent_token: tokenResponse.token, - audience_did: 'did:sonr:delegated-audience', - attenuations: [ - { - can: ['sign'], - with: 'vault://limited-access', - }, - ], - expires_at: Date.now() + (2 * 60 * 60 * 1000), // 2 hours - }); - console.log('✅ Attenuated token created:', attenuatedResponse.token.substring(0, 50) + '...'); - - // Sign data - console.log('✍️ Signing data...'); - const dataToSign = new TextEncoder().encode('Hello, Motor WASM!'); - const signResponse = await plugin.signData({ data: dataToSign }); - console.log('✅ Data signed, signature length:', signResponse.signature.length); - - // Verify signature - console.log('🔍 Verifying signature...'); - const verifyResponse = await plugin.verifyData({ - data: dataToSign, - signature: signResponse.signature, - }); - console.log('✅ Signature valid:', verifyResponse.valid); - - } catch (error) { - console.error('❌ Wallet operation failed:', error); - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ DWN Operations │ -// ╰─────────────────────────────────────────────────────────╯ - -async function demonstrateDWNOperations(plugin: MotorPlugin): Promise { - console.log('🌐 Demonstrating DWN operations...'); - - try { - // Create a record - console.log('📝 Creating DWN record...'); - const recordData = new TextEncoder().encode(JSON.stringify({ - message: 'Hello from Motor DWN!', - timestamp: new Date().toISOString(), - version: '1.0.0', - })); - - const createRequest: CreateRecordRequest = { - target: 'did:sonr:alice', - data: recordData, - schema: 'https://schema.org/Message', - protocol: 'https://protocol.example.com/messaging', - published: true, - encrypt: true, // Encrypt the data - }; - - const createResponse = await plugin.createRecord?.(createRequest); - if (!createResponse) { - console.log('ℹ️ DWN operations not available in this plugin instance'); - return; - } - - console.log('✅ Record created:', createResponse.record_id); - console.log('📅 Created at:', new Date(createResponse.created_at * 1000).toISOString()); - console.log('🔒 Encrypted:', createResponse.is_encrypted); - - // Read the record - console.log('📖 Reading DWN record...'); - const readResponse = await plugin.readRecord?.(createResponse.record_id, createRequest.target); - if (readResponse) { - const decodedData = new TextDecoder().decode(readResponse.data); - console.log('✅ Record data:', JSON.parse(decodedData)); - console.log('🔓 Decrypted successfully:', !readResponse.is_encrypted || readResponse.data.length > 0); - } - - // Update the record - console.log('✏️ Updating DWN record...'); - const updatedData = new TextEncoder().encode(JSON.stringify({ - message: 'Updated message from Motor DWN!', - timestamp: new Date().toISOString(), - version: '1.1.0', - updated: true, - })); - - const updateResponse = await plugin.updateRecord?.({ - record_id: createResponse.record_id, - target: createRequest.target, - data: updatedData, - published: true, - }); - - if (updateResponse) { - console.log('✅ Record updated at:', new Date(updateResponse.updated_at * 1000).toISOString()); - } - - // Delete the record - console.log('🗑️ Deleting DWN record...'); - const deleteResponse = await plugin.deleteRecord?.(createResponse.record_id, createRequest.target); - if (deleteResponse) { - console.log('✅ Record deleted:', deleteResponse.status); - } - - } catch (error) { - console.error('❌ DWN operation failed:', error); - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Health Monitoring │ -// ╰─────────────────────────────────────────────────────────╯ - -async function checkServiceHealth(plugin: MotorPlugin): Promise { - console.log('🏥 Checking service health...'); - - try { - // Test connection - const connected = await plugin.testConnection(); - console.log('🔗 Connected:', connected); - - if (connected) { - // Get health status - const health = await plugin.getHealth(); - console.log('💓 Health status:', health.status); - console.log('🏷️ Service:', health.service); - console.log('📦 Version:', health.version); - - // Get service info - const info = await plugin.getServiceInfo(); - console.log('📋 Service info:', { - description: info.description, - endpoints: Object.keys(info.endpoints), - }); - } - } catch (error) { - console.error('❌ Health check failed:', error); - } -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Main Demo │ -// ╰─────────────────────────────────────────────────────────╯ - -async function runDemo(): Promise { - console.log('🎬 Starting Motor WASM Service Worker Demo'); - console.log('=========================================='); - - try { - // Detect environment - await detectEnvironment(); - console.log(); - - // Create plugin (auto-detection) - const plugin = await createPlugin(); - console.log(); - - // Check service health - await checkServiceHealth(plugin); - console.log(); - - // Demonstrate wallet operations - await demonstrateWalletOperations(plugin); - console.log(); - - // Demonstrate DWN operations - await demonstrateDWNOperations(plugin); - console.log(); - - // Cleanup - console.log('🧹 Cleaning up...'); - await plugin.cleanup?.(); - console.log('✅ Demo completed successfully!'); - - } catch (error) { - console.error('❌ Demo failed:', error); - } -} - -// Export for use in other modules -export { - detectEnvironment, - createPlugin, - createBrowserPlugin, - createNodePlugin, - demonstrateWalletOperations, - demonstrateDWNOperations, - checkServiceHealth, - runDemo, -}; - -// Run demo if this file is executed directly -if (typeof require !== 'undefined' && require.main === module) { - runDemo().catch(console.error); -} \ No newline at end of file diff --git a/packages/es/examples/plugins-usage.ts b/packages/es/examples/plugins-usage.ts deleted file mode 100644 index be1e43f4a..000000000 --- a/packages/es/examples/plugins-usage.ts +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Example demonstrating the usage of plugins from @sonr.io/es - */ - -// Import plugins module -import { plugins } from '@sonr.io/es'; - -// Or import specific plugins -import { createVaultClient, createMotorPlugin } from '@sonr.io/es/plugins'; - -// Or import plugins directly -import { VaultClient } from '@sonr.io/es/plugins/vault'; -import { MotorPluginImpl } from '@sonr.io/es/plugins/motor'; - -async function demonstrateVaultPlugin() { - console.log('=== Vault Plugin Demo ==='); - - // Create a vault client - const vault = createVaultClient({ - chainId: 'sonr-testnet-1', - // enclave configuration would go here - }); - - // Initialize the vault - await vault.initialize(); - - // Get issuer DID - const issuerInfo = await vault.getIssuerDID(); - console.log('Issuer DID:', issuerInfo.issuer_did); - console.log('Address:', issuerInfo.address); - - // Create a UCAN token - const tokenResponse = await vault.newOriginToken({ - audience_did: 'did:sonr:example123', - attenuations: [ - { can: ['sign', 'verify'], with: 'vault://keys/*' } - ], - expires_at: Date.now() + 3600000, // 1 hour from now - }); - console.log('UCAN Token created:', tokenResponse.token.substring(0, 50) + '...'); - - // Sign some data - const dataToSign = new TextEncoder().encode('Hello, Sonr!'); - const signature = await vault.signData({ data: dataToSign }); - console.log('Signature created'); - - // Verify the signature - const verification = await vault.verifyData({ - data: dataToSign, - signature: signature.signature, - }); - console.log('Signature valid:', verification.valid); - - // Clean up - await vault.cleanup(); -} - -async function demonstrateMotorPlugin() { - console.log('\n=== Motor Plugin Demo ==='); - - // Create a motor plugin (auto-detects environment) - const motor = await createMotorPlugin({ - debug: true, - timeout: 30000, - }); - - // Check if motor is ready - const isReady = await motor.isReady(); - console.log('Motor ready:', isReady); - - // Get service info - const serviceInfo = await motor.getServiceInfo(); - console.log('Service version:', serviceInfo.version); - console.log('Service status:', serviceInfo.status); - - // Create a DWN record - const record = await motor.createRecord({ - data: { message: 'Hello from Motor!' }, - published: false, - schema: 'https://schema.org/Message', - dataFormat: 'application/json', - }); - console.log('Record created:', record.record_id); - - // Read the record back - const readResult = await motor.readRecord(record.record_id); - console.log('Record data:', readResult.data); - - // Create a UCAN token using motor - const tokenResponse = await motor.newOriginToken({ - audience_did: 'did:sonr:motor123', - attenuations: [ - { can: ['create', 'read', 'update', 'delete'], with: 'dwn://records/*' } - ], - }); - console.log('Motor UCAN Token:', tokenResponse.token.substring(0, 50) + '...'); - - // Clean up - await motor.cleanup(); -} - -async function demonstratePluginNamespaces() { - console.log('\n=== Using Plugin Namespaces ==='); - - // Access plugins through namespace - const vaultClient = plugins.vault.createVaultClient(); - const motorPlugin = await plugins.motor.createMotorPlugin(); - - console.log('Vault client created via namespace'); - console.log('Motor plugin created via namespace'); - - // Use the plugins... - // ... - - // Clean up - await vaultClient.cleanup(); - await motorPlugin.cleanup(); -} - -// Main execution -async function main() { - try { - await demonstrateVaultPlugin(); - await demonstrateMotorPlugin(); - await demonstratePluginNamespaces(); - - console.log('\n✅ All plugin demonstrations completed successfully!'); - } catch (error) { - console.error('❌ Error during plugin demonstration:', error); - } -} - -// Run if executed directly -if (import.meta.url === `file://${process.argv[1]}`) { - main(); -} \ No newline at end of file diff --git a/packages/es/examples/webauthn-enhanced.html b/packages/es/examples/webauthn-enhanced.html deleted file mode 100644 index 22cdd7aa6..000000000 --- a/packages/es/examples/webauthn-enhanced.html +++ /dev/null @@ -1,382 +0,0 @@ - - - - - - Enhanced WebAuthn Example - Sonr ES - - - -
-

🔐 Enhanced WebAuthn Demo

-

Sonr ES Package - Advanced Passkey Features

- -
-
WebAuthn: Checking...
-
Platform: Checking...
-
Autofill: Checking...
-
- -
- - -
- -
- - -
- -
- - -
- -
-

Status

-
Ready to start...
-
- -
-
Console initialized. Callbacks will appear here...
-
-
- - - - - \ No newline at end of file diff --git a/packages/es/package.json b/packages/es/package.json deleted file mode 100644 index 52056d14d..000000000 --- a/packages/es/package.json +++ /dev/null @@ -1,151 +0,0 @@ -{ - "name": "@sonr.io/es", - "version": "0.0.12", - "private": false, - "sideEffects": false, - "type": "module", - "publishConfig": { - "access": "public" - }, - "files": [ - "dist", - "README.md" - ], - "main": "./dist/index.js", - "module": "./dist/index.js", - "jsdelivr": "./dist/index.js", - "unpkg": "./dist/index.js", - "browser": "./dist/index.js", - "exports": { - ".": { - "import": "./dist/index.js", - "default": "./dist/index.js" - }, - "./autoloader": { - "import": "./dist/autoloader.js", - "default": "./dist/autoloader.js" - }, - "./client": { - "import": "./dist/client/index.js", - "default": "./dist/client/index.js" - }, - "./client/auth": { - "import": "./dist/client/auth/index.js", - "default": "./dist/client/auth/index.js" - }, - "./plugins": { - "import": "./dist/plugins/index.js", - "default": "./dist/plugins/index.js" - }, - "./plugins/motor": { - "import": "./dist/plugins/motor/index.js", - "default": "./dist/plugins/motor/index.js" - }, - "./plugins/vault": { - "import": "./dist/plugins/vault/index.js", - "default": "./dist/plugins/vault/index.js" - }, - "./codec": { - "import": "./dist/codec/index.js", - "default": "./dist/codec/index.js" - }, - "./protobufs": { - "import": "./dist/protobufs/index.js", - "default": "./dist/protobufs/index.js" - }, - "./registry": { - "import": "./dist/registry/index.js", - "default": "./dist/registry/index.js" - }, - "./wallet": { - "import": "./dist/wallet/index.js", - "default": "./dist/wallet/index.js" - } - }, - "scripts": { - "clean": "rimraf dist", - "generate": "pnpm gen:protobufs && pnpm gen:registry", - "build": "pnpm clean && tsc && tsc-alias && pnpm copy:assets", - "copy:assets": "npm run copy:wasm && npm run copy:autoloader", - "copy:wasm": "npm run copy:vault-wasm && npm run copy:motor-wasm", - "copy:vault-wasm": "cp src/plugin/plugin.wasm dist/plugin/ 2>/dev/null || true", - "copy:motor-wasm": "cp src/worker/app.wasm dist/worker/ 2>/dev/null || true && cp src/worker/wasm_exec.js dist/worker/ 2>/dev/null || true", - "copy:autoloader": "cp src/autoloader.js dist/autoloader.js 2>/dev/null || true", - "dev": "concurrently \"tsc -w\" \"tsc-alias -w\"", - "gen:protobufs": "node scripts/gen-protobufs.mjs", - "gen:registry": "node scripts/gen-registry.mjs", - "lint": "biome lint .", - "format": "biome format . --write", - "check": "biome check .", - "typecheck": "tsc --noEmit", - "test": "vitest --run", - "test:suite": "pnpm check && pnpm typecheck && pnpm test", - "prepublishOnly": "pnpm build", - "release": "cz --no-raise 6,21 bump --yes --increment PATCH" - }, - "peerDependencies": { - "@bufbuild/protobuf": "1.2.0", - "@noble/hashes": "^1.3.2", - "@noble/secp256k1": "^2.0.0", - "@scure/base": "^1.1.3", - "@scure/bip32": "^1.3.2", - "@scure/bip39": "^1.2.1", - "@walletconnect/legacy-client": "^2.0.0", - "@walletconnect/sign-client": "2.8.6", - "lodash-es": "^4.17.21" - }, - "devDependencies": { - "@biomejs/biome": "^2.1.2", - "@bufbuild/buf": "1.18.0-1", - "@bufbuild/protobuf": "1.2.0", - "@bufbuild/protoc-gen-es": "1.2.0", - "@bufbuild/protoplugin": "1.2.0", - "@keplr-wallet/types": "^0.11.62", - "@metamask/providers": "^14.0.2", - "@noble/hashes": "^1.3.2", - "@noble/secp256k1": "^2.0.0", - "@scure/base": "^1.1.3", - "@scure/bip32": "^1.3.2", - "@scure/bip39": "^1.2.1", - "@simplewebauthn/types": "^12.0.0", - "@testing-library/jest-dom": "^6.8.0", - "@testing-library/react": "^16.3.0", - "@types/degit": "^2.8.3", - "@types/lodash-es": "^4.17.7", - "@vitest/ui": "^3.2.4", - "@walletconnect/legacy-client": "^2.0.0", - "@walletconnect/legacy-types": "^2.0.0", - "@walletconnect/sign-client": "2.8.6", - "@walletconnect/types": "2.8.6", - "autoprefixer": "^10.4.14", - "concurrently": "^8.0.1", - "degit": "^2.8.4", - "glob": "^10.2.3", - "jsdom": "^26.1.0", - "json-schema-to-typescript": "^13.1.1", - "lodash-es": "^4.17.21", - "postcss": "^8.4.23", - "rimraf": "^5.0.0", - "tsc-alias": "^1.8.6", - "tsx": "^3.12.7", - "typescript": "^5.0.4", - "vitest": "^3.2.4", - "fake-indexeddb": "^6.0.0" - }, - "dependencies": { - "@extism/extism": "2.0.0-rc13", - "@simplewebauthn/browser": "^9.0.1", - "dexie": "^4.0.1", - "helia": "^4.0.0", - "@helia/unixfs": "^3.0.0", - "@helia/verified-fetch": "^1.0.0", - "@helia/strings": "^3.0.0", - "@libp2p/webrtc": "^4.0.0", - "@libp2p/websockets": "^8.0.0", - "@chainsafe/libp2p-noise": "^15.0.0", - "@chainsafe/libp2p-yamux": "^6.0.0", - "multiformats": "^13.0.0", - "uint8arrays": "^5.0.0", - "@tanstack/query-core": "^5.0.0" - } -} diff --git a/packages/es/scripts/gen-protobufs.mjs b/packages/es/scripts/gen-protobufs.mjs deleted file mode 100644 index a4bed06e0..000000000 --- a/packages/es/scripts/gen-protobufs.mjs +++ /dev/null @@ -1,199 +0,0 @@ -// @ts-check - -/** - * This script generates the src/protobufs directory from the proto files in the - * repos specified in `REPOS`. It uses `buf` to generate TS files from the proto - * files, and then generates an `index.ts` file to re-export the generated code. - */ - -import { spawnSync } from "child_process"; -import degit from "degit"; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs"; -import { globSync } from "glob"; -import { capitalize } from "lodash-es"; -import { dirname, join } from "path"; -import { fileURLToPath } from "url"; - -/** - * @typedef Repo - * @type {object} - * @property {string} repo - Git repo and branch to clone - * @property {string[]} paths - Paths to proto files relative to the repo root - */ - -/** - * TODO: Add more repos here when necessary. - * @type {Repo[]} - */ -const REPOS = [ - // NOTE: cosmos-sdk is excluded because we use pre-generated cosmos proto files - // to avoid issues with degit and version mismatches - { - repo: "cosmos/ibc-go#main", - paths: ["proto"], - }, - // Use local proto files for sonr instead of fetching from external repo - // { - // repo: "onsonr/sonr#main", - // paths: ["proto"], - // }, - { - repo: "CosmWasm/wasmd#main", - paths: ["proto"], - }, - { - repo: "osmosis-labs/osmosis#main", - paths: ["proto"], - }, - { - repo: "evmos/ethermint#main", - paths: ["proto"], - }, - // Commented out babylon as it requires cosmos/staking which we don't generate - // { - // repo: "nomic-io/nomic#develop", - // paths: ["src/babylon/proto"], - // }, -]; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const PROTOBUFS_DIR = join(__dirname, "..", "src", "protobufs"); -const TMP_DIR = join(PROTOBUFS_DIR, ".tmp"); -/** Generates a unique dirname from `repo` to use in `TMP_DIR`. */ -const id = (/** @type {string} */ repo) => repo.replace(/[#/]/g, "-"); - -console.log("Initialising directories..."); -{ - // Don't delete the entire protobufs directory to preserve cosmos files - // Only delete directories that will be regenerated - rmSync(TMP_DIR, { recursive: true, force: true }); - mkdirSync(TMP_DIR); - - // Ensure protobufs directory exists - mkdirSync(PROTOBUFS_DIR, { recursive: true }); - - // Only clean up directories for repos we're regenerating - const dirsToClean = [ - "ibc", - "cosmwasm", - "osmosis", - "ethermint", - "babylon", // Add babylon to clean list - "did", - "dwn", - "svc", - ]; - for (const dir of dirsToClean) { - const dirPath = join(PROTOBUFS_DIR, dir); - rmSync(dirPath, { recursive: true, force: true }); - } -} - -console.log("Cloning required repos..."); -{ - await Promise.all( - REPOS.map(({ repo }) => degit(repo).clone(join(TMP_DIR, id(repo)))) - ); -} - -console.log("Generating TS files from proto files..."); -{ - for (const { repo, paths } of REPOS) { - for (const path of paths) { - spawnSync( - "pnpm", - [ - "buf", - "generate", - join(TMP_DIR, id(repo), path), - "--output", - join( - PROTOBUFS_DIR, - repo.startsWith("dymensionxyz") ? "dymension" : "" - ), - ], - { - cwd: process.cwd(), - stdio: "inherit", - } - ); - } - console.log(`✔️ [${repo}]`); - } - - // Generate from local Sonr proto files - console.log("Generating TS files from local Sonr proto files..."); - const localProtoPath = join(__dirname, "..", "..", "..", "proto"); - spawnSync( - "pnpm", - ["buf", "generate", localProtoPath, "--output", PROTOBUFS_DIR], - { - cwd: process.cwd(), - stdio: "inherit", - } - ); - console.log(`✔️ [local sonr proto files]`); -} - -console.log("Generating src/index.ts file and renaming exports..."); -{ - const LAST_SEGMENT_REGEX = /[^/]+$/; - const EXPORTED_NAME_REGEX = /^export \w+ (\w+) /gm; - let contents = - "/** This file is generated by gen-protobufs.mjs. Do not edit. */\n\n"; - /** - * Builds the `src/proto/index.ts` file to re-export generated code. - * A prefix is added to the exported names to avoid name collisions. - * The prefix is the names of the directories in `proto` leading up - * to the directory of the exported code, concatenated in PascalCase. - * For example, if the exported code is in `proto/foo/bar/goo.ts`, the - * prefix will be `FooBar`. - * @param {string} dir - */ - function generateIndexExports(dir) { - const files = globSync(join(dir, "*")); - if (files.length === 0) { - return; - } - const prefixName = dir - .replace(PROTOBUFS_DIR + "/", "") - .split("/") - .map((name) => - // convert all names to PascalCase - name.split(/[-_]/).map(capitalize).join("") - ) - .join(""); - for (const file of files) { - const fileName = file.match(LAST_SEGMENT_REGEX)?.[0]; - if (!fileName) { - console.error("Could not find name for", file); - continue; - } - if (!fileName.endsWith(".ts")) { - continue; - } - const code = readFileSync(file, "utf8"); - contents += `export {\n`; - for (const match of code.matchAll(EXPORTED_NAME_REGEX)) { - const exportedName = match[1]; - contents += ` ${exportedName} as ${prefixName + exportedName},\n`; - } - const exportedFile = file - .replace(PROTOBUFS_DIR + "/", "") - .replace(".ts", ".js"); - contents += `} from "./${exportedFile}";\n`; - } - for (const file of files) { - generateIndexExports(file); - } - } - generateIndexExports(PROTOBUFS_DIR); - writeFileSync(join(PROTOBUFS_DIR, "index.ts"), contents); -} - -console.log("Cleaning up..."); -{ - rmSync(TMP_DIR, { recursive: true, force: true }); -} - -console.log("Proto generation completed successfully!"); diff --git a/packages/es/scripts/gen-registry.mjs b/packages/es/scripts/gen-registry.mjs deleted file mode 100644 index 789a0afec..000000000 --- a/packages/es/scripts/gen-registry.mjs +++ /dev/null @@ -1,53 +0,0 @@ -import { writeFileSync } from "fs"; -import { compile } from "json-schema-to-typescript"; -import { dirname, join } from "path"; -import { fileURLToPath } from "url"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); - -async function genChainRegistryChainInfo() { - const tsName = "ChainRegistryChainInfo"; - const tsFile = tsName + ".ts"; - - console.log("Retrieving JSON schema..."); - const res = await fetch( - "https://raw.githubusercontent.com/cosmos/chain-registry/master/chain.schema.json" - ); - const schema = await res.json(); - schema.title = tsName; - - console.log("Compiling JSON schema to TypeScript..."); - const types = await compile(schema, tsName, { - // See: https://github.com/bcherny/json-schema-to-typescript?tab=readme-ov-file#options - strictIndexSignatures: true, - }); - - const target = join(__dirname, "..", "src", "registry", "types", tsFile); - writeFileSync(target, types); - console.log("Wrote types to", target); -} - -async function genChainRegistryAssetList() { - const tsName = "ChainRegistryAssetList"; - const tsFile = tsName + ".ts"; - - console.log("Retrieving JSON schema..."); - const res = await fetch( - "https://raw.githubusercontent.com/cosmos/chain-registry/master/assetlist.schema.json" - ); - const schema = await res.json(); - schema.title = tsName; - - console.log("Compiling JSON schema to TypeScript..."); - const types = await compile(schema, tsName, { - // See: https://github.com/bcherny/json-schema-to-typescript?tab=readme-ov-file#options - strictIndexSignatures: true, - }); - - const target = join(__dirname, "..", "src", "registry", "types", tsFile); - writeFileSync(target, types); - console.log("Wrote types to", target); -} - -await genChainRegistryChainInfo(); -await genChainRegistryAssetList(); diff --git a/packages/es/scripts/protoc-gen-cosmes.mjs b/packages/es/scripts/protoc-gen-cosmes.mjs deleted file mode 100755 index c75ef3d05..000000000 --- a/packages/es/scripts/protoc-gen-cosmes.mjs +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env node -// @ts-check - -/** - * This is a custom plugin for `buf` that generates TS files from the services - * defined in the proto files, and is referred to by the root `buf.gen.yaml`. - * Files generated using this plugin contains the `_@sonr.io/es` suffix. - * - * Do not convert this to a TS file as it runs 4x slower! - */ - -import { createEcmaScriptPlugin, runNodeJs } from "@bufbuild/protoplugin"; -import { - literalString, - localName, - makeJsDoc, -} from "@bufbuild/protoplugin/ecmascript"; - -export function generateTs(schema) { - for (const protoFile of schema.files) { - const file = schema.generateFile(protoFile.name + "_cosmes.ts"); - file.preamble(protoFile); - for (const service of protoFile.services) { - generateService(schema, file, service); - } - } -} - -function generateService(schema, f, service) { - f.print("const TYPE_NAME = ", literalString(service.typeName), ";"); - f.print(""); - for (const method of service.methods) { - f.print(makeJsDoc(method)); - f.print("export const ", localName(service), method.name, "Service = {"); - f.print(" typeName: TYPE_NAME,"); - f.print(" method: ", literalString(method.name), ","); - f.print(" Request: ", method.input, ","); - f.print(" Response: ", method.output, ","); - f.print("} as const;"); - f.print(""); - } -} - -runNodeJs( - createEcmaScriptPlugin({ - name: "protoc-gen-cosmes", - version: "v0.0.1", - generateTs, - }) -); diff --git a/packages/es/src/autoloader.js b/packages/es/src/autoloader.js deleted file mode 100644 index 8ec9e5c3a..000000000 --- a/packages/es/src/autoloader.js +++ /dev/null @@ -1,203 +0,0 @@ -/** - * @sonr.io/es - ESM Autoloader for Browser - * - * This file automatically loads and exposes all Sonr ES modules - * for browser usage via script tag or dynamic import. - * - * Usage: - * - * - * All exports are available on window.Sonr namespace - */ - -// Import all modules -import * as auth from './client/auth/index.js'; -import * as client from './client/index.js'; -import * as codec from './codec/index.js'; -import * as wallet from './wallet/index.js'; -import * as registry from './registry/index.js'; -import * as plugins from './plugins/index.js'; - -// Import specific auth utilities for convenience -import { - registerWithPasskey, - loginWithPasskey, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, - bufferToBase64url, - base64urlToBuffer, - checkConditionalMediationSupport, - createRegistrationButton, - createLoginButton, - DEFAULT_WEBAUTHN_CONFIG, - WEBAUTHN_PRESETS -} from './client/auth/webauthn.js'; - -// Create the main Sonr namespace -const Sonr = { - // Core modules - auth, - client, - codec, - wallet, - registry, - plugins, - - // Convenience shortcuts for common operations - webauthn: { - register: registerWithPasskey, - login: loginWithPasskey, - isSupported: isWebAuthnSupported, - isAvailable: isWebAuthnAvailable, - isConditionalAvailable: isConditionalMediationAvailable, - bufferToBase64url, - base64urlToBuffer, - checkSupport: checkConditionalMediationSupport, - createRegistrationButton, - createLoginButton, - - // Configuration - config: DEFAULT_WEBAUTHN_CONFIG, - presets: WEBAUTHN_PRESETS - }, - - // Plugin shortcuts - motor: plugins.motor, - vault: plugins.vault, - - // Factory functions for plugins - createMotorPlugin: plugins.createMotorPlugin, - createVaultClient: plugins.createVaultClient, - - // Version info - version: '0.0.8', - - // Initialization function for custom configuration - init: async (config = {}) => { - console.log('[Sonr] Initializing with config:', config); - - // Initialize Motor plugin if service worker is available - if ('serviceWorker' in navigator && config.enableMotor !== false) { - try { - const motorPlugin = await plugins.createMotorPluginForBrowser({ - wasmUrl: config.motorWasmUrl || '/motor.wasm', - ...config.motor - }); - Sonr.motor.instance = motorPlugin; - console.log('[Sonr] Motor plugin initialized'); - } catch (error) { - console.warn('[Sonr] Motor plugin initialization failed:', error); - } - } - - // Initialize Vault client if requested - if (config.enableVault) { - try { - const vaultClient = await plugins.createVaultClient(config.vault); - Sonr.vault.instance = vaultClient; - console.log('[Sonr] Vault client initialized'); - } catch (error) { - console.warn('[Sonr] Vault client initialization failed:', error); - } - } - - // Check WebAuthn availability - if (await isWebAuthnAvailable()) { - console.log('[Sonr] WebAuthn is available'); - Sonr.webauthn.available = true; - - // Check for conditional mediation (autofill) - if (await isConditionalMediationAvailable()) { - console.log('[Sonr] Conditional mediation (autofill) is available'); - Sonr.webauthn.conditionalAvailable = true; - } - } - - return Sonr; - }, - - // Helper to check if running in browser - isBrowser: typeof window !== 'undefined', - - // Helper to check if running in Node.js - isNode: typeof process !== 'undefined' && process.versions && process.versions.node, - - // Helper to get environment info - getEnvironment: () => { - if (typeof window !== 'undefined') { - return { - type: 'browser', - userAgent: navigator.userAgent, - platform: navigator.platform, - language: navigator.language, - online: navigator.onLine, - serviceWorker: 'serviceWorker' in navigator, - webauthn: 'credentials' in navigator - }; - } else if (typeof process !== 'undefined') { - return { - type: 'node', - version: process.version, - platform: process.platform, - arch: process.arch - }; - } - return { type: 'unknown' }; - } -}; - -// Auto-initialize with default settings if in browser -if (typeof window !== 'undefined') { - // Make Sonr globally available - window.Sonr = Sonr; - - // Auto-init on DOMContentLoaded if not already loaded - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', async () => { - if (!window.Sonr.initialized) { - await Sonr.init(); - window.Sonr.initialized = true; - console.log('[Sonr] Auto-initialized on DOMContentLoaded'); - - // Dispatch custom event - window.dispatchEvent(new CustomEvent('sonr:ready', { detail: Sonr })); - } - }); - } else { - // DOM already loaded, init immediately - (async () => { - if (!window.Sonr.initialized) { - await Sonr.init(); - window.Sonr.initialized = true; - console.log('[Sonr] Auto-initialized (DOM already loaded)'); - - // Dispatch custom event - window.dispatchEvent(new CustomEvent('sonr:ready', { detail: Sonr })); - } - })(); - } - - // Log availability - console.log('[Sonr] Library loaded. Access via window.Sonr or import modules directly.'); - console.log('[Sonr] Environment:', Sonr.getEnvironment()); -} - -// Export everything for ES module usage -export default Sonr; -export { - auth, - client, - codec, - wallet, - registry, - plugins, - // WebAuthn shortcuts - registerWithPasskey, - loginWithPasskey, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, - bufferToBase64url, - base64urlToBuffer -}; \ No newline at end of file diff --git a/packages/es/src/client/apis/broadcastTx.ts b/packages/es/src/client/apis/broadcastTx.ts deleted file mode 100644 index f38cbafb3..000000000 --- a/packages/es/src/client/apis/broadcastTx.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Prettify } from '../../typeutils/prettify'; -import { RpcClient } from '../clients/RpcClient'; -import type { ToSignedProtoParams, Tx } from '../models/Tx'; - -export type BroadcastTxParams = Prettify< - ToSignedProtoParams & { - tx: Tx; - } ->; - -/** - * Broadcasts a tx to the network and returns the tx hash if successful. - */ -export async function broadcastTx(endpoint: string, { tx, ...params }: BroadcastTxParams) { - return RpcClient.broadcastTx(endpoint, tx.toSignedProto(params)); -} diff --git a/packages/es/src/client/apis/getAccount.ts b/packages/es/src/client/apis/getAccount.ts deleted file mode 100644 index 722544b42..000000000 --- a/packages/es/src/client/apis/getAccount.ts +++ /dev/null @@ -1,26 +0,0 @@ -// TODO: This file needs CosmosAuthV1beta1QueryAccountService from protobufs -// which is not currently available. The function is stubbed out until -// the protobuf definitions are added. - -export type GetAccountParams = { - address: string; -}; - -export type GetAccountResponse = any; // TODO: Define proper type - -// TODO: Implement getAccount function when CosmosAuthV1beta1QueryAccountService protobuf is available -// This function should query account information from the auth module -// Parameters: endpoint (RPC/API endpoint), params (address to query) -// Returns: Account information including account number, sequence, and public key -export async function getAccount( - _endpoint: string, - _params: GetAccountParams -): Promise { - // TODO: Implement when QueryAccountService is available - // Steps needed: - // 1. Import CosmosAuthV1beta1QueryAccountService from protobufs - // 2. Create query request with address from params - // 3. Send query to endpoint - // 4. Parse and return account response - throw new Error('getAccount not implemented - missing QueryAccountService'); -} diff --git a/packages/es/src/client/apis/getCw20Balance.ts b/packages/es/src/client/apis/getCw20Balance.ts deleted file mode 100644 index 902d4ad52..000000000 --- a/packages/es/src/client/apis/getCw20Balance.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { queryContract } from './queryContract'; - -export type GetCw20BalanceParams = { - address: string; - token: string; -}; - -type Response = { - balance: string; -}; - -export async function getCw20Balance( - endpoint: string, - { address, token }: GetCw20BalanceParams -): Promise { - try { - const { balance } = await queryContract(endpoint, { - address: token, - query: { - balance: { - address: address, - }, - }, - }); - return BigInt(balance); - } catch (err) { - console.error(err); - return 0n; - } -} diff --git a/packages/es/src/client/apis/getNativeBalances.ts b/packages/es/src/client/apis/getNativeBalances.ts deleted file mode 100644 index adbf8e155..000000000 --- a/packages/es/src/client/apis/getNativeBalances.ts +++ /dev/null @@ -1,53 +0,0 @@ -// TODO: This file needs CosmosBankV1beta1QueryAllBalancesService from protobufs -// which is not currently available. The functions are stubbed out until -// the protobuf definitions are added. - -export type GetNativeBalancesParams = { - address: string; - pagination?: { - key?: Uint8Array; - offset?: bigint; - limit?: bigint; - countTotal?: boolean; - reverse?: boolean; - }; -}; - -/** - * Gets native balances for an address with pagination support. - * - * NOTE: This function currently has a placeholder implementation because - * CosmosBankV1beta1QueryAllBalancesService is not available in the current - * protobufs. It should be updated when bank module protobufs are added. - */ -// TODO: Implement getNativeBalances function when CosmosBankV1beta1QueryAllBalancesService protobuf is available -// This function should query all balances for a given address with pagination support -// Parameters: endpoint (RPC/API endpoint), params (address and pagination options) -// Returns: Array of coin balances with pagination metadata -export async function getNativeBalances(_endpoint: string, _params: GetNativeBalancesParams) { - // TODO: Implement when CosmosBankV1beta1QueryAllBalancesService is available - // Steps needed: - // 1. Import CosmosBankV1beta1QueryAllBalancesService from protobufs - // 2. Create query request with address and pagination from params - // 3. Send query to endpoint - // 4. Parse and return balances with pagination info - throw new Error( - 'Bank module not available - CosmosBankV1beta1QueryAllBalancesService needs to be added to protobufs' - ); -} - -// TODO: Implement getAllNativeBalances function when CosmosBankV1beta1QueryAllBalancesService protobuf is available -// This function should query all balances for a given address without pagination limits -// Parameters: endpoint (RPC/API endpoint), address (account address to query) -// Returns: Complete array of all coin balances for the address -export async function getAllNativeBalances(_endpoint: string, _address: string): Promise { - // TODO: Implement when CosmosBankV1beta1QueryAllBalancesService is available - // Steps needed: - // 1. Import CosmosBankV1beta1QueryAllBalancesService from protobufs - // 2. Create query request with address, iterate through all pages - // 3. Send multiple queries if needed to get all balances - // 4. Aggregate and return complete balance list - throw new Error( - 'Bank module not available - CosmosBankV1beta1QueryAllBalancesService needs to be added to protobufs' - ); -} diff --git a/packages/es/src/client/apis/getTx.ts b/packages/es/src/client/apis/getTx.ts deleted file mode 100644 index 3e605a0e2..000000000 --- a/packages/es/src/client/apis/getTx.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { - type CosmosTxV1beta1GetTxResponse as GetTxResponse, - CosmosTxV1beta1ServiceGetTxService as GetTxService, -} from '@sonr.io/es/protobufs'; - -import { RpcClient } from '../clients/RpcClient'; - -export type GetTxParams = { - hash: string; -}; - -/** - * Returns the tx matching the given hash. Throws if the tx is not found. - */ -export async function getTx(endpoint: string, params: GetTxParams) { - const res = await RpcClient.query(endpoint, GetTxService, params); - if (!res.tx || !res.txResponse) { - throw new Error('Tx not found'); - } - return res as Required; -} diff --git a/packages/es/src/client/apis/pollTx.ts b/packages/es/src/client/apis/pollTx.ts deleted file mode 100644 index f71191431..000000000 --- a/packages/es/src/client/apis/pollTx.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { wait } from '../utils/wait'; -import { getTx } from './getTx'; - -export type PollTxParams = { - hash: string; - intervalSeconds?: number; - maxAttempts?: number; -}; - -/** - * Polls for the tx matching the given `hash`, with a minimum interval of - * `intervalSeconds`. Throws if the tx is not found after the given number - * of `maxAttempts`. - */ -export async function pollTx( - endpoint: string, - { intervalSeconds = 2, maxAttempts = 64, ...getTxParams }: PollTxParams -) { - const intervalMillis = intervalSeconds * 1000; - for (let i = 0; i < maxAttempts; i++) { - try { - return await getTx(endpoint, getTxParams); - } catch (_err) { - await wait(intervalMillis); - } - } - throw new Error('Tx not found'); -} diff --git a/packages/es/src/client/apis/queryContract.ts b/packages/es/src/client/apis/queryContract.ts deleted file mode 100644 index a2f91d1be..000000000 --- a/packages/es/src/client/apis/queryContract.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { JsonValue } from '@bufbuild/protobuf'; -import { utf8 } from '@sonr.io/es/codec'; -import { CosmwasmWasmV1QuerySmartContractStateService as QuerySmartContractStateService } from '@sonr.io/es/protobufs'; - -import { RpcClient } from '../clients/RpcClient'; - -export type QueryContractParams = { - address: string; - query: JsonValue; -}; - -/** - * Queries the contract at `address` with the given `query` JSON message, - * and returns the parsed JSON response. - */ -export async function queryContract( - endpoint: string, - { address, query }: QueryContractParams -): Promise { - const { data } = await RpcClient.query(endpoint, QuerySmartContractStateService, { - address, - queryData: utf8.decode(JSON.stringify(query)) as any, - }); - return JSON.parse(utf8.encode(data)); -} diff --git a/packages/es/src/client/apis/simulateAstroportSinglePoolSwap.ts b/packages/es/src/client/apis/simulateAstroportSinglePoolSwap.ts deleted file mode 100644 index 5bcfe888c..000000000 --- a/packages/es/src/client/apis/simulateAstroportSinglePoolSwap.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { queryContract } from './queryContract'; - -export type SimulateAstroportSinglePoolSwapParams = { - poolId: string; - fromAsset: string; - fromAmount: bigint; - isCW20?: boolean | undefined; -}; - -type Response = { - return_amount: string; - spread_amount: string; - commission_amount: string; -}; - -/** - * Simulates the amount of assets that would be received by swapping - * `fromAmount` amount of `fromAsset` assets via the `poolId` pool. - * If `fromAsset` is a CW20 token, `isCW20` must be set to `true`. - */ -export async function simulateAstroportSinglePoolSwap( - endpoint: string, - { poolId, fromAsset, fromAmount, isCW20 }: SimulateAstroportSinglePoolSwapParams -): Promise { - try { - const { return_amount } = await queryContract(endpoint, { - address: poolId, - query: { - simulation: { - offer_asset: { - info: isCW20 - ? { token: { contract_addr: fromAsset } } - : { native_token: { denom: fromAsset } }, - amount: fromAmount.toString(), - }, - }, - }, - }); - return BigInt(return_amount); - } catch (err) { - console.error(err); - return 0n; - } -} diff --git a/packages/es/src/client/apis/simulateKujiraSinglePoolSwap.ts b/packages/es/src/client/apis/simulateKujiraSinglePoolSwap.ts deleted file mode 100644 index 06e5bde78..000000000 --- a/packages/es/src/client/apis/simulateKujiraSinglePoolSwap.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { queryContract } from './queryContract'; - -export type SimulateKujiraSinglePoolSwapParams = { - poolId: string; - fromAsset: string; - fromAmount: bigint; -}; - -type Response = { - return_amount: string; - spread_amount: string; - commission_amount: string; -}; - -/** - * Simulates the amount of assets that would be received by swapping - * `fromAmount` amount of `fromAsset` assets via the `poolId` pool. - */ -export async function simulateKujiraSinglePoolSwap( - endpoint: string, - { poolId, fromAsset, fromAmount }: SimulateKujiraSinglePoolSwapParams -): Promise { - try { - const { return_amount } = await queryContract(endpoint, { - address: poolId, - query: { - simulation: { - offer_asset: { - info: { - native_token: { - denom: fromAsset, - }, - }, - amount: fromAmount.toString(), - }, - }, - }, - }); - return BigInt(return_amount); - } catch (err) { - console.error(err); - return 0n; - } -} diff --git a/packages/es/src/client/apis/simulateTx.ts b/packages/es/src/client/apis/simulateTx.ts deleted file mode 100644 index 74801fa0b..000000000 --- a/packages/es/src/client/apis/simulateTx.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { CosmosTxV1beta1ServiceSimulateService as SimulateService } from '@sonr.io/es/protobufs'; - -import type { Prettify } from '../../typeutils/prettify'; -import { RpcClient } from '../clients/RpcClient'; -import type { ToUnsignedProtoParams, Tx } from '../models/Tx'; - -export type SimulateTxParams = Prettify< - ToUnsignedProtoParams & { - tx: Tx; - } ->; - -/** - * Simulates a tx for the purpose of estimating gas fees. - */ -export async function simulateTx(endpoint: string, { tx, ...params }: SimulateTxParams) { - return RpcClient.query(endpoint, SimulateService, { - txBytes: tx.toUnsignedProto(params).toBinary() as any, - }); -} diff --git a/packages/es/src/client/auth/README.md b/packages/es/src/client/auth/README.md deleted file mode 100644 index fcb8f24e8..000000000 --- a/packages/es/src/client/auth/README.md +++ /dev/null @@ -1,190 +0,0 @@ -# Sonr WebAuthn Authentication Module - -This module provides WebAuthn helper methods for integrating passwordless authentication with the Sonr blockchain. It wraps the `@simplewebauthn/browser` library and provides convenient methods for registering and authenticating users with WebAuthn credentials. - -## Installation - -The auth module is part of the `@sonr.io/es` package: - -```bash -npm install @sonr.io/es -# or -pnpm add @sonr.io/es -``` - -## Usage - -```typescript -import { - registerWebAuthn, - loginWebAuthn, - isWebAuthnSupported -} from '@sonr.io/es/auth'; -``` - -## Core Functions - -### Registration - -#### `registerWebAuthn(apiUrl, options)` -Performs a complete WebAuthn registration flow. - -```typescript -await registerWebAuthn('http://localhost:8080', { - username: 'alice', - rpId: 'localhost', - rpName: 'Sonr Local', - timeout: 60000 // optional, defaults to 60 seconds -}); -``` - -#### `beginRegistration(apiUrl, options)` -Initiates the registration process and returns credential creation options. - -#### `finishRegistration(apiUrl, username, credential)` -Completes the registration by sending the credential to the server for verification. - -### Authentication - -#### `loginWebAuthn(apiUrl, options)` -Performs a complete WebAuthn authentication flow. - -```typescript -const result = await loginWebAuthn('http://localhost:8080', { - username: 'alice', - rpId: 'localhost', - timeout: 30000 // optional, defaults to 30 seconds -}); - -if (result.success) { - console.log('Login successful'); -} -``` - -#### `beginLogin(apiUrl, options)` -Initiates the authentication process and returns credential request options. - -#### `finishLogin(apiUrl, username, credential)` -Completes the authentication by verifying the credential with the server. - -### Utility Functions - -#### `isWebAuthnSupported()` -Checks if the browser supports WebAuthn. - -```typescript -if (isWebAuthnSupported()) { - // WebAuthn is available -} -``` - -#### `isWebAuthnAvailable()` -Checks if a platform authenticator is available (e.g., Touch ID, Face ID, Windows Hello). - -```typescript -const available = await isWebAuthnAvailable(); -if (available) { - // Platform authenticator is available -} -``` - -#### `isConditionalMediationAvailable()` -Checks if conditional mediation (autofill) is supported for seamless authentication. - -```typescript -const autofillSupported = await isConditionalMediationAvailable(); -``` - -#### `bufferToBase64url(buffer)` -Converts an ArrayBuffer to a base64url-encoded string. - -#### `base64urlToBuffer(base64url)` -Converts a base64url-encoded string to an ArrayBuffer. - -## Advanced Usage - -### Custom Registration Flow - -```typescript -import { - beginRegistration, - finishRegistration -} from '@sonr.io/es/auth'; -import { startRegistration } from '@simplewebauthn/browser'; - -// Step 1: Get registration options -const options = await beginRegistration('http://localhost:8080', { - username: 'alice', - rpId: 'localhost', - rpName: 'Sonr Local' -}); - -// Step 2: Create credential (with custom UI feedback) -console.log('Touch your security key...'); -const credential = await startRegistration(options); - -// Step 3: Verify with server -await finishRegistration('http://localhost:8080', 'alice', credential); -``` - -### Custom Authentication Flow - -```typescript -import { - beginLogin, - finishLogin -} from '@sonr.io/es/auth'; -import { startAuthentication } from '@simplewebauthn/browser'; - -// Step 1: Get authentication options -const options = await beginLogin('http://localhost:8080', { - username: 'alice', - rpId: 'localhost' -}); - -// Step 2: Get credential from authenticator -const credential = await startAuthentication(options); - -// Step 3: Verify with server -const result = await finishLogin('http://localhost:8080', 'alice', credential); -``` - -## Server Requirements - -The WebAuthn helpers expect a server that implements the following endpoints: - -- `GET /begin-register?username={username}` - Returns credential creation options -- `POST /finish-register?username={username}` - Verifies and stores the credential -- `GET /begin-login?username={username}` - Returns credential request options -- `POST /finish-login?username={username}` - Verifies the authentication credential - -These endpoints are implemented in the Sonr blockchain's x/did module WebAuthn server. - -## Browser Compatibility - -WebAuthn is supported in modern browsers: -- Chrome/Edge 67+ -- Firefox 60+ -- Safari 14+ - -Platform authenticator support varies by device: -- macOS: Touch ID (MacBooks), Face ID (supported iPads) -- Windows: Windows Hello -- Android: Fingerprint, Face unlock -- iOS: Touch ID, Face ID - -## Security Considerations - -1. Always use HTTPS in production (WebAuthn requires secure contexts) -2. The `rpId` must match the domain where the authentication is performed -3. Store credentials securely on the server -4. Implement proper session management after successful authentication -5. Consider implementing backup authentication methods - -## Examples - -See `examples.ts` for complete usage examples including: -- Checking WebAuthn support -- Simple registration and authentication -- Advanced flows with custom handling -- Conditional UI authentication (autofill) \ No newline at end of file diff --git a/packages/es/src/client/auth/examples.ts b/packages/es/src/client/auth/examples.ts deleted file mode 100644 index f129d54df..000000000 --- a/packages/es/src/client/auth/examples.ts +++ /dev/null @@ -1,206 +0,0 @@ -/** - * Example usage of Passkey authentication methods - * - * These examples demonstrate how to use the passkey helpers - * with a Sonr blockchain node running locally or remotely. - */ - -import { - registerWithPasskey, - loginWithPasskey, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, -} from './webauthn'; - -// Example 1: Check WebAuthn/Passkey availability -export async function checkPasskeySupport() { - const supported = isWebAuthnSupported(); - console.log('Passkey supported:', supported); - - if (supported) { - const available = await isWebAuthnAvailable(); - console.log('Platform authenticator available:', available); - - const conditionalMediation = await isConditionalMediationAvailable(); - console.log('Conditional mediation available:', conditionalMediation); - } -} - -// Example 2: Register a new user with passkey and email -export async function registerUserWithEmail(username: string, email: string) { - const apiUrl = 'http://localhost:1317'; // Your Sonr node API - - try { - const result = await registerWithPasskey(apiUrl, { - username, - email, - rpId: 'localhost', - rpName: 'Sonr Network', - displayName: username, - createVault: true, - }); - - if (result.success) { - console.log('Registration successful!'); - console.log('DID:', result.did); - console.log('Vault ID:', result.vaultId); - console.log('Assertion methods:', result.assertionMethods); - } else { - console.error('Registration failed:', result.error); - } - } catch (error) { - console.error('Registration error:', error); - } -} - -// Example 3: Register a new user with passkey and phone number -export async function registerUserWithPhone(username: string, phoneNumber: string) { - const apiUrl = 'http://localhost:1317'; // Your Sonr node API - - try { - const result = await registerWithPasskey(apiUrl, { - username, - tel: phoneNumber, - rpId: 'localhost', - rpName: 'Sonr Network', - displayName: username, - createVault: true, - }); - - if (result.success) { - console.log('Registration successful!'); - console.log('DID:', result.did); - console.log('Vault ID:', result.vaultId); - console.log('Assertion methods:', result.assertionMethods); - } else { - console.error('Registration failed:', result.error); - } - } catch (error) { - console.error('Registration error:', error); - } -} - -// Example 4: Authenticate a user with passkey -export async function authenticateUser(username: string) { - const apiUrl = 'http://localhost:1317'; // Your Sonr node API - - try { - const result = await loginWithPasskey(apiUrl, { - username, - rpId: 'localhost', - rpName: 'Sonr Network', - }); - - if (result.success) { - console.log('Authentication successful!'); - console.log('DID:', result.did); - console.log('Vault ID:', result.vaultId); - console.log('Session token:', result.sessionToken); - } else { - console.error('Authentication failed:', result.error); - } - } catch (error) { - console.error('Authentication error:', error); - } -} - -// Example 5: Registration with custom server configuration -export async function registerWithCustomServer( - username: string, - email: string, - serverUrl: string, - rpId: string, - rpName: string -) { - try { - const result = await registerWithPasskey(serverUrl, { - username, - email, - rpId, - rpName, - displayName: username, - createVault: true, - timeout: 120000, // 2 minutes - }); - - if (result.success) { - console.log(`User ${username} registered successfully on ${rpName}`); - console.log('DID:', result.did); - console.log('Vault ID:', result.vaultId); - } else { - console.error('Custom registration failed:', result.error); - } - } catch (error) { - console.error('Custom registration error:', error); - } -} - -// Example 6: Conditional UI authentication (autofill) -export async function setupConditionalAuthentication() { - const supported = await isConditionalMediationAvailable(); - - if (supported) { - console.log('Conditional mediation is available'); - // You can now use conditional UI for seamless authentication - // This allows the browser to suggest available credentials - // in form fields marked with autocomplete="username webauthn" - } else { - console.log('Conditional mediation not supported'); - // Fall back to traditional authentication button - } -} - -// Example 7: Full registration flow with error handling -export async function fullRegistrationFlow( - username: string, - email?: string, - phoneNumber?: string -) { - const apiUrl = 'http://localhost:1317'; - - // Check if passkeys are supported - if (!isWebAuthnSupported()) { - console.error('Passkeys are not supported in this browser'); - return; - } - - // Check if platform authenticator is available - const platformAvailable = await isWebAuthnAvailable(); - if (!platformAvailable) { - console.warn('No platform authenticator available, using cross-platform'); - } - - try { - const result = await registerWithPasskey(apiUrl, { - username, - email, - tel: phoneNumber, - rpId: 'localhost', - rpName: 'Sonr Network', - displayName: `${username} User`, - createVault: true, - }); - - if (result.success) { - console.log('✅ Registration successful!'); - console.log('📝 DID Document:', result.did); - console.log('🔐 Vault ID:', result.vaultId); - console.log('🔑 Assertion Methods:', result.assertionMethods); - console.log('🎫 UCAN Token:', result.ucanToken); - - // Store the UCAN token for future operations - localStorage.setItem('ucan_token', result.ucanToken || ''); - localStorage.setItem('user_did', result.did || ''); - localStorage.setItem('vault_id', result.vaultId || ''); - - return result; - } else { - console.error('❌ Registration failed:', result.error); - return null; - } - } catch (error) { - console.error('❌ Unexpected error during registration:', error); - return null; - } -} \ No newline at end of file diff --git a/packages/es/src/client/auth/index.ts b/packages/es/src/client/auth/index.ts deleted file mode 100644 index 7b3e4297a..000000000 --- a/packages/es/src/client/auth/index.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Export passkey authentication functions -export { - registerWithPasskey, - loginWithPasskey, - // Utility functions - bufferToBase64url, - base64urlToBuffer, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, - // Enhanced utilities - checkConditionalMediationSupport, - createRegistrationButton, - createLoginButton, - // Configuration and presets - DEFAULT_WEBAUTHN_CONFIG, - WEBAUTHN_PRESETS, -} from './webauthn'; - -// Export types -export type { - PasskeyRegistrationOptions, - PasskeyLoginOptions, - PasskeyRegistrationResult, - PasskeyLoginResult, - WebAuthnConfig, -} from './webauthn'; diff --git a/packages/es/src/client/auth/test-webauthn.html b/packages/es/src/client/auth/test-webauthn.html deleted file mode 100644 index 0eb469e55..000000000 --- a/packages/es/src/client/auth/test-webauthn.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - Sonr WebAuthn Test - - - -
-

Sonr WebAuthn Test Page

- -
-

WebAuthn Support

-
-
- -
-

Registration

- - -
-
- -
-

Authentication

- - -
-
-
- - - - \ No newline at end of file diff --git a/packages/es/src/client/auth/webauthn.test.ts b/packages/es/src/client/auth/webauthn.test.ts deleted file mode 100644 index e58e9bd2d..000000000 --- a/packages/es/src/client/auth/webauthn.test.ts +++ /dev/null @@ -1,412 +0,0 @@ -/** - * Integration tests for WebAuthn/Passkey authentication - */ - -import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; -import { - registerWithPasskey, - loginWithPasskey, - isWebAuthnSupported, - isWebAuthnAvailable, - bufferToBase64url, - base64urlToBuffer, -} from './webauthn'; - -// Mock @simplewebauthn/browser for testing -vi.mock('@simplewebauthn/browser', () => ({ - browserSupportsWebAuthn: () => true, - platformAuthenticatorIsAvailable: () => Promise.resolve(true), - browserSupportsWebAuthnAutofill: () => Promise.resolve(true), - startRegistration: vi.fn(), - startAuthentication: vi.fn(), - bufferToBase64URLString: (buffer: ArrayBuffer) => { - const bytes = new Uint8Array(buffer); - let binary = ''; - for (let i = 0; i < bytes.byteLength; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); - }, - base64URLStringToBuffer: (base64url: string) => { - const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/'); - const binary = atob(base64); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes.buffer; - }, -})); - -// Mock fetch for API calls -global.fetch = vi.fn(); - -describe('WebAuthn/Passkey Authentication', () => { - const mockApiUrl = 'http://localhost:1317'; - - beforeAll(() => { - // Setup any global mocks or test data - }); - - afterAll(() => { - vi.clearAllMocks(); - }); - - describe('Utility Functions', () => { - it('should check WebAuthn support', () => { - const supported = isWebAuthnSupported(); - expect(supported).toBe(true); - }); - - it('should check platform authenticator availability', async () => { - const available = await isWebAuthnAvailable(); - expect(available).toBe(true); - }); - - it('should convert buffer to base64url and back', () => { - const testString = 'Hello, WebAuthn!'; - const encoder = new TextEncoder(); - const buffer = encoder.encode(testString).buffer; - - const base64url = bufferToBase64url(buffer); - expect(base64url).toBeTruthy(); - expect(base64url).not.toContain('+'); - expect(base64url).not.toContain('/'); - expect(base64url).not.toContain('='); - - const decodedBuffer = base64urlToBuffer(base64url); - const decoder = new TextDecoder(); - const decodedString = decoder.decode(decodedBuffer); - expect(decodedString).toBe(testString); - }); - }); - - describe('Registration with Passkey', () => { - it('should successfully register with email assertion', async () => { - const { startRegistration } = await import('@simplewebauthn/browser'); - - // Mock RegisterStart response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - challenge: 'test-challenge', - rp: { id: 'localhost', name: 'Sonr Network' }, - user: { id: 'user-id', name: 'alice', displayName: 'Alice' }, - }), - }); - - // Mock startRegistration - (startRegistration as any).mockResolvedValueOnce({ - id: 'credential-id', - rawId: 'credential-raw-id', - response: { - publicKey: 'mock-public-key', - attestationObject: 'mock-attestation', - clientDataJSON: 'mock-client-data', - }, - authenticatorAttachment: 'platform', - type: 'public-key', - }); - - // Mock registration submission response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - did: 'did:email:abc123', - vault_id: 'vault-123', - ucan_token: 'ucan-token-123', - credential: { id: 'credential-id' }, - }), - }); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'alice', - email: 'alice@example.com', - rpId: 'localhost', - rpName: 'Sonr Network', - displayName: 'Alice Smith', - createVault: true, - }); - - expect(result.success).toBe(true); - expect(result.did).toBe('did:email:abc123'); - expect(result.vaultId).toBe('vault-123'); - expect(result.ucanToken).toBe('ucan-token-123'); - expect(result.assertionMethods).toEqual([ - 'did:sonr:alice', - 'did:email:alice@example.com', - ]); - }); - - it('should successfully register with phone assertion', async () => { - const { startRegistration } = await import('@simplewebauthn/browser'); - - // Mock RegisterStart response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - challenge: 'test-challenge', - rp: { id: 'localhost', name: 'Sonr Network' }, - user: { id: 'user-id', name: 'bob', displayName: 'Bob' }, - }), - }); - - // Mock startRegistration - (startRegistration as any).mockResolvedValueOnce({ - id: 'credential-id-2', - rawId: 'credential-raw-id-2', - response: { - publicKey: 'mock-public-key-2', - attestationObject: 'mock-attestation-2', - clientDataJSON: 'mock-client-data-2', - }, - authenticatorAttachment: 'platform', - type: 'public-key', - }); - - // Mock registration submission response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - did: 'did:tel:xyz789', - vault_id: 'vault-456', - ucan_token: 'ucan-token-456', - credential: { id: 'credential-id-2' }, - }), - }); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'bob', - tel: '+1234567890', - rpId: 'localhost', - rpName: 'Sonr Network', - displayName: 'Bob Johnson', - createVault: true, - }); - - expect(result.success).toBe(true); - expect(result.did).toBe('did:tel:xyz789'); - expect(result.vaultId).toBe('vault-456'); - expect(result.assertionMethods).toEqual([ - 'did:sonr:bob', - 'did:tel:+1234567890', - ]); - }); - - it('should handle registration failure gracefully', async () => { - // Mock RegisterStart failure - (global.fetch as any).mockResolvedValueOnce({ - ok: false, - json: async () => ({ error: 'Invalid origin' }), - }); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'charlie', - email: 'charlie@example.com', - rpId: 'malicious.com', - rpName: 'Malicious Site', - createVault: false, - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('Invalid origin'); - }); - - it('should handle WebAuthn ceremony cancellation', async () => { - const { startRegistration } = await import('@simplewebauthn/browser'); - - // Mock RegisterStart success - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - challenge: 'test-challenge', - rp: { id: 'localhost', name: 'Sonr Network' }, - user: { id: 'user-id', name: 'dave', displayName: 'Dave' }, - }), - }); - - // Mock user cancellation - (startRegistration as any).mockRejectedValueOnce( - new Error('User cancelled the ceremony') - ); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'dave', - email: 'dave@example.com', - rpId: 'localhost', - rpName: 'Sonr Network', - createVault: true, - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('User cancelled'); - }); - }); - - describe('Login with Passkey', () => { - it('should successfully authenticate with passkey', async () => { - const { startAuthentication } = await import('@simplewebauthn/browser'); - - // Mock LoginStart response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - challenge: 'login-challenge', - rpId: 'localhost', - allowCredentials: [ - { id: 'credential-id', type: 'public-key' }, - ], - userVerification: 'preferred', - }), - }); - - // Mock startAuthentication - (startAuthentication as any).mockResolvedValueOnce({ - id: 'credential-id', - rawId: 'credential-raw-id', - response: { - authenticatorData: 'mock-auth-data', - clientDataJSON: 'mock-client-data', - signature: 'mock-signature', - }, - type: 'public-key', - }); - - // Mock login finish response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - did: 'did:email:abc123', - vault_id: 'vault-123', - session_token: 'session-token-xyz', - }), - }); - - const result = await loginWithPasskey(mockApiUrl, { - username: 'alice', - rpId: 'localhost', - }); - - expect(result.success).toBe(true); - expect(result.did).toBe('did:email:abc123'); - expect(result.vaultId).toBe('vault-123'); - expect(result.sessionToken).toBe('session-token-xyz'); - }); - - it('should handle authentication failure', async () => { - // Mock LoginStart failure - (global.fetch as any).mockResolvedValueOnce({ - ok: false, - text: async () => 'User not found', - }); - - const result = await loginWithPasskey(mockApiUrl, { - username: 'nonexistent', - rpId: 'localhost', - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('User not found'); - }); - - it('should handle invalid credentials', async () => { - const { startAuthentication } = await import('@simplewebauthn/browser'); - - // Mock LoginStart success - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => ({ - challenge: 'login-challenge', - rpId: 'localhost', - allowCredentials: [], - }), - }); - - // Mock authentication with wrong credential - (startAuthentication as any).mockResolvedValueOnce({ - id: 'wrong-credential-id', - rawId: 'wrong-credential-raw-id', - response: { - authenticatorData: 'mock-auth-data', - clientDataJSON: 'mock-client-data', - signature: 'mock-signature', - }, - type: 'public-key', - }); - - // Mock login finish failure - (global.fetch as any).mockResolvedValueOnce({ - ok: false, - json: async () => ({ error: 'Invalid credential' }), - }); - - const result = await loginWithPasskey(mockApiUrl, { - username: 'alice', - rpId: 'localhost', - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('Invalid credential'); - }); - }); - - describe('Edge Cases and Error Handling', () => { - it('should handle network errors', async () => { - // Mock network error - (global.fetch as any).mockRejectedValueOnce( - new Error('Network request failed') - ); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'network-test', - email: 'test@example.com', - rpId: 'localhost', - rpName: 'Sonr Network', - createVault: false, - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('Network request failed'); - }); - - it('should handle malformed API responses', async () => { - // Mock malformed response - (global.fetch as any).mockResolvedValueOnce({ - ok: true, - json: async () => { throw new Error('Invalid JSON'); }, - }); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'malformed-test', - email: 'test@example.com', - rpId: 'localhost', - rpName: 'Sonr Network', - createVault: false, - }); - - expect(result.success).toBe(false); - expect(result.error).toBeTruthy(); - }); - - it('should handle timeout scenarios', async () => { - // Mock timeout - (global.fetch as any).mockImplementationOnce(() => - new Promise((_, reject) => - setTimeout(() => reject(new Error('Request timeout')), 100) - ) - ); - - const result = await registerWithPasskey(mockApiUrl, { - username: 'timeout-test', - email: 'test@example.com', - rpId: 'localhost', - rpName: 'Sonr Network', - timeout: 50, // Very short timeout - createVault: false, - }); - - expect(result.success).toBe(false); - expect(result.error).toContain('timeout'); - }); - }); -}); \ No newline at end of file diff --git a/packages/es/src/client/auth/webauthn.ts b/packages/es/src/client/auth/webauthn.ts deleted file mode 100644 index dee7dd1aa..000000000 --- a/packages/es/src/client/auth/webauthn.ts +++ /dev/null @@ -1,621 +0,0 @@ -import { - base64URLStringToBuffer, - browserSupportsWebAuthn, - browserSupportsWebAuthnAutofill, - bufferToBase64URLString, - platformAuthenticatorIsAvailable, - startAuthentication, - startRegistration, -} from '@simplewebauthn/browser'; -import type { - AuthenticationResponseJSON, - PublicKeyCredentialCreationOptionsJSON, - PublicKeyCredentialRequestOptionsJSON, - RegistrationResponseJSON, -} from '@simplewebauthn/types'; - -// Configuration for WebAuthn operations -export interface WebAuthnConfig { - // Authenticator preferences - authenticatorSelection?: { - authenticatorAttachment?: 'platform' | 'cross-platform'; - requireResidentKey?: boolean; - residentKey?: 'required' | 'preferred' | 'discouraged'; - userVerification?: 'required' | 'preferred' | 'discouraged'; - }; - - // Attestation preference - attestation?: 'none' | 'indirect' | 'direct' | 'enterprise'; - - // Algorithm preferences (in order of preference) - algorithms?: number[]; - - // UI/UX options - showQROption?: boolean; - preferPlatformAuthenticator?: boolean; - - // Callbacks - onStart?: (options: any) => void | Promise; - onComplete?: (credential: any) => void | Promise; - onError?: (error: Error) => void | Promise; - onStatusUpdate?: (status: string, type: 'info' | 'success' | 'error' | 'warning') => void; -} - -// Default configuration with broad compatibility -export const DEFAULT_WEBAUTHN_CONFIG: WebAuthnConfig = { - authenticatorSelection: { - // No authenticatorAttachment to allow both platform and cross-platform - requireResidentKey: false, - residentKey: 'preferred', - userVerification: 'preferred', // Broad compatibility - }, - attestation: 'none', // Simplest option for broad compatibility - algorithms: [ - -7, // ES256 (most common) - -257, // RS256 - -8, // EdDSA - ], - showQROption: true, - preferPlatformAuthenticator: false, -}; - -// Preset configurations for common use cases -export const WEBAUTHN_PRESETS = { - // Maximum compatibility - works with most devices - BROAD_COMPATIBILITY: DEFAULT_WEBAUTHN_CONFIG, - - // Platform only - for native app feel - PLATFORM_ONLY: { - ...DEFAULT_WEBAUTHN_CONFIG, - authenticatorSelection: { - authenticatorAttachment: 'platform' as const, - requireResidentKey: true, - residentKey: 'required' as const, - userVerification: 'required' as const, - }, - showQROption: false, - preferPlatformAuthenticator: true, - }, - - // Security key focused - SECURITY_KEY: { - ...DEFAULT_WEBAUTHN_CONFIG, - authenticatorSelection: { - authenticatorAttachment: 'cross-platform' as const, - requireResidentKey: false, - residentKey: 'discouraged' as const, - userVerification: 'preferred' as const, - }, - attestation: 'direct' as const, - showQROption: false, - }, - - // Mobile friendly with QR codes - MOBILE_FRIENDLY: { - ...DEFAULT_WEBAUTHN_CONFIG, - authenticatorSelection: { - requireResidentKey: false, - residentKey: 'preferred' as const, - userVerification: 'preferred' as const, - }, - showQROption: true, - preferPlatformAuthenticator: false, - }, - - // High security (enterprise) - HIGH_SECURITY: { - ...DEFAULT_WEBAUTHN_CONFIG, - authenticatorSelection: { - requireResidentKey: true, - residentKey: 'required' as const, - userVerification: 'required' as const, - }, - attestation: 'direct' as const, - }, -}; - -// Types for passkey registration and login -export interface PasskeyRegistrationOptions { - username: string; - rpId?: string; - rpName?: string; - email?: string; - tel?: string; - displayName?: string; - createVault?: boolean; - timeout?: number; - config?: WebAuthnConfig; -} - -export interface PasskeyLoginOptions { - username: string; - rpId?: string; - rpName?: string; - timeout?: number; - config?: WebAuthnConfig; -} - -export interface PasskeyRegistrationResult { - success: boolean; - did?: string; - vaultId?: string; - assertionMethods?: string[]; - ucanToken?: string; - credential?: any; - error?: string; -} - -export interface PasskeyLoginResult { - success: boolean; - did?: string; - vaultId?: string; - sessionToken?: string; - error?: string; -} - -// Utility exports -export const bufferToBase64url = bufferToBase64URLString; -export const base64urlToBuffer = base64URLStringToBuffer; -export const isWebAuthnSupported = browserSupportsWebAuthn; -export const isWebAuthnAvailable = platformAuthenticatorIsAvailable; -export const isConditionalMediationAvailable = browserSupportsWebAuthnAutofill; - -/** - * Register with a passkey (WebAuthn) - * Supports email/tel assertion methods for Sonr blockchain - */ -export async function registerWithPasskey( - apiUrl: string, - options: PasskeyRegistrationOptions -): Promise { - const config = { ...DEFAULT_WEBAUTHN_CONFIG, ...options.config }; - - try { - // Check WebAuthn support - if (!browserSupportsWebAuthn()) { - throw new Error('WebAuthn is not supported in this browser'); - } - - // Check platform authenticator if preferred - if (config.preferPlatformAuthenticator) { - const hasPlatform = await platformAuthenticatorIsAvailable(); - if (!hasPlatform) { - config.onStatusUpdate?.('Platform authenticator not available, using cross-platform options', 'warning'); - } - } - - config.onStatusUpdate?.('Preparing registration...', 'info'); - - // If using custom config, build options directly - if (options.config) { - const registrationOptions: PublicKeyCredentialCreationOptionsJSON = { - challenge: generateChallenge(), - rp: { - id: options.rpId || window.location.hostname, - name: options.rpName || 'Sonr Identity', - }, - user: { - id: btoa(options.username), - name: options.username, - displayName: options.displayName || options.username, - }, - pubKeyCredParams: (config.algorithms || DEFAULT_WEBAUTHN_CONFIG.algorithms!).map(alg => ({ - type: 'public-key' as const, - alg, - })), - authenticatorSelection: config.authenticatorSelection, - timeout: options.timeout || 60000, - attestation: config.attestation as AttestationConveyancePreference, - }; - - // Call start callback - await config.onStart?.(registrationOptions); - - config.onStatusUpdate?.('Please interact with your authenticator...', 'info'); - - // Create credential with WebAuthn - const credential = await startRegistration(registrationOptions); - - // Call complete callback - await config.onComplete?.(credential); - - config.onStatusUpdate?.('Registration successful!', 'success'); - - // For custom config, return simplified result - return { - success: true, - credential, - did: `did:sonr:${options.username}`, // Placeholder - }; - } - - // Original flow for Sonr blockchain integration - const registrationOptions = await beginRegistrationPasskey(apiUrl, options); - await config.onStart?.(registrationOptions); - - config.onStatusUpdate?.('Please interact with your authenticator...', 'info'); - const credential = await startRegistration(registrationOptions); - await config.onComplete?.(credential); - - const result = await finishRegistrationPasskey( - apiUrl, - options, - credential, - registrationOptions.challenge - ); - - config.onStatusUpdate?.('Registration successful!', 'success'); - return result; - } catch (error) { - const err = error as Error; - await config.onError?.(err); - config.onStatusUpdate?.(`Registration failed: ${err.message}`, 'error'); - - console.error('Passkey registration failed:', error); - return { - success: false, - error: err.message, - }; - } -} - -/** - * Login with a passkey (WebAuthn) - */ -export async function loginWithPasskey( - apiUrl: string, - options: PasskeyLoginOptions -): Promise { - const config = { ...DEFAULT_WEBAUTHN_CONFIG, ...options.config }; - - try { - // Check WebAuthn support - if (!browserSupportsWebAuthn()) { - throw new Error('WebAuthn is not supported in this browser'); - } - - config.onStatusUpdate?.('Preparing authentication...', 'info'); - - // If using custom config, build options directly - if (options.config) { - const authOptions: PublicKeyCredentialRequestOptionsJSON = { - challenge: generateChallenge(), - rpId: options.rpId || window.location.hostname, - timeout: options.timeout || 60000, - userVerification: config.authenticatorSelection?.userVerification || 'preferred', - }; - - // Call start callback - await config.onStart?.(authOptions); - - config.onStatusUpdate?.('Please authenticate with your passkey...', 'info'); - - // Authenticate with WebAuthn - const credential = await startAuthentication(authOptions); - - // Call complete callback - await config.onComplete?.(credential); - - config.onStatusUpdate?.('Authentication successful!', 'success'); - - // For custom config, return simplified result - return { - success: true, - did: `did:sonr:${options.username}`, // Placeholder - sessionToken: credential.id, - }; - } - - // Original flow for Sonr blockchain integration - const loginOptions = await beginLoginPasskey(apiUrl, options); - await config.onStart?.(loginOptions); - - config.onStatusUpdate?.('Please authenticate with your passkey...', 'info'); - const credential = await startAuthentication(loginOptions); - await config.onComplete?.(credential); - - const result = await finishLoginPasskey( - apiUrl, - options.username, - credential, - loginOptions.challenge - ); - - config.onStatusUpdate?.('Authentication successful!', 'success'); - return result; - } catch (error) { - const err = error as Error; - await config.onError?.(err); - config.onStatusUpdate?.(`Authentication failed: ${err.message}`, 'error'); - - console.error('Passkey authentication failed:', error); - return { - success: false, - error: err.message, - }; - } -} - -/** - * Generate a random challenge (for demo purposes) - * In production, this should come from the server - */ -function generateChallenge(): string { - const array = new Uint8Array(32); - crypto.getRandomValues(array); - return btoa(String.fromCharCode(...array)) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); -} - -/** - * Utility to create a button with WebAuthn registration - */ -export function createRegistrationButton( - buttonElement: HTMLButtonElement, - apiUrl: string, - options: PasskeyRegistrationOptions -): void { - buttonElement.addEventListener('click', async () => { - buttonElement.disabled = true; - const originalText = buttonElement.textContent; - - // Default status update if not provided - const config = options.config || {}; - if (!config.onStatusUpdate) { - config.onStatusUpdate = (status, type) => { - buttonElement.textContent = status; - buttonElement.className = `webauthn-button webauthn-${type}`; - }; - } - - const result = await registerWithPasskey(apiUrl, { ...options, config }); - - if (result.success) { - buttonElement.textContent = '✓ Registered'; - } else { - buttonElement.textContent = originalText; - buttonElement.disabled = false; - } - }); -} - -/** - * Utility to create a button with WebAuthn login - */ -export function createLoginButton( - buttonElement: HTMLButtonElement, - apiUrl: string, - options: PasskeyLoginOptions -): void { - buttonElement.addEventListener('click', async () => { - buttonElement.disabled = true; - const originalText = buttonElement.textContent; - - // Default status update if not provided - const config = options.config || {}; - if (!config.onStatusUpdate) { - config.onStatusUpdate = (status, type) => { - buttonElement.textContent = status; - buttonElement.className = `webauthn-button webauthn-${type}`; - }; - } - - const result = await loginWithPasskey(apiUrl, { ...options, config }); - - if (result.success) { - buttonElement.textContent = '✓ Logged In'; - } else { - buttonElement.textContent = originalText; - buttonElement.disabled = false; - } - }); -} - -/** - * Check if conditional mediation (autofill) is available - */ -export async function checkConditionalMediationSupport(): Promise<{ - supported: boolean; - available: boolean; - platformAuthenticator: boolean; -}> { - const supported = browserSupportsWebAuthn(); - const available = supported && await browserSupportsWebAuthnAutofill(); - const platformAuthenticator = supported && await platformAuthenticatorIsAvailable(); - - return { - supported, - available, - platformAuthenticator, - }; -} - -// Internal helper functions - -async function beginRegistrationPasskey( - apiUrl: string, - options: PasskeyRegistrationOptions -): Promise { - // Determine assertion type and value - const assertionValue = options.email || options.tel || options.username; - const assertionType = options.email ? 'email' : options.tel ? 'tel' : 'username'; - const serviceOrigin = typeof window !== 'undefined' ? window.location.origin : options.rpId; - - // Call Sonr's RegisterStart query - const response = await fetch(`${apiUrl}/did/v1/register/start`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - assertion_value: assertionValue, - assertion_type: assertionType, - service_origin: serviceOrigin, - }), - }); - - if (!response.ok) { - const error = await response - .json() - .catch(() => ({ error: 'Failed to get registration options' })); - throw new Error(error.error || 'Failed to get registration options'); - } - - const data = await response.json(); - - // Generate a challenge if not provided - const challenge = data.challenge || generateChallenge(); - - // Create WebAuthn options - const publicKeyOptions: PublicKeyCredentialCreationOptionsJSON = { - challenge, - rp: { - id: data.rp?.id || options.rpId, - name: data.rp?.name || options.rpName, - }, - user: { - id: data.user?.id || generateUserId(), - name: options.username, - displayName: options.displayName || options.username, - }, - pubKeyCredParams: data.pubKeyCredParams || [ - { alg: -7, type: 'public-key' }, // ES256 - { alg: -257, type: 'public-key' }, // RS256 - ], - timeout: data.timeout || options.timeout || 60000, - attestation: data.attestation || 'direct', - authenticatorSelection: data.authenticatorSelection || { - authenticatorAttachment: 'platform', - requireResidentKey: false, - userVerification: 'preferred', - }, - }; - - return publicKeyOptions; -} - -async function finishRegistrationPasskey( - apiUrl: string, - options: PasskeyRegistrationOptions, - credential: RegistrationResponseJSON, - challenge: string -): Promise { - const assertionValue = options.email || options.tel || options.username; - const assertionType = options.email ? 'email' : options.tel ? 'tel' : 'username'; - - const response = await fetch(`${apiUrl}/did/v1/tx/register-webauthn-credential`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - username: options.username, - assertion_value: assertionValue, - assertion_type: assertionType, - webauthn_credential: { - credential_id: credential.id, - public_key: credential.response.publicKey, - attestation_object: credential.response.attestationObject, - client_data_json: credential.response.clientDataJSON, - authenticator_attachment: credential.authenticatorAttachment, - }, - create_vault: options.createVault ?? true, - challenge, - }), - }); - - if (!response.ok) { - const error = await response - .json() - .catch(() => ({ error: 'Registration submission failed' })); - throw new Error(error.error || 'Registration submission failed'); - } - - const result = await response.json(); - return { - success: true, - did: result.did, - vaultId: result.vault_id, - assertionMethods: [ - `did:sonr:${options.username}`, - `did:${assertionType}:${assertionValue}`, - ], - ucanToken: result.ucan_token, - credential: result.credential, - }; -} - -async function beginLoginPasskey( - apiUrl: string, - options: PasskeyLoginOptions -): Promise { - const url = new URL(`${apiUrl}/did/v1/login/start`); - - const response = await fetch(url.toString(), { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username: options.username }), - }); - - if (!response.ok) { - const error = await response.text(); - throw new Error('Failed to get authentication options: ' + error); - } - - const loginOptions = await response.json(); - - const publicKeyOptions: PublicKeyCredentialRequestOptionsJSON = { - challenge: loginOptions.challenge, - rpId: loginOptions.rpId || options.rpId, - allowCredentials: loginOptions.allowCredentials, - userVerification: loginOptions.userVerification || 'preferred', - timeout: loginOptions.timeout || options.timeout || 30000, - }; - - return publicKeyOptions; -} - -async function finishLoginPasskey( - apiUrl: string, - username: string, - credential: AuthenticationResponseJSON, - challenge: string -): Promise { - const response = await fetch(`${apiUrl}/did/v1/login/finish`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - username, - credential, - challenge, - }), - }); - - if (!response.ok) { - const error = await response - .json() - .catch(() => ({ error: 'Authentication verification failed' })); - throw new Error(error.error || 'Authentication verification failed'); - } - - const result = await response.json(); - return { - success: true, - did: result.did, - vaultId: result.vault_id, - sessionToken: result.session_token, - }; -} - - -// Helper function to generate a random user ID -function generateUserId(): string { - const array = new Uint8Array(16); - if (typeof window !== 'undefined' && window.crypto) { - window.crypto.getRandomValues(array); - } else { - // Fallback for Node.js environment - for (let i = 0; i < array.length; i++) { - array[i] = Math.floor(Math.random() * 256); - } - } - return bufferToBase64URLString(array.buffer); -} \ No newline at end of file diff --git a/packages/es/src/client/clients/FetchClient.ts b/packages/es/src/client/clients/FetchClient.ts deleted file mode 100644 index cbe6ec285..000000000 --- a/packages/es/src/client/clients/FetchClient.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { JsonValue } from '@bufbuild/protobuf'; - -/** - * A simple and minimal wrapper around the native `fetch` API. - */ -export class FetchClient { - /** - * Performs a GET request to the given `endpoint`, and returns the - * JSON response. - */ - public static async get( - endpoint: string, - searchParams?: Record | undefined - ): Promise { - const url = new URL(endpoint); - url.search = new URLSearchParams(searchParams).toString(); - const res = await fetch(url, { method: 'GET' }); - return res.json(); - } - - /** - * Performs a POST request to the given `endpoint`, and returns the - * JSON response. - */ - public static async post(endpoint: string, body: JsonValue): Promise { - const res = await fetch(endpoint, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - return res.json(); - } -} diff --git a/packages/es/src/client/clients/RpcClient.ts b/packages/es/src/client/clients/RpcClient.ts deleted file mode 100644 index af88d07d2..000000000 --- a/packages/es/src/client/clients/RpcClient.ts +++ /dev/null @@ -1,199 +0,0 @@ -import type { JsonValue, Message, PartialMessage } from '@bufbuild/protobuf'; -import { base16, base64 } from '@sonr.io/es/codec'; -import type { CosmosTxV1beta1TxRaw as TxRaw } from '@sonr.io/es/protobufs'; - -import { FetchClient } from './FetchClient'; - -type ErrorResponse = { - id: number; - jsonrpc: string; - error: { - code: number; - message: string; - data: string; - }; - result: never; -}; -type SuccessResponse = { - id: number; - jsonrpc: string; - result: T; - error: never; -}; -type Response = SuccessResponse | ErrorResponse; - -type QueryResult = { - response: { - code: number; - log: string; - info: string; - index: string; - key: string | null; - value: string | null; - proofOps: string[] | null; - height: string; - codespace: string; - }; -}; -type QueryService, U extends Message> = { - typeName: string; - method: string; - Request: new (msg: PartialMessage) => T; - Response: { fromBinary: (bytes: Uint8Array) => U }; -}; - -type BroadcastTxResult = { - code: number; - codespace: string; - data: string; - hash: string; - log: string; -}; - -/** - * Wraps the request message with an optional `height` field. - */ -type RequestMessage> = T extends { - height: bigint | string | number; -} - ? PartialMessage - : PartialMessage & { - /** - * The block height at which the query should be executed. Providing a height - * that is outside the range of the full node will result in an error. Leave - * this field empty to default to the latest block. - */ - height?: number | undefined; - }; - -export class RpcClient { - private static async doRequest(endpoint: string, method: string, params: JsonValue) { - const { result, error } = await FetchClient.post>(endpoint, { - id: Date.now(), - jsonrpc: '2.0', - method, - params, - }); - if (error != null) { - throw new Error(error.data); - } - return result; - } - - /** - * Posts an ABCI query to the RPC `endpoint`. If successful, returns the response, - * otherwise throws an error. - */ - public static async query, U extends Message>( - endpoint: string, - { typeName, method, Request, Response }: QueryService, - requestMsg: RequestMessage - ): Promise { - const { response } = await RpcClient.doRequest(endpoint, 'abci_query', { - path: `/${typeName}/${method}`, - data: base16.encode(new Request(requestMsg).toBinary()), - ...(requestMsg.height ? { height: requestMsg.height.toString() } : {}), - }); - const { log, value } = response; - if (!value) { - throw new Error(log); - } - return Response.fromBinary(base64.decode(value)); - } - - /** - * Posts a `broadcast_tx_sync` request to the RPC `endpoint`. If successful, - * returns the tx hash, otherwise throws an error. - */ - public static async broadcastTx(endpoint: string, txRaw: TxRaw): Promise { - const { code, log, hash } = await RpcClient.doRequest( - endpoint, - 'broadcast_tx_sync', - { - tx: base64.encode(txRaw.toBinary()), - } - ); - if (code !== 0) { - throw new Error(log); - } - return hash; - } - - /** - * Creates a new ABCI batch query. - */ - public static newBatchQuery(endpoint: string): BatchQuery { - return new BatchQuery(endpoint); - } -} - -class BatchQuery { - private readonly endpoint: string; - private readonly queries: { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - queryService: QueryService; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - requestMsg: RequestMessage; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback: (err: Error | null, response: any) => unknown; - }[] = []; - - constructor(endpoint: string) { - this.endpoint = endpoint; - } - - /** - * Adds an `abci_query` to this query batch. - * - * @param callback An error-first callback function for the response of the query. - * If `err` is not `null`, `response` will be `null` and should not be used. - */ - public add, U extends Message>( - queryService: QueryService, - requestMsg: RequestMessage, - callback: (err: Error | null, response: U) => unknown - ) { - this.queries.push({ queryService, requestMsg, callback }); - return this; - } - - /** - * Executes the batched query. - */ - public async send() { - if (this.queries.length === 0) { - return; - } - const payload = this.queries.map(({ queryService, requestMsg }, idx) => ({ - id: idx, - jsonrpc: '2.0', - method: 'abci_query', - params: { - path: `/${queryService.typeName}/${queryService.method}`, - data: base16.encode(new queryService.Request(requestMsg).toBinary()), - ...(requestMsg.height ? { height: requestMsg.height.toString() } : {}), - }, - })); - const res = await FetchClient.post< - // Array is returned if and only if the payload has more than one query - Response[] | Response - >(this.endpoint, payload); - const results = Array.isArray(res) ? res : [res]; - for (const { id, result, error } of results) { - const query = this.queries[id]; - if (!query) continue; - const { queryService, callback: handler } = query; - if (error != null) { - handler(new Error(error.data), null); - continue; - } - const { log, value } = result.response; - if (!value) { - handler(new Error(log), null); - continue; - } - const responseMsg = queryService.Response.fromBinary(base64.decode(value)); - handler(null, responseMsg); - } - } -} diff --git a/packages/es/src/client/index.ts b/packages/es/src/client/index.ts deleted file mode 100644 index 4a052448a..000000000 --- a/packages/es/src/client/index.ts +++ /dev/null @@ -1,67 +0,0 @@ -export { type BroadcastTxParams, broadcastTx } from './apis/broadcastTx'; -export { type GetAccountParams, getAccount } from './apis/getAccount'; -// Commented out - CosmWasm files have been removed -// export { -// type GetCw20BalanceParams, -// getCw20Balance, -// } from "./apis/getCw20Balance"; -export { - type GetNativeBalancesParams, - getNativeBalances, -} from './apis/getNativeBalances'; -export { type GetTxParams, getTx } from './apis/getTx'; -export { type PollTxParams, pollTx } from './apis/pollTx'; -// Commented out - CosmWasm files have been removed -// export { type QueryContractParams, queryContract } from "./apis/queryContract"; -// Commented out - CosmWasm files have been removed -// export { -// type SimulateAstroportSinglePoolSwapParams, -// simulateAstroportSinglePoolSwap, -// } from "./apis/simulateAstroportSinglePoolSwap"; -// export { -// type SimulateKujiraSinglePoolSwapParams, -// simulateKujiraSinglePoolSwap, -// } from "./apis/simulateKujiraSinglePoolSwap"; -export { type SimulateTxParams, simulateTx } from './apis/simulateTx'; -export { RpcClient } from './clients/RpcClient'; -export type { Adapter } from './models/Adapter'; -export { MsgBeginRedelegate } from './models/MsgBeginRedelegate'; -export { MsgDelegate } from './models/MsgDelegate'; -export { MsgIbcTransfer } from './models/MsgIbcTransfer'; -export { MsgSend } from './models/MsgSend'; -export { MsgStoreCode } from './models/MsgStoreCode'; -export { MsgUndelegate } from './models/MsgUndelegate'; -export { MsgWithdrawDelegatorRewards } from './models/MsgWithdrawDelegatorRewards'; -export { MsgWithdrawValidatorCommission } from './models/MsgWithdrawValidatorCommission'; - -export { Secp256k1PubKey } from './models/Secp256k1PubKey'; -export { - type ToSignDocParams, - type ToSignedProtoParams, - type ToStdSignDocParams, - type ToUnsignedProtoParams, - Tx, -} from './models/Tx'; -export { calculateFee } from './utils/calculateFee'; -export { toAny } from './utils/toAny'; -export { toBaseAccount } from './utils/toBaseAccount'; - -// Export passkey authentication functions -export { - registerWithPasskey, - loginWithPasskey, - // Utility functions - bufferToBase64url, - base64urlToBuffer, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, -} from './auth'; - -// Export passkey types -export type { - PasskeyRegistrationOptions, - PasskeyLoginOptions, - PasskeyRegistrationResult, - PasskeyLoginResult, -} from './auth'; diff --git a/packages/es/src/client/models/Adapter.ts b/packages/es/src/client/models/Adapter.ts deleted file mode 100644 index f6fcad665..000000000 --- a/packages/es/src/client/models/Adapter.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Message } from '@bufbuild/protobuf'; - -/** - * An adapter to translate between protobuf and amino encodings. - */ -export type Adapter = { - toProto: () => Message; - toAmino: () => { - type: string; - value: Record; - }; -}; diff --git a/packages/es/src/client/models/MsgBeginRedelegate.ts b/packages/es/src/client/models/MsgBeginRedelegate.ts deleted file mode 100644 index 87dade14d..000000000 --- a/packages/es/src/client/models/MsgBeginRedelegate.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosStakingV1beta1MsgBeginRedelegate not available in protobufs -// // TODO: Missing from protobufs -// import { CosmosStakingV1beta1MsgBeginRedelegate as ProtoMsgBeginRedelegate } from "../../protobufs"; -const _ProtoMsgBeginRedelegate: any = {}; -type ProtoMsgBeginRedelegate = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgBeginRedelegate implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - // TODO: Implement toProto() method when CosmosStakingV1beta1MsgBeginRedelegate protobuf is available - // This method should create and return a proper ProtoMsgBeginRedelegate instance with this.data - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgBeginRedelegate is available - // throw new Error("MsgBeginRedelegate not implemented - missing protobuf definition"); - // return new ProtoMsgBeginRedelegate(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the redelegation message to amino JSON format - public toAmino() { - return { - type: 'cosmos-sdk/MsgBeginRedelegate', - value: { - delegator_address: this.data.delegatorAddress, - validator_src_address: this.data.validatorSrcAddress, - validator_dst_address: this.data.validatorDstAddress, - amount: this.data.amount, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgDelegate.ts b/packages/es/src/client/models/MsgDelegate.ts deleted file mode 100644 index 1f1c4f695..000000000 --- a/packages/es/src/client/models/MsgDelegate.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosStakingV1beta1MsgDelegate not available in protobufs -// // TODO: Missing from protobufs -// import { CosmosStakingV1beta1MsgDelegate as ProtoMsgDelegate } from "../../protobufs"; -const _ProtoMsgDelegate: any = {}; -type ProtoMsgDelegate = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgDelegate implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - // TODO: Implement toProto() method when CosmosStakingV1beta1MsgDelegate protobuf is available - // This method should create and return a proper ProtoMsgDelegate instance with this.data - // Required implementation: - // 1. Import the correct protobuf type from @sonr.io/es/protobufs - // 2. Create new ProtoMsgDelegate instance with validated data - // 3. Set delegatorAddress, validatorAddress, and amount fields - // 4. Validate validator address format and amount positivity - // 5. Handle coin conversion for amount field (denom and amount) - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgDelegate is available - // throw new Error("MsgDelegate not implemented - missing protobuf definition"); - // return new ProtoMsgDelegate(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the staking delegation message to amino JSON format - public toAmino() { - return { - type: 'cosmos-sdk/MsgDelegate', - value: { - delegator_address: this.data.delegatorAddress, - validator_address: this.data.validatorAddress, - amount: this.data.amount, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgIbcTransfer.ts b/packages/es/src/client/models/MsgIbcTransfer.ts deleted file mode 100644 index 83629f683..000000000 --- a/packages/es/src/client/models/MsgIbcTransfer.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -import { IbcApplicationsTransferV1MsgTransfer as ProtoMsgIbcTransfer } from '../../protobufs'; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgIbcTransfer implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - public toProto() { - return new ProtoMsgIbcTransfer(this.data); - } - - public toAmino() { - return { - type: 'cosmos-sdk/MsgTransfer', - value: { - source_port: this.data.sourcePort, - source_channel: this.data.sourceChannel, - token: this.data.token, - sender: this.data.sender, - receiver: this.data.receiver, - /** - * Protobuf type is optional, but Amino type is non-optional. - * - * @see https://github.com/cosmos/cosmjs/blob/358260bff71c9d3e7ad6644fcf64dc00325cdfb9/packages/stargate/src/modules/ibc/aminomessages.ts#L16-L42 - */ - timeout_height: this.data.timeoutHeight - ? { - revision_number: this.data.timeoutHeight.revisionNumber.toString(), - revision_height: this.data.timeoutHeight.revisionHeight.toString(), - } - : {}, - timeout_timestamp: this.data.timeoutTimestamp.toString(), - memo: this.data.memo, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgSend.ts b/packages/es/src/client/models/MsgSend.ts deleted file mode 100644 index 0601c7645..000000000 --- a/packages/es/src/client/models/MsgSend.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosBankV1beta1MsgSend not available in protobufs -// // TODO: Missing from protobufs -// import { CosmosBankV1beta1MsgSend as ProtoMsgSend } from "@sonr.io/es/protobufs"; -const _ProtoMsgSend: any = {}; -type ProtoMsgSend = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgSend implements Adapter { - private readonly data: Data; - private readonly legacy: boolean; - - constructor(data: Data, legacy = false) { - this.data = data; - this.legacy = legacy; - } - - // TODO: Implement toProto() method when CosmosBankV1beta1MsgSend protobuf is available - // This method should create and return a proper ProtoMsgSend instance with this.data - // Required implementation: - // 1. Import the correct protobuf type from @sonr.io/es/protobufs - // 2. Create new ProtoMsgSend instance with validated data - // 3. Set fromAddress, toAddress, and amount fields - // 4. Handle coin conversion for amount field (denom and amount) - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgSend is available - // throw new Error("MsgSend not implemented - missing protobuf definition"); - // return new ProtoMsgSend(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the message to amino JSON format for legacy support - public toAmino() { - return { - type: this.legacy ? 'bank/MsgSend' : 'cosmos-sdk/MsgSend', - value: { - from_address: this.data.fromAddress, - to_address: this.data.toAddress, - amount: this.data.amount, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgStoreCode.ts b/packages/es/src/client/models/MsgStoreCode.ts deleted file mode 100644 index f72e53f94..000000000 --- a/packages/es/src/client/models/MsgStoreCode.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -import { base64 } from '@sonr.io/es/codec'; -import { CosmwasmWasmV1MsgStoreCode as ProtoMsgStoreCode } from '@sonr.io/es/protobufs'; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgStoreCode implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - public toProto() { - return new ProtoMsgStoreCode({ - ...this.data, - }); - } - - public toAmino() { - return { - type: 'wasm/MsgStoreCode', - value: { - sender: this.data.sender, - wasm_byte_code: base64.encode(this.data.wasmByteCode), - instantiate_permission: this.data.instantiatePermission, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgUndelegate.ts b/packages/es/src/client/models/MsgUndelegate.ts deleted file mode 100644 index 33e0ff7fe..000000000 --- a/packages/es/src/client/models/MsgUndelegate.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosStakingV1beta1MsgUndelegate not available in protobufs -// // TODO: Missing from protobufs -// import { CosmosStakingV1beta1MsgUndelegate as ProtoMsgUndelegate } from "@sonr.io/es/protobufs"; -const _ProtoMsgUndelegate: any = {}; -type ProtoMsgUndelegate = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgUndelegate implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - // TODO: Implement toProto() method when CosmosStakingV1beta1MsgUndelegate protobuf is available - // This method should create and return a proper ProtoMsgUndelegate instance with this.data - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgUndelegate is available - // throw new Error("MsgUndelegate not implemented - missing protobuf definition"); - // return new ProtoMsgUndelegate(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the undelegation message to amino JSON format - public toAmino() { - return { - type: 'cosmos-sdk/MsgUndelegate', - value: { - delegator_address: this.data.delegatorAddress, - validator_address: this.data.validatorAddress, - amount: this.data.amount, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgWithdrawDelegatorRewards.ts b/packages/es/src/client/models/MsgWithdrawDelegatorRewards.ts deleted file mode 100644 index 397dd557b..000000000 --- a/packages/es/src/client/models/MsgWithdrawDelegatorRewards.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosDistributionV1beta1MsgWithdrawDelegatorReward not available in protobufs -// import { CosmosDistributionV1beta1MsgWithdrawDelegatorReward as ProtoMsgWithdrawDelegatorRewards } from "@sonr.io/es/protobufs"; -type ProtoMsgWithdrawDelegatorRewards = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgWithdrawDelegatorRewards implements Adapter { - private readonly data: Data; - private readonly isLegacy: boolean; - - constructor(data: Data, isLegacy = false) { - this.data = data; - this.isLegacy = isLegacy; - } - - // TODO: Implement toProto() method when CosmosDistributionV1beta1MsgWithdrawDelegatorReward protobuf is available - // This method should create and return a proper ProtoMsgWithdrawDelegatorRewards instance with this.data - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgWithdrawDelegatorRewards is available - // throw new Error("MsgWithdrawDelegatorRewards not implemented - missing protobuf definition"); - // return new ProtoMsgWithdrawDelegatorRewards(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the withdraw delegator rewards message to amino JSON format - public toAmino() { - return { - type: this.isLegacy - ? 'distribution/MsgWithdrawDelegationReward' - : 'cosmos-sdk/MsgWithdrawDelegationReward', - value: { - validator_address: this.data.validatorAddress, - delegator_address: this.data.delegatorAddress, - }, - }; - } -} diff --git a/packages/es/src/client/models/MsgWithdrawValidatorCommission.ts b/packages/es/src/client/models/MsgWithdrawValidatorCommission.ts deleted file mode 100644 index 1b88d5f2f..000000000 --- a/packages/es/src/client/models/MsgWithdrawValidatorCommission.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -// TODO: CosmosDistributionV1beta1MsgWithdrawValidatorCommission not available in protobufs -// import { CosmosDistributionV1beta1MsgWithdrawValidatorCommission as ProtoMsgWithdrawValidatorCommission } from "@sonr.io/es/protobufs"; -type ProtoMsgWithdrawValidatorCommission = any; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify>; - -export class MsgWithdrawValidatorCommission implements Adapter { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - // TODO: Implement toProto() method when CosmosDistributionV1beta1MsgWithdrawValidatorCommission protobuf is available - // This method should create and return a proper ProtoMsgWithdrawValidatorCommission instance with this.data - // Currently returns empty object due to missing protobuf definition - public toProto(): any { - // TODO: Implement when ProtoMsgWithdrawValidatorCommission is available - // throw new Error("MsgWithdrawValidatorCommission not implemented - missing protobuf definition"); - // return new ProtoMsgWithdrawValidatorCommission(this.data); - return {} as any; - } - - // TODO: Verify toAmino() implementation against latest Cosmos SDK amino encoding standards - // This method converts the withdraw validator commission message to amino JSON format - public toAmino() { - return { - type: 'cosmos-sdk/MsgWithdrawValidatorCommission', - value: { - validator_address: this.data.validatorAddress, - }, - }; - } -} diff --git a/packages/es/src/client/models/Secp256k1PubKey.ts b/packages/es/src/client/models/Secp256k1PubKey.ts deleted file mode 100644 index 9cb3ffde2..000000000 --- a/packages/es/src/client/models/Secp256k1PubKey.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -import { base64 } from '@sonr.io/es/codec'; -import { - EthermintCryptoV1Ethsecp256k1PubKey as ProtoEthermintSecp256k1PubKey, - CosmosCryptoSecp256k1PubKey as ProtoSecp256k1PubKey, -} from '@sonr.io/es/protobufs'; - -import type { DeepPrettify } from '../../typeutils/prettify'; -import type { Adapter } from './Adapter'; - -type Data = DeepPrettify< - { - chainId?: string | undefined; - } & PlainMessage ->; - -export class Secp256k1PubKey implements Adapter { - private readonly data: Data; - private readonly type: string; - - constructor(data: Data) { - this.data = data; - this.type = data.chainId?.split(/[-_]/, 2).at(0) ?? ''; - } - - public toProto() { - const isEthermintChain = - this.type === 'dymension' || this.type === 'evmos' || this.type === 'injective'; - return isEthermintChain - ? new ProtoEthermintSecp256k1PubKey(this.data) - : new ProtoSecp256k1PubKey(this.data); - } - - public toAmino() { - const isEthermintChain = - this.type === 'dymension' || this.type === 'evmos' || this.type === 'injective'; - - return { - type: isEthermintChain ? 'ethermint/PubKeyEthSecp256k1' : 'tendermint/PubKeySecp256k1', - value: { - key: base64.encode(this.data.key), - }, - }; - } -} diff --git a/packages/es/src/client/models/Tx.ts b/packages/es/src/client/models/Tx.ts deleted file mode 100644 index e7366d421..000000000 --- a/packages/es/src/client/models/Tx.ts +++ /dev/null @@ -1,208 +0,0 @@ -import type { Message, PlainMessage } from '@bufbuild/protobuf'; -import { base64 } from '@scure/base'; -import { - CosmosTxV1beta1AuthInfo as ProtoAuthInfo, - CosmosTxV1beta1Fee as ProtoFee, - CosmosTxV1beta1SignDoc as ProtoSignDoc, - CosmosTxSigningV1beta1SignMode as ProtoSignMode, - type CosmosTxV1beta1SignerInfo as ProtoSignerInfo, - CosmosTxV1beta1TxBody as ProtoTxBody, - CosmosTxV1beta1TxRaw as ProtoTxRaw, -} from '@sonr.io/es/protobufs'; -import type { SignDoc, StdSignDoc } from '@sonr.io/es/registry'; - -import { toAny } from '../utils/toAny'; -import type { Adapter } from './Adapter'; -import type { Secp256k1PubKey } from './Secp256k1PubKey'; - -type Data = { - chainId: string; - pubKey: Secp256k1PubKey; - msgs: Adapter[]; -}; - -export type ToSignedProtoParams = { - sequence: bigint; - fee: ProtoFee; - signMode: ProtoSignMode; - signature: Uint8Array; - memo?: string | undefined; - timeoutHeight?: bigint | undefined; - extensionOptions?: Message[] | undefined; -}; - -export type ToUnsignedProtoParams = Pick< - ToSignedProtoParams, - 'sequence' | 'memo' | 'timeoutHeight' ->; - -export type ToSignDocParams = { - accountNumber: bigint; - sequence: bigint; - fee: ProtoFee; - memo?: string | undefined; - timeoutHeight?: bigint | undefined; -}; - -export type ToStdSignDocParams = ToSignDocParams; - -export class Tx { - private readonly data: Data; - - constructor(data: Data) { - this.data = data; - } - - /** - * Returns the signed, proto-encoded tx, ready to be broadcasted. To create an - * unsigned tx for the purpose of simulating it, use {@link toUnsignedProto}. - */ - public toSignedProto({ - fee, - sequence, - signMode, - signature, - memo, - timeoutHeight, - extensionOptions, - }: ToSignedProtoParams): ProtoTxRaw { - return new ProtoTxRaw({ - authInfoBytes: new ProtoAuthInfo({ - fee: fee, - signerInfos: [this.getSignerInfo(sequence, signMode)], - }).toBinary() as any, - bodyBytes: new ProtoTxBody({ - messages: this.data.msgs.map((m) => toAny(m.toProto())), - memo: memo, - timeoutHeight: timeoutHeight, - extensionOptions: extensionOptions?.map(toAny), - }).toBinary() as any, - signatures: [signature], - }); - } - - /** - * Returns the proto-encoded tx with the sign mode set to `UNSPECIFIED`, useful - * for simulating the tx. To create a signed tx, use {@link toSignedProto}. - */ - public toUnsignedProto(info: ToUnsignedProtoParams): ProtoTxRaw { - return this.toSignedProto({ - ...info, - fee: new ProtoFee(), - signMode: ProtoSignMode.UNSPECIFIED, - signature: new Uint8Array(), - }); - } - - /** - * Combines the given `StdSignDoc` and `signature` and returns the proto-encoded - * tx with sign mode set to `LEGACY_AMINO_JSON`, ready to be broadcasted. - * - * @param signature Must be a base64 encoded string or an `Uint8Array` - */ - public toSignedAmino( - { sequence, fee, memo, timeout_height }: StdSignDoc, - signature: string | Uint8Array - ): ProtoTxRaw { - return this.toSignedProto({ - sequence: BigInt(sequence), - fee: new ProtoFee({ - amount: fee.amount.slice(), - gasLimit: BigInt(fee.gas), - payer: fee.payer, - granter: fee.granter, - }), - signMode: ProtoSignMode.LEGACY_AMINO_JSON, - signature: typeof signature === 'string' ? base64.decode(signature) : signature, - memo: memo, - timeoutHeight: timeout_height ? BigInt(timeout_height) : undefined, - }); - } - - /** - * Combines the given `SignDoc` and `signature` and returns the proto-encoded tx, - * ready to be broadcasted. - * - * @param signature Must be a base64 encoded string or an `Uint8Array` - */ - public toSignedDirect( - { bodyBytes, authInfoBytes }: SignDoc, - signature: string | Uint8Array - ): ProtoTxRaw { - return new ProtoTxRaw({ - authInfoBytes: authInfoBytes as any, - bodyBytes: bodyBytes as any, - signatures: [typeof signature === 'string' ? base64.decode(signature) : signature], - }); - } - - /** - * Returns the unsigned, proto-encoded tx ready to be signed by a wallet. - */ - public toSignDoc({ - accountNumber, - sequence, - fee, - memo, - timeoutHeight, - }: ToSignDocParams): ProtoSignDoc { - return new ProtoSignDoc({ - chainId: this.data.chainId, - accountNumber: accountNumber, - authInfoBytes: new ProtoAuthInfo({ - fee: fee, - signerInfos: [this.getSignerInfo(sequence, ProtoSignMode.DIRECT)], - }).toBinary() as any, - bodyBytes: new ProtoTxBody({ - messages: this.data.msgs.map((m) => toAny(m.toProto())), - memo: memo, - timeoutHeight: timeoutHeight, - }).toBinary() as any, - }); - } - - /** - * Returns the unsigned, amino-encoded tx ready to be signed by a wallet. - */ - public toStdSignDoc({ - accountNumber, - sequence, - fee, - memo, - timeoutHeight, - }: ToStdSignDocParams): StdSignDoc { - return { - chain_id: this.data.chainId, - account_number: accountNumber.toString(), - sequence: sequence.toString(), - fee: { - amount: fee.amount, - gas: fee.gasLimit.toString(), - }, - msgs: this.data.msgs.map((m) => m.toAmino()), - memo: memo ?? '', - timeout_height: timeoutHeight?.toString(), - }; - } - - /** - * Returns the signer info. The chain ID is used to determine if the public key - * should be encoded using Injective's custom protobuf. - * - * **Warning**: Injective's chain ID might change, causing potential issues here. - */ - private getSignerInfo(sequence: bigint, mode: ProtoSignMode): PlainMessage { - return { - publicKey: toAny(this.data.pubKey.toProto()), - sequence: sequence, - modeInfo: { - sum: { - case: 'single', - value: { - mode: mode, - }, - }, - }, - }; - } -} diff --git a/packages/es/src/client/utils/calculateFee.ts b/packages/es/src/client/utils/calculateFee.ts deleted file mode 100644 index 257a52803..000000000 --- a/packages/es/src/client/utils/calculateFee.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { - type CosmosBaseV1beta1Coin as Coin, - CosmosTxV1beta1Fee as Fee, - type CosmosBaseAbciV1beta1GasInfo as GasInfo, -} from '@sonr.io/es/protobufs'; - -/** - * Estimates the fee for a transaction. For txs which uses more gas, the - * `multiplier` can be decreased (default: `1.4`). - */ -export function calculateFee({ gasUsed }: GasInfo, { amount, denom }: Coin, multiplier = 1.4): Fee { - const gasLimit = Number(gasUsed) * multiplier; - return new Fee({ - amount: [ - { - amount: Math.ceil(gasLimit * Number(amount)).toFixed(0), - denom: denom, - }, - ], - gasLimit: BigInt(Math.floor(gasLimit)), - }); -} diff --git a/packages/es/src/client/utils/toAny.ts b/packages/es/src/client/utils/toAny.ts deleted file mode 100644 index e0f73acdf..000000000 --- a/packages/es/src/client/utils/toAny.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Any, type Message } from '@bufbuild/protobuf'; - -export function toAny(msg: Message): Any { - return new Any({ - typeUrl: `/${msg.getType().typeName}`, - value: msg.toBinary(), - }); -} diff --git a/packages/es/src/client/utils/toBaseAccount.ts b/packages/es/src/client/utils/toBaseAccount.ts deleted file mode 100644 index e17880d6e..000000000 --- a/packages/es/src/client/utils/toBaseAccount.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { Any } from '@bufbuild/protobuf'; -import { - EthermintTypesV1EthAccount as EthermintAccount, - IbcApplicationsInterchainAccountsV1InterchainAccount as InterchainAccount, -} from '@sonr.io/es/protobufs'; - -const ERR_UNKNOWN_ACCOUNT_TYPE = 'Unknown account type'; -const ERR_UNABLE_TO_RESOLVE_BASE_ACCOUNT = 'Unable to resolve base account'; - -// Type definition for BaseAccount - this should match the cosmos auth BaseAccount structure -type BaseAccount = { - address: string; - pubKey?: any; - accountNumber: bigint; - sequence: bigint; -}; - -/** - * Parses an `Any` protobuf message and returns the `BaseAccount`. Throws if unable - * to parse correctly. - * - * NOTE: This function currently supports only the account types available in the - * current protobufs. Missing types that should be added when protobufs are updated: - * - cosmos.auth.v1beta1.BaseAccount - * - cosmos.vesting.v1beta1.BaseVestingAccount - * - cosmos.vesting.v1beta1.ContinuousVestingAccount - * - cosmos.vesting.v1beta1.DelayedVestingAccount - * - cosmos.vesting.v1beta1.PeriodicVestingAccount - * - cosmos.auth.v1beta1.ModuleAccount - * - cosmos.vesting.v1beta1.PermanentLockedAccount - */ -export function toBaseAccount({ typeUrl, value }: Any): BaseAccount { - switch (typeUrl.slice(1)) { - case EthermintAccount.typeName: { - const { baseAccount } = EthermintAccount.fromBinary(value); - if (!baseAccount) { - throw new Error(ERR_UNABLE_TO_RESOLVE_BASE_ACCOUNT); - } - return baseAccount; - } - case InterchainAccount.typeName: { - const { baseAccount } = InterchainAccount.fromBinary(value); - if (!baseAccount) { - throw new Error(ERR_UNABLE_TO_RESOLVE_BASE_ACCOUNT); - } - return baseAccount; - } - default: { - throw new Error(`${ERR_UNKNOWN_ACCOUNT_TYPE}: ${typeUrl.slice(1)}`); - } - } -} diff --git a/packages/es/src/client/utils/wait.ts b/packages/es/src/client/utils/wait.ts deleted file mode 100644 index 9b98a392d..000000000 --- a/packages/es/src/client/utils/wait.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Synchronously waits for the given number of `milliseconds`. - */ -export async function wait(milliseconds: number) { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); -} diff --git a/packages/es/src/codec/address.test.ts b/packages/es/src/codec/address.test.ts deleted file mode 100644 index 34863c42a..000000000 --- a/packages/es/src/codec/address.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { resolveBech32Address, translateEthToBech32Address } from './address'; - -const PUB_KEY_1 = 'A6Y9fcWSn5Av/HLHBwthTaVE/vdyRKvsTzi5U7j9bFj5'; // random pub key -const PUB_KEY_2 = 'Ag/a1BOl3cdwh67Z8iCbGmAu4WWmBwtuQlQMbDaN385V'; // coinhall.org val pubkey -const PUB_KEY_3 = 'AmGjuPKUsuIAuGgJ3xH7KGWlSU9cwVnsesrwWwyYLbMg'; // random pub key - -const ETH_ADDRESS_1 = '0xd6E80d86483C0cF463E03cC95246bDc0FeF6cfbD'; // random eth address - -describe('resolveBech32Address', () => { - it('should resolve stars address correctly', () => { - const translated = resolveBech32Address(PUB_KEY_1, 'stars'); - expect(translated).toBe('stars14y420auq56p6xgt78sl8vwz3jxy77r9cuw900r'); - }); - - it('should resolve cosmos address correctly', () => { - const translated = resolveBech32Address(PUB_KEY_1, 'cosmos'); - expect(translated).toBe('cosmos14y420auq56p6xgt78sl8vwz3jxy77r9cgjjjyj'); - }); - - it('should resolve terra address correctly', () => { - const translated = resolveBech32Address(PUB_KEY_2, 'terra'); - expect(translated).toBe('terra1ge3vqn6cjkk2xkfwpg5ussjwxvahs2f6aytr5j'); - }); - - it('should resolve terravaloper address correctly', () => { - const translated = resolveBech32Address(PUB_KEY_2, 'terravaloper'); - expect(translated).toBe('terravaloper1ge3vqn6cjkk2xkfwpg5ussjwxvahs2f6at87yp'); - }); - - it('should resolve ethsecp256k1 type address correctly', () => { - const translated = resolveBech32Address(PUB_KEY_3, 'inj', 'ethsecp256k1'); - expect(translated).toBe('inj1ys3hr2a6sn3wwqsmmrk8pgrvk58e8wrn6zn44m'); - }); -}); - -describe('translateEthToBech32Address', () => { - it('should translate eth address correctly', () => { - const translated = translateEthToBech32Address(ETH_ADDRESS_1, 'inj'); - expect(translated).toBe('inj16m5qmpjg8sx0gclq8ny4y34acrl0dnaantdev0'); - }); -}); diff --git a/packages/es/src/codec/address.ts b/packages/es/src/codec/address.ts deleted file mode 100644 index b06ceb13c..000000000 --- a/packages/es/src/codec/address.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { ripemd160 } from '@noble/hashes/ripemd160'; -import { keccak_256 } from '@noble/hashes/sha3'; -import { sha256 } from '@noble/hashes/sha256'; -import { ProjectivePoint } from '@noble/secp256k1'; -import { base64, bech32 } from '@scure/base'; - -import { ethhex } from './ethhex'; - -/** - * Returns the bech32 address from the given `publicKey` and `prefix`. If needed, - * the `type` of the key should be appropriately set. - * - * @param publicKey Must be either a base64 encoded string or a `Uint8Array`. - */ -export function resolveBech32Address( - publicKey: string | Uint8Array, - prefix: string, - type: 'secp256k1' | 'ed25519' | 'ethsecp256k1' = 'secp256k1' -): string { - const pubKey = typeof publicKey === 'string' ? base64.decode(publicKey) : publicKey; - const address = - type === 'secp256k1' - ? // For cosmos: take the ripemd160 of the sha256 of the public key - ripemd160(sha256(pubKey)) - : type === 'ed25519' - ? // For cosmos: take the first 20 bytes of the sha256 of the public key - sha256(pubKey).slice(0, 20) - : // For eth: take the last 20 bytes of the keccak of the uncompressed public key without the first byte - keccak_256(ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1)).slice(-20); - return bech32.encode(prefix, bech32.toWords(address)); -} - -/** - * Translates the given ethereum address to a bech32 address. - * @param ethAddress Must be a valid ethereum address (eg. `0x123...DeF`). - */ -export function translateEthToBech32Address(ethAddress: string, prefix: string) { - const bytes = ethhex.decode(ethAddress); - return bech32.encode(prefix, bech32.toWords(bytes)); -} diff --git a/packages/es/src/codec/ethhex.ts b/packages/es/src/codec/ethhex.ts deleted file mode 100644 index 8ca1865b5..000000000 --- a/packages/es/src/codec/ethhex.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { type BytesCoder, hex } from '@scure/base'; - -/** - * Convenience wrapper around `hex` that deals with hex strings typically - * seen in Ethereum, where strings start with `0x` and are lower case. - * - * - For `encode`, the resulting string will be lower case - * - For `decode`, the `str` arg can either be lower or upper case - */ -export const ethhex = { - encode: (bytes) => `0x${hex.encode(bytes)}`, - decode: (str) => hex.decode(str.replace(/^0x/, '').toLowerCase()), -} satisfies BytesCoder; diff --git a/packages/es/src/codec/index.ts b/packages/es/src/codec/index.ts deleted file mode 100644 index 5ff0e5260..000000000 --- a/packages/es/src/codec/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Re-export @scure/base for their codecs -export * from '@scure/base'; - -export { resolveBech32Address, translateEthToBech32Address } from './address'; -export { ethhex } from './ethhex'; -export { resolveKeyPair } from './key'; -export { serialiseSignDoc } from './serialise'; -export { - hashEthArbitraryMessage, - recoverPubKeyFromEthSignature, - signAmino, - signDirect, -} from './sign'; -export { verifyADR36, verifyECDSA, verifyEIP191 } from './verify'; diff --git a/packages/es/src/codec/key.test.ts b/packages/es/src/codec/key.test.ts deleted file mode 100644 index 60f97a32e..000000000 --- a/packages/es/src/codec/key.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { base64 } from '@scure/base'; -import { describe, expect, it } from 'vitest'; - -import { resolveKeyPair } from './key'; - -// Randomly generated seed phrase -const SEED_PHRASE_1 = - 'witness snack faint milk gesture memory exhibit oak require mountain hammer crawl innocent day library drum youth result mutual remove capable hour front connect'; - -describe('resolveKeyPair', () => { - it('should resolve 118 coin type correctly', () => { - const { publicKey, privateKey } = resolveKeyPair(SEED_PHRASE_1); - expect(base64.encode(publicKey)).toBe('AijdjMWZdjiXxSj0YCNbJHgnW6EsYwNyB9Yf7Wg5PcmE'); - expect(base64.encode(privateKey)).toBe('SojKJzJhFNruMSceBq3Imw3qZ+kS4p/6+iEpxdPsNg0='); - }); - - it('should resolve 330 coin type correctly', () => { - const { publicKey, privateKey } = resolveKeyPair(SEED_PHRASE_1, { - coinType: 330, - }); - expect(base64.encode(publicKey)).toBe('A5G4nX2MIYCsnEdm40NJx7Bb1Z+oUNbEWWcVMssrgI3n'); - expect(base64.encode(privateKey)).toBe('kpvZKN+f7oWhVLLLk1pmKOazycgfECinugqQZgKRlXg='); - }); - - it('should resolve provided index correctly', () => { - const { publicKey, privateKey } = resolveKeyPair(SEED_PHRASE_1, { - index: 69, - }); - expect(base64.encode(publicKey)).toBe('ArHwuHKnyiuPDbprTpWLVl3ZuomV70yzquzzlunGXlmj'); - expect(base64.encode(privateKey)).toBe('Fdm+CxL/KnM35bjDx/wg3eZc3tZN2q83I+xcY2wSMwk='); - }); -}); diff --git a/packages/es/src/codec/key.ts b/packages/es/src/codec/key.ts deleted file mode 100644 index d30ad2dd2..000000000 --- a/packages/es/src/codec/key.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { HDKey } from '@scure/bip32'; -import { mnemonicToSeedSync } from '@scure/bip39'; - -/** - * Resolves the given `mnemonic` (aka 12-24 words seed phrase) to its public and - * private key pair. Derivation path uses the default for Cosmos chains - provide - * the optional `opts` to override. - */ -export function resolveKeyPair( - mnemonic: string, - opts?: { coinType?: number | undefined; index?: number | undefined } | undefined -): { - publicKey: Uint8Array; - privateKey: Uint8Array; -} { - const seed = mnemonicToSeedSync(mnemonic); - const { publicKey, privateKey } = HDKey.fromMasterSeed(seed).derive( - `m/44'/${opts?.coinType ?? 118}'/0'/0/${opts?.index ?? 0}` - ); - if (!publicKey || !privateKey) { - throw new Error('invalid mnemonic'); - } - return { - publicKey, - privateKey, - }; -} diff --git a/packages/es/src/codec/serialise.test.ts b/packages/es/src/codec/serialise.test.ts deleted file mode 100644 index 8a637f2f1..000000000 --- a/packages/es/src/codec/serialise.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { sortObjectByKey } from './serialise'; - -describe('sortObjectByKey', () => { - it('should sort keys correctly', () => { - const obj = { - zzz: 1, - aaa: 1, - xxx: null, - bbb: { - ttt: { - ppp: true, - iii: undefined, - lll: '1', - }, - ddd: [4, 8, 3, undefined, 4, 5, 7, 8], - }, - }; - const expected = { - aaa: 1, - bbb: { - ddd: [4, 8, 3, undefined, 4, 5, 7, 8], // arrays are not sorted - ttt: { - iii: undefined, - lll: '1', - ppp: true, - }, - }, - xxx: null, - zzz: 1, - }; - // Before sorting, the stringified versions of the objects should NOT be equal - expect(JSON.stringify(obj)).not.toBe(JSON.stringify(expected)); - // After sorting, the stringified versions of the objects should be equal - expect(JSON.stringify(sortObjectByKey(obj))).toBe(JSON.stringify(expected)); - }); -}); diff --git a/packages/es/src/codec/serialise.ts b/packages/es/src/codec/serialise.ts deleted file mode 100644 index b545932f7..000000000 --- a/packages/es/src/codec/serialise.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { utf8 } from '@scure/base'; -import type { StdSignDoc } from '@sonr.io/es/registry'; - -/** - * Escapes <,>,& in string. - * Golang's json marshaller escapes <,>,& by default. - * However, because JS doesn't do that by default, to match the sign doc with cosmos-sdk, - * we should escape <,>,& in string manually. - * @param str - */ -function escapeHtml(str: string): string { - return str.replace(//g, '\\u003e').replace(/&/g, '\\u0026'); -} - -export function sortObjectByKey(obj: T): T { - if (typeof obj !== 'object' || obj == null) { - return obj; - } - if (Array.isArray(obj)) { - return obj.map(sortObjectByKey) as T; - } - const sortedKeys = Object.keys(obj).sort(); - const result: Record = {}; - for (const key of sortedKeys) { - result[key] = sortObjectByKey((obj as Record)[key]); - } - return result as T; -} - -/** - * Serialises the given sign doc to a `Uint8Array` in a deterministic manner. - */ -export function serialiseSignDoc(doc: StdSignDoc): Uint8Array { - return utf8.decode(escapeHtml(JSON.stringify(sortObjectByKey(doc)))); -} diff --git a/packages/es/src/codec/sign.test.ts b/packages/es/src/codec/sign.test.ts deleted file mode 100644 index 57c146f4e..000000000 --- a/packages/es/src/codec/sign.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { StdSignDoc } from '@keplr-wallet/types'; -import { base16, base64, utf8 } from '@scure/base'; -import { describe, expect, it } from 'vitest'; - -import { ethhex } from './ethhex'; -import { hashEthArbitraryMessage, recoverPubKeyFromEthSignature, signAmino } from './sign'; - -describe('signAmino', () => { - it('should sign Injective txs correctly', () => { - const stdSignDoc: StdSignDoc = { - chain_id: '', - account_number: '0', - sequence: '0', - fee: { - gas: '0', - amount: [], - }, - msgs: [ - { - type: 'sign/MsgSignData', - value: { - signer: 'inj1l8w4vvmhcku28ryntpeazm37umshetzzl2gc33', - data: base64.encode( - utf8.decode( - 'Hi from CosmeES! This is a test message just to prove that the wallet is working.' - ) - ), - }, - }, - ], - memo: '', - }; - const privKey = base64.decode('o5di+2p2NdLgRYLtBIhJl9gsB9FWll8wKBaep3CmbI0='); - const expected = // Signature taken from keplr signArbitrary - 'qrkZpuo1jpfXgbF3TtBtdR7DynE1nV3xd//bsGXm2FkS08waXeiJJ+FAvdtt9hvStyP/wGae07hxnyYPHEw+Uw=='; - const actual = base64.encode(signAmino(stdSignDoc, privKey, 'ethsecp256k1')); - expect(actual).toStrictEqual(expected); - }); -}); - -describe('hashEthArbitraryMessage', () => { - it('should hash correctly', () => { - const msg = utf8.decode('Hello World!'); - const expected = hashEthArbitraryMessage(msg); - const actual = ethhex.decode( - '0xec3608877ecbf8084c29896b7eab2a368b2b3c8d003288584d145613dfa4706c' - ); - expect(actual).toStrictEqual(expected); - }); -}); - -describe('recoverPubKeyFromEthSignature', () => { - it('should recover public key correctly from a personal_sign signature', () => { - const message = utf8.decode('Hello World'); - const signature = ethhex.decode( - '0x63da4222cbcc36f43b22cbe417aa78963c29d088f7db3c9c6d06417dc34cf2df2dc6ffe9a5c9072a12a16a71c93bebf42bf388357aff81190d7dce166e4fa7ad1c' - ); - const expected = base16.decode( - '03f73842e6959e5b79f7979f81016e1e4f4d9481a7351a492ddb0807d98bb31f19'.toUpperCase() - ); - const actual = recoverPubKeyFromEthSignature(message, signature); - expect(expected).toStrictEqual(actual); - }); -}); diff --git a/packages/es/src/codec/sign.ts b/packages/es/src/codec/sign.ts deleted file mode 100644 index f7bee7647..000000000 --- a/packages/es/src/codec/sign.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { hmac } from '@noble/hashes/hmac'; -import { keccak_256 } from '@noble/hashes/sha3'; -import { sha256 } from '@noble/hashes/sha256'; -import * as secp256k1 from '@noble/secp256k1'; -import { utf8 } from '@scure/base'; -import type { CosmosTxV1beta1SignDoc as SignDoc } from '@sonr.io/es/protobufs'; -import type { StdSignDoc } from '@sonr.io/es/registry'; - -import { serialiseSignDoc } from './serialise'; - -function sign( - bytes: Uint8Array, - privateKey: Uint8Array, - type: 'secp256k1' | 'ethsecp256k1' -): Uint8Array { - // Required polyfills for secp256k1 that must be called before any sign ops. - // See: https://github.com/paulmillr/noble-secp256k1?tab=readme-ov-file#usage - secp256k1.etc.hmacSha256Sync = (k, ...m) => hmac(sha256, k, secp256k1.etc.concatBytes(...m)); - const hash = type === 'secp256k1' ? sha256(bytes) : keccak_256(bytes); - return secp256k1.sign(hash, privateKey).toCompactRawBytes(); -} - -/** - * Signs the given amino-encoded `stdSignDoc` with the given `privateKey` using - * secp256k1, and returns the signature bytes. For Injective, the `type` param - * must be set to `ethsecp256k1`. - */ -export function signAmino( - stdSignDoc: StdSignDoc, - privateKey: Uint8Array, - type: 'secp256k1' | 'ethsecp256k1' = 'secp256k1' -): Uint8Array { - return sign(serialiseSignDoc(stdSignDoc), privateKey, type); -} - -/** - * Signs the given proto-encoded `signDoc` with the given `privateKey` using - * secp256k1, and returns the signature bytes. For Injective, the `type` param - * must be set to `ethsecp256k1`. - */ -export function signDirect( - signDoc: SignDoc, - privateKey: Uint8Array, - type: 'secp256k1' | 'ethsecp256k1' = 'secp256k1' -): Uint8Array { - return sign(signDoc.toBinary(), privateKey, type); -} - -/** - * Hashes and returns the digest of the given EIP191 `message` bytes. - */ -export function hashEthArbitraryMessage(message: Uint8Array): Uint8Array { - return keccak_256( - Uint8Array.from([ - ...utf8.decode('\x19Ethereum Signed Message:\n'), - ...utf8.decode(message.length.toString()), - ...message, - ]) - ); -} - -/** - * Recovers and returns the secp256k1 public key of the signer given the arbitrary - * `message` and `signature` that was signed using EIP191. - */ -export function recoverPubKeyFromEthSignature( - message: Uint8Array, - signature: Uint8Array -): Uint8Array { - if (signature.length !== 65) { - throw new Error('Invalid signature'); - } - const r = signature.slice(0, 32); - const s = signature.slice(32, 64); - const v = signature[64]; - // Adapted from https://github.com/ethers-io/ethers.js/blob/6017d3d39a4d428793bddae33d82fd814cacd878/src.ts/crypto/signature.ts#L255-L265 - const yParity = v <= 1 ? v : (v + 1) % 2; - const secpSignature = secp256k1.Signature.fromCompact( - Uint8Array.from([...r, ...s]) - ).addRecoveryBit(yParity); - const digest = hashEthArbitraryMessage(message); - return secpSignature.recoverPublicKey(digest).toRawBytes(true); -} diff --git a/packages/es/src/codec/verify.test.ts b/packages/es/src/codec/verify.test.ts deleted file mode 100644 index 822667634..000000000 --- a/packages/es/src/codec/verify.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { base64, utf8 } from '@scure/base'; -import { describe, expect, it } from 'vitest'; - -import { verifyADR36, verifyECDSA, verifyEIP191 } from './verify'; - -const DATA = utf8.decode( - 'Hi from CosmeES! This is a test message just to prove that the wallet is working.' -); -// Generated using coin type "330" and seed phrase "poverty flat amazing draw goose clay sorry nothing erase switch law intact only invest find memory what weasel fan connect tilt detect trap viable" -const VALID_PUBKEY_1 = base64.decode('Ai7ZXTtRWFte/tX7Z6MlKWVd9XA49p3cDNqd61RuKTdT'); -// Generated using coin type "118" and seed phrase "poverty flat amazing draw goose clay sorry nothing erase switch law intact only invest find memory what weasel fan connect tilt detect trap viable" -const VALID_PUBKEY_2 = base64.decode('A8i9vMNUGcTtUgpbmiZqcFtsIrPZ6n8ZYN4/PVRlQvGr'); -// Generated using coin type "60" and seed phrase "poverty flat amazing draw goose clay sorry nothing erase switch law intact only invest find memory what weasel fan connect tilt detect trap viable" -const VALID_PUBKEY_3 = base64.decode('AmGjuPKUsuIAuGgJ3xH7KGWlSU9cwVnsesrwWwyYLbMg'); - -describe('verifyECDSA', () => { - it('should verify correctly', () => { - // Signed using Station wallet on Terra - const signature = base64.decode( - 'Od87qNoOyXuDOVdLCGTXB6dFN7U0XF9Oegc8KDa+AWwX3jkrDXG++2nlPfsF4VJzlDHsoikPeZpxrB7v9PINnw==' - ); - const res1 = verifyECDSA({ - pubKey: VALID_PUBKEY_1, - data: DATA, - signature, - }); - expect(res1).toBe(true); - - // Different pub key - const res2 = verifyECDSA({ - pubKey: VALID_PUBKEY_2, - data: DATA, - signature, - }); - expect(res2).toBe(false); - }); -}); - -describe('verifyADR36', () => { - it('should verify correctly', () => { - // Signed using Keplr wallet on Osmosis - const signature = base64.decode( - 'nvlcV0x0Ge8ADXLSAQGtfMw6EJkOfpmkDxgP7UI79uR8MhnAOp9T+e+ofgW9kY4bEIr0yhyBG+vSVAZRv9uCxA==' - ); - const res1 = verifyADR36({ - bech32Prefix: 'osmo', - pubKey: VALID_PUBKEY_2, - data: DATA, - signature, - }); - expect(res1).toBe(true); - - // Different bech32 prefix - const res2 = verifyADR36({ - bech32Prefix: 'terra', - pubKey: VALID_PUBKEY_2, - data: DATA, - signature, - }); - expect(res2).toBe(false); - - // Different pub key - const res3 = verifyADR36({ - bech32Prefix: 'osmo', - pubKey: VALID_PUBKEY_1, - data: DATA, - signature, - }); - expect(res3).toBe(false); - }); - - it('should verify ethsecp256k1 type signatures correctly', () => { - // Signed using Keplr wallet on Injective - const signature = base64.decode( - '+7PNZm4XxKtpvZA+HqxpMKJgZcqA2w3WVSheLGvzrrIBJZGOTdcpBT7wLUhluY46EokTeRRWUaBDSv2vVoEdfw==' - ); - const res1 = verifyADR36({ - bech32Prefix: 'inj', - pubKey: VALID_PUBKEY_3, - data: DATA, - signature, - type: 'ethsecp256k1', - }); - expect(res1).toBe(true); - }); -}); - -describe('verifyEIP191', () => { - it('should verify correctly', () => { - // Signed using MetaMask wallet on Injective - const signature = base64.decode( - 'MpriWY0Kq7C+/jR3eOfNB5vUQM144tQk7KkzKyYCTFB5QHGLZjzJyeOSr8/ENFES0k+aaEF47Wepk7OHoZuLzxs=' - ); - const res1 = verifyEIP191({ - pubKey: VALID_PUBKEY_3, - data: DATA, - signature, - }); - expect(res1).toBe(true); - - // Different pub key - const res2 = verifyEIP191({ - pubKey: VALID_PUBKEY_2, - data: DATA, - signature, - }); - expect(res2).toBe(false); - }); -}); diff --git a/packages/es/src/codec/verify.ts b/packages/es/src/codec/verify.ts deleted file mode 100644 index 8c7a76d94..000000000 --- a/packages/es/src/codec/verify.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { keccak_256 } from '@noble/hashes/sha3'; -import { sha256 } from '@noble/hashes/sha256'; -import * as secp256k1 from '@noble/secp256k1'; -import { base64 } from '@scure/base'; - -import { resolveBech32Address } from './address'; -import { serialiseSignDoc } from './serialise'; -import { recoverPubKeyFromEthSignature } from './sign'; - -type VerifyArbitraryParams = { - /** The public key which created the signature */ - pubKey: Uint8Array; - /** The bech32 account address prefix of the signer */ - bech32Prefix: string; - /** The arbitrary bytes that was signed */ - data: Uint8Array; - /** The signature bytes */ - signature: Uint8Array; - /** The type of the signature */ - type?: 'secp256k1' | 'ethsecp256k1'; -}; - -export function verifyECDSA({ - pubKey, - data, - signature, - type, -}: Omit): boolean { - return secp256k1.verify( - signature, - type === 'ethsecp256k1' ? keccak_256(data) : sha256(data), - pubKey - ); -} - -export function verifyADR36({ - pubKey, - bech32Prefix, - data, - signature, - type, -}: VerifyArbitraryParams): boolean { - const msg = serialiseSignDoc({ - chain_id: '', - account_number: '0', - sequence: '0', - fee: { - gas: '0', - amount: [], - }, - msgs: [ - { - type: 'sign/MsgSignData', - value: { - signer: resolveBech32Address(pubKey, bech32Prefix, type), - data: base64.encode(data), - }, - }, - ], - memo: '', - }); - return verifyECDSA({ - pubKey, - data: msg, - signature, - type, - }); -} - -export function verifyEIP191({ - pubKey, - data, - signature, -}: Omit): boolean { - const recoveredPubKey = recoverPubKeyFromEthSignature(data, signature); - return ( - pubKey.length === recoveredPubKey.length && pubKey.every((v, i) => v === recoveredPubKey[i]) - ); -} diff --git a/packages/es/src/index.ts b/packages/es/src/index.ts deleted file mode 100644 index 52d27fda1..000000000 --- a/packages/es/src/index.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @sonr.io/es - Sonr ES Module - * Main entry point for browser/CDN usage - */ -// Motor Plugin - Service worker and WebAssembly runtime -// Re-export main interfaces and classes for convenience -export { - MotorPluginImpl, - createMotorPlugin, - createMotorPluginForNode, - createMotorPluginForBrowser, -} from './worker'; - -export { VaultClient, createVaultClient, getDefaultVaultClient } from './plugin'; - -// Re-export Motor types -export type { - MotorPlugin, - MotorPluginConfig, - MotorServiceWorkerConfig, - // Payment types - PaymentInstrument, - PaymentMethod, - PaymentDetails, - ProcessPaymentRequest, - ProcessPaymentResponse, - PaymentStatus, - // OIDC types - OIDCConfiguration, - OIDCTokenRequest, - OIDCTokenResponse, - OIDCUserInfo, -} from './worker'; - -// Re-export Service worker types -export type { - ServiceWorkerStatus, - EnvironmentInfo, - HealthCheckResponse, - ServiceInfoResponse, - ErrorResponse, -} from './worker'; - -// Re-export Vault types -export type { - VaultConfig, - VaultPlugin, - EnclaveData, - NewOriginTokenRequest, - NewAttenuatedTokenRequest, - UCANTokenResponse, - SignDataRequest, - SignDataResponse, - VerifyDataRequest, - VerifyDataResponse, - GetIssuerDIDResponse, -} from './plugin'; - -// Re-export error classes -export { VaultError, VaultErrorCode } from './plugin'; -// Re-export auth functions directly for CDN usage -export { - registerWithPasskey, - loginWithPasskey, - isWebAuthnSupported, - isWebAuthnAvailable, - isConditionalMediationAvailable, - bufferToBase64url, - base64urlToBuffer, -} from './client/auth/webauthn'; - -// Re-export client functionality -export * from './client'; - -// Re-export codec utilities -export * from './codec'; - -// Re-export wallet functionality (be selective to avoid conflicts) -export type { ChainInfo, ConnectedWallet, WalletType } from './wallet'; - -// Re-export registry -export * from './registry'; - -// Re-export protobufs -export * from './protobufs'; - -// Export IPFS services namespace -export * as ipfs from './client/services'; - -// Vault Plugin - MPC-based cryptographic vault -export * as vault from './plugin'; -export * as motor from './worker'; - diff --git a/packages/es/src/plugin/README.md b/packages/es/src/plugin/README.md deleted file mode 100644 index 1a1431c4e..000000000 --- a/packages/es/src/plugin/README.md +++ /dev/null @@ -1,224 +0,0 @@ -# Vault Plugin with Dexie.js Persistence - -The Vault plugin now supports persistent storage using Dexie.js (IndexedDB wrapper), allowing vault state and UCAN tokens to persist across browser sessions. - -## Features - -- 🔐 **Account-based database separation** - Each account has its own isolated database -- 💾 **Automatic persistence** - Tokens are automatically saved when created -- 🔄 **Cross-browser support** - Works with all modern browsers supporting IndexedDB -- ⚡ **Backward compatible** - Storage is opt-in, existing code continues to work -- 🧹 **Automatic cleanup** - Expired tokens and sessions are cleaned up periodically - -## Basic Usage - -### Without Persistence (Default Behavior) - -```typescript -import { createVaultClient } from '@sonr.io/es/plugins/vault'; - -// Create vault client without persistence (backward compatible) -const vault = createVaultClient(); - -// Initialize the vault -await vault.initialize(); - -// Use vault as before -const token = await vault.newOriginToken({ - audience_did: 'did:example:123', -}); -``` - -### With Persistence Enabled - -```typescript -import { createVaultClient } from '@sonr.io/es/plugins/vault'; - -// Create vault client with persistence enabled -const vault = createVaultClient({ - enablePersistence: true, - autoCleanup: true, - cleanupInterval: 3600000, // 1 hour -}); - -// Initialize with account address for database separation -const accountAddress = 'sonr1abc123...'; -await vault.initialize('/plugin.wasm', accountAddress); - -// Vault state and tokens are now automatically persisted -const token = await vault.newOriginToken({ - audience_did: 'did:example:123', -}); -// Token is automatically saved to IndexedDB - -// Retrieve all persisted tokens -const tokens = await vault.getPersistedTokens(); -console.log(`Found ${tokens.length} saved tokens`); -``` - -## Advanced Usage - -### Multi-Account Support - -```typescript -// Start with account 1 -await vault.initialize('/plugin.wasm', 'sonr1account1'); - -// Do some work... -const token1 = await vault.newOriginToken({ audience_did: 'did:1' }); - -// Switch to account 2 -await vault.switchAccount('sonr1account2'); - -// Work with account 2's isolated database -const token2 = await vault.newOriginToken({ audience_did: 'did:2' }); - -// List all accounts with persisted data -const accounts = await vault.listPersistedAccounts(); -console.log('Accounts with saved data:', accounts); - -// Remove an account's data -await vault.removeAccount('sonr1account1'); -``` - -### State Management - -```typescript -// Manually save current state -await vault.persistState(); - -// Load persisted state -const state = await vault.loadPersistedState(); -if (state) { - console.log('Vault initialized:', state.isInitialized); - console.log('Last accessed:', new Date(state.lastAccessed)); -} - -// Clear all persisted data for current account -await vault.clearPersistedState(); -``` - -### Token Management - -```typescript -// Manually save a token -await vault.saveToken({ - token: 'eyJ...', - issuer: 'did:sonr:123', - address: 'sonr1abc...', -}); - -// Get all saved tokens -const tokens = await vault.getPersistedTokens(); - -// Remove expired tokens -await vault.removeExpiredTokens(); -``` - -### Storage Persistence - -```typescript -import { VaultStorageManager } from '@sonr.io/es/plugins/vault'; - -const storageManager = new VaultStorageManager({ - enablePersistence: true, -}); - -// Request persistent storage (prompts user in some browsers) -const isPersisted = await storageManager.requestPersistentStorage(); -console.log('Storage persisted:', isPersisted); - -// Check persistence status -const status = await storageManager.tryPersistWithoutPromptingUser(); -// Returns: 'persisted' | 'prompt' | 'never' - -// Get storage estimate -const estimate = await storageManager.getStorageEstimate(); -if (estimate) { - console.log(`Using ${estimate.usage} of ${estimate.quota} bytes`); -} -``` - -## Configuration Options - -```typescript -interface VaultStorageConfig { - enablePersistence?: boolean; // Enable IndexedDB storage (default: false) - storageQuotaRequest?: number; // Storage quota to request in bytes - autoCleanup?: boolean; // Enable automatic cleanup (default: true) - cleanupInterval?: number; // Cleanup interval in ms (default: 3600000) -} -``` - -## Browser Compatibility - -- ✅ Chrome/Edge 23+ -- ✅ Firefox 16+ -- ✅ Safari 10+ -- ✅ Opera 15+ -- ✅ iOS Safari 10+ -- ✅ Chrome for Android - -## Storage Limits - -- **Chrome/Edge**: 60% of total disk space -- **Firefox**: 50% of free disk space -- **Safari**: 1GB initially, can request more -- **Mobile browsers**: Varies by device - -## Migration Guide - -### From Non-Persistent to Persistent - -```typescript -// Before (non-persistent) -const vault = createVaultClient(); -await vault.initialize(); - -// After (with persistence) -const vault = createVaultClient({ - enablePersistence: true, -}); -await vault.initialize('/plugin.wasm', accountAddress); -``` - -No other code changes required - all existing methods work the same way. - -## Security Considerations - -- Databases are named by account address for isolation -- No private keys or sensitive cryptographic material is stored -- Only UCAN tokens and metadata are persisted -- Use HTTPS in production for better storage persistence -- Consider encrypting sensitive data before storage - -## Troubleshooting - -### Storage Not Persisting - -1. Check if running on HTTPS (required for persistence in some browsers) -2. Verify IndexedDB is not disabled in browser settings -3. Check available storage quota -4. Try requesting persistent storage explicitly - -### Database Errors - -```typescript -try { - await vault.initialize('/plugin.wasm', accountAddress); -} catch (error) { - if (error.code === 'VAULT_NOT_INITIALIZED') { - // Handle initialization error - } -} -``` - -### Cleanup Issues - -If automatic cleanup is not working: - -```typescript -// Manually trigger cleanup -const storageManager = new VaultStorageManager(); -await storageManager.cleanupExpiredData(); -``` \ No newline at end of file diff --git a/packages/es/src/plugin/__tests__/enclave.test.ts b/packages/es/src/plugin/__tests__/enclave.test.ts deleted file mode 100644 index c814c6415..000000000 --- a/packages/es/src/plugin/__tests__/enclave.test.ts +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Unit tests for MPC enclave manager - */ - -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { EnclaveIPFSManager, createEnclaveIPFSManager } from '../enclave'; -import type { IPFSClient } from '../../../client/services/ipfs'; -import type { EnclaveDataWithCID } from '../enclave'; - -// Mock IPFS client -const mockIPFSClient: IPFSClient = { - initialize: vi.fn(), - addEnclaveData: vi.fn().mockResolvedValue({ - cid: 'QmTestCID123', - size: 100, - timestamp: Date.now(), - }), - getEnclaveData: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - verifiedFetch: vi.fn(), - pin: vi.fn(), - unpin: vi.fn(), - isPinned: vi.fn().mockResolvedValue(true), - listPins: vi.fn().mockResolvedValue(['QmCID1', 'QmCID2']), - getNodeStatus: vi.fn(), - isInitialized: vi.fn().mockReturnValue(true), - cleanup: vi.fn(), - addString: vi.fn(), - getString: vi.fn(), -} as any; - -describe('EnclaveIPFSManager', () => { - let manager: EnclaveIPFSManager; - const validEnclaveData: EnclaveDataWithCID = { - publicKey: 'public-key-123', - privateKeyShares: ['share1', 'share2', 'share3'], - threshold: 2, - parties: 3, - encryptionMetadata: { - algorithm: 'AES-256-GCM', - keyVersion: 1, - consensusHeight: 100, - nonce: 'test-nonce', - }, - }; - - beforeEach(() => { - vi.clearAllMocks(); - manager = new EnclaveIPFSManager(mockIPFSClient, { - encryptionRequired: true, - pinningEnabled: true, - redundancy: 3, - maxRetries: 2, - operationTimeout: 5000, - }); - }); - - describe('storeEnclaveData', () => { - it('should store encrypted enclave data', async () => { - const encryptedPayload = new Uint8Array([10, 20, 30]); - - const result = await manager.storeEnclaveData( - validEnclaveData, - encryptedPayload - ); - - expect(result.cid).toBe('QmTestCID123'); - expect(result.isPinned).toBe(true); - expect(result.size).toBe(100); - expect(mockIPFSClient.addEnclaveData).toHaveBeenCalledWith(encryptedPayload); - expect(mockIPFSClient.pin).toHaveBeenCalledWith('QmTestCID123'); - }); - - it('should require encryption metadata when encryption is required', async () => { - const dataWithoutMetadata: EnclaveDataWithCID = { - ...validEnclaveData, - encryptionMetadata: undefined, - }; - - await expect( - manager.storeEnclaveData(dataWithoutMetadata, new Uint8Array()) - ).rejects.toThrow('Encryption metadata required for enclave data storage'); - }); - - it('should validate enclave data structure', async () => { - const invalidData: EnclaveDataWithCID = { - ...validEnclaveData, - threshold: 5, // Invalid: threshold > parties - }; - - await expect( - manager.storeEnclaveData(invalidData, new Uint8Array()) - ).rejects.toThrow('Invalid threshold value'); - }); - - it('should retry on failure', async () => { - (mockIPFSClient.addEnclaveData as any) - .mockRejectedValueOnce(new Error('Network error')) - .mockResolvedValueOnce({ - cid: 'QmRetryCID', - size: 50, - timestamp: Date.now(), - }); - - const result = await manager.storeEnclaveData( - validEnclaveData, - new Uint8Array() - ); - - expect(result.cid).toBe('QmRetryCID'); - expect(mockIPFSClient.addEnclaveData).toHaveBeenCalledTimes(2); - }); - - it('should fail after max retries', async () => { - (mockIPFSClient.addEnclaveData as any).mockRejectedValue( - new Error('Persistent error') - ); - - await expect( - manager.storeEnclaveData(validEnclaveData, new Uint8Array()) - ).rejects.toThrow('Failed to store enclave data after 2 attempts'); - }); - }); - - describe('retrieveEnclaveData', () => { - it('should retrieve enclave data', async () => { - const data = await manager.retrieveEnclaveData('QmTestCID123'); - - expect(data).toBeInstanceOf(Uint8Array); - expect(Array.from(data)).toEqual([1, 2, 3, 4, 5]); - expect(mockIPFSClient.getEnclaveData).toHaveBeenCalledWith('QmTestCID123'); - }); - - it('should retry on failure', async () => { - (mockIPFSClient.getEnclaveData as any) - .mockRejectedValueOnce(new Error('Network error')) - .mockResolvedValueOnce(new Uint8Array([9, 8, 7])); - - const data = await manager.retrieveEnclaveData('QmTestCID123'); - - expect(Array.from(data)).toEqual([9, 8, 7]); - expect(mockIPFSClient.getEnclaveData).toHaveBeenCalledTimes(2); - }); - }); - - describe('verifyEnclaveDataIntegrity', () => { - it('should verify data integrity successfully', async () => { - const expectedData = new Uint8Array([1, 2, 3, 4, 5]); - (mockIPFSClient.getEnclaveData as any).mockResolvedValue(expectedData); - - const isValid = await manager.verifyEnclaveDataIntegrity( - 'QmTestCID123', - expectedData - ); - - expect(isValid).toBe(true); - }); - - it('should detect data mismatch', async () => { - const expectedData = new Uint8Array([1, 2, 3]); - const actualData = new Uint8Array([4, 5, 6]); - (mockIPFSClient.getEnclaveData as any).mockResolvedValue(actualData); - - const isValid = await manager.verifyEnclaveDataIntegrity( - 'QmTestCID123', - expectedData - ); - - expect(isValid).toBe(false); - }); - - it('should handle retrieval errors', async () => { - (mockIPFSClient.getEnclaveData as any).mockRejectedValue( - new Error('Retrieval failed') - ); - - const isValid = await manager.verifyEnclaveDataIntegrity( - 'QmTestCID123', - new Uint8Array() - ); - - expect(isValid).toBe(false); - }); - }); - - describe('batch operations', () => { - it('should batch store multiple enclaves', async () => { - const enclaves = [ - { data: validEnclaveData, payload: new Uint8Array([1, 2, 3]) }, - { data: validEnclaveData, payload: new Uint8Array([4, 5, 6]) }, - ]; - - (mockIPFSClient.addEnclaveData as any) - .mockResolvedValueOnce({ cid: 'QmCID1', size: 10, timestamp: Date.now() }) - .mockResolvedValueOnce({ cid: 'QmCID2', size: 20, timestamp: Date.now() }); - - const results = await manager.batchStoreEnclaves(enclaves); - - expect(results).toHaveLength(2); - expect(results[0].cid).toBe('QmCID1'); - expect(results[1].cid).toBe('QmCID2'); - }); - - it('should continue batch operation even if one fails', async () => { - const enclaves = [ - { data: validEnclaveData, payload: new Uint8Array([1, 2, 3]) }, - { data: { ...validEnclaveData, threshold: 10 }, payload: new Uint8Array() }, // Invalid - { data: validEnclaveData, payload: new Uint8Array([4, 5, 6]) }, - ]; - - (mockIPFSClient.addEnclaveData as any) - .mockResolvedValueOnce({ cid: 'QmCID1', size: 10, timestamp: Date.now() }) - .mockResolvedValueOnce({ cid: 'QmCID3', size: 30, timestamp: Date.now() }); - - const results = await manager.batchStoreEnclaves(enclaves); - - expect(results).toHaveLength(2); - expect(results[0].cid).toBe('QmCID1'); - expect(results[1].cid).toBe('QmCID3'); - }); - }); - - describe('pin management', () => { - it('should list pinned enclaves', async () => { - const pins = await manager.listPinnedEnclaves(); - - expect(pins).toEqual(['QmCID1', 'QmCID2']); - expect(mockIPFSClient.listPins).toHaveBeenCalled(); - }); - - it('should remove enclave data', async () => { - await manager.removeEnclaveData('QmTestCID123'); - - expect(mockIPFSClient.isPinned).toHaveBeenCalledWith('QmTestCID123'); - expect(mockIPFSClient.unpin).toHaveBeenCalledWith('QmTestCID123'); - }); - - it('should skip unpinning if not pinned', async () => { - (mockIPFSClient.isPinned as any).mockResolvedValue(false); - - await manager.removeEnclaveData('QmTestCID123'); - - expect(mockIPFSClient.unpin).not.toHaveBeenCalled(); - }); - }); - - describe('getEnclaveStatus', () => { - it('should get enclave status', async () => { - // Set timeout to 0 for instant response - manager = new EnclaveIPFSManager(mockIPFSClient, { - encryptionRequired: true, - pinningEnabled: true, - redundancy: 3, - maxRetries: 1, - operationTimeout: 0, - }); - - // Mock the getEnclaveData to return a valid response - (mockIPFSClient.getEnclaveData as any).mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])); - (mockIPFSClient.isPinned as any).mockResolvedValue(true); - - const status = await manager.getEnclaveStatus('QmTestCID123'); - - expect(status.exists).toBe(true); - expect(status.isPinned).toBe(true); - expect(status.size).toBe(5); - }); - - it('should handle non-existent enclave', async () => { - // Set timeout to 0 for instant response - manager = new EnclaveIPFSManager(mockIPFSClient, { - encryptionRequired: true, - pinningEnabled: true, - redundancy: 3, - maxRetries: 1, - operationTimeout: 0, - }); - - (mockIPFSClient.getEnclaveData as any).mockRejectedValue( - new Error('Not found') - ); - (mockIPFSClient.isPinned as any).mockResolvedValue(false); - - const status = await manager.getEnclaveStatus('QmNonExistent'); - - expect(status.exists).toBe(false); - expect(status.isPinned).toBe(false); - }); - }); -}); - -describe('createEnclaveIPFSManager factory', () => { - it('should create manager with initialized IPFS client', async () => { - const manager = await createEnclaveIPFSManager(mockIPFSClient); - - expect(manager).toBeInstanceOf(EnclaveIPFSManager); - }); - - it('should throw if IPFS client not initialized', async () => { - (mockIPFSClient.isInitialized as any).mockReturnValue(false); - - await expect(createEnclaveIPFSManager(mockIPFSClient)).rejects.toThrow( - 'IPFS client must be initialized before creating enclave manager' - ); - }); -}); \ No newline at end of file diff --git a/packages/es/src/plugin/client-ipfs.ts b/packages/es/src/plugin/client-ipfs.ts deleted file mode 100644 index a3d3ca2cb..000000000 --- a/packages/es/src/plugin/client-ipfs.ts +++ /dev/null @@ -1,416 +0,0 @@ -/** - * Enhanced VaultClient with IPFS integration - */ - -import { VaultClient } from './client'; -import { IPFSClient, createIPFSClient } from '../client/services/ipfs'; -import { EnclaveIPFSManager, createEnclaveIPFSManager, type EnclaveDataWithCID } from './enclave'; -import type { - VaultConfigWithIPFS, - VaultError, - VaultErrorCode, - IPFSEnclaveReference, - VaultStateWithIPFS, -} from './types'; - -/** - * VaultClient with integrated IPFS support for MPC enclave data - */ -export class VaultClientWithIPFS extends VaultClient { - private ipfsClient: IPFSClient | null = null; - private enclaveManager: EnclaveIPFSManager | null = null; - private ipfsConfig: VaultConfigWithIPFS; - - constructor(config: VaultConfigWithIPFS = {}) { - super(config); - this.ipfsConfig = config; - } - - /** - * Initialize vault with IPFS support - */ - async initializeWithIPFS( - wasmPath?: string, - accountAddress?: string, - ipfsConfig?: any - ): Promise { - // Initialize base vault client - await super.initialize(wasmPath, accountAddress); - - // Initialize IPFS client - try { - this.ipfsClient = await createIPFSClient({ - gateways: this.ipfsConfig.ipfsGateways, - enablePersistence: this.ipfsConfig.enableIPFSPersistence, - libp2pConfig: ipfsConfig || this.ipfsConfig.ipfsNodeConfig, - }); - - // Initialize enclave manager - this.enclaveManager = await createEnclaveIPFSManager(this.ipfsClient, { - encryptionRequired: true, - pinningEnabled: this.ipfsConfig.enableIPFSPersistence ?? true, - maxRetries: 3, - }); - } catch (error) { - console.error('Failed to initialize IPFS:', error); - throw new Error(`IPFS initialization failed: ${error}`); - } - } - - /** - * Store enclave data to IPFS - */ - async storeEnclaveToIPFS( - enclaveData: EnclaveDataWithCID, - encryptedPayload: Uint8Array - ): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - const result = await this.enclaveManager.storeEnclaveData( - enclaveData, - encryptedPayload - ); - - // Save reference to database if persistence is enabled - if (this.ipfsConfig.enablePersistence) { - await this.saveIPFSReference({ - cid: result.cid, - storedAt: result.timestamp, - isPinned: result.isPinned, - size: result.size, - }); - } - - return result.cid; - } - - /** - * Retrieve enclave data from IPFS - */ - async retrieveEnclaveFromIPFS(cid: string): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - return await this.enclaveManager.retrieveEnclaveData(cid); - } - - /** - * Store vault enclave with automatic encryption - */ - async storeVaultEnclave( - privateKeyShares: string[] - ): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - // Get current enclave configuration - const enclaveConfig = this.ipfsConfig.enclave; - if (!enclaveConfig) { - throw new Error('Enclave configuration not set'); - } - - // Create enclave data with CID - const enclaveData: EnclaveDataWithCID = { - ...enclaveConfig, - encryptionMetadata: { - algorithm: 'AES-256-GCM', - keyVersion: 1, - consensusHeight: 0, - nonce: this.generateNonce(), - }, - }; - - // Prepare encrypted payload - const payload = JSON.stringify({ - publicKey: enclaveData.publicKey, - privateKeyShares, - threshold: enclaveData.threshold, - parties: enclaveData.parties, - timestamp: Date.now(), - }); - - const encryptedPayload = new TextEncoder().encode(payload); - - // Store to IPFS - return await this.storeEnclaveToIPFS(enclaveData, encryptedPayload); - } - - /** - * Retrieve and decrypt vault enclave - */ - async retrieveVaultEnclave(cid: string): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - // Retrieve encrypted data - const encryptedData = await this.retrieveEnclaveFromIPFS(cid); - - // Decrypt and parse - const decryptedString = new TextDecoder().decode(encryptedData); - const enclaveData = JSON.parse(decryptedString); - - return { - ...enclaveData, - cid, - }; - } - - /** - * Verify enclave data integrity - */ - async verifyEnclaveIntegrity( - cid: string, - expectedData: Uint8Array - ): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - return await this.enclaveManager.verifyEnclaveDataIntegrity( - cid, - expectedData - ); - } - - /** - * Get IPFS node status - */ - async getIPFSStatus(): Promise { - if (!this.ipfsClient) { - throw new Error('IPFS not initialized'); - } - - return await this.ipfsClient.getNodeStatus(); - } - - /** - * List all pinned enclave CIDs - */ - async listPinnedEnclaves(): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - return await this.enclaveManager.listPinnedEnclaves(); - } - - /** - * Remove enclave from IPFS (unpin) - */ - async removeEnclaveFromIPFS(cid: string): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - await this.enclaveManager.removeEnclaveData(cid); - - // Remove reference from database - if (this.ipfsConfig.enablePersistence) { - await this.removeIPFSReference(cid); - } - } - - /** - * Batch store multiple enclaves - */ - async batchStoreEnclaves( - enclaves: Array<{ - data: EnclaveDataWithCID; - payload: Uint8Array; - }> - ): Promise { - if (!this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - const results = await this.enclaveManager.batchStoreEnclaves(enclaves); - - // Save references if persistence is enabled - if (this.ipfsConfig.enablePersistence) { - for (const result of results) { - await this.saveIPFSReference({ - cid: result.cid, - storedAt: result.timestamp, - isPinned: result.isPinned, - size: result.size, - }); - } - } - - return results.map(r => r.cid); - } - - /** - * Sync enclave data with IPFS network - */ - async syncWithIPFS(): Promise { - if (!this.ipfsClient || !this.enclaveManager) { - throw new Error('IPFS not initialized'); - } - - // Get stored references - const references = await this.getIPFSReferences(); - - // Verify each reference - for (const ref of references) { - try { - const status = await this.enclaveManager.getEnclaveStatus(ref.cid); - - // Re-pin if needed - if (!status.isPinned && ref.isPinned) { - await this.ipfsClient.pin(ref.cid); - } - } catch (error) { - console.warn(`Failed to sync CID ${ref.cid}:`, error); - } - } - - // Update last sync timestamp - await this.updateLastIPFSSync(); - } - - // ============= Storage Methods ============= - - /** - * Save IPFS reference to storage - */ - private async saveIPFSReference(ref: IPFSEnclaveReference): Promise { - const database = (this as any).database; - if (!database) return; - - // Store in metadata collection - await database.metadata.put({ - id: `ipfs_${ref.cid}`, - type: 'ipfs_reference', - data: ref, - createdAt: Date.now(), - }); - } - - /** - * Get all IPFS references - */ - private async getIPFSReferences(): Promise { - const database = (this as any).database; - if (!database) return []; - - const metadata = await database.metadata - .where('type') - .equals('ipfs_reference') - .toArray(); - - return metadata.map((m: any) => m.data); - } - - /** - * Remove IPFS reference - */ - private async removeIPFSReference(cid: string): Promise { - const database = (this as any).database; - if (!database) return; - - await database.metadata.delete(`ipfs_${cid}`); - } - - /** - * Update last IPFS sync timestamp - */ - private async updateLastIPFSSync(): Promise { - const database = (this as any).database; - if (!database) return; - - await database.metadata.put({ - id: 'ipfs_last_sync', - type: 'ipfs_sync', - timestamp: Date.now(), - }); - } - - /** - * Persist state with IPFS references - */ - async persistState(): Promise { - await super.persistState(); - - // Add IPFS-specific state - const database = (this as any).database; - const accountAddress = (this as any).accountAddress; - - if (!database || !accountAddress) return; - - const references = await this.getIPFSReferences(); - - const state: VaultStateWithIPFS = { - id: 'current', - accountAddress, - isInitialized: this.isReady(), - enclave: this.ipfsConfig.enclave ? - JSON.stringify(this.ipfsConfig.enclave) : undefined, - lastAccessed: Date.now(), - createdAt: Date.now(), - ipfsReferences: references, - lastIPFSSync: Date.now(), - }; - - await database.state.put(state); - } - - /** - * Generate a random nonce - */ - private generateNonce(): string { - const bytes = new Uint8Array(16); - crypto.getRandomValues(bytes); - return Array.from(bytes) - .map(b => b.toString(16).padStart(2, '0')) - .join(''); - } - - /** - * Cleanup with IPFS shutdown - */ - async cleanup(): Promise { - // Clean up IPFS resources - if (this.ipfsClient) { - await this.ipfsClient.cleanup(); - this.ipfsClient = null; - } - - this.enclaveManager = null; - - // Call parent cleanup - await super.cleanup(); - } -} - -/** - * Create a VaultClient with IPFS support - */ -export function createVaultClientWithIPFS( - config?: VaultConfigWithIPFS -): VaultClientWithIPFS { - return new VaultClientWithIPFS(config); -} - -/** - * Default IPFS-enabled vault client instance - */ -let defaultIPFSClient: VaultClientWithIPFS | null = null; - -/** - * Get or create the default IPFS-enabled vault client - */ -export async function getDefaultVaultClientWithIPFS( - config?: VaultConfigWithIPFS -): Promise { - if (!defaultIPFSClient) { - defaultIPFSClient = createVaultClientWithIPFS(config); - await defaultIPFSClient.initializeWithIPFS(); - } - return defaultIPFSClient; -} \ No newline at end of file diff --git a/packages/es/src/plugin/client.ts b/packages/es/src/plugin/client.ts deleted file mode 100644 index 69d1f1a73..000000000 --- a/packages/es/src/plugin/client.ts +++ /dev/null @@ -1,515 +0,0 @@ -import { createPlugin, Plugin } from '@extism/extism'; -import { - VaultError, - VaultErrorCode, -} from './types'; -import type { - VaultConfig, - VaultPlugin, - NewOriginTokenRequest, - NewAttenuatedTokenRequest, - SignDataRequest, - VerifyDataRequest, - UCANTokenResponse, - SignDataResponse, - VerifyDataResponse, - GetIssuerDIDResponse, - VaultConfigWithStorage, - StoredVaultState, - StoredUCANToken, -} from './types'; -import { VaultStorageManager } from './storage'; -import type { AccountVaultDatabase } from './storage'; - -/** - * Vault client for interacting with the WASM vault module - */ -export class VaultClient implements VaultPlugin { - private plugin: Plugin | null = null; - private config: VaultConfigWithStorage; - private wasmModule: ArrayBuffer | null = null; - private storageManager: VaultStorageManager | null = null; - private database: any | null = null; - private accountAddress: string | null = null; - - constructor(config: VaultConfigWithStorage = {}) { - this.config = config; - - // Initialize storage manager if persistence is enabled - if (config.enablePersistence) { - this.storageManager = new VaultStorageManager(config); - } - } - - /** - * Initialize the vault with WASM module - */ - async initialize(wasmPath?: string, accountAddress?: string): Promise { - // Initialize storage first if account address is provided and persistence is enabled - // This ensures storage works even if WASM loading fails - if (accountAddress && this.config.enablePersistence && this.storageManager) { - this.accountAddress = accountAddress; - this.database = await this.storageManager.getDatabase(accountAddress); - await this.loadPersistedState(); - } - - try { - // Load WASM module - if (wasmPath) { - // Load from provided path - const response = await fetch(wasmPath); - this.wasmModule = await response.arrayBuffer(); - } else { - // Load from default location - const response = await fetch('/plugin.wasm'); - this.wasmModule = await response.arrayBuffer(); - } - - // Create Extism plugin with configuration - const pluginConfig = { - wasm: [{ data: new Uint8Array(this.wasmModule) }], - config: this.prepareConfig(), - }; - - this.plugin = await createPlugin(pluginConfig, { - useWasi: true, - }); - - } catch (error) { - throw new VaultError( - VaultErrorCode.WASM_NOT_LOADED, - `Failed to initialize vault: ${error}`, - error - ); - } - } - - /** - * Prepare configuration for the plugin - */ - private prepareConfig(): Record { - const config: Record = {}; - - if (this.config.chainId) { - config.chain_id = this.config.chainId; - } - - return config; - } - - /** - * Ensure plugin is initialized - */ - private ensureInitialized(): void { - if (!this.plugin) { - throw new VaultError( - VaultErrorCode.NOT_INITIALIZED, - 'Vault client not initialized. Call initialize() first.' - ); - } - } - - /** - * Convert JavaScript object to JSON for plugin input - */ - private toPluginInput(data: any): Uint8Array { - const json = JSON.stringify(data); - return new TextEncoder().encode(json); - } - - /** - * Parse plugin output as JSON - */ - private parsePluginOutput(output: any): T { - if (!output) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - 'No output from plugin' - ); - } - - // Handle both Uint8Array and PluginOutput types - let text: string; - if (output instanceof Uint8Array) { - text = new TextDecoder().decode(output); - } else if (output.bytes) { - // PluginOutput type from Extism - text = new TextDecoder().decode(output.bytes()); - } else if (output.text) { - text = output.text(); - } else { - text = output.toString(); - } - - return JSON.parse(text) as T; - } - - /** - * Create a new origin UCAN token - */ - async newOriginToken(request: NewOriginTokenRequest): Promise { - this.ensureInitialized(); - - try { - const input = this.toPluginInput(request); - const output = await this.plugin!.call('new_origin_token', input); - const response = this.parsePluginOutput(output); - - if (response.error) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - response.error - ); - } - - // Save token if persistence is enabled - if (this.config.enablePersistence && this.database) { - await this.saveToken(response); - } - - return response; - } catch (error) { - if (error instanceof VaultError) { - throw error; - } - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - `Failed to create origin token: ${error}`, - error - ); - } - } - - /** - * Create a new attenuated UCAN token - */ - async newAttenuatedToken(request: NewAttenuatedTokenRequest): Promise { - this.ensureInitialized(); - - try { - const input = this.toPluginInput(request); - const output = await this.plugin!.call('new_attenuated_token', input); - const response = this.parsePluginOutput(output); - - if (response.error) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - response.error - ); - } - - // Save token if persistence is enabled - if (this.config.enablePersistence && this.database) { - await this.saveToken(response); - } - - return response; - } catch (error) { - if (error instanceof VaultError) { - throw error; - } - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - `Failed to create attenuated token: ${error}`, - error - ); - } - } - - /** - * Sign data with the vault's MPC enclave - */ - async signData(request: SignDataRequest): Promise { - this.ensureInitialized(); - - try { - const input = this.toPluginInput({ - data: Array.from(request.data), - }); - const output = await this.plugin!.call('sign_data', input); - const response = this.parsePluginOutput(output); - - if (response.error) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - response.error - ); - } - - return { - signature: new Uint8Array(response.signature), - error: response.error, - }; - } catch (error) { - if (error instanceof VaultError) { - throw error; - } - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - `Failed to sign data: ${error}`, - error - ); - } - } - - /** - * Verify a signature with the vault's MPC enclave - */ - async verifyData(request: VerifyDataRequest): Promise { - this.ensureInitialized(); - - try { - const input = this.toPluginInput({ - data: Array.from(request.data), - signature: Array.from(request.signature), - }); - const output = await this.plugin!.call('verify_data', input); - const response = this.parsePluginOutput(output); - - if (response.error) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - response.error - ); - } - - return response; - } catch (error) { - if (error instanceof VaultError) { - throw error; - } - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - `Failed to verify data: ${error}`, - error - ); - } - } - - /** - * Get the issuer DID and address from the vault - */ - async getIssuerDID(): Promise { - this.ensureInitialized(); - - try { - const output = await this.plugin!.call('get_issuer_did', new Uint8Array()); - const response = this.parsePluginOutput(output); - - if (response.error) { - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - response.error - ); - } - - return response; - } catch (error) { - if (error instanceof VaultError) { - throw error; - } - throw new VaultError( - VaultErrorCode.OPERATION_FAILED, - `Failed to get issuer DID: ${error}`, - error - ); - } - } - - /** - * Check if the vault is ready - */ - isReady(): boolean { - return this.plugin !== null; - } - - // ============= Storage Management Methods ============= - - /** - * Persist current vault state - */ - async persistState(): Promise { - if (!this.database || !this.accountAddress) return; - - const state: StoredVaultState = { - id: 'current', - accountAddress: this.accountAddress, - isInitialized: this.isReady(), - enclave: this.config.enclave ? JSON.stringify(this.config.enclave) : undefined, - lastAccessed: Date.now(), - createdAt: Date.now(), - }; - - await this.database.state.put(state); - } - - /** - * Load persisted vault state - */ - async loadPersistedState(): Promise { - if (!this.database) return null; - - const state = await this.database.state.get('current'); - if (state && state.enclave) { - // Restore enclave configuration if present - this.config.enclave = JSON.parse(state.enclave); - } - return state || null; - } - - /** - * Clear persisted vault state - */ - async clearPersistedState(): Promise { - if (!this.database) return; - - await this.database.state.clear(); - await this.database.tokens.clear(); - await this.database.sessions.clear(); - await this.database.metadata.clear(); - } - - // ============= Token Management Methods ============= - - /** - * Save UCAN token to storage - */ - async saveToken(token: UCANTokenResponse): Promise { - if (!this.database) return; - - const storedToken: StoredUCANToken = { - id: `${Date.now()}_${Math.random()}`, - token: token.token, - type: 'origin', // Default to origin, can be enhanced - issuer: token.issuer, - audience: token.address, - createdAt: Date.now(), - }; - - await this.database.tokens.put(storedToken); - } - - /** - * Get all persisted tokens - */ - async getPersistedTokens(): Promise { - if (!this.database) return []; - - const tokens = await this.database.tokens.toArray(); - return tokens || []; - } - - /** - * Remove expired tokens - */ - async removeExpiredTokens(): Promise { - if (!this.database) return; - - const now = Date.now(); - await this.database.tokens - .where('expiresAt') - .below(now) - .delete(); - } - - // ============= Account Management Methods ============= - - /** - * Switch to a different account - */ - async switchAccount(newAccountAddress: string): Promise { - if (!this.storageManager) { - throw new VaultError( - VaultErrorCode.NOT_INITIALIZED, - 'Storage manager not initialized' - ); - } - - // Save current state before switching - if (this.accountAddress && this.database) { - await this.persistState(); - } - - // Switch to new account database - this.accountAddress = newAccountAddress; - this.database = await this.storageManager.getDatabase(newAccountAddress); - - // Load new account state - await this.loadPersistedState(); - } - - /** - * List all persisted accounts - */ - async listPersistedAccounts(): Promise { - if (!this.storageManager) return []; - - return await this.storageManager.listPersistedAccounts(); - } - - /** - * Remove an account and its data - */ - async removeAccount(accountAddress: string): Promise { - if (!this.storageManager) return; - - // If removing current account, clear local references - if (accountAddress === this.accountAddress) { - this.accountAddress = null; - this.database = null; - } - - await this.storageManager.removeDatabase(accountAddress); - } - - /** - * Cleanup and release resources - */ - async cleanup(): Promise { - // Save current state before cleanup - if (this.database && this.accountAddress) { - await this.persistState(); - } - - if (this.plugin) { - await this.plugin.close(); - this.plugin = null; - } - - if (this.storageManager) { - await this.storageManager.closeAll(); - } - - this.wasmModule = null; - this.database = null; - this.accountAddress = null; - } -} - -/** - * Create a new vault client instance - */ -export function createVaultClient(config?: VaultConfigWithStorage): VaultClient { - return new VaultClient(config); -} - -/** - * Default vault client instance - */ -let defaultClient: VaultClient | null = null; - -/** - * Get or create the default vault client - */ -export async function getDefaultVaultClient(config?: VaultConfigWithStorage): Promise { - if (!defaultClient) { - defaultClient = createVaultClient(config); - await defaultClient.initialize(); - } - return defaultClient; -} - -/** - * Export error class for convenience - */ -export { VaultError, VaultErrorCode } from './types'; \ No newline at end of file diff --git a/packages/es/src/plugin/enclave.ts b/packages/es/src/plugin/enclave.ts deleted file mode 100644 index a3a04f99b..000000000 --- a/packages/es/src/plugin/enclave.ts +++ /dev/null @@ -1,398 +0,0 @@ -/** - * MPC Enclave manager for IPFS-based vault data operations - */ - -import type { IPFSClient } from '../client/services/ipfs' -import { EnclaveData } from './types' - -/** - * Extended enclave data with CID reference - */ -export interface EnclaveDataWithCID extends EnclaveData { - /** IPFS CID for the encrypted enclave data */ - cid?: string - /** Encryption metadata for consensus-based encryption */ - encryptionMetadata?: EncryptionMetadata -} - -/** - * Encryption metadata for consensus-based encryption - */ -export interface EncryptionMetadata { - /** Encryption algorithm used */ - algorithm: string - /** Version of the encryption key */ - keyVersion: number - /** Consensus height at encryption time */ - consensusHeight: number - /** Nonce for encryption */ - nonce: string -} - -/** - * Configuration for enclave storage operations - */ -export interface EnclaveStorageConfig { - /** Whether encryption is required for all enclave data */ - encryptionRequired: boolean - /** Enable automatic pinning of enclave data */ - pinningEnabled: boolean - /** Number of redundant copies to maintain */ - redundancy: number - /** Maximum retry attempts for failed operations */ - maxRetries: number - /** Timeout for operations in milliseconds */ - operationTimeout?: number -} - -/** - * Result of enclave storage operation - */ -export interface EnclaveStorageResult { - /** CID of stored data */ - cid: string - /** Whether data was pinned */ - isPinned: boolean - /** Size of stored data */ - size: number - /** Timestamp of storage */ - timestamp: number -} - -/** - * Manages MPC enclave data operations with IPFS - */ -export class EnclaveIPFSManager { - private ipfsClient: IPFSClient - private config: EnclaveStorageConfig - - constructor( - ipfsClient: IPFSClient, - config: Partial = {} - ) { - this.ipfsClient = ipfsClient - this.config = { - encryptionRequired: true, - pinningEnabled: true, - redundancy: 3, - maxRetries: 3, - operationTimeout: 30000, - ...config - } - } - - /** - * Store encrypted enclave data to IPFS - */ - async storeEnclaveData( - enclaveData: EnclaveDataWithCID, - encryptedPayload: Uint8Array - ): Promise { - // Validate encryption requirement - if (this.config.encryptionRequired && !enclaveData.encryptionMetadata) { - throw new Error('Encryption metadata required for enclave data storage') - } - - // Validate enclave data structure - this.validateEnclaveData(enclaveData) - - // Store with retry logic - let lastError: Error | null = null - let result: EnclaveStorageResult | null = null - - for (let attempt = 0; attempt < this.config.maxRetries; attempt++) { - try { - // Store encrypted data to IPFS - const { cid, size, timestamp } = await this.ipfsClient.addEnclaveData(encryptedPayload) - - // Pin the content if enabled - let isPinned = false - if (this.config.pinningEnabled) { - await this.ipfsClient.pin(cid) - isPinned = true - } - - result = { - cid, - isPinned, - size, - timestamp - } - - break - } catch (error) { - lastError = error as Error - console.warn(`Attempt ${attempt + 1} failed:`, error) - - // Exponential backoff - if (attempt < this.config.maxRetries - 1) { - await this.delay(Math.pow(2, attempt) * 1000) - } - } - } - - if (!result) { - throw new Error( - `Failed to store enclave data after ${this.config.maxRetries} attempts: ${lastError?.message}` - ) - } - - return result - } - - /** - * Retrieve encrypted enclave data from IPFS - */ - async retrieveEnclaveData(cid: string): Promise { - let lastError: Error | null = null - - for (let attempt = 0; attempt < this.config.maxRetries; attempt++) { - try { - // Create a race between operation and timeout - const timeoutPromise = this.createTimeoutPromise() - const dataPromise = this.ipfsClient.getEnclaveData(cid) - - const data = await Promise.race([dataPromise, timeoutPromise]) - - if (data === null) { - throw new Error('Operation timed out') - } - - return data as Uint8Array - } catch (error) { - lastError = error as Error - console.warn(`Retrieval attempt ${attempt + 1} failed:`, error) - - // Exponential backoff - if (attempt < this.config.maxRetries - 1) { - await this.delay(Math.pow(2, attempt) * 1000) - } - } - } - - throw new Error( - `Failed to retrieve enclave data after ${this.config.maxRetries} attempts: ${lastError?.message}` - ) - } - - /** - * Verify enclave data integrity by comparing CID - */ - async verifyEnclaveDataIntegrity( - cid: string, - expectedData: Uint8Array - ): Promise { - try { - const retrievedData = await this.retrieveEnclaveData(cid) - - // Compare byte arrays - if (retrievedData.length !== expectedData.length) { - return false - } - - for (let i = 0; i < retrievedData.length; i++) { - if (retrievedData[i] !== expectedData[i]) { - return false - } - } - - return true - } catch (error) { - console.error('Failed to verify enclave data integrity:', error) - return false - } - } - - /** - * Store enclave data with metadata - */ - async storeEnclaveWithMetadata( - enclaveData: EnclaveDataWithCID, - privateKeyShares: Uint8Array[], - encryptionKey: Uint8Array - ): Promise { - // Prepare the complete enclave payload - const payload = this.prepareEnclavePayload(enclaveData, privateKeyShares) - - // Encrypt the payload - const encryptedPayload = await this.encryptPayload(payload, encryptionKey) - - // Store to IPFS - return await this.storeEnclaveData(enclaveData, encryptedPayload) - } - - /** - * Batch store multiple enclave data - */ - async batchStoreEnclaves( - enclaves: Array<{ - data: EnclaveDataWithCID - payload: Uint8Array - }> - ): Promise { - const results: EnclaveStorageResult[] = [] - - for (const enclave of enclaves) { - try { - const result = await this.storeEnclaveData(enclave.data, enclave.payload) - results.push(result) - } catch (error) { - console.error('Failed to store enclave:', error) - // Continue with other enclaves even if one fails - } - } - - return results - } - - /** - * List all pinned enclave CIDs - */ - async listPinnedEnclaves(): Promise { - return await this.ipfsClient.listPins() - } - - /** - * Remove enclave data from IPFS (unpin) - */ - async removeEnclaveData(cid: string): Promise { - try { - // Check if pinned before unpinning - const isPinned = await this.ipfsClient.isPinned(cid) - if (isPinned) { - await this.ipfsClient.unpin(cid) - } - } catch (error) { - console.error('Failed to remove enclave data:', error) - throw error - } - } - - /** - * Get enclave storage status - */ - async getEnclaveStatus(cid: string): Promise<{ - exists: boolean - isPinned: boolean - size?: number - }> { - try { - const isPinned = await this.ipfsClient.isPinned(cid) - - // Try to retrieve to check existence - let exists = false - let size: number | undefined - - try { - const data = await this.retrieveEnclaveData(cid) - exists = true - size = data.length - } catch { - // Data doesn't exist or is not accessible - } - - return { - exists, - isPinned, - size - } - } catch (error) { - console.error('Failed to get enclave status:', error) - return { - exists: false, - isPinned: false - } - } - } - - /** - * Validate enclave data structure - */ - private validateEnclaveData(data: EnclaveDataWithCID): void { - if (!data.publicKey) { - throw new Error('Public key is required for enclave data') - } - - if (!data.privateKeyShares || data.privateKeyShares.length === 0) { - throw new Error('Private key shares are required for enclave data') - } - - if (data.threshold < 1 || data.threshold > data.parties) { - throw new Error('Invalid threshold value') - } - - if (data.parties !== data.privateKeyShares.length) { - throw new Error('Number of parties must match number of key shares') - } - } - - /** - * Prepare enclave payload for storage - */ - private prepareEnclavePayload( - enclaveData: EnclaveDataWithCID, - privateKeyShares: Uint8Array[] - ): Uint8Array { - // Create JSON representation - const payload = { - publicKey: enclaveData.publicKey, - privateKeyShares: privateKeyShares.map(share => - Buffer.from(share).toString('base64') - ), - threshold: enclaveData.threshold, - parties: enclaveData.parties, - encryptionMetadata: enclaveData.encryptionMetadata - } - - // Convert to bytes - const jsonString = JSON.stringify(payload) - return new TextEncoder().encode(jsonString) - } - - /** - * Encrypt payload (placeholder - actual implementation would use consensus keys) - */ - private async encryptPayload( - payload: Uint8Array, - encryptionKey: Uint8Array - ): Promise { - // TODO: Implement actual consensus-based encryption - // For now, return the payload as-is - // In production, this would use the consensus encryption key - return payload - } - - /** - * Create a timeout promise - */ - private createTimeoutPromise(): Promise { - if (!this.config.operationTimeout) { - return new Promise(() => {}) // Never resolves - } - - return new Promise((resolve) => { - setTimeout(() => resolve(null), this.config.operationTimeout) - }) - } - - /** - * Delay helper for retry logic - */ - private delay(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)) - } -} - -/** - * Factory function to create an enclave manager - */ -export async function createEnclaveIPFSManager( - ipfsClient: IPFSClient, - config?: Partial -): Promise { - if (!ipfsClient.isInitialized()) { - throw new Error('IPFS client must be initialized before creating enclave manager') - } - - return new EnclaveIPFSManager(ipfsClient, config) -} \ No newline at end of file diff --git a/packages/es/src/plugin/index.ts b/packages/es/src/plugin/index.ts deleted file mode 100644 index b4c029a63..000000000 --- a/packages/es/src/plugin/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Vault client module for interacting with the MPC-based vault WASM module - * - * This module provides secure key management and cryptographic operations - * through a WebAssembly-based vault that uses Multi-Party Computation (MPC) - * for enhanced security. - * - * Now includes IPFS integration for distributed enclave data storage. - */ - -export * from './types'; -export * from './client'; -export * from './loader'; -export * from './storage'; - -// IPFS-enhanced components -export * from './client-ipfs'; -export * from './enclave'; \ No newline at end of file diff --git a/packages/es/src/plugin/loader.ts b/packages/es/src/plugin/loader.ts deleted file mode 100644 index e53c66060..000000000 --- a/packages/es/src/plugin/loader.ts +++ /dev/null @@ -1,201 +0,0 @@ -/** - * WASM loader utilities for the vault module - */ - -import { VaultError, VaultErrorCode } from './types'; - -/** - * Options for loading WASM module - */ -export interface WASMLoadOptions { - /** URL to load WASM from */ - url?: string; - /** Use CDN for loading (jsDelivr) */ - useCDN?: boolean; - /** Package version for CDN loading */ - version?: string; - /** Timeout for loading in milliseconds */ - timeout?: number; -} - -/** - * Default CDN configuration - */ -const CDN_BASE = 'https://cdn.jsdelivr.net/npm/@sonr.io/es'; -const DEFAULT_TIMEOUT = 30000; // 30 seconds - -/** - * Load vault WASM module - */ -export async function loadVaultWASM(options: WASMLoadOptions = {}): Promise { - const { - url, - useCDN = false, - version = 'latest', - timeout = DEFAULT_TIMEOUT, - } = options; - - let wasmUrl: string; - - if (url) { - // Use provided URL - wasmUrl = url; - } else if (useCDN) { - // Use jsDelivr CDN - wasmUrl = `${CDN_BASE}@${version}/dist/plugins/vault/plugin.wasm`; - } else { - // Use local path - wasmUrl = '/plugin.wasm'; - } - - try { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeout); - - const response = await fetch(wasmUrl, { - signal: controller.signal, - headers: { - 'Accept': 'application/wasm', - }, - }); - - clearTimeout(timeoutId); - - if (!response.ok) { - throw new Error(`Failed to load WASM: ${response.status} ${response.statusText}`); - } - - const contentType = response.headers.get('content-type'); - if (contentType && !contentType.includes('wasm') && !contentType.includes('octet-stream')) { - console.warn(`Unexpected content type for WASM: ${contentType}`); - } - - return await response.arrayBuffer(); - } catch (error: any) { - if (error.name === 'AbortError') { - throw new VaultError( - VaultErrorCode.TIMEOUT, - `WASM loading timed out after ${timeout}ms`, - { url: wasmUrl } - ); - } - - throw new VaultError( - VaultErrorCode.WASM_NOT_LOADED, - `Failed to load WASM from ${wasmUrl}: ${error.message}`, - error - ); - } -} - -/** - * Verify WASM module is valid - */ -export async function verifyWASM(wasmBuffer: ArrayBuffer): Promise { - try { - // Check WASM magic number (0x00 0x61 0x73 0x6D) - const view = new DataView(wasmBuffer); - const magic = view.getUint32(0, true); - - if (magic !== 0x6D736100) { - throw new Error('Invalid WASM magic number'); - } - - // Try to compile the module - await WebAssembly.compile(wasmBuffer); - - return true; - } catch (error) { - console.error('WASM verification failed:', error); - return false; - } -} - -/** - * Get WASM module info - */ -export async function getWASMInfo(wasmBuffer: ArrayBuffer): Promise<{ - size: number; - exports: string[]; - imports: string[]; -}> { - const module = await WebAssembly.compile(wasmBuffer); - - const exports = WebAssembly.Module.exports(module).map(exp => exp.name); - const imports = WebAssembly.Module.imports(module).map(imp => `${imp.module}.${imp.name}`); - - return { - size: wasmBuffer.byteLength, - exports, - imports, - }; -} - -/** - * Cache for loaded WASM modules - */ -class WASMCache { - private cache = new Map(); - - set(key: string, buffer: ArrayBuffer): void { - this.cache.set(key, buffer); - } - - get(key: string): ArrayBuffer | undefined { - return this.cache.get(key); - } - - has(key: string): boolean { - return this.cache.has(key); - } - - clear(): void { - this.cache.clear(); - } - - remove(key: string): boolean { - return this.cache.delete(key); - } -} - -/** - * Global WASM cache instance - */ -export const wasmCache = new WASMCache(); - -/** - * Load WASM with caching - */ -export async function loadVaultWASMCached( - cacheKey: string, - options: WASMLoadOptions = {} -): Promise { - // Check cache first - if (wasmCache.has(cacheKey)) { - const cached = wasmCache.get(cacheKey); - if (cached) { - return cached; - } - } - - // Load WASM - const wasmBuffer = await loadVaultWASM(options); - - // Verify and cache - if (await verifyWASM(wasmBuffer)) { - wasmCache.set(cacheKey, wasmBuffer); - } - - return wasmBuffer; -} - -/** - * Preload vault WASM module for faster initialization - */ -export async function preloadVaultWASM(options: WASMLoadOptions = {}): Promise { - try { - await loadVaultWASMCached('vault-default', options); - } catch (error) { - console.error('Failed to preload vault WASM:', error); - } -} \ No newline at end of file diff --git a/packages/es/src/plugin/storage.e2e.test.ts b/packages/es/src/plugin/storage.e2e.test.ts deleted file mode 100644 index 22138b6bf..000000000 --- a/packages/es/src/plugin/storage.e2e.test.ts +++ /dev/null @@ -1,586 +0,0 @@ -/** - * End-to-end tests for Dexie.js integration with VaultClient - * Tests real IndexedDB functionality without mocks - */ - -import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi } from 'vitest'; - -// Setup fake IndexedDB for Node.js environment BEFORE importing Dexie -import 'fake-indexeddb/auto'; -import FDBFactory from 'fake-indexeddb/lib/FDBFactory'; -import FDBKeyRange from 'fake-indexeddb/lib/FDBKeyRange'; - -// Set up globals before Dexie import -globalThis.indexedDB = new FDBFactory(); -globalThis.IDBKeyRange = FDBKeyRange; - -import Dexie from 'dexie'; -import { VaultStorageManager, AccountVaultDatabase } from './storage'; -import { VaultClient, createVaultClient } from './client'; -import type { StoredVaultState, StoredUCANToken, VaultStorageConfig } from './types'; - -describe('VaultClient with Dexie.js Storage - End to End', () => { - let storageManager: VaultStorageManager; - let vaultClient: VaultClient; - const testAccount1 = 'sonr1testaccount123'; - const testAccount2 = 'sonr1testaccount456'; - - beforeAll(async () => { - // Clean up any existing test databases - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - }); - - afterAll(async () => { - // Final cleanup - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - }); - - describe('Storage Manager Initialization', () => { - it('should create storage manager with default config', () => { - const manager = new VaultStorageManager(); - expect(manager).toBeInstanceOf(VaultStorageManager); - }); - - it('should create storage manager with custom config', () => { - const config: VaultStorageConfig = { - enablePersistence: true, - autoCleanup: false, - cleanupInterval: 5000, - }; - const manager = new VaultStorageManager(config); - expect(manager).toBeInstanceOf(VaultStorageManager); - }); - }); - - describe('Database Lifecycle', () => { - beforeEach(() => { - storageManager = new VaultStorageManager({ - autoCleanup: false, // Disable for predictable tests - }); - }); - - afterEach(async () => { - await storageManager.closeAll(); - }); - - it('should create a new database for an account', async () => { - const db = await storageManager.getDatabase(testAccount1); - - expect(db).toBeInstanceOf(AccountVaultDatabase); - expect(db.name).toBe(`vault_${testAccount1}`); - expect(db.isOpen()).toBe(true); - }); - - it('should reuse existing database for same account', async () => { - const db1 = await storageManager.getDatabase(testAccount1); - const db2 = await storageManager.getDatabase(testAccount1); - - expect(db1).toBe(db2); - expect(db1.isOpen()).toBe(true); - }); - - it('should create separate databases for different accounts', async () => { - const db1 = await storageManager.getDatabase(testAccount1); - const db2 = await storageManager.getDatabase(testAccount2); - - expect(db1).not.toBe(db2); - expect(db1.name).toBe(`vault_${testAccount1}`); - expect(db2.name).toBe(`vault_${testAccount2}`); - }); - - it('should list all persisted accounts', async () => { - await storageManager.getDatabase(testAccount1); - await storageManager.getDatabase(testAccount2); - - const accounts = await storageManager.listPersistedAccounts(); - - expect(accounts).toContain(testAccount1); - expect(accounts).toContain(testAccount2); - }); - - it('should remove database for an account', async () => { - await storageManager.getDatabase(testAccount1); - - let accounts = await storageManager.listPersistedAccounts(); - expect(accounts).toContain(testAccount1); - - await storageManager.removeDatabase(testAccount1); - - accounts = await storageManager.listPersistedAccounts(); - expect(accounts).not.toContain(testAccount1); - }); - }); - - describe('VaultClient Integration', () => { - beforeEach(async () => { - // Clean up any existing databases before each test - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - - vaultClient = createVaultClient({ - enablePersistence: true, - autoCleanup: false, - }); - }); - - afterEach(async () => { - await vaultClient.cleanup(); - - // Clean up databases after each test - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - }); - - it('should initialize vault with persistence enabled', async () => { - // Initialize without WASM (will fail but storage should work) - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected to fail due to missing WASM - } - - // Storage should still be initialized - const accounts = await vaultClient.listPersistedAccounts(); - expect(accounts).toContain(testAccount1); - }); - - it('should persist and load vault state', async () => { - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected - } - - // Persist state - await vaultClient.persistState(); - - // Load state - const state = await vaultClient.loadPersistedState(); - expect(state).toBeDefined(); - expect(state?.accountAddress).toBe(testAccount1); - expect(state?.isInitialized).toBe(false); // WASM not loaded - }); - - it('should save and retrieve tokens', async () => { - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected - } - - // Save a mock token - const mockToken = { - token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9...', - issuer: 'did:sonr:123', - address: testAccount1, - }; - - await vaultClient.saveToken(mockToken); - - // Retrieve tokens - const tokens = await vaultClient.getPersistedTokens(); - expect(tokens).toHaveLength(1); - expect(tokens[0].token).toBe(mockToken.token); - expect(tokens[0].issuer).toBe(mockToken.issuer); - }); - - it('should clear persisted state', async () => { - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected - } - - // Add some data - await vaultClient.persistState(); - await vaultClient.saveToken({ - token: 'test-token', - issuer: 'did:test', - address: testAccount1, - }); - - // Verify data exists - let state = await vaultClient.loadPersistedState(); - let tokens = await vaultClient.getPersistedTokens(); - expect(state).toBeDefined(); - expect(tokens).toHaveLength(1); - - // Clear all data - await vaultClient.clearPersistedState(); - - // Verify data is cleared - state = await vaultClient.loadPersistedState(); - tokens = await vaultClient.getPersistedTokens(); - expect(state).toBeNull(); - expect(tokens).toHaveLength(0); - }); - }); - - describe('Multi-Account Support', () => { - beforeEach(async () => { - // Clean up any existing databases before each test - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - - vaultClient = createVaultClient({ - enablePersistence: true, - autoCleanup: false, - }); - }); - - afterEach(async () => { - await vaultClient.cleanup(); - - // Clean up databases after each test - const dbs = await Dexie.getDatabaseNames(); - for (const dbName of dbs) { - if (dbName.startsWith('vault_')) { - await Dexie.delete(dbName); - } - } - }); - - it('should switch between accounts', async () => { - // Initialize with account 1 - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected - } - - // Save token for account 1 - await vaultClient.saveToken({ - token: 'token-account1', - issuer: 'did:account1', - address: testAccount1, - }); - - // Switch to account 2 - await vaultClient.switchAccount(testAccount2); - - // Save token for account 2 - await vaultClient.saveToken({ - token: 'token-account2', - issuer: 'did:account2', - address: testAccount2, - }); - - // Verify account 2 has its own token - let tokens = await vaultClient.getPersistedTokens(); - expect(tokens).toHaveLength(1); - expect(tokens[0].token).toBe('token-account2'); - - // Switch back to account 1 - await vaultClient.switchAccount(testAccount1); - - // Verify account 1 still has its token - tokens = await vaultClient.getPersistedTokens(); - expect(tokens).toHaveLength(1); - expect(tokens[0].token).toBe('token-account1'); - }); - - it('should maintain separate databases for each account', async () => { - // Initialize with account 1 - try { - await vaultClient.initialize('/fake/path.wasm', testAccount1); - } catch (error) { - // Expected - } - - await vaultClient.persistState(); - await vaultClient.saveToken({ - token: 'account1-token', - issuer: 'did:1', - address: testAccount1, - }); - - // Switch to account 2 - await vaultClient.switchAccount(testAccount2); - await vaultClient.persistState(); - await vaultClient.saveToken({ - token: 'account2-token', - issuer: 'did:2', - address: testAccount2, - }); - - // List all accounts - const accounts = await vaultClient.listPersistedAccounts(); - expect(accounts).toContain(testAccount1); - expect(accounts).toContain(testAccount2); - - // Remove account 1 - await vaultClient.removeAccount(testAccount1); - - // Verify account 1 is removed but account 2 remains - const remainingAccounts = await vaultClient.listPersistedAccounts(); - expect(remainingAccounts).not.toContain(testAccount1); - expect(remainingAccounts).toContain(testAccount2); - - // Account 2 data should still be accessible - const tokens = await vaultClient.getPersistedTokens(); - expect(tokens).toHaveLength(1); - expect(tokens[0].token).toBe('account2-token'); - }); - }); - - describe('Token Expiration and Cleanup', () => { - let db: AccountVaultDatabase; - - beforeEach(async () => { - storageManager = new VaultStorageManager({ - autoCleanup: false, - }); - db = await storageManager.getDatabase(testAccount1); - }); - - afterEach(async () => { - await storageManager.closeAll(); - }); - - it('should store tokens with expiration', async () => { - const now = Date.now(); - const expiredToken: StoredUCANToken = { - id: 'token1', - token: 'expired-token', - type: 'origin', - issuer: 'did:expired', - audience: testAccount1, - expiresAt: now - 1000, // Expired 1 second ago - createdAt: now - 10000, - }; - - const validToken: StoredUCANToken = { - id: 'token2', - token: 'valid-token', - type: 'origin', - issuer: 'did:valid', - audience: testAccount1, - expiresAt: now + 10000, // Expires in 10 seconds - createdAt: now, - }; - - await db.tokens.bulkAdd([expiredToken, validToken]); - - // Verify both tokens are stored - let tokens = await db.tokens.toArray(); - expect(tokens).toHaveLength(2); - - // Clean up expired tokens - await storageManager.cleanupExpiredData(); - - // Verify only valid token remains - tokens = await db.tokens.toArray(); - expect(tokens).toHaveLength(1); - expect(tokens[0].id).toBe('token2'); - }); - - it('should clean up expired sessions', async () => { - const now = Date.now(); - - await db.sessions.add({ - id: 'session1', - accountAddress: testAccount1, - sessionData: 'expired-session', - expiresAt: now - 1000, - createdAt: now - 10000, - }); - - await db.sessions.add({ - id: 'session2', - accountAddress: testAccount1, - sessionData: 'valid-session', - expiresAt: now + 10000, - createdAt: now, - }); - - // Verify both sessions are stored - let sessions = await db.sessions.toArray(); - expect(sessions).toHaveLength(2); - - // Clean up expired sessions - await storageManager.cleanupExpiredData(); - - // Verify only valid session remains - sessions = await db.sessions.toArray(); - expect(sessions).toHaveLength(1); - expect(sessions[0].id).toBe('session2'); - }); - }); - - describe('Storage Persistence API', () => { - beforeEach(() => { - storageManager = new VaultStorageManager({ - enablePersistence: true, - }); - }); - - afterEach(async () => { - await storageManager.closeAll(); - }); - - it('should handle storage persistence status', async () => { - // In test environment, these will return false/never - const isPersisted = await storageManager.isStoragePersisted(); - expect(typeof isPersisted).toBe('boolean'); - - const status = await storageManager.tryPersistWithoutPromptingUser(); - expect(['persisted', 'prompt', 'never']).toContain(status); - }); - - it('should handle storage estimate', async () => { - const estimate = await storageManager.getStorageEstimate(); - // In test environment, this might return null - if (estimate) { - expect(estimate).toHaveProperty('usage'); - expect(estimate).toHaveProperty('quota'); - } - }); - }); - - describe('Database Schema and Tables', () => { - let db: AccountVaultDatabase; - - beforeEach(async () => { - db = new AccountVaultDatabase(testAccount1); - await db.open(); - }); - - afterEach(async () => { - await db.close(); - await db.delete(); - }); - - it('should have correct table structure', () => { - expect(db.state).toBeDefined(); - expect(db.tokens).toBeDefined(); - expect(db.sessions).toBeDefined(); - expect(db.metadata).toBeDefined(); - }); - - it('should store and retrieve state', async () => { - const state: StoredVaultState = { - id: 'current', - accountAddress: testAccount1, - isInitialized: true, - enclave: JSON.stringify({ test: 'data' }), - lastAccessed: Date.now(), - createdAt: Date.now(), - }; - - await db.state.put(state); - const retrieved = await db.state.get('current'); - - expect(retrieved).toBeDefined(); - expect(retrieved?.accountAddress).toBe(testAccount1); - expect(retrieved?.isInitialized).toBe(true); - }); - - it('should store and retrieve metadata', async () => { - await db.metadata.add({ - id: 'meta1', - accountAddress: testAccount1, - key: 'theme', - value: 'dark', - updatedAt: Date.now(), - }); - - const metadata = await db.metadata.toArray(); - expect(metadata).toHaveLength(1); - expect(metadata[0].key).toBe('theme'); - expect(metadata[0].value).toBe('dark'); - }); - }); - - describe('Error Handling', () => { - beforeEach(() => { - storageManager = new VaultStorageManager(); - }); - - afterEach(async () => { - await storageManager.closeAll(); - }); - - it('should handle invalid account address', async () => { - await expect(storageManager.getDatabase('')).rejects.toThrow('Account address is required'); - await expect(storageManager.getDatabase(null as any)).rejects.toThrow('Account address is required'); - }); - - it('should handle database errors gracefully', async () => { - const db = await storageManager.getDatabase(testAccount1); - - // Close the database - await db.close(); - - // Try to perform operations on closed database - try { - await db.state.toArray(); - } catch (error: any) { - expect(error).toBeDefined(); - expect(error.message).toContain('closed'); - } - }); - }); - - describe('Backward Compatibility', () => { - it('should work without persistence enabled', () => { - const client = createVaultClient({ - enablePersistence: false, - }); - - expect(client).toBeInstanceOf(VaultClient); - expect(client.isReady()).toBe(false); - }); - - it('should work with default configuration', () => { - const client = createVaultClient(); - - expect(client).toBeInstanceOf(VaultClient); - expect(client.isReady()).toBe(false); - }); - - it('should not persist when disabled', async () => { - const client = createVaultClient({ - enablePersistence: false, - }); - - try { - await client.initialize('/fake/path.wasm'); - } catch (error) { - // Expected - } - - // These methods should return empty/null when persistence is disabled - const state = await client.loadPersistedState(); - const tokens = await client.getPersistedTokens(); - const accounts = await client.listPersistedAccounts(); - - expect(state).toBeNull(); - expect(tokens).toHaveLength(0); - expect(accounts).toHaveLength(0); - - await client.cleanup(); - }); - }); -}); \ No newline at end of file diff --git a/packages/es/src/plugin/storage.test.ts b/packages/es/src/plugin/storage.test.ts deleted file mode 100644 index 37fedcc49..000000000 --- a/packages/es/src/plugin/storage.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { VaultStorageManager, AccountVaultDatabase } from './storage'; -import type { StoredVaultState, StoredUCANToken, VaultStorageConfig } from './types'; -import Dexie from 'dexie'; - -describe('VaultStorageManager', () => { - let storageManager: VaultStorageManager; - const testAccountAddress = 'sonr1test123abc'; - - beforeEach(() => { - storageManager = new VaultStorageManager({ - enablePersistence: true, - autoCleanup: false, // Disable auto cleanup for tests - }); - }); - - afterEach(async () => { - await storageManager.closeAll(); - }); - - describe('Database Management', () => { - it('should create a database for an account', async () => { - const db = await storageManager.getDatabase(testAccountAddress); - expect(db).toBeDefined(); - expect(db).toBeInstanceOf(AccountVaultDatabase); - }); - - it('should reuse existing database for the same account', async () => { - const db1 = await storageManager.getDatabase(testAccountAddress); - const db2 = await storageManager.getDatabase(testAccountAddress); - expect(db1).toBe(db2); - }); - - it('should create separate databases for different accounts', async () => { - const account1 = 'sonr1account1'; - const account2 = 'sonr1account2'; - - const db1 = await storageManager.getDatabase(account1); - const db2 = await storageManager.getDatabase(account2); - - expect(db1).not.toBe(db2); - }); - - it('should throw error when account address is not provided', async () => { - await expect(storageManager.getDatabase('')).rejects.toThrow('Account address is required'); - }); - - it('should remove a database for an account', async () => { - const db = await storageManager.getDatabase(testAccountAddress); - expect(db).toBeDefined(); - - await storageManager.removeDatabase(testAccountAddress); - - // Getting the database again should create a new instance - const newDb = await storageManager.getDatabase(testAccountAddress); - expect(newDb).not.toBe(db); - }); - }); - - describe('Storage Persistence', () => { - it('should request persistent storage when enabled', async () => { - const mockPersist = vi.fn().mockResolvedValue(true); - Object.defineProperty(global, 'navigator', { - value: { - storage: { - persist: mockPersist, - }, - }, - configurable: true, - }); - - const result = await storageManager.requestPersistentStorage(); - expect(result).toBe(true); - expect(mockPersist).toHaveBeenCalled(); - }); - - it('should handle missing storage API gracefully', async () => { - Object.defineProperty(global, 'navigator', { - value: {}, - configurable: true, - }); - - const result = await storageManager.requestPersistentStorage(); - expect(result).toBe(false); - }); - - it('should check if storage is persisted', async () => { - const mockPersisted = vi.fn().mockResolvedValue(true); - Object.defineProperty(global, 'navigator', { - value: { - storage: { - persisted: mockPersisted, - }, - }, - configurable: true, - }); - - const result = await storageManager.isStoragePersisted(); - expect(result).toBe(true); - expect(mockPersisted).toHaveBeenCalled(); - }); - - it('should get storage estimate', async () => { - const mockEstimate = { - usage: 1024 * 1024 * 10, // 10MB - quota: 1024 * 1024 * 100, // 100MB - }; - - Object.defineProperty(global, 'navigator', { - value: { - storage: { - estimate: vi.fn().mockResolvedValue(mockEstimate), - }, - }, - configurable: true, - }); - - const estimate = await storageManager.getStorageEstimate(); - expect(estimate).toEqual(mockEstimate); - }); - }); - - describe('Cleanup Operations', () => { - it('should clean up expired data', async () => { - const db = await storageManager.getDatabase(testAccountAddress); - - // Mock the database tables - const mockTokensDelete = vi.fn().mockResolvedValue(2); - const mockSessionsDelete = vi.fn().mockResolvedValue(1); - const mockStateModify = vi.fn().mockResolvedValue(1); - - db.tokens = { - where: vi.fn().mockReturnThis(), - below: vi.fn().mockReturnThis(), - delete: mockTokensDelete, - } as any; - - db.sessions = { - where: vi.fn().mockReturnThis(), - below: vi.fn().mockReturnThis(), - delete: mockSessionsDelete, - } as any; - - db.state = { - where: vi.fn().mockReturnThis(), - equals: vi.fn().mockReturnThis(), - modify: mockStateModify, - } as any; - - await storageManager.cleanupExpiredData(); - - expect(mockTokensDelete).toHaveBeenCalled(); - expect(mockSessionsDelete).toHaveBeenCalled(); - expect(mockStateModify).toHaveBeenCalled(); - }); - - it('should close all databases', async () => { - const db1 = await storageManager.getDatabase('account1'); - const db2 = await storageManager.getDatabase('account2'); - - const mockClose1 = vi.fn(); - const mockClose2 = vi.fn(); - - db1.close = mockClose1; - db2.close = mockClose2; - - await storageManager.closeAll(); - - expect(mockClose1).toHaveBeenCalled(); - expect(mockClose2).toHaveBeenCalled(); - }); - }); - - describe('Persistence Status', () => { - it('should return "persisted" when storage is already persisted', async () => { - Object.defineProperty(global, 'navigator', { - value: { - storage: { - persisted: vi.fn().mockResolvedValue(true), - persist: vi.fn().mockResolvedValue(true), - }, - }, - configurable: true, - }); - - const status = await storageManager.tryPersistWithoutPromptingUser(); - expect(status).toBe('persisted'); - }); - - it('should return "prompt" when persistence requires user interaction', async () => { - Object.defineProperty(global, 'navigator', { - value: { - storage: { - persisted: vi.fn().mockResolvedValue(false), - persist: vi.fn().mockResolvedValue(false), - }, - }, - configurable: true, - }); - - const status = await storageManager.tryPersistWithoutPromptingUser(); - expect(status).toBe('prompt'); - }); - - it('should return "never" when storage API is not available', async () => { - Object.defineProperty(global, 'navigator', { - value: {}, - configurable: true, - }); - - const status = await storageManager.tryPersistWithoutPromptingUser(); - expect(status).toBe('never'); - }); - }); -}); - -describe('AccountVaultDatabase', () => { - const testAccountAddress = 'sonr1test123abc'; - - it('should create database with correct name', () => { - const db = new AccountVaultDatabase(testAccountAddress); - expect(db.name).toBe(`vault_${testAccountAddress}`); - }); - - it('should have correct table definitions', () => { - const db = new AccountVaultDatabase(testAccountAddress); - - // Verify table properties exist - expect(db).toHaveProperty('state'); - expect(db).toHaveProperty('tokens'); - expect(db).toHaveProperty('sessions'); - expect(db).toHaveProperty('metadata'); - }); -}); \ No newline at end of file diff --git a/packages/es/src/plugin/storage.ts b/packages/es/src/plugin/storage.ts deleted file mode 100644 index f013fc37b..000000000 --- a/packages/es/src/plugin/storage.ts +++ /dev/null @@ -1,264 +0,0 @@ -import Dexie, { type Table } from 'dexie'; -import type { - StoredVaultState, - StoredUCANToken, - VaultStorageConfig -} from './types'; - -/** - * Session data stored in IndexedDB - */ -export interface StoredSession { - id: string; - accountAddress: string; - sessionData: string; - expiresAt: number; - createdAt: number; -} - -/** - * Metadata stored in IndexedDB - */ -export interface StoredMetadata { - id: string; - accountAddress: string; - key: string; - value: string; - updatedAt: number; -} - -/** - * Account-specific vault database - */ -export class AccountVaultDatabase extends Dexie { - state!: Table; - tokens!: Table; - sessions!: Table; - metadata!: Table; - - constructor(accountAddress: string) { - super(`vault_${accountAddress}`); - - // Define schema version 1 - this.version(1).stores({ - state: 'id, accountAddress, lastAccessed', - tokens: 'id, type, issuer, audience, expiresAt, createdAt', - sessions: 'id, accountAddress, expiresAt, createdAt', - metadata: 'id, accountAddress, key, updatedAt' - }); - } -} - -/** - * Manages vault storage for multiple accounts - */ -export class VaultStorageManager { - private databases: Map = new Map(); - private config: VaultStorageConfig; - private cleanupTimer?: NodeJS.Timeout; - - constructor(config: VaultStorageConfig = {}) { - this.config = { - enablePersistence: false, - autoCleanup: true, - cleanupInterval: 3600000, // 1 hour - ...config - }; - - if (this.config.autoCleanup) { - this.startCleanupTimer(); - } - } - - /** - * Get or create database for account - */ - async getDatabase(accountAddress: string): Promise { - if (!accountAddress) { - throw new Error('Account address is required'); - } - - // Return existing database if available - let db = this.databases.get(accountAddress); - if (db) { - return db; - } - - // Create new database for account - db = new AccountVaultDatabase(accountAddress); - await db.open(); - - this.databases.set(accountAddress, db); - - // Request persistent storage if configured - if (this.config.enablePersistence) { - await this.requestPersistentStorage(); - } - - return db; - } - - /** - * Remove database for account - */ - async removeDatabase(accountAddress: string): Promise { - const db = this.databases.get(accountAddress); - if (db) { - await db.close(); - await db.delete(); - this.databases.delete(accountAddress); - } - } - - /** - * List all persisted accounts - */ - async listPersistedAccounts(): Promise { - const databases = await Dexie.getDatabaseNames(); - return databases - .filter(name => name.startsWith('vault_')) - .map(name => name.replace('vault_', '')); - } - - /** - * Request persistent storage from browser - */ - async requestPersistentStorage(): Promise { - if ('storage' in navigator && 'persist' in navigator.storage) { - try { - return await navigator.storage.persist(); - } catch (error) { - console.warn('Failed to request persistent storage:', error); - return false; - } - } - return false; - } - - /** - * Check if storage is persisted - */ - async isStoragePersisted(): Promise { - if ('storage' in navigator && 'persisted' in navigator.storage) { - try { - return await navigator.storage.persisted(); - } catch (error) { - console.warn('Failed to check storage persistence:', error); - return false; - } - } - return false; - } - - /** - * Get storage estimate - */ - async getStorageEstimate(): Promise { - if ('storage' in navigator && 'estimate' in navigator.storage) { - try { - return await navigator.storage.estimate(); - } catch (error) { - console.warn('Failed to get storage estimate:', error); - return null; - } - } - return null; - } - - /** - * Clean up expired tokens and sessions - */ - async cleanupExpiredData(): Promise { - const now = Date.now(); - - for (const [accountAddress, db] of this.databases.entries()) { - try { - // Remove expired tokens - await db.tokens - .where('expiresAt') - .below(now) - .delete(); - - // Remove expired sessions - await db.sessions - .where('expiresAt') - .below(now) - .delete(); - - // Update last accessed time for state - await db.state.where('accountAddress').equals(accountAddress).modify({ - lastAccessed: now - }); - } catch (error) { - console.error(`Cleanup failed for account ${accountAddress}:`, error); - } - } - } - - /** - * Start automatic cleanup timer - */ - private startCleanupTimer(): void { - if (this.cleanupTimer) { - clearInterval(this.cleanupTimer); - } - - this.cleanupTimer = setInterval(async () => { - await this.cleanupExpiredData(); - }, this.config.cleanupInterval!); - } - - /** - * Stop cleanup timer - */ - stopCleanupTimer(): void { - if (this.cleanupTimer) { - clearInterval(this.cleanupTimer); - this.cleanupTimer = undefined; - } - } - - /** - * Close all databases - */ - async closeAll(): Promise { - this.stopCleanupTimer(); - - for (const db of this.databases.values()) { - await db.close(); - } - - this.databases.clear(); - } - - /** - * Try to persist storage without user prompt - */ - async tryPersistWithoutPromptingUser(): Promise { - if (!('storage' in navigator) || !('persist' in navigator.storage)) { - return 'never'; - } - - // Check if already persisted - const persisted = await navigator.storage.persisted(); - if (persisted) { - return 'persisted'; - } - - // Try to persist without prompt - const result = await navigator.storage.persist(); - if (result) { - return 'persisted'; - } - - return 'prompt'; - } -} - -/** - * Default storage manager instance - */ -export const defaultStorageManager = new VaultStorageManager({ - enablePersistence: true, - autoCleanup: true -}); \ No newline at end of file diff --git a/packages/es/src/plugin/types.ts b/packages/es/src/plugin/types.ts deleted file mode 100644 index 9d66f59e2..000000000 --- a/packages/es/src/plugin/types.ts +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Type definitions for Vault WASM module - * Mirrors the Go plugin interface from cmd/vault - */ - -/** - * MPC Enclave data for vault initialization - */ -export interface EnclaveData { - publicKey: string; - privateKeyShares: string[]; - threshold: number; - parties: number; -} - -/** - * Vault configuration options - */ -export interface VaultConfig { - chainId?: string; - enclave?: EnclaveData; - [key: string]: any; -} - -/** - * Request for creating a new origin UCAN token - */ -export interface NewOriginTokenRequest { - audience_did: string; - attenuations?: Record[]; - facts?: string[]; - not_before?: number; - expires_at?: number; -} - -/** - * Request for creating a new attenuated UCAN token - */ -export interface NewAttenuatedTokenRequest { - parent_token: string; - audience_did: string; - attenuations?: Record[]; - facts?: string[]; - not_before?: number; - expires_at?: number; -} - -/** - * UCAN token response - */ -export interface UCANTokenResponse { - token: string; - issuer: string; - address: string; - error?: string; -} - -/** - * Request for signing data - */ -export interface SignDataRequest { - data: Uint8Array; -} - -/** - * Response from signing data - */ -export interface SignDataResponse { - signature: Uint8Array; - error?: string; -} - -/** - * Request for verifying data - */ -export interface VerifyDataRequest { - data: Uint8Array; - signature: Uint8Array; -} - -/** - * Response from verifying data - */ -export interface VerifyDataResponse { - valid: boolean; - error?: string; -} - -/** - * Response for getting issuer DID - */ -export interface GetIssuerDIDResponse { - issuer_did: string; - address: string; - chain_code: string; - error?: string; -} - -/** - * Vault plugin interface matching the WASM exports - */ -export interface VaultPlugin { - newOriginToken(request: NewOriginTokenRequest): Promise; - newAttenuatedToken(request: NewAttenuatedTokenRequest): Promise; - signData(request: SignDataRequest): Promise; - verifyData(request: VerifyDataRequest): Promise; - getIssuerDID(): Promise; -} - -/** - * Error codes for vault operations - */ -export enum VaultErrorCode { - NOT_INITIALIZED = 'VAULT_NOT_INITIALIZED', - ALREADY_INITIALIZED = 'VAULT_ALREADY_INITIALIZED', - LOCKED = 'VAULT_LOCKED', - KEY_NOT_FOUND = 'KEY_NOT_FOUND', - INVALID_KEY_TYPE = 'INVALID_KEY_TYPE', - OPERATION_FAILED = 'OPERATION_FAILED', - INVALID_PASSPHRASE = 'INVALID_PASSPHRASE', - WASM_NOT_LOADED = 'WASM_NOT_LOADED', - TIMEOUT = 'TIMEOUT', -} - -/** - * Vault error class - */ -export class VaultError extends Error { - constructor( - public code: VaultErrorCode, - message: string, - public details?: any - ) { - super(message); - this.name = 'VaultError'; - } -} - -/** - * Vault event types - */ -export enum VaultEventType { - INITIALIZED = 'vault:initialized', - LOCKED = 'vault:locked', - UNLOCKED = 'vault:unlocked', - KEY_GENERATED = 'vault:key_generated', - KEY_DELETED = 'vault:key_deleted', - EXPORTED = 'vault:exported', - IMPORTED = 'vault:imported', - ERROR = 'vault:error', -} - -/** - * Vault event - */ -export interface VaultEvent { - type: VaultEventType; - timestamp: number; - data?: any; -} - -/** - * Vault event listener - */ -export type VaultEventListener = (event: VaultEvent) => void; - -/** - * Storage configuration for vault - */ -export interface VaultStorageConfig { - enablePersistence?: boolean; - storageQuotaRequest?: number; - autoCleanup?: boolean; - cleanupInterval?: number; -} - -/** - * Enhanced vault configuration with storage options - */ -export interface VaultConfigWithStorage extends VaultConfig, VaultStorageConfig {} - -/** - * Stored vault state in IndexedDB - */ -export interface StoredVaultState { - id: string; - accountAddress: string; - isInitialized: boolean; - enclave?: string; - lastAccessed: number; - createdAt: number; -} - -/** - * Stored UCAN token in IndexedDB - */ -export interface StoredUCANToken { - id: string; - token: string; - type: 'origin' | 'attenuated'; - issuer: string; - audience: string; - capabilities?: string; - expiresAt?: number; - createdAt: number; -} - -/** - * Storage persistence status - */ -export type StoragePersistenceStatus = 'persisted' | 'prompt' | 'never'; - -/** - * Storage statistics - */ -export interface StorageStats { - accountCount: number; - tokenCount: number; - sessionCount: number; - storageUsed?: number; - storageQuota?: number; - isPersisted: boolean; -} - -/** - * IPFS-specific vault configuration - */ -export interface VaultIPFSConfig { - /** IPFS gateway URLs for fallback */ - ipfsGateways?: string[]; - /** Enable IPFS persistence */ - enableIPFSPersistence?: boolean; - /** Custom IPFS node configuration */ - ipfsNodeConfig?: any; -} - -/** - * Enhanced vault configuration with IPFS support - */ -export interface VaultConfigWithIPFS extends VaultConfigWithStorage, VaultIPFSConfig {} - -/** - * IPFS-stored enclave reference - */ -export interface IPFSEnclaveReference { - /** CID of the encrypted enclave data */ - cid: string; - /** Timestamp when stored */ - storedAt: number; - /** Whether the data is pinned */ - isPinned: boolean; - /** Size of the encrypted data */ - size: number; -} - -/** - * Vault state with IPFS references - */ -export interface VaultStateWithIPFS extends StoredVaultState { - /** IPFS CID references for enclave data */ - ipfsReferences?: IPFSEnclaveReference[]; - /** Last IPFS sync timestamp */ - lastIPFSSync?: number; -} \ No newline at end of file diff --git a/packages/es/src/protobufs/cosmos/app/runtime/v1alpha1/module_pb.ts b/packages/es/src/protobufs/cosmos/app/runtime/v1alpha1/module_pb.ts deleted file mode 100644 index e86cacb48..000000000 --- a/packages/es/src/protobufs/cosmos/app/runtime/v1alpha1/module_pb.ts +++ /dev/null @@ -1,248 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/app/runtime/v1alpha1/module.proto (package cosmos.app.runtime.v1alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * Module is the config object for the runtime module. - * - * @generated from message cosmos.app.runtime.v1alpha1.Module - */ -export class Module extends Message { - /** - * app_name is the name of the app. - * - * @generated from field: string app_name = 1; - */ - appName = ''; - - /** - * begin_blockers specifies the module names of begin blockers - * to call in the order in which they should be called. If this is left empty - * no begin blocker will be registered. - * - * @generated from field: repeated string begin_blockers = 2; - */ - beginBlockers: string[] = []; - - /** - * end_blockers specifies the module names of the end blockers - * to call in the order in which they should be called. If this is left empty - * no end blocker will be registered. - * - * @generated from field: repeated string end_blockers = 3; - */ - endBlockers: string[] = []; - - /** - * init_genesis specifies the module names of init genesis functions - * to call in the order in which they should be called. If this is left empty - * no init genesis function will be registered. - * - * @generated from field: repeated string init_genesis = 4; - */ - initGenesis: string[] = []; - - /** - * export_genesis specifies the order in which to export module genesis data. - * If this is left empty, the init_genesis order will be used for export genesis - * if it is specified. - * - * @generated from field: repeated string export_genesis = 5; - */ - exportGenesis: string[] = []; - - /** - * override_store_keys is an optional list of overrides for the module store keys - * to be used in keeper construction. - * - * @generated from field: repeated cosmos.app.runtime.v1alpha1.StoreKeyConfig override_store_keys = 6; - */ - overrideStoreKeys: StoreKeyConfig[] = []; - - /** - * order_migrations defines the order in which module migrations are performed. - * If this is left empty, it uses the default migration order. - * https://pkg.go.dev/github.com/cosmos/cosmos-sdk@v0.47.0-alpha2/types/module#DefaultMigrationsOrder - * - * @generated from field: repeated string order_migrations = 7; - */ - orderMigrations: string[] = []; - - /** - * precommiters specifies the module names of the precommiters - * to call in the order in which they should be called. If this is left empty - * no precommit function will be registered. - * - * @generated from field: repeated string precommiters = 8; - */ - precommiters: string[] = []; - - /** - * prepare_check_staters specifies the module names of the prepare_check_staters - * to call in the order in which they should be called. If this is left empty - * no preparecheckstate function will be registered. - * - * @generated from field: repeated string prepare_check_staters = 9; - */ - prepareCheckStaters: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.runtime.v1alpha1.Module'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'app_name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'begin_blockers', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 3, - name: 'end_blockers', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 4, - name: 'init_genesis', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 5, - name: 'export_genesis', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 6, - name: 'override_store_keys', - kind: 'message', - T: StoreKeyConfig, - repeated: true, - }, - { - no: 7, - name: 'order_migrations', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 8, - name: 'precommiters', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 9, - name: 'prepare_check_staters', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals( - a: Module | PlainMessage | undefined, - b: Module | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Module, a, b); - } -} - -/** - * StoreKeyConfig may be supplied to override the default module store key, which - * is the module name. - * - * @generated from message cosmos.app.runtime.v1alpha1.StoreKeyConfig - */ -export class StoreKeyConfig extends Message { - /** - * name of the module to override the store key of - * - * @generated from field: string module_name = 1; - */ - moduleName = ''; - - /** - * the kv store key to use instead of the module name. - * - * @generated from field: string kv_store_key = 2; - */ - kvStoreKey = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.runtime.v1alpha1.StoreKeyConfig'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'module_name', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { - no: 2, - name: 'kv_store_key', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreKeyConfig { - return new StoreKeyConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreKeyConfig { - return new StoreKeyConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreKeyConfig { - return new StoreKeyConfig().fromJsonString(jsonString, options); - } - - static equals( - a: StoreKeyConfig | PlainMessage | undefined, - b: StoreKeyConfig | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StoreKeyConfig, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/app/v1alpha1/config_pb.ts b/packages/es/src/protobufs/cosmos/app/v1alpha1/config_pb.ts deleted file mode 100644 index 2edd8fad8..000000000 --- a/packages/es/src/protobufs/cosmos/app/v1alpha1/config_pb.ts +++ /dev/null @@ -1,226 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/app/v1alpha1/config.proto (package cosmos.app.v1alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3 } from '@bufbuild/protobuf'; - -/** - * Config represents the configuration for a Cosmos SDK ABCI app. - * It is intended that all state machine logic including the version of - * baseapp and tx handlers (and possibly even Tendermint) that an app needs - * can be described in a config object. For compatibility, the framework should - * allow a mixture of declarative and imperative app wiring, however, apps - * that strive for the maximum ease of maintainability should be able to describe - * their state machine with a config object alone. - * - * @generated from message cosmos.app.v1alpha1.Config - */ -export class Config extends Message { - /** - * modules are the module configurations for the app. - * - * @generated from field: repeated cosmos.app.v1alpha1.ModuleConfig modules = 1; - */ - modules: ModuleConfig[] = []; - - /** - * golang_bindings specifies explicit interface to implementation type bindings which - * depinject uses to resolve interface inputs to provider functions. The scope of this - * field's configuration is global (not module specific). - * - * @generated from field: repeated cosmos.app.v1alpha1.GolangBinding golang_bindings = 2; - */ - golangBindings: GolangBinding[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.Config'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'modules', - kind: 'message', - T: ModuleConfig, - repeated: true, - }, - { - no: 2, - name: 'golang_bindings', - kind: 'message', - T: GolangBinding, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Config { - return new Config().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Config { - return new Config().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Config { - return new Config().fromJsonString(jsonString, options); - } - - static equals( - a: Config | PlainMessage | undefined, - b: Config | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Config, a, b); - } -} - -/** - * ModuleConfig is a module configuration for an app. - * - * @generated from message cosmos.app.v1alpha1.ModuleConfig - */ -export class ModuleConfig extends Message { - /** - * name is the unique name of the module within the app. It should be a name - * that persists between different versions of a module so that modules - * can be smoothly upgraded to new versions. - * - * For example, for the module cosmos.bank.module.v1.Module, we may chose - * to simply name the module "bank" in the app. When we upgrade to - * cosmos.bank.module.v2.Module, the app-specific name "bank" stays the same - * and the framework knows that the v2 module should receive all the same state - * that the v1 module had. Note: modules should provide info on which versions - * they can migrate from in the ModuleDescriptor.can_migration_from field. - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * config is the config object for the module. Module config messages should - * define a ModuleDescriptor using the cosmos.app.v1alpha1.is_module extension. - * - * @generated from field: google.protobuf.Any config = 2; - */ - config?: Any; - - /** - * golang_bindings specifies explicit interface to implementation type bindings which - * depinject uses to resolve interface inputs to provider functions. The scope of this - * field's configuration is module specific. - * - * @generated from field: repeated cosmos.app.v1alpha1.GolangBinding golang_bindings = 3; - */ - golangBindings: GolangBinding[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.ModuleConfig'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'config', kind: 'message', T: Any }, - { - no: 3, - name: 'golang_bindings', - kind: 'message', - T: GolangBinding, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleConfig { - return new ModuleConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleConfig { - return new ModuleConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleConfig { - return new ModuleConfig().fromJsonString(jsonString, options); - } - - static equals( - a: ModuleConfig | PlainMessage | undefined, - b: ModuleConfig | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModuleConfig, a, b); - } -} - -/** - * GolangBinding is an explicit interface type to implementing type binding for dependency injection. - * - * @generated from message cosmos.app.v1alpha1.GolangBinding - */ -export class GolangBinding extends Message { - /** - * interface_type is the interface type which will be bound to a specific implementation type - * - * @generated from field: string interface_type = 1; - */ - interfaceType = ''; - - /** - * implementation is the implementing type which will be supplied when an input of type interface is requested - * - * @generated from field: string implementation = 2; - */ - implementation = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.GolangBinding'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'interface_type', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { - no: 2, - name: 'implementation', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GolangBinding { - return new GolangBinding().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GolangBinding { - return new GolangBinding().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GolangBinding { - return new GolangBinding().fromJsonString(jsonString, options); - } - - static equals( - a: GolangBinding | PlainMessage | undefined, - b: GolangBinding | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GolangBinding, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/app/v1alpha1/module_pb.ts b/packages/es/src/protobufs/cosmos/app/v1alpha1/module_pb.ts deleted file mode 100644 index c3c06e0d6..000000000 --- a/packages/es/src/protobufs/cosmos/app/v1alpha1/module_pb.ts +++ /dev/null @@ -1,229 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/app/v1alpha1/module.proto (package cosmos.app.v1alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * ModuleDescriptor describes an app module. - * - * @generated from message cosmos.app.v1alpha1.ModuleDescriptor - */ -export class ModuleDescriptor extends Message { - /** - * go_import names the package that should be imported by an app to load the - * module in the runtime module registry. It is required to make debugging - * of configuration errors easier for users. - * - * @generated from field: string go_import = 1; - */ - goImport = ''; - - /** - * use_package refers to a protobuf package that this module - * uses and exposes to the world. In an app, only one module should "use" - * or own a single protobuf package. It is assumed that the module uses - * all of the .proto files in a single package. - * - * @generated from field: repeated cosmos.app.v1alpha1.PackageReference use_package = 2; - */ - usePackage: PackageReference[] = []; - - /** - * can_migrate_from defines which module versions this module can migrate - * state from. The framework will check that one module version is able to - * migrate from a previous module version before attempting to update its - * config. It is assumed that modules can transitively migrate from earlier - * versions. For instance if v3 declares it can migrate from v2, and v2 - * declares it can migrate from v1, the framework knows how to migrate - * from v1 to v3, assuming all 3 module versions are registered at runtime. - * - * @generated from field: repeated cosmos.app.v1alpha1.MigrateFromInfo can_migrate_from = 3; - */ - canMigrateFrom: MigrateFromInfo[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.ModuleDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'go_import', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'use_package', - kind: 'message', - T: PackageReference, - repeated: true, - }, - { - no: 3, - name: 'can_migrate_from', - kind: 'message', - T: MigrateFromInfo, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleDescriptor { - return new ModuleDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleDescriptor { - return new ModuleDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleDescriptor { - return new ModuleDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: ModuleDescriptor | PlainMessage | undefined, - b: ModuleDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModuleDescriptor, a, b); - } -} - -/** - * PackageReference is a reference to a protobuf package used by a module. - * - * @generated from message cosmos.app.v1alpha1.PackageReference - */ -export class PackageReference extends Message { - /** - * name is the fully-qualified name of the package. - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * revision is the optional revision of the package that is being used. - * Protobuf packages used in Cosmos should generally have a major version - * as the last part of the package name, ex. foo.bar.baz.v1. - * The revision of a package can be thought of as the minor version of a - * package which has additional backwards compatible definitions that weren't - * present in a previous version. - * - * A package should indicate its revision with a source code comment - * above the package declaration in one of its files containing the - * text "Revision N" where N is an integer revision. All packages start - * at revision 0 the first time they are released in a module. - * - * When a new version of a module is released and items are added to existing - * .proto files, these definitions should contain comments of the form - * "Since: Revision N" where N is an integer revision. - * - * When the module runtime starts up, it will check the pinned proto - * image and panic if there are runtime protobuf definitions that are not - * in the pinned descriptor which do not have - * a "Since Revision N" comment or have a "Since Revision N" comment where - * N is <= to the revision specified here. This indicates that the protobuf - * files have been updated, but the pinned file descriptor hasn't. - * - * If there are items in the pinned file descriptor with a revision - * greater than the value indicated here, this will also cause a panic - * as it may mean that the pinned descriptor for a legacy module has been - * improperly updated or that there is some other versioning discrepancy. - * Runtime protobuf definitions will also be checked for compatibility - * with pinned file descriptors to make sure there are no incompatible changes. - * - * This behavior ensures that: - * * pinned proto images are up-to-date - * * protobuf files are carefully annotated with revision comments which - * are important good client UX - * * protobuf files are changed in backwards and forwards compatible ways - * - * @generated from field: uint32 revision = 2; - */ - revision = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.PackageReference'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'revision', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PackageReference { - return new PackageReference().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PackageReference { - return new PackageReference().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PackageReference { - return new PackageReference().fromJsonString(jsonString, options); - } - - static equals( - a: PackageReference | PlainMessage | undefined, - b: PackageReference | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PackageReference, a, b); - } -} - -/** - * MigrateFromInfo is information on a module version that a newer module - * can migrate from. - * - * @generated from message cosmos.app.v1alpha1.MigrateFromInfo - */ -export class MigrateFromInfo extends Message { - /** - * module is the fully-qualified protobuf name of the module config object - * for the previous module version, ex: "cosmos.group.module.v1.Module". - * - * @generated from field: string module = 1; - */ - module = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.MigrateFromInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'module', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MigrateFromInfo { - return new MigrateFromInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MigrateFromInfo { - return new MigrateFromInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MigrateFromInfo { - return new MigrateFromInfo().fromJsonString(jsonString, options); - } - - static equals( - a: MigrateFromInfo | PlainMessage | undefined, - b: MigrateFromInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(MigrateFromInfo, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/app/v1alpha1/query_cosmes.ts b/packages/es/src/protobufs/cosmos/app/v1alpha1/query_cosmes.ts deleted file mode 100644 index 5308c04a1..000000000 --- a/packages/es/src/protobufs/cosmos/app/v1alpha1/query_cosmes.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/app/v1alpha1/query.proto (package cosmos.app.v1alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryConfigRequest, QueryConfigResponse } from './query_pb.js'; - -const TYPE_NAME = 'cosmos.app.v1alpha1.Query'; - -/** - * Config returns the current app config. - * - * @generated from rpc cosmos.app.v1alpha1.Query.Config - */ -export const QueryConfigService = { - typeName: TYPE_NAME, - method: 'Config', - Request: QueryConfigRequest, - Response: QueryConfigResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/app/v1alpha1/query_pb.ts b/packages/es/src/protobufs/cosmos/app/v1alpha1/query_pb.ts deleted file mode 100644 index 8ba7521ee..000000000 --- a/packages/es/src/protobufs/cosmos/app/v1alpha1/query_pb.ts +++ /dev/null @@ -1,100 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/app/v1alpha1/query.proto (package cosmos.app.v1alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; -import { Config } from './config_pb.js'; - -/** - * QueryConfigRequest is the Query/Config request type. - * - * @generated from message cosmos.app.v1alpha1.QueryConfigRequest - */ -export class QueryConfigRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.QueryConfigRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConfigRequest { - return new QueryConfigRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConfigRequest { - return new QueryConfigRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): QueryConfigRequest { - return new QueryConfigRequest().fromJsonString(jsonString, options); - } - - static equals( - a: QueryConfigRequest | PlainMessage | undefined, - b: QueryConfigRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(QueryConfigRequest, a, b); - } -} - -/** - * QueryConfigRequest is the Query/Config response type. - * - * @generated from message cosmos.app.v1alpha1.QueryConfigResponse - */ -export class QueryConfigResponse extends Message { - /** - * config is the current app config. - * - * @generated from field: cosmos.app.v1alpha1.Config config = 1; - */ - config?: Config; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.app.v1alpha1.QueryConfigResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'config', kind: 'message', T: Config }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConfigResponse { - return new QueryConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConfigResponse { - return new QueryConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): QueryConfigResponse { - return new QueryConfigResponse().fromJsonString(jsonString, options); - } - - static equals( - a: QueryConfigResponse | PlainMessage | undefined, - b: QueryConfigResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(QueryConfigResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/autocli/v1/options_pb.ts b/packages/es/src/protobufs/cosmos/autocli/v1/options_pb.ts deleted file mode 100644 index 2a9ff60cd..000000000 --- a/packages/es/src/protobufs/cosmos/autocli/v1/options_pb.ts +++ /dev/null @@ -1,495 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/autocli/v1/options.proto (package cosmos.autocli.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * ModuleOptions describes the CLI options for a Cosmos SDK module. - * - * @generated from message cosmos.autocli.v1.ModuleOptions - */ -export class ModuleOptions extends Message { - /** - * tx describes the tx commands for the module. - * - * @generated from field: cosmos.autocli.v1.ServiceCommandDescriptor tx = 1; - */ - tx?: ServiceCommandDescriptor; - - /** - * query describes the queries commands for the module. - * - * @generated from field: cosmos.autocli.v1.ServiceCommandDescriptor query = 2; - */ - query?: ServiceCommandDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.ModuleOptions'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: ServiceCommandDescriptor }, - { no: 2, name: 'query', kind: 'message', T: ServiceCommandDescriptor }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleOptions { - return new ModuleOptions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleOptions { - return new ModuleOptions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleOptions { - return new ModuleOptions().fromJsonString(jsonString, options); - } - - static equals( - a: ModuleOptions | PlainMessage | undefined, - b: ModuleOptions | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModuleOptions, a, b); - } -} - -/** - * ServiceCommandDescriptor describes a CLI command based on a protobuf service. - * - * @generated from message cosmos.autocli.v1.ServiceCommandDescriptor - */ -export class ServiceCommandDescriptor extends Message { - /** - * service is the fully qualified name of the protobuf service to build - * the command from. It can be left empty if sub_commands are used instead - * which may be the case if a module provides multiple tx and/or query services. - * - * @generated from field: string service = 1; - */ - service = ''; - - /** - * rpc_command_options are options for commands generated from rpc methods. - * If no options are specified for a given rpc method on the service, a - * command will be generated for that method with the default options. - * - * @generated from field: repeated cosmos.autocli.v1.RpcCommandOptions rpc_command_options = 2; - */ - rpcCommandOptions: RpcCommandOptions[] = []; - - /** - * sub_commands is a map of optional sub-commands for this command based on - * different protobuf services. The map key is used as the name of the - * sub-command. - * - * @generated from field: map sub_commands = 3; - */ - subCommands: { [key: string]: ServiceCommandDescriptor } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.ServiceCommandDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'service', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'rpc_command_options', - kind: 'message', - T: RpcCommandOptions, - repeated: true, - }, - { - no: 3, - name: 'sub_commands', - kind: 'map', - K: 9 /* ScalarType.STRING */, - V: { kind: 'message', T: ServiceCommandDescriptor }, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ServiceCommandDescriptor { - return new ServiceCommandDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ServiceCommandDescriptor { - return new ServiceCommandDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ServiceCommandDescriptor { - return new ServiceCommandDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: ServiceCommandDescriptor | PlainMessage | undefined, - b: ServiceCommandDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ServiceCommandDescriptor, a, b); - } -} - -/** - * RpcCommandOptions specifies options for commands generated from protobuf - * rpc methods. - * - * @generated from message cosmos.autocli.v1.RpcCommandOptions - */ -export class RpcCommandOptions extends Message { - /** - * rpc_method is short name of the protobuf rpc method that this command is - * generated from. - * - * @generated from field: string rpc_method = 1; - */ - rpcMethod = ''; - - /** - * use is the one-line usage method. It also allows specifying an alternate - * name for the command as the first word of the usage text. - * - * By default the name of an rpc command is the kebab-case short name of the - * rpc method. - * - * @generated from field: string use = 2; - */ - use = ''; - - /** - * long is the long message shown in the 'help ' output. - * - * @generated from field: string long = 3; - */ - long = ''; - - /** - * short is the short description shown in the 'help' output. - * - * @generated from field: string short = 4; - */ - short = ''; - - /** - * example is examples of how to use the command. - * - * @generated from field: string example = 5; - */ - example = ''; - - /** - * alias is an array of aliases that can be used instead of the first word in Use. - * - * @generated from field: repeated string alias = 6; - */ - alias: string[] = []; - - /** - * suggest_for is an array of command names for which this command will be suggested - - * similar to aliases but only suggests. - * - * @generated from field: repeated string suggest_for = 7; - */ - suggestFor: string[] = []; - - /** - * deprecated defines, if this command is deprecated and should print this string when used. - * - * @generated from field: string deprecated = 8; - */ - deprecated = ''; - - /** - * version defines the version for this command. If this value is non-empty and the command does not - * define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - * will print content of the "Version" variable. A shorthand "v" flag will also be added if the - * command does not define one. - * - * @generated from field: string version = 9; - */ - version = ''; - - /** - * flag_options are options for flags generated from rpc request fields. - * By default all request fields are configured as flags. They can - * also be configured as positional args instead using positional_args. - * - * @generated from field: map flag_options = 10; - */ - flagOptions: { [key: string]: FlagOptions } = {}; - - /** - * positional_args specifies positional arguments for the command. - * - * @generated from field: repeated cosmos.autocli.v1.PositionalArgDescriptor positional_args = 11; - */ - positionalArgs: PositionalArgDescriptor[] = []; - - /** - * skip specifies whether to skip this rpc method when generating commands. - * - * @generated from field: bool skip = 12; - */ - skip = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.RpcCommandOptions'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'rpc_method', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'use', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'long', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 4, name: 'short', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 5, name: 'example', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 6, - name: 'alias', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { - no: 7, - name: 'suggest_for', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { no: 8, name: 'deprecated', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 9, name: 'version', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 10, - name: 'flag_options', - kind: 'map', - K: 9 /* ScalarType.STRING */, - V: { kind: 'message', T: FlagOptions }, - }, - { - no: 11, - name: 'positional_args', - kind: 'message', - T: PositionalArgDescriptor, - repeated: true, - }, - { no: 12, name: 'skip', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RpcCommandOptions { - return new RpcCommandOptions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RpcCommandOptions { - return new RpcCommandOptions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RpcCommandOptions { - return new RpcCommandOptions().fromJsonString(jsonString, options); - } - - static equals( - a: RpcCommandOptions | PlainMessage | undefined, - b: RpcCommandOptions | PlainMessage | undefined - ): boolean { - return proto3.util.equals(RpcCommandOptions, a, b); - } -} - -/** - * FlagOptions are options for flags generated from rpc request fields. - * By default, all request fields are configured as flags based on the - * kebab-case name of the field. Fields can be turned into positional arguments - * instead by using RpcCommandOptions.positional_args. - * - * @generated from message cosmos.autocli.v1.FlagOptions - */ -export class FlagOptions extends Message { - /** - * name is an alternate name to use for the field flag. - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * shorthand is a one-letter abbreviated flag. - * - * @generated from field: string shorthand = 2; - */ - shorthand = ''; - - /** - * usage is the help message. - * - * @generated from field: string usage = 3; - */ - usage = ''; - - /** - * default_value is the default value as text. - * - * @generated from field: string default_value = 4; - */ - defaultValue = ''; - - /** - * deprecated is the usage text to show if this flag is deprecated. - * - * @generated from field: string deprecated = 6; - */ - deprecated = ''; - - /** - * shorthand_deprecated is the usage text to show if the shorthand of this flag is deprecated. - * - * @generated from field: string shorthand_deprecated = 7; - */ - shorthandDeprecated = ''; - - /** - * hidden hides the flag from help/usage text - * - * @generated from field: bool hidden = 8; - */ - hidden = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.FlagOptions'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'shorthand', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'usage', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 4, - name: 'default_value', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { no: 6, name: 'deprecated', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 7, - name: 'shorthand_deprecated', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { no: 8, name: 'hidden', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FlagOptions { - return new FlagOptions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FlagOptions { - return new FlagOptions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FlagOptions { - return new FlagOptions().fromJsonString(jsonString, options); - } - - static equals( - a: FlagOptions | PlainMessage | undefined, - b: FlagOptions | PlainMessage | undefined - ): boolean { - return proto3.util.equals(FlagOptions, a, b); - } -} - -/** - * PositionalArgDescriptor describes a positional argument. - * - * @generated from message cosmos.autocli.v1.PositionalArgDescriptor - */ -export class PositionalArgDescriptor extends Message { - /** - * proto_field specifies the proto field to use as the positional arg. Any - * fields used as positional args will not have a flag generated. - * - * @generated from field: string proto_field = 1; - */ - protoField = ''; - - /** - * varargs makes a positional parameter a varargs parameter. This can only be - * applied to last positional parameter and the proto_field must a repeated - * field. - * - * @generated from field: bool varargs = 2; - */ - varargs = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.PositionalArgDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'proto_field', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { no: 2, name: 'varargs', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): PositionalArgDescriptor { - return new PositionalArgDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): PositionalArgDescriptor { - return new PositionalArgDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): PositionalArgDescriptor { - return new PositionalArgDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: PositionalArgDescriptor | PlainMessage | undefined, - b: PositionalArgDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PositionalArgDescriptor, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/autocli/v1/query_cosmes.ts b/packages/es/src/protobufs/cosmos/autocli/v1/query_cosmes.ts deleted file mode 100644 index 5bdda777b..000000000 --- a/packages/es/src/protobufs/cosmos/autocli/v1/query_cosmes.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/autocli/v1/query.proto (package cosmos.autocli.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { AppOptionsRequest, AppOptionsResponse } from './query_pb.js'; - -const TYPE_NAME = 'cosmos.autocli.v1.Query'; - -/** - * AppOptions returns the autocli options for all of the modules in an app. - * - * @generated from rpc cosmos.autocli.v1.Query.AppOptions - */ -export const QueryAppOptionsService = { - typeName: TYPE_NAME, - method: 'AppOptions', - Request: AppOptionsRequest, - Response: AppOptionsResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/autocli/v1/query_pb.ts b/packages/es/src/protobufs/cosmos/autocli/v1/query_pb.ts deleted file mode 100644 index 8bbdbe8f0..000000000 --- a/packages/es/src/protobufs/cosmos/autocli/v1/query_pb.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/autocli/v1/query.proto (package cosmos.autocli.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; -import { ModuleOptions } from './options_pb.js'; - -/** - * AppOptionsRequest is the RemoteInfoService/AppOptions request type. - * - * @generated from message cosmos.autocli.v1.AppOptionsRequest - */ -export class AppOptionsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.AppOptionsRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): AppOptionsRequest { - return new AppOptionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AppOptionsRequest { - return new AppOptionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AppOptionsRequest { - return new AppOptionsRequest().fromJsonString(jsonString, options); - } - - static equals( - a: AppOptionsRequest | PlainMessage | undefined, - b: AppOptionsRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AppOptionsRequest, a, b); - } -} - -/** - * AppOptionsResponse is the RemoteInfoService/AppOptions response type. - * - * @generated from message cosmos.autocli.v1.AppOptionsResponse - */ -export class AppOptionsResponse extends Message { - /** - * module_options is a map of module name to autocli module options. - * - * @generated from field: map module_options = 1; - */ - moduleOptions: { [key: string]: ModuleOptions } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.autocli.v1.AppOptionsResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'module_options', - kind: 'map', - K: 9 /* ScalarType.STRING */, - V: { kind: 'message', T: ModuleOptions }, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AppOptionsResponse { - return new AppOptionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AppOptionsResponse { - return new AppOptionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): AppOptionsResponse { - return new AppOptionsResponse().fromJsonString(jsonString, options); - } - - static equals( - a: AppOptionsResponse | PlainMessage | undefined, - b: AppOptionsResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AppOptionsResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/abci/v1beta1/abci_pb.ts b/packages/es/src/protobufs/cosmos/base/abci/v1beta1/abci_pb.ts deleted file mode 100644 index a4670687e..000000000 --- a/packages/es/src/protobufs/cosmos/base/abci/v1beta1/abci_pb.ts +++ /dev/null @@ -1,792 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/abci/v1beta1/abci.proto (package cosmos.base.abci.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { Event } from '../../../../tendermint/abci/types_pb.js'; -import { Block } from '../../../../tendermint/types/block_pb.js'; - -/** - * TxResponse defines a structure containing relevant tx data and metadata. The - * tags are stringified and the log is JSON decoded. - * - * @generated from message cosmos.base.abci.v1beta1.TxResponse - */ -export class TxResponse extends Message { - /** - * The block height - * - * @generated from field: int64 height = 1; - */ - height = protoInt64.zero; - - /** - * The transaction hash. - * - * @generated from field: string txhash = 2; - */ - txhash = ''; - - /** - * Namespace for the Code - * - * @generated from field: string codespace = 3; - */ - codespace = ''; - - /** - * Response code. - * - * @generated from field: uint32 code = 4; - */ - code = 0; - - /** - * Result bytes, if any. - * - * @generated from field: string data = 5; - */ - data = ''; - - /** - * The output of the application's logger (raw string). May be - * non-deterministic. - * - * @generated from field: string raw_log = 6; - */ - rawLog = ''; - - /** - * The output of the application's logger (typed). May be non-deterministic. - * - * @generated from field: repeated cosmos.base.abci.v1beta1.ABCIMessageLog logs = 7; - */ - logs: ABCIMessageLog[] = []; - - /** - * Additional information. May be non-deterministic. - * - * @generated from field: string info = 8; - */ - info = ''; - - /** - * Amount of gas requested for transaction. - * - * @generated from field: int64 gas_wanted = 9; - */ - gasWanted = protoInt64.zero; - - /** - * Amount of gas consumed by transaction. - * - * @generated from field: int64 gas_used = 10; - */ - gasUsed = protoInt64.zero; - - /** - * The request transaction bytes. - * - * @generated from field: google.protobuf.Any tx = 11; - */ - tx?: Any; - - /** - * Time of the previous block. For heights > 1, it's the weighted median of - * the timestamps of the valid votes in the block.LastCommit. For height == 1, - * it's genesis time. - * - * @generated from field: string timestamp = 12; - */ - timestamp = ''; - - /** - * Events defines all the events emitted by processing a transaction. Note, - * these events include those emitted by processing all the messages and those - * emitted from the ante. Whereas Logs contains the events, with - * additional metadata, emitted only by processing the messages. - * - * Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 - * - * @generated from field: repeated tendermint.abci.Event events = 13; - */ - events: Event[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.TxResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: 'txhash', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'codespace', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 4, name: 'code', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 5, name: 'data', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 6, name: 'raw_log', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 7, name: 'logs', kind: 'message', T: ABCIMessageLog, repeated: true }, - { no: 8, name: 'info', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 9, name: 'gas_wanted', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 10, name: 'gas_used', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 11, name: 'tx', kind: 'message', T: Any }, - { no: 12, name: 'timestamp', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 13, name: 'events', kind: 'message', T: Event, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxResponse { - return new TxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxResponse { - return new TxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxResponse { - return new TxResponse().fromJsonString(jsonString, options); - } - - static equals( - a: TxResponse | PlainMessage | undefined, - b: TxResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxResponse, a, b); - } -} - -/** - * ABCIMessageLog defines a structure containing an indexed tx ABCI message log. - * - * @generated from message cosmos.base.abci.v1beta1.ABCIMessageLog - */ -export class ABCIMessageLog extends Message { - /** - * @generated from field: uint32 msg_index = 1; - */ - msgIndex = 0; - - /** - * @generated from field: string log = 2; - */ - log = ''; - - /** - * Events contains a slice of Event objects that were emitted during some - * execution. - * - * @generated from field: repeated cosmos.base.abci.v1beta1.StringEvent events = 3; - */ - events: StringEvent[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.ABCIMessageLog'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'msg_index', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: 'log', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'events', kind: 'message', T: StringEvent, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ABCIMessageLog { - return new ABCIMessageLog().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ABCIMessageLog { - return new ABCIMessageLog().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ABCIMessageLog { - return new ABCIMessageLog().fromJsonString(jsonString, options); - } - - static equals( - a: ABCIMessageLog | PlainMessage | undefined, - b: ABCIMessageLog | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ABCIMessageLog, a, b); - } -} - -/** - * StringEvent defines en Event object wrapper where all the attributes - * contain key/value pairs that are strings instead of raw bytes. - * - * @generated from message cosmos.base.abci.v1beta1.StringEvent - */ -export class StringEvent extends Message { - /** - * @generated from field: string type = 1; - */ - type = ''; - - /** - * @generated from field: repeated cosmos.base.abci.v1beta1.Attribute attributes = 2; - */ - attributes: Attribute[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.StringEvent'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'type', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'attributes', - kind: 'message', - T: Attribute, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StringEvent { - return new StringEvent().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StringEvent { - return new StringEvent().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StringEvent { - return new StringEvent().fromJsonString(jsonString, options); - } - - static equals( - a: StringEvent | PlainMessage | undefined, - b: StringEvent | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StringEvent, a, b); - } -} - -/** - * Attribute defines an attribute wrapper where the key and value are - * strings instead of raw bytes. - * - * @generated from message cosmos.base.abci.v1beta1.Attribute - */ -export class Attribute extends Message { - /** - * @generated from field: string key = 1; - */ - key = ''; - - /** - * @generated from field: string value = 2; - */ - value = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.Attribute'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'value', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Attribute { - return new Attribute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Attribute { - return new Attribute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Attribute { - return new Attribute().fromJsonString(jsonString, options); - } - - static equals( - a: Attribute | PlainMessage | undefined, - b: Attribute | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Attribute, a, b); - } -} - -/** - * GasInfo defines tx execution gas context. - * - * @generated from message cosmos.base.abci.v1beta1.GasInfo - */ -export class GasInfo extends Message { - /** - * GasWanted is the maximum units of work we allow this tx to perform. - * - * @generated from field: uint64 gas_wanted = 1; - */ - gasWanted = protoInt64.zero; - - /** - * GasUsed is the amount of gas actually consumed. - * - * @generated from field: uint64 gas_used = 2; - */ - gasUsed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.GasInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'gas_wanted', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: 'gas_used', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GasInfo { - return new GasInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GasInfo { - return new GasInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GasInfo { - return new GasInfo().fromJsonString(jsonString, options); - } - - static equals( - a: GasInfo | PlainMessage | undefined, - b: GasInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GasInfo, a, b); - } -} - -/** - * Result is the union of ResponseFormat and ResponseCheckTx. - * - * @generated from message cosmos.base.abci.v1beta1.Result - */ -export class Result extends Message { - /** - * Data is any data returned from message or handler execution. It MUST be - * length prefixed in order to separate data from multiple message executions. - * Deprecated. This field is still populated, but prefer msg_response instead - * because it also contains the Msg response typeURL. - * - * @generated from field: bytes data = 1 [deprecated = true]; - * @deprecated - */ - data = new Uint8Array(0); - - /** - * Log contains the log information from message or handler execution. - * - * @generated from field: string log = 2; - */ - log = ''; - - /** - * Events contains a slice of Event objects that were emitted during message - * or handler execution. - * - * @generated from field: repeated tendermint.abci.Event events = 3; - */ - events: Event[] = []; - - /** - * msg_responses contains the Msg handler responses type packed in Anys. - * - * Since: cosmos-sdk 0.46 - * - * @generated from field: repeated google.protobuf.Any msg_responses = 4; - */ - msgResponses: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.Result'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'data', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'log', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'events', kind: 'message', T: Event, repeated: true }, - { no: 4, name: 'msg_responses', kind: 'message', T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Result { - return new Result().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Result { - return new Result().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Result { - return new Result().fromJsonString(jsonString, options); - } - - static equals( - a: Result | PlainMessage | undefined, - b: Result | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Result, a, b); - } -} - -/** - * SimulationResponse defines the response generated when a transaction is - * successfully simulated. - * - * @generated from message cosmos.base.abci.v1beta1.SimulationResponse - */ -export class SimulationResponse extends Message { - /** - * @generated from field: cosmos.base.abci.v1beta1.GasInfo gas_info = 1; - */ - gasInfo?: GasInfo; - - /** - * @generated from field: cosmos.base.abci.v1beta1.Result result = 2; - */ - result?: Result; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.SimulationResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'gas_info', kind: 'message', T: GasInfo }, - { no: 2, name: 'result', kind: 'message', T: Result }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SimulationResponse { - return new SimulationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SimulationResponse { - return new SimulationResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SimulationResponse { - return new SimulationResponse().fromJsonString(jsonString, options); - } - - static equals( - a: SimulationResponse | PlainMessage | undefined, - b: SimulationResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SimulationResponse, a, b); - } -} - -/** - * MsgData defines the data returned in a Result object during message - * execution. - * - * @generated from message cosmos.base.abci.v1beta1.MsgData - * @deprecated - */ -export class MsgData extends Message { - /** - * @generated from field: string msg_type = 1; - */ - msgType = ''; - - /** - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.MsgData'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'msg_type', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'data', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgData { - return new MsgData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgData { - return new MsgData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgData { - return new MsgData().fromJsonString(jsonString, options); - } - - static equals( - a: MsgData | PlainMessage | undefined, - b: MsgData | PlainMessage | undefined - ): boolean { - return proto3.util.equals(MsgData, a, b); - } -} - -/** - * TxMsgData defines a list of MsgData. A transaction will have a MsgData object - * for each message. - * - * @generated from message cosmos.base.abci.v1beta1.TxMsgData - */ -export class TxMsgData extends Message { - /** - * data field is deprecated and not populated. - * - * @generated from field: repeated cosmos.base.abci.v1beta1.MsgData data = 1 [deprecated = true]; - * @deprecated - */ - data: MsgData[] = []; - - /** - * msg_responses contains the Msg handler responses packed into Anys. - * - * Since: cosmos-sdk 0.46 - * - * @generated from field: repeated google.protobuf.Any msg_responses = 2; - */ - msgResponses: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.TxMsgData'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'data', kind: 'message', T: MsgData, repeated: true }, - { no: 2, name: 'msg_responses', kind: 'message', T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxMsgData { - return new TxMsgData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxMsgData { - return new TxMsgData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxMsgData { - return new TxMsgData().fromJsonString(jsonString, options); - } - - static equals( - a: TxMsgData | PlainMessage | undefined, - b: TxMsgData | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxMsgData, a, b); - } -} - -/** - * SearchTxsResult defines a structure for querying txs pageable - * - * @generated from message cosmos.base.abci.v1beta1.SearchTxsResult - */ -export class SearchTxsResult extends Message { - /** - * Count of all txs - * - * @generated from field: uint64 total_count = 1; - */ - totalCount = protoInt64.zero; - - /** - * Count of txs in current page - * - * @generated from field: uint64 count = 2; - */ - count = protoInt64.zero; - - /** - * Index of current page, start from 1 - * - * @generated from field: uint64 page_number = 3; - */ - pageNumber = protoInt64.zero; - - /** - * Count of total pages - * - * @generated from field: uint64 page_total = 4; - */ - pageTotal = protoInt64.zero; - - /** - * Max count txs per page - * - * @generated from field: uint64 limit = 5; - */ - limit = protoInt64.zero; - - /** - * List of txs in current page - * - * @generated from field: repeated cosmos.base.abci.v1beta1.TxResponse txs = 6; - */ - txs: TxResponse[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.SearchTxsResult'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'total_count', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - { no: 2, name: 'count', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { - no: 3, - name: 'page_number', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - { no: 4, name: 'page_total', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: 'limit', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: 'txs', kind: 'message', T: TxResponse, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SearchTxsResult { - return new SearchTxsResult().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SearchTxsResult { - return new SearchTxsResult().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SearchTxsResult { - return new SearchTxsResult().fromJsonString(jsonString, options); - } - - static equals( - a: SearchTxsResult | PlainMessage | undefined, - b: SearchTxsResult | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SearchTxsResult, a, b); - } -} - -/** - * SearchBlocksResult defines a structure for querying blocks pageable - * - * @generated from message cosmos.base.abci.v1beta1.SearchBlocksResult - */ -export class SearchBlocksResult extends Message { - /** - * Count of all blocks - * - * @generated from field: int64 total_count = 1; - */ - totalCount = protoInt64.zero; - - /** - * Count of blocks in current page - * - * @generated from field: int64 count = 2; - */ - count = protoInt64.zero; - - /** - * Index of current page, start from 1 - * - * @generated from field: int64 page_number = 3; - */ - pageNumber = protoInt64.zero; - - /** - * Count of total pages - * - * @generated from field: int64 page_total = 4; - */ - pageTotal = protoInt64.zero; - - /** - * Max count blocks per page - * - * @generated from field: int64 limit = 5; - */ - limit = protoInt64.zero; - - /** - * List of blocks in current page - * - * @generated from field: repeated tendermint.types.Block blocks = 6; - */ - blocks: Block[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.abci.v1beta1.SearchBlocksResult'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'total_count', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: 'count', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: 'page_number', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: 'page_total', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: 'limit', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: 'blocks', kind: 'message', T: Block, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SearchBlocksResult { - return new SearchBlocksResult().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SearchBlocksResult { - return new SearchBlocksResult().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SearchBlocksResult { - return new SearchBlocksResult().fromJsonString(jsonString, options); - } - - static equals( - a: SearchBlocksResult | PlainMessage | undefined, - b: SearchBlocksResult | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SearchBlocksResult, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_cosmes.ts deleted file mode 100644 index 8bff9eab5..000000000 --- a/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,32 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/base/node/v1beta1/query.proto (package cosmos.base.node.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ConfigRequest, ConfigResponse, StatusRequest, StatusResponse } from './query_pb.js'; - -const TYPE_NAME = 'cosmos.base.node.v1beta1.Service'; - -/** - * Config queries for the operator configuration. - * - * @generated from rpc cosmos.base.node.v1beta1.Service.Config - */ -export const ServiceConfigService = { - typeName: TYPE_NAME, - method: 'Config', - Request: ConfigRequest, - Response: ConfigResponse, -} as const; - -/** - * Status queries for the node status. - * - * @generated from rpc cosmos.base.node.v1beta1.Service.Status - */ -export const ServiceStatusService = { - typeName: TYPE_NAME, - method: 'Status', - Request: StatusRequest, - Response: StatusResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_pb.ts b/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_pb.ts deleted file mode 100644 index 29539e91e..000000000 --- a/packages/es/src/protobufs/cosmos/base/node/v1beta1/query_pb.ts +++ /dev/null @@ -1,250 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/node/v1beta1/query.proto (package cosmos.base.node.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, Timestamp, proto3, protoInt64 } from '@bufbuild/protobuf'; - -/** - * ConfigRequest defines the request structure for the Config gRPC query. - * - * @generated from message cosmos.base.node.v1beta1.ConfigRequest - */ -export class ConfigRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.node.v1beta1.ConfigRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConfigRequest { - return new ConfigRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConfigRequest { - return new ConfigRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConfigRequest { - return new ConfigRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ConfigRequest | PlainMessage | undefined, - b: ConfigRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ConfigRequest, a, b); - } -} - -/** - * ConfigResponse defines the response structure for the Config gRPC query. - * - * @generated from message cosmos.base.node.v1beta1.ConfigResponse - */ -export class ConfigResponse extends Message { - /** - * @generated from field: string minimum_gas_price = 1; - */ - minimumGasPrice = ''; - - /** - * @generated from field: string pruning_keep_recent = 2; - */ - pruningKeepRecent = ''; - - /** - * @generated from field: string pruning_interval = 3; - */ - pruningInterval = ''; - - /** - * @generated from field: uint64 halt_height = 4; - */ - haltHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.node.v1beta1.ConfigResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'minimum_gas_price', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { - no: 2, - name: 'pruning_keep_recent', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { - no: 3, - name: 'pruning_interval', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - { - no: 4, - name: 'halt_height', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConfigResponse { - return new ConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConfigResponse { - return new ConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConfigResponse { - return new ConfigResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ConfigResponse | PlainMessage | undefined, - b: ConfigResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ConfigResponse, a, b); - } -} - -/** - * StateRequest defines the request structure for the status of a node. - * - * @generated from message cosmos.base.node.v1beta1.StatusRequest - */ -export class StatusRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.node.v1beta1.StatusRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): StatusRequest { - return new StatusRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StatusRequest { - return new StatusRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StatusRequest { - return new StatusRequest().fromJsonString(jsonString, options); - } - - static equals( - a: StatusRequest | PlainMessage | undefined, - b: StatusRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StatusRequest, a, b); - } -} - -/** - * StateResponse defines the response structure for the status of a node. - * - * @generated from message cosmos.base.node.v1beta1.StatusResponse - */ -export class StatusResponse extends Message { - /** - * earliest block height available in the store - * - * @generated from field: uint64 earliest_store_height = 1; - */ - earliestStoreHeight = protoInt64.zero; - - /** - * current block height - * - * @generated from field: uint64 height = 2; - */ - height = protoInt64.zero; - - /** - * block height timestamp - * - * @generated from field: google.protobuf.Timestamp timestamp = 3; - */ - timestamp?: Timestamp; - - /** - * app hash of the current block - * - * @generated from field: bytes app_hash = 4; - */ - appHash = new Uint8Array(0); - - /** - * validator hash provided by the consensus header - * - * @generated from field: bytes validator_hash = 5; - */ - validatorHash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.node.v1beta1.StatusResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'earliest_store_height', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - { no: 2, name: 'height', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: 'timestamp', kind: 'message', T: Timestamp }, - { no: 4, name: 'app_hash', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { - no: 5, - name: 'validator_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StatusResponse { - return new StatusResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StatusResponse { - return new StatusResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StatusResponse { - return new StatusResponse().fromJsonString(jsonString, options); - } - - static equals( - a: StatusResponse | PlainMessage | undefined, - b: StatusResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StatusResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/query/v1beta1/pagination_pb.ts b/packages/es/src/protobufs/cosmos/base/query/v1beta1/pagination_pb.ts deleted file mode 100644 index 390e5b447..000000000 --- a/packages/es/src/protobufs/cosmos/base/query/v1beta1/pagination_pb.ts +++ /dev/null @@ -1,167 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/query/v1beta1/pagination.proto (package cosmos.base.query.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3, protoInt64 } from '@bufbuild/protobuf'; - -/** - * PageRequest is to be embedded in gRPC request messages for efficient - * pagination. Ex: - * - * message SomeRequest { - * Foo some_parameter = 1; - * PageRequest pagination = 2; - * } - * - * @generated from message cosmos.base.query.v1beta1.PageRequest - */ -export class PageRequest extends Message { - /** - * key is a value returned in PageResponse.next_key to begin - * querying the next page most efficiently. Only one of offset or key - * should be set. - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * offset is a numeric offset that can be used when key is unavailable. - * It is less efficient than using key. Only one of offset or key should - * be set. - * - * @generated from field: uint64 offset = 2; - */ - offset = protoInt64.zero; - - /** - * limit is the total number of results to be returned in the result page. - * If left empty it will default to a value to be set by each app. - * - * @generated from field: uint64 limit = 3; - */ - limit = protoInt64.zero; - - /** - * count_total is set to true to indicate that the result set should include - * a count of the total number of items available for pagination in UIs. - * count_total is only respected when offset is used. It is ignored when key - * is set. - * - * @generated from field: bool count_total = 4; - */ - countTotal = false; - - /** - * reverse is set to true if results are to be returned in the descending order. - * - * Since: cosmos-sdk 0.43 - * - * @generated from field: bool reverse = 5; - */ - reverse = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.query.v1beta1.PageRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'offset', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: 'limit', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: 'count_total', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: 'reverse', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PageRequest { - return new PageRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PageRequest { - return new PageRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PageRequest { - return new PageRequest().fromJsonString(jsonString, options); - } - - static equals( - a: PageRequest | PlainMessage | undefined, - b: PageRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PageRequest, a, b); - } -} - -/** - * PageResponse is to be embedded in gRPC response messages where the - * corresponding request message has used PageRequest. - * - * message SomeResponse { - * repeated Bar results = 1; - * PageResponse page = 2; - * } - * - * @generated from message cosmos.base.query.v1beta1.PageResponse - */ -export class PageResponse extends Message { - /** - * next_key is the key to be passed to PageRequest.key to - * query the next page most efficiently. It will be empty if - * there are no more results. - * - * @generated from field: bytes next_key = 1; - */ - nextKey = new Uint8Array(0); - - /** - * total is total number of results available if PageRequest.count_total - * was set, its value is undefined otherwise - * - * @generated from field: uint64 total = 2; - */ - total = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.query.v1beta1.PageResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'next_key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'total', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PageResponse { - return new PageResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PageResponse { - return new PageResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PageResponse { - return new PageResponse().fromJsonString(jsonString, options); - } - - static equals( - a: PageResponse | PlainMessage | undefined, - b: PageResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PageResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_cosmes.ts b/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_cosmes.ts deleted file mode 100644 index ed93de770..000000000 --- a/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_cosmes.ts +++ /dev/null @@ -1,39 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/base/reflection/v1beta1/reflection.proto (package cosmos.base.reflection.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { - ListAllInterfacesRequest, - ListAllInterfacesResponse, - ListImplementationsRequest, - ListImplementationsResponse, -} from './reflection_pb.js'; - -const TYPE_NAME = 'cosmos.base.reflection.v1beta1.ReflectionService'; - -/** - * ListAllInterfaces lists all the interfaces registered in the interface - * registry. - * - * @generated from rpc cosmos.base.reflection.v1beta1.ReflectionService.ListAllInterfaces - */ -export const ReflectionServiceListAllInterfacesService = { - typeName: TYPE_NAME, - method: 'ListAllInterfaces', - Request: ListAllInterfacesRequest, - Response: ListAllInterfacesResponse, -} as const; - -/** - * ListImplementations list all the concrete types that implement a given - * interface. - * - * @generated from rpc cosmos.base.reflection.v1beta1.ReflectionService.ListImplementations - */ -export const ReflectionServiceListImplementationsService = { - typeName: TYPE_NAME, - method: 'ListImplementations', - Request: ListImplementationsRequest, - Response: ListImplementationsResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_pb.ts b/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_pb.ts deleted file mode 100644 index e88c4e9f5..000000000 --- a/packages/es/src/protobufs/cosmos/base/reflection/v1beta1/reflection_pb.ts +++ /dev/null @@ -1,234 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/reflection/v1beta1/reflection.proto (package cosmos.base.reflection.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * ListAllInterfacesRequest is the request type of the ListAllInterfaces RPC. - * - * @generated from message cosmos.base.reflection.v1beta1.ListAllInterfacesRequest - */ -export class ListAllInterfacesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v1beta1.ListAllInterfacesRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListAllInterfacesRequest { - return new ListAllInterfacesRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListAllInterfacesRequest { - return new ListAllInterfacesRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListAllInterfacesRequest { - return new ListAllInterfacesRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ListAllInterfacesRequest | PlainMessage | undefined, - b: ListAllInterfacesRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListAllInterfacesRequest, a, b); - } -} - -/** - * ListAllInterfacesResponse is the response type of the ListAllInterfaces RPC. - * - * @generated from message cosmos.base.reflection.v1beta1.ListAllInterfacesResponse - */ -export class ListAllInterfacesResponse extends Message { - /** - * interface_names is an array of all the registered interfaces. - * - * @generated from field: repeated string interface_names = 1; - */ - interfaceNames: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v1beta1.ListAllInterfacesResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'interface_names', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListAllInterfacesResponse { - return new ListAllInterfacesResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListAllInterfacesResponse { - return new ListAllInterfacesResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListAllInterfacesResponse { - return new ListAllInterfacesResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ListAllInterfacesResponse | PlainMessage | undefined, - b: ListAllInterfacesResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListAllInterfacesResponse, a, b); - } -} - -/** - * ListImplementationsRequest is the request type of the ListImplementations - * RPC. - * - * @generated from message cosmos.base.reflection.v1beta1.ListImplementationsRequest - */ -export class ListImplementationsRequest extends Message { - /** - * interface_name defines the interface to query the implementations for. - * - * @generated from field: string interface_name = 1; - */ - interfaceName = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v1beta1.ListImplementationsRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'interface_name', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListImplementationsRequest { - return new ListImplementationsRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListImplementationsRequest { - return new ListImplementationsRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListImplementationsRequest { - return new ListImplementationsRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ListImplementationsRequest | PlainMessage | undefined, - b: ListImplementationsRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListImplementationsRequest, a, b); - } -} - -/** - * ListImplementationsResponse is the response type of the ListImplementations - * RPC. - * - * @generated from message cosmos.base.reflection.v1beta1.ListImplementationsResponse - */ -export class ListImplementationsResponse extends Message { - /** - * @generated from field: repeated string implementation_message_names = 1; - */ - implementationMessageNames: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v1beta1.ListImplementationsResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'implementation_message_names', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListImplementationsResponse { - return new ListImplementationsResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListImplementationsResponse { - return new ListImplementationsResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListImplementationsResponse { - return new ListImplementationsResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ListImplementationsResponse | PlainMessage | undefined, - b: ListImplementationsResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListImplementationsResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_cosmes.ts b/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_cosmes.ts deleted file mode 100644 index d8311a9e0..000000000 --- a/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_cosmes.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Since: cosmos-sdk 0.43 - -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/base/reflection/v2alpha1/reflection.proto (package cosmos.base.reflection.v2alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { - GetAuthnDescriptorRequest, - GetAuthnDescriptorResponse, - GetChainDescriptorRequest, - GetChainDescriptorResponse, - GetCodecDescriptorRequest, - GetCodecDescriptorResponse, - GetConfigurationDescriptorRequest, - GetConfigurationDescriptorResponse, - GetQueryServicesDescriptorRequest, - GetQueryServicesDescriptorResponse, - GetTxDescriptorRequest, - GetTxDescriptorResponse, -} from './reflection_pb.js'; - -const TYPE_NAME = 'cosmos.base.reflection.v2alpha1.ReflectionService'; - -/** - * GetAuthnDescriptor returns information on how to authenticate transactions in the application - * NOTE: this RPC is still experimental and might be subject to breaking changes or removal in - * future releases of the cosmos-sdk. - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetAuthnDescriptor - */ -export const ReflectionServiceGetAuthnDescriptorService = { - typeName: TYPE_NAME, - method: 'GetAuthnDescriptor', - Request: GetAuthnDescriptorRequest, - Response: GetAuthnDescriptorResponse, -} as const; - -/** - * GetChainDescriptor returns the description of the chain - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetChainDescriptor - */ -export const ReflectionServiceGetChainDescriptorService = { - typeName: TYPE_NAME, - method: 'GetChainDescriptor', - Request: GetChainDescriptorRequest, - Response: GetChainDescriptorResponse, -} as const; - -/** - * GetCodecDescriptor returns the descriptor of the codec of the application - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetCodecDescriptor - */ -export const ReflectionServiceGetCodecDescriptorService = { - typeName: TYPE_NAME, - method: 'GetCodecDescriptor', - Request: GetCodecDescriptorRequest, - Response: GetCodecDescriptorResponse, -} as const; - -/** - * GetConfigurationDescriptor returns the descriptor for the sdk.Config of the application - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetConfigurationDescriptor - */ -export const ReflectionServiceGetConfigurationDescriptorService = { - typeName: TYPE_NAME, - method: 'GetConfigurationDescriptor', - Request: GetConfigurationDescriptorRequest, - Response: GetConfigurationDescriptorResponse, -} as const; - -/** - * GetQueryServicesDescriptor returns the available gRPC queryable services of the application - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetQueryServicesDescriptor - */ -export const ReflectionServiceGetQueryServicesDescriptorService = { - typeName: TYPE_NAME, - method: 'GetQueryServicesDescriptor', - Request: GetQueryServicesDescriptorRequest, - Response: GetQueryServicesDescriptorResponse, -} as const; - -/** - * GetTxDescriptor returns information on the used transaction object and available msgs that can be used - * - * @generated from rpc cosmos.base.reflection.v2alpha1.ReflectionService.GetTxDescriptor - */ -export const ReflectionServiceGetTxDescriptorService = { - typeName: TYPE_NAME, - method: 'GetTxDescriptor', - Request: GetTxDescriptorRequest, - Response: GetTxDescriptorResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_pb.ts b/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_pb.ts deleted file mode 100644 index 0a2e7e5c1..000000000 --- a/packages/es/src/protobufs/cosmos/base/reflection/v2alpha1/reflection_pb.ts +++ /dev/null @@ -1,1515 +0,0 @@ -// Since: cosmos-sdk 0.43 - -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/reflection/v2alpha1/reflection.proto (package cosmos.base.reflection.v2alpha1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * AppDescriptor describes a cosmos-sdk based application - * - * @generated from message cosmos.base.reflection.v2alpha1.AppDescriptor - */ -export class AppDescriptor extends Message { - /** - * AuthnDescriptor provides information on how to authenticate transactions on the application - * NOTE: experimental and subject to change in future releases. - * - * @generated from field: cosmos.base.reflection.v2alpha1.AuthnDescriptor authn = 1; - */ - authn?: AuthnDescriptor; - - /** - * chain provides the chain descriptor - * - * @generated from field: cosmos.base.reflection.v2alpha1.ChainDescriptor chain = 2; - */ - chain?: ChainDescriptor; - - /** - * codec provides metadata information regarding codec related types - * - * @generated from field: cosmos.base.reflection.v2alpha1.CodecDescriptor codec = 3; - */ - codec?: CodecDescriptor; - - /** - * configuration provides metadata information regarding the sdk.Config type - * - * @generated from field: cosmos.base.reflection.v2alpha1.ConfigurationDescriptor configuration = 4; - */ - configuration?: ConfigurationDescriptor; - - /** - * query_services provides metadata information regarding the available queriable endpoints - * - * @generated from field: cosmos.base.reflection.v2alpha1.QueryServicesDescriptor query_services = 5; - */ - queryServices?: QueryServicesDescriptor; - - /** - * tx provides metadata information regarding how to send transactions to the given application - * - * @generated from field: cosmos.base.reflection.v2alpha1.TxDescriptor tx = 6; - */ - tx?: TxDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.AppDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'authn', kind: 'message', T: AuthnDescriptor }, - { no: 2, name: 'chain', kind: 'message', T: ChainDescriptor }, - { no: 3, name: 'codec', kind: 'message', T: CodecDescriptor }, - { - no: 4, - name: 'configuration', - kind: 'message', - T: ConfigurationDescriptor, - }, - { - no: 5, - name: 'query_services', - kind: 'message', - T: QueryServicesDescriptor, - }, - { no: 6, name: 'tx', kind: 'message', T: TxDescriptor }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AppDescriptor { - return new AppDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AppDescriptor { - return new AppDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AppDescriptor { - return new AppDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: AppDescriptor | PlainMessage | undefined, - b: AppDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AppDescriptor, a, b); - } -} - -/** - * TxDescriptor describes the accepted transaction type - * - * @generated from message cosmos.base.reflection.v2alpha1.TxDescriptor - */ -export class TxDescriptor extends Message { - /** - * fullname is the protobuf fullname of the raw transaction type (for instance the tx.Tx type) - * it is not meant to support polymorphism of transaction types, it is supposed to be used by - * reflection clients to understand if they can handle a specific transaction type in an application. - * - * @generated from field: string fullname = 1; - */ - fullname = ''; - - /** - * msgs lists the accepted application messages (sdk.Msg) - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.MsgDescriptor msgs = 2; - */ - msgs: MsgDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.TxDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'fullname', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'msgs', kind: 'message', T: MsgDescriptor, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxDescriptor { - return new TxDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxDescriptor { - return new TxDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxDescriptor { - return new TxDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: TxDescriptor | PlainMessage | undefined, - b: TxDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxDescriptor, a, b); - } -} - -/** - * AuthnDescriptor provides information on how to sign transactions without relying - * on the online RPCs GetTxMetadata and CombineUnsignedTxAndSignatures - * - * @generated from message cosmos.base.reflection.v2alpha1.AuthnDescriptor - */ -export class AuthnDescriptor extends Message { - /** - * sign_modes defines the supported signature algorithm - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1; - */ - signModes: SigningModeDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.AuthnDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'sign_modes', - kind: 'message', - T: SigningModeDescriptor, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AuthnDescriptor { - return new AuthnDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AuthnDescriptor { - return new AuthnDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AuthnDescriptor { - return new AuthnDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: AuthnDescriptor | PlainMessage | undefined, - b: AuthnDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AuthnDescriptor, a, b); - } -} - -/** - * SigningModeDescriptor provides information on a signing flow of the application - * NOTE(fdymylja): here we could go as far as providing an entire flow on how - * to sign a message given a SigningModeDescriptor, but it's better to think about - * this another time - * - * @generated from message cosmos.base.reflection.v2alpha1.SigningModeDescriptor - */ -export class SigningModeDescriptor extends Message { - /** - * name defines the unique name of the signing mode - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * number is the unique int32 identifier for the sign_mode enum - * - * @generated from field: int32 number = 2; - */ - number = 0; - - /** - * authn_info_provider_method_fullname defines the fullname of the method to call to get - * the metadata required to authenticate using the provided sign_modes - * - * @generated from field: string authn_info_provider_method_fullname = 3; - */ - authnInfoProviderMethodFullname = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.SigningModeDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'number', kind: 'scalar', T: 5 /* ScalarType.INT32 */ }, - { - no: 3, - name: 'authn_info_provider_method_fullname', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SigningModeDescriptor { - return new SigningModeDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SigningModeDescriptor { - return new SigningModeDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SigningModeDescriptor { - return new SigningModeDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: SigningModeDescriptor | PlainMessage | undefined, - b: SigningModeDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SigningModeDescriptor, a, b); - } -} - -/** - * ChainDescriptor describes chain information of the application - * - * @generated from message cosmos.base.reflection.v2alpha1.ChainDescriptor - */ -export class ChainDescriptor extends Message { - /** - * id is the chain id - * - * @generated from field: string id = 1; - */ - id = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.ChainDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'id', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ChainDescriptor { - return new ChainDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ChainDescriptor { - return new ChainDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ChainDescriptor { - return new ChainDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: ChainDescriptor | PlainMessage | undefined, - b: ChainDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ChainDescriptor, a, b); - } -} - -/** - * CodecDescriptor describes the registered interfaces and provides metadata information on the types - * - * @generated from message cosmos.base.reflection.v2alpha1.CodecDescriptor - */ -export class CodecDescriptor extends Message { - /** - * interfaces is a list of the registerted interfaces descriptors - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.InterfaceDescriptor interfaces = 1; - */ - interfaces: InterfaceDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.CodecDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'interfaces', - kind: 'message', - T: InterfaceDescriptor, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CodecDescriptor { - return new CodecDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CodecDescriptor { - return new CodecDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CodecDescriptor { - return new CodecDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: CodecDescriptor | PlainMessage | undefined, - b: CodecDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CodecDescriptor, a, b); - } -} - -/** - * InterfaceDescriptor describes the implementation of an interface - * - * @generated from message cosmos.base.reflection.v2alpha1.InterfaceDescriptor - */ -export class InterfaceDescriptor extends Message { - /** - * fullname is the name of the interface - * - * @generated from field: string fullname = 1; - */ - fullname = ''; - - /** - * interface_accepting_messages contains information regarding the proto messages which contain the interface as - * google.protobuf.Any field - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.InterfaceAcceptingMessageDescriptor interface_accepting_messages = 2; - */ - interfaceAcceptingMessages: InterfaceAcceptingMessageDescriptor[] = []; - - /** - * interface_implementers is a list of the descriptors of the interface implementers - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.InterfaceImplementerDescriptor interface_implementers = 3; - */ - interfaceImplementers: InterfaceImplementerDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.InterfaceDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'fullname', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'interface_accepting_messages', - kind: 'message', - T: InterfaceAcceptingMessageDescriptor, - repeated: true, - }, - { - no: 3, - name: 'interface_implementers', - kind: 'message', - T: InterfaceImplementerDescriptor, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InterfaceDescriptor { - return new InterfaceDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InterfaceDescriptor { - return new InterfaceDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): InterfaceDescriptor { - return new InterfaceDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: InterfaceDescriptor | PlainMessage | undefined, - b: InterfaceDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(InterfaceDescriptor, a, b); - } -} - -/** - * InterfaceImplementerDescriptor describes an interface implementer - * - * @generated from message cosmos.base.reflection.v2alpha1.InterfaceImplementerDescriptor - */ -export class InterfaceImplementerDescriptor extends Message { - /** - * fullname is the protobuf queryable name of the interface implementer - * - * @generated from field: string fullname = 1; - */ - fullname = ''; - - /** - * type_url defines the type URL used when marshalling the type as any - * this is required so we can provide type safe google.protobuf.Any marshalling and - * unmarshalling, making sure that we don't accept just 'any' type - * in our interface fields - * - * @generated from field: string type_url = 2; - */ - typeUrl = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.InterfaceImplementerDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'fullname', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'type_url', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): InterfaceImplementerDescriptor { - return new InterfaceImplementerDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): InterfaceImplementerDescriptor { - return new InterfaceImplementerDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): InterfaceImplementerDescriptor { - return new InterfaceImplementerDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: InterfaceImplementerDescriptor | PlainMessage | undefined, - b: InterfaceImplementerDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(InterfaceImplementerDescriptor, a, b); - } -} - -/** - * InterfaceAcceptingMessageDescriptor describes a protobuf message which contains - * an interface represented as a google.protobuf.Any - * - * @generated from message cosmos.base.reflection.v2alpha1.InterfaceAcceptingMessageDescriptor - */ -export class InterfaceAcceptingMessageDescriptor extends Message { - /** - * fullname is the protobuf fullname of the type containing the interface - * - * @generated from field: string fullname = 1; - */ - fullname = ''; - - /** - * field_descriptor_names is a list of the protobuf name (not fullname) of the field - * which contains the interface as google.protobuf.Any (the interface is the same, but - * it can be in multiple fields of the same proto message) - * - * @generated from field: repeated string field_descriptor_names = 2; - */ - fieldDescriptorNames: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.InterfaceAcceptingMessageDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'fullname', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'field_descriptor_names', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): InterfaceAcceptingMessageDescriptor { - return new InterfaceAcceptingMessageDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): InterfaceAcceptingMessageDescriptor { - return new InterfaceAcceptingMessageDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): InterfaceAcceptingMessageDescriptor { - return new InterfaceAcceptingMessageDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: - | InterfaceAcceptingMessageDescriptor - | PlainMessage - | undefined, - b: - | InterfaceAcceptingMessageDescriptor - | PlainMessage - | undefined - ): boolean { - return proto3.util.equals(InterfaceAcceptingMessageDescriptor, a, b); - } -} - -/** - * ConfigurationDescriptor contains metadata information on the sdk.Config - * - * @generated from message cosmos.base.reflection.v2alpha1.ConfigurationDescriptor - */ -export class ConfigurationDescriptor extends Message { - /** - * bech32_account_address_prefix is the account address prefix - * - * @generated from field: string bech32_account_address_prefix = 1; - */ - bech32AccountAddressPrefix = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.ConfigurationDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'bech32_account_address_prefix', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ConfigurationDescriptor { - return new ConfigurationDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ConfigurationDescriptor { - return new ConfigurationDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ConfigurationDescriptor { - return new ConfigurationDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: ConfigurationDescriptor | PlainMessage | undefined, - b: ConfigurationDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ConfigurationDescriptor, a, b); - } -} - -/** - * MsgDescriptor describes a cosmos-sdk message that can be delivered with a transaction - * - * @generated from message cosmos.base.reflection.v2alpha1.MsgDescriptor - */ -export class MsgDescriptor extends Message { - /** - * msg_type_url contains the TypeURL of a sdk.Msg. - * - * @generated from field: string msg_type_url = 1; - */ - msgTypeUrl = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.MsgDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'msg_type_url', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDescriptor { - return new MsgDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDescriptor { - return new MsgDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDescriptor { - return new MsgDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: MsgDescriptor | PlainMessage | undefined, - b: MsgDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(MsgDescriptor, a, b); - } -} - -/** - * GetAuthnDescriptorRequest is the request used for the GetAuthnDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetAuthnDescriptorRequest - */ -export class GetAuthnDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetAuthnDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetAuthnDescriptorRequest { - return new GetAuthnDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetAuthnDescriptorRequest { - return new GetAuthnDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetAuthnDescriptorRequest { - return new GetAuthnDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetAuthnDescriptorRequest | PlainMessage | undefined, - b: GetAuthnDescriptorRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetAuthnDescriptorRequest, a, b); - } -} - -/** - * GetAuthnDescriptorResponse is the response returned by the GetAuthnDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetAuthnDescriptorResponse - */ -export class GetAuthnDescriptorResponse extends Message { - /** - * authn describes how to authenticate to the application when sending transactions - * - * @generated from field: cosmos.base.reflection.v2alpha1.AuthnDescriptor authn = 1; - */ - authn?: AuthnDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetAuthnDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'authn', kind: 'message', T: AuthnDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetAuthnDescriptorResponse { - return new GetAuthnDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetAuthnDescriptorResponse { - return new GetAuthnDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetAuthnDescriptorResponse { - return new GetAuthnDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetAuthnDescriptorResponse | PlainMessage | undefined, - b: GetAuthnDescriptorResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetAuthnDescriptorResponse, a, b); - } -} - -/** - * GetChainDescriptorRequest is the request used for the GetChainDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetChainDescriptorRequest - */ -export class GetChainDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetChainDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetChainDescriptorRequest { - return new GetChainDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetChainDescriptorRequest { - return new GetChainDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetChainDescriptorRequest { - return new GetChainDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetChainDescriptorRequest | PlainMessage | undefined, - b: GetChainDescriptorRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetChainDescriptorRequest, a, b); - } -} - -/** - * GetChainDescriptorResponse is the response returned by the GetChainDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetChainDescriptorResponse - */ -export class GetChainDescriptorResponse extends Message { - /** - * chain describes application chain information - * - * @generated from field: cosmos.base.reflection.v2alpha1.ChainDescriptor chain = 1; - */ - chain?: ChainDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetChainDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'chain', kind: 'message', T: ChainDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetChainDescriptorResponse { - return new GetChainDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetChainDescriptorResponse { - return new GetChainDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetChainDescriptorResponse { - return new GetChainDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetChainDescriptorResponse | PlainMessage | undefined, - b: GetChainDescriptorResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetChainDescriptorResponse, a, b); - } -} - -/** - * GetCodecDescriptorRequest is the request used for the GetCodecDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetCodecDescriptorRequest - */ -export class GetCodecDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetCodecDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetCodecDescriptorRequest { - return new GetCodecDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetCodecDescriptorRequest { - return new GetCodecDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetCodecDescriptorRequest { - return new GetCodecDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetCodecDescriptorRequest | PlainMessage | undefined, - b: GetCodecDescriptorRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetCodecDescriptorRequest, a, b); - } -} - -/** - * GetCodecDescriptorResponse is the response returned by the GetCodecDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetCodecDescriptorResponse - */ -export class GetCodecDescriptorResponse extends Message { - /** - * codec describes the application codec such as registered interfaces and implementations - * - * @generated from field: cosmos.base.reflection.v2alpha1.CodecDescriptor codec = 1; - */ - codec?: CodecDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetCodecDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'codec', kind: 'message', T: CodecDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetCodecDescriptorResponse { - return new GetCodecDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetCodecDescriptorResponse { - return new GetCodecDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetCodecDescriptorResponse { - return new GetCodecDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetCodecDescriptorResponse | PlainMessage | undefined, - b: GetCodecDescriptorResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetCodecDescriptorResponse, a, b); - } -} - -/** - * GetConfigurationDescriptorRequest is the request used for the GetConfigurationDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetConfigurationDescriptorRequest - */ -export class GetConfigurationDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetConfigurationDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetConfigurationDescriptorRequest { - return new GetConfigurationDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetConfigurationDescriptorRequest { - return new GetConfigurationDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetConfigurationDescriptorRequest { - return new GetConfigurationDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: - | GetConfigurationDescriptorRequest - | PlainMessage - | undefined, - b: - | GetConfigurationDescriptorRequest - | PlainMessage - | undefined - ): boolean { - return proto3.util.equals(GetConfigurationDescriptorRequest, a, b); - } -} - -/** - * GetConfigurationDescriptorResponse is the response returned by the GetConfigurationDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetConfigurationDescriptorResponse - */ -export class GetConfigurationDescriptorResponse extends Message { - /** - * config describes the application's sdk.Config - * - * @generated from field: cosmos.base.reflection.v2alpha1.ConfigurationDescriptor config = 1; - */ - config?: ConfigurationDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetConfigurationDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'config', kind: 'message', T: ConfigurationDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetConfigurationDescriptorResponse { - return new GetConfigurationDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetConfigurationDescriptorResponse { - return new GetConfigurationDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetConfigurationDescriptorResponse { - return new GetConfigurationDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: - | GetConfigurationDescriptorResponse - | PlainMessage - | undefined, - b: - | GetConfigurationDescriptorResponse - | PlainMessage - | undefined - ): boolean { - return proto3.util.equals(GetConfigurationDescriptorResponse, a, b); - } -} - -/** - * GetQueryServicesDescriptorRequest is the request used for the GetQueryServicesDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetQueryServicesDescriptorRequest - */ -export class GetQueryServicesDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetQueryServicesDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetQueryServicesDescriptorRequest { - return new GetQueryServicesDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetQueryServicesDescriptorRequest { - return new GetQueryServicesDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetQueryServicesDescriptorRequest { - return new GetQueryServicesDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: - | GetQueryServicesDescriptorRequest - | PlainMessage - | undefined, - b: - | GetQueryServicesDescriptorRequest - | PlainMessage - | undefined - ): boolean { - return proto3.util.equals(GetQueryServicesDescriptorRequest, a, b); - } -} - -/** - * GetQueryServicesDescriptorResponse is the response returned by the GetQueryServicesDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetQueryServicesDescriptorResponse - */ -export class GetQueryServicesDescriptorResponse extends Message { - /** - * queries provides information on the available queryable services - * - * @generated from field: cosmos.base.reflection.v2alpha1.QueryServicesDescriptor queries = 1; - */ - queries?: QueryServicesDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetQueryServicesDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'queries', kind: 'message', T: QueryServicesDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetQueryServicesDescriptorResponse { - return new GetQueryServicesDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetQueryServicesDescriptorResponse { - return new GetQueryServicesDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetQueryServicesDescriptorResponse { - return new GetQueryServicesDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: - | GetQueryServicesDescriptorResponse - | PlainMessage - | undefined, - b: - | GetQueryServicesDescriptorResponse - | PlainMessage - | undefined - ): boolean { - return proto3.util.equals(GetQueryServicesDescriptorResponse, a, b); - } -} - -/** - * GetTxDescriptorRequest is the request used for the GetTxDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetTxDescriptorRequest - */ -export class GetTxDescriptorRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetTxDescriptorRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetTxDescriptorRequest { - return new GetTxDescriptorRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetTxDescriptorRequest { - return new GetTxDescriptorRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetTxDescriptorRequest { - return new GetTxDescriptorRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxDescriptorRequest | PlainMessage | undefined, - b: GetTxDescriptorRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxDescriptorRequest, a, b); - } -} - -/** - * GetTxDescriptorResponse is the response returned by the GetTxDescriptor RPC - * - * @generated from message cosmos.base.reflection.v2alpha1.GetTxDescriptorResponse - */ -export class GetTxDescriptorResponse extends Message { - /** - * tx provides information on msgs that can be forwarded to the application - * alongside the accepted transaction protobuf type - * - * @generated from field: cosmos.base.reflection.v2alpha1.TxDescriptor tx = 1; - */ - tx?: TxDescriptor; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.GetTxDescriptorResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: TxDescriptor }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetTxDescriptorResponse { - return new GetTxDescriptorResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetTxDescriptorResponse { - return new GetTxDescriptorResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetTxDescriptorResponse { - return new GetTxDescriptorResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxDescriptorResponse | PlainMessage | undefined, - b: GetTxDescriptorResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxDescriptorResponse, a, b); - } -} - -/** - * QueryServicesDescriptor contains the list of cosmos-sdk queriable services - * - * @generated from message cosmos.base.reflection.v2alpha1.QueryServicesDescriptor - */ -export class QueryServicesDescriptor extends Message { - /** - * query_services is a list of cosmos-sdk QueryServiceDescriptor - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.QueryServiceDescriptor query_services = 1; - */ - queryServices: QueryServiceDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.QueryServicesDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'query_services', - kind: 'message', - T: QueryServiceDescriptor, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): QueryServicesDescriptor { - return new QueryServicesDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): QueryServicesDescriptor { - return new QueryServicesDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): QueryServicesDescriptor { - return new QueryServicesDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: QueryServicesDescriptor | PlainMessage | undefined, - b: QueryServicesDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(QueryServicesDescriptor, a, b); - } -} - -/** - * QueryServiceDescriptor describes a cosmos-sdk queryable service - * - * @generated from message cosmos.base.reflection.v2alpha1.QueryServiceDescriptor - */ -export class QueryServiceDescriptor extends Message { - /** - * fullname is the protobuf fullname of the service descriptor - * - * @generated from field: string fullname = 1; - */ - fullname = ''; - - /** - * is_module describes if this service is actually exposed by an application's module - * - * @generated from field: bool is_module = 2; - */ - isModule = false; - - /** - * methods provides a list of query service methods - * - * @generated from field: repeated cosmos.base.reflection.v2alpha1.QueryMethodDescriptor methods = 3; - */ - methods: QueryMethodDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.QueryServiceDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'fullname', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'is_module', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - { - no: 3, - name: 'methods', - kind: 'message', - T: QueryMethodDescriptor, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): QueryServiceDescriptor { - return new QueryServiceDescriptor().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): QueryServiceDescriptor { - return new QueryServiceDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): QueryServiceDescriptor { - return new QueryServiceDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: QueryServiceDescriptor | PlainMessage | undefined, - b: QueryServiceDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(QueryServiceDescriptor, a, b); - } -} - -/** - * QueryMethodDescriptor describes a queryable method of a query service - * no other info is provided beside method name and tendermint queryable path - * because it would be redundant with the grpc reflection service - * - * @generated from message cosmos.base.reflection.v2alpha1.QueryMethodDescriptor - */ -export class QueryMethodDescriptor extends Message { - /** - * name is the protobuf name (not fullname) of the method - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * full_query_path is the path that can be used to query - * this method via tendermint abci.Query - * - * @generated from field: string full_query_path = 2; - */ - fullQueryPath = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.reflection.v2alpha1.QueryMethodDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 2, - name: 'full_query_path', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): QueryMethodDescriptor { - return new QueryMethodDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryMethodDescriptor { - return new QueryMethodDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): QueryMethodDescriptor { - return new QueryMethodDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: QueryMethodDescriptor | PlainMessage | undefined, - b: QueryMethodDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(QueryMethodDescriptor, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_cosmes.ts deleted file mode 100644 index bf4dd4763..000000000 --- a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,111 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/base/tendermint/v1beta1/query.proto (package cosmos.base.tendermint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { - ABCIQueryRequest, - ABCIQueryResponse, - GetBlockByHeightRequest, - GetBlockByHeightResponse, - GetLatestBlockRequest, - GetLatestBlockResponse, - GetLatestValidatorSetRequest, - GetLatestValidatorSetResponse, - GetNodeInfoRequest, - GetNodeInfoResponse, - GetSyncingRequest, - GetSyncingResponse, - GetValidatorSetByHeightRequest, - GetValidatorSetByHeightResponse, -} from './query_pb.js'; - -const TYPE_NAME = 'cosmos.base.tendermint.v1beta1.Service'; - -/** - * GetNodeInfo queries the current node info. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetNodeInfo - */ -export const ServiceGetNodeInfoService = { - typeName: TYPE_NAME, - method: 'GetNodeInfo', - Request: GetNodeInfoRequest, - Response: GetNodeInfoResponse, -} as const; - -/** - * GetSyncing queries node syncing. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetSyncing - */ -export const ServiceGetSyncingService = { - typeName: TYPE_NAME, - method: 'GetSyncing', - Request: GetSyncingRequest, - Response: GetSyncingResponse, -} as const; - -/** - * GetLatestBlock returns the latest block. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetLatestBlock - */ -export const ServiceGetLatestBlockService = { - typeName: TYPE_NAME, - method: 'GetLatestBlock', - Request: GetLatestBlockRequest, - Response: GetLatestBlockResponse, -} as const; - -/** - * GetBlockByHeight queries block for given height. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetBlockByHeight - */ -export const ServiceGetBlockByHeightService = { - typeName: TYPE_NAME, - method: 'GetBlockByHeight', - Request: GetBlockByHeightRequest, - Response: GetBlockByHeightResponse, -} as const; - -/** - * GetLatestValidatorSet queries latest validator-set. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetLatestValidatorSet - */ -export const ServiceGetLatestValidatorSetService = { - typeName: TYPE_NAME, - method: 'GetLatestValidatorSet', - Request: GetLatestValidatorSetRequest, - Response: GetLatestValidatorSetResponse, -} as const; - -/** - * GetValidatorSetByHeight queries validator-set at a given height. - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.GetValidatorSetByHeight - */ -export const ServiceGetValidatorSetByHeightService = { - typeName: TYPE_NAME, - method: 'GetValidatorSetByHeight', - Request: GetValidatorSetByHeightRequest, - Response: GetValidatorSetByHeightResponse, -} as const; - -/** - * ABCIQuery defines a query handler that supports ABCI queries directly to the - * application, bypassing Tendermint completely. The ABCI query must contain - * a valid and supported path, including app, custom, p2p, and store. - * - * Since: cosmos-sdk 0.46 - * - * @generated from rpc cosmos.base.tendermint.v1beta1.Service.ABCIQuery - */ -export const ServiceABCIQueryService = { - typeName: TYPE_NAME, - method: 'ABCIQuery', - Request: ABCIQueryRequest, - Response: ABCIQueryResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_pb.ts b/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_pb.ts deleted file mode 100644 index 685074f9c..000000000 --- a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/query_pb.ts +++ /dev/null @@ -1,1158 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/tendermint/v1beta1/query.proto (package cosmos.base.tendermint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { DefaultNodeInfo } from '../../../../tendermint/p2p/types_pb.js'; -import { Block } from '../../../../tendermint/types/block_pb.js'; -import { BlockID } from '../../../../tendermint/types/types_pb.js'; -import { PageRequest, PageResponse } from '../../query/v1beta1/pagination_pb.js'; -import { Block as Block$1 } from './types_pb.js'; - -/** - * GetValidatorSetByHeightRequest is the request type for the Query/GetValidatorSetByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightRequest - */ -export class GetValidatorSetByHeightRequest extends Message { - /** - * @generated from field: int64 height = 1; - */ - height = protoInt64.zero; - - /** - * pagination defines an pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: 'pagination', kind: 'message', T: PageRequest }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetValidatorSetByHeightRequest { - return new GetValidatorSetByHeightRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetValidatorSetByHeightRequest { - return new GetValidatorSetByHeightRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetValidatorSetByHeightRequest { - return new GetValidatorSetByHeightRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetValidatorSetByHeightRequest | PlainMessage | undefined, - b: GetValidatorSetByHeightRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetValidatorSetByHeightRequest, a, b); - } -} - -/** - * GetValidatorSetByHeightResponse is the response type for the Query/GetValidatorSetByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightResponse - */ -export class GetValidatorSetByHeightResponse extends Message { - /** - * @generated from field: int64 block_height = 1; - */ - blockHeight = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.base.tendermint.v1beta1.Validator validators = 2; - */ - validators: Validator[] = []; - - /** - * pagination defines an pagination for the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 3; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetValidatorSetByHeightResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'block_height', - kind: 'scalar', - T: 3 /* ScalarType.INT64 */, - }, - { - no: 2, - name: 'validators', - kind: 'message', - T: Validator, - repeated: true, - }, - { no: 3, name: 'pagination', kind: 'message', T: PageResponse }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetValidatorSetByHeightResponse { - return new GetValidatorSetByHeightResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetValidatorSetByHeightResponse { - return new GetValidatorSetByHeightResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetValidatorSetByHeightResponse { - return new GetValidatorSetByHeightResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetValidatorSetByHeightResponse | PlainMessage | undefined, - b: GetValidatorSetByHeightResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetValidatorSetByHeightResponse, a, b); - } -} - -/** - * GetLatestValidatorSetRequest is the request type for the Query/GetValidatorSetByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetLatestValidatorSetRequest - */ -export class GetLatestValidatorSetRequest extends Message { - /** - * pagination defines an pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetLatestValidatorSetRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'pagination', kind: 'message', T: PageRequest }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetLatestValidatorSetRequest { - return new GetLatestValidatorSetRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetLatestValidatorSetRequest { - return new GetLatestValidatorSetRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetLatestValidatorSetRequest { - return new GetLatestValidatorSetRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetLatestValidatorSetRequest | PlainMessage | undefined, - b: GetLatestValidatorSetRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetLatestValidatorSetRequest, a, b); - } -} - -/** - * GetLatestValidatorSetResponse is the response type for the Query/GetValidatorSetByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetLatestValidatorSetResponse - */ -export class GetLatestValidatorSetResponse extends Message { - /** - * @generated from field: int64 block_height = 1; - */ - blockHeight = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.base.tendermint.v1beta1.Validator validators = 2; - */ - validators: Validator[] = []; - - /** - * pagination defines an pagination for the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 3; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetLatestValidatorSetResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'block_height', - kind: 'scalar', - T: 3 /* ScalarType.INT64 */, - }, - { - no: 2, - name: 'validators', - kind: 'message', - T: Validator, - repeated: true, - }, - { no: 3, name: 'pagination', kind: 'message', T: PageResponse }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetLatestValidatorSetResponse { - return new GetLatestValidatorSetResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetLatestValidatorSetResponse { - return new GetLatestValidatorSetResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetLatestValidatorSetResponse { - return new GetLatestValidatorSetResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetLatestValidatorSetResponse | PlainMessage | undefined, - b: GetLatestValidatorSetResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetLatestValidatorSetResponse, a, b); - } -} - -/** - * Validator is the type for the validator-set. - * - * @generated from message cosmos.base.tendermint.v1beta1.Validator - */ -export class Validator extends Message { - /** - * @generated from field: string address = 1; - */ - address = ''; - - /** - * @generated from field: google.protobuf.Any pub_key = 2; - */ - pubKey?: Any; - - /** - * @generated from field: int64 voting_power = 3; - */ - votingPower = protoInt64.zero; - - /** - * @generated from field: int64 proposer_priority = 4; - */ - proposerPriority = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.Validator'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'address', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'pub_key', kind: 'message', T: Any }, - { - no: 3, - name: 'voting_power', - kind: 'scalar', - T: 3 /* ScalarType.INT64 */, - }, - { - no: 4, - name: 'proposer_priority', - kind: 'scalar', - T: 3 /* ScalarType.INT64 */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Validator { - return new Validator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Validator { - return new Validator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Validator { - return new Validator().fromJsonString(jsonString, options); - } - - static equals( - a: Validator | PlainMessage | undefined, - b: Validator | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Validator, a, b); - } -} - -/** - * GetBlockByHeightRequest is the request type for the Query/GetBlockByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetBlockByHeightRequest - */ -export class GetBlockByHeightRequest extends Message { - /** - * @generated from field: int64 height = 1; - */ - height = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetBlockByHeightRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetBlockByHeightRequest { - return new GetBlockByHeightRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetBlockByHeightRequest { - return new GetBlockByHeightRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetBlockByHeightRequest { - return new GetBlockByHeightRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetBlockByHeightRequest | PlainMessage | undefined, - b: GetBlockByHeightRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetBlockByHeightRequest, a, b); - } -} - -/** - * GetBlockByHeightResponse is the response type for the Query/GetBlockByHeight RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetBlockByHeightResponse - */ -export class GetBlockByHeightResponse extends Message { - /** - * @generated from field: tendermint.types.BlockID block_id = 1; - */ - blockId?: BlockID; - - /** - * Deprecated: please use `sdk_block` instead - * - * @generated from field: tendermint.types.Block block = 2; - */ - block?: Block; - - /** - * Since: cosmos-sdk 0.47 - * - * @generated from field: cosmos.base.tendermint.v1beta1.Block sdk_block = 3; - */ - sdkBlock?: Block$1; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetBlockByHeightResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'block_id', kind: 'message', T: BlockID }, - { no: 2, name: 'block', kind: 'message', T: Block }, - { no: 3, name: 'sdk_block', kind: 'message', T: Block$1 }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetBlockByHeightResponse { - return new GetBlockByHeightResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetBlockByHeightResponse { - return new GetBlockByHeightResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetBlockByHeightResponse { - return new GetBlockByHeightResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetBlockByHeightResponse | PlainMessage | undefined, - b: GetBlockByHeightResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetBlockByHeightResponse, a, b); - } -} - -/** - * GetLatestBlockRequest is the request type for the Query/GetLatestBlock RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetLatestBlockRequest - */ -export class GetLatestBlockRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetLatestBlockRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetLatestBlockRequest { - return new GetLatestBlockRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetLatestBlockRequest { - return new GetLatestBlockRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetLatestBlockRequest { - return new GetLatestBlockRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetLatestBlockRequest | PlainMessage | undefined, - b: GetLatestBlockRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetLatestBlockRequest, a, b); - } -} - -/** - * GetLatestBlockResponse is the response type for the Query/GetLatestBlock RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetLatestBlockResponse - */ -export class GetLatestBlockResponse extends Message { - /** - * @generated from field: tendermint.types.BlockID block_id = 1; - */ - blockId?: BlockID; - - /** - * Deprecated: please use `sdk_block` instead - * - * @generated from field: tendermint.types.Block block = 2; - */ - block?: Block; - - /** - * Since: cosmos-sdk 0.47 - * - * @generated from field: cosmos.base.tendermint.v1beta1.Block sdk_block = 3; - */ - sdkBlock?: Block$1; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetLatestBlockResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'block_id', kind: 'message', T: BlockID }, - { no: 2, name: 'block', kind: 'message', T: Block }, - { no: 3, name: 'sdk_block', kind: 'message', T: Block$1 }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetLatestBlockResponse { - return new GetLatestBlockResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetLatestBlockResponse { - return new GetLatestBlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetLatestBlockResponse { - return new GetLatestBlockResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetLatestBlockResponse | PlainMessage | undefined, - b: GetLatestBlockResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetLatestBlockResponse, a, b); - } -} - -/** - * GetSyncingRequest is the request type for the Query/GetSyncing RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetSyncingRequest - */ -export class GetSyncingRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetSyncingRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetSyncingRequest { - return new GetSyncingRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetSyncingRequest { - return new GetSyncingRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetSyncingRequest { - return new GetSyncingRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetSyncingRequest | PlainMessage | undefined, - b: GetSyncingRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetSyncingRequest, a, b); - } -} - -/** - * GetSyncingResponse is the response type for the Query/GetSyncing RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetSyncingResponse - */ -export class GetSyncingResponse extends Message { - /** - * @generated from field: bool syncing = 1; - */ - syncing = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetSyncingResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'syncing', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetSyncingResponse { - return new GetSyncingResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetSyncingResponse { - return new GetSyncingResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetSyncingResponse { - return new GetSyncingResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetSyncingResponse | PlainMessage | undefined, - b: GetSyncingResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetSyncingResponse, a, b); - } -} - -/** - * GetNodeInfoRequest is the request type for the Query/GetNodeInfo RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetNodeInfoRequest - */ -export class GetNodeInfoRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetNodeInfoRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetNodeInfoRequest { - return new GetNodeInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetNodeInfoRequest { - return new GetNodeInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetNodeInfoRequest { - return new GetNodeInfoRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetNodeInfoRequest | PlainMessage | undefined, - b: GetNodeInfoRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetNodeInfoRequest, a, b); - } -} - -/** - * GetNodeInfoResponse is the response type for the Query/GetNodeInfo RPC method. - * - * @generated from message cosmos.base.tendermint.v1beta1.GetNodeInfoResponse - */ -export class GetNodeInfoResponse extends Message { - /** - * @generated from field: tendermint.p2p.DefaultNodeInfo default_node_info = 1; - */ - defaultNodeInfo?: DefaultNodeInfo; - - /** - * @generated from field: cosmos.base.tendermint.v1beta1.VersionInfo application_version = 2; - */ - applicationVersion?: VersionInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.GetNodeInfoResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'default_node_info', kind: 'message', T: DefaultNodeInfo }, - { no: 2, name: 'application_version', kind: 'message', T: VersionInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetNodeInfoResponse { - return new GetNodeInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetNodeInfoResponse { - return new GetNodeInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetNodeInfoResponse { - return new GetNodeInfoResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetNodeInfoResponse | PlainMessage | undefined, - b: GetNodeInfoResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetNodeInfoResponse, a, b); - } -} - -/** - * VersionInfo is the type for the GetNodeInfoResponse message. - * - * @generated from message cosmos.base.tendermint.v1beta1.VersionInfo - */ -export class VersionInfo extends Message { - /** - * @generated from field: string name = 1; - */ - name = ''; - - /** - * @generated from field: string app_name = 2; - */ - appName = ''; - - /** - * @generated from field: string version = 3; - */ - version = ''; - - /** - * @generated from field: string git_commit = 4; - */ - gitCommit = ''; - - /** - * @generated from field: string build_tags = 5; - */ - buildTags = ''; - - /** - * @generated from field: string go_version = 6; - */ - goVersion = ''; - - /** - * @generated from field: repeated cosmos.base.tendermint.v1beta1.Module build_deps = 7; - */ - buildDeps: Module[] = []; - - /** - * Since: cosmos-sdk 0.43 - * - * @generated from field: string cosmos_sdk_version = 8; - */ - cosmosSdkVersion = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.VersionInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'app_name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'version', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 4, name: 'git_commit', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 5, name: 'build_tags', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 6, name: 'go_version', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 7, name: 'build_deps', kind: 'message', T: Module, repeated: true }, - { - no: 8, - name: 'cosmos_sdk_version', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VersionInfo { - return new VersionInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VersionInfo { - return new VersionInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VersionInfo { - return new VersionInfo().fromJsonString(jsonString, options); - } - - static equals( - a: VersionInfo | PlainMessage | undefined, - b: VersionInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(VersionInfo, a, b); - } -} - -/** - * Module is the type for VersionInfo - * - * @generated from message cosmos.base.tendermint.v1beta1.Module - */ -export class Module extends Message { - /** - * module path - * - * @generated from field: string path = 1; - */ - path = ''; - - /** - * module version - * - * @generated from field: string version = 2; - */ - version = ''; - - /** - * checksum - * - * @generated from field: string sum = 3; - */ - sum = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.Module'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'path', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'version', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'sum', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals( - a: Module | PlainMessage | undefined, - b: Module | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Module, a, b); - } -} - -/** - * ABCIQueryRequest defines the request structure for the ABCIQuery gRPC query. - * - * @generated from message cosmos.base.tendermint.v1beta1.ABCIQueryRequest - */ -export class ABCIQueryRequest extends Message { - /** - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - /** - * @generated from field: string path = 2; - */ - path = ''; - - /** - * @generated from field: int64 height = 3; - */ - height = protoInt64.zero; - - /** - * @generated from field: bool prove = 4; - */ - prove = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.ABCIQueryRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'data', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'path', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: 'prove', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ABCIQueryRequest { - return new ABCIQueryRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ABCIQueryRequest { - return new ABCIQueryRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ABCIQueryRequest { - return new ABCIQueryRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ABCIQueryRequest | PlainMessage | undefined, - b: ABCIQueryRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ABCIQueryRequest, a, b); - } -} - -/** - * ABCIQueryResponse defines the response structure for the ABCIQuery gRPC query. - * - * Note: This type is a duplicate of the ResponseQuery proto type defined in - * Tendermint. - * - * @generated from message cosmos.base.tendermint.v1beta1.ABCIQueryResponse - */ -export class ABCIQueryResponse extends Message { - /** - * @generated from field: uint32 code = 1; - */ - code = 0; - - /** - * nondeterministic - * - * @generated from field: string log = 3; - */ - log = ''; - - /** - * nondeterministic - * - * @generated from field: string info = 4; - */ - info = ''; - - /** - * @generated from field: int64 index = 5; - */ - index = protoInt64.zero; - - /** - * @generated from field: bytes key = 6; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 7; - */ - value = new Uint8Array(0); - - /** - * @generated from field: cosmos.base.tendermint.v1beta1.ProofOps proof_ops = 8; - */ - proofOps?: ProofOps; - - /** - * @generated from field: int64 height = 9; - */ - height = protoInt64.zero; - - /** - * @generated from field: string codespace = 10; - */ - codespace = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.ABCIQueryResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'code', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: 'log', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 4, name: 'info', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 5, name: 'index', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: 'proof_ops', kind: 'message', T: ProofOps }, - { no: 9, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 10, name: 'codespace', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ABCIQueryResponse { - return new ABCIQueryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ABCIQueryResponse { - return new ABCIQueryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ABCIQueryResponse { - return new ABCIQueryResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ABCIQueryResponse | PlainMessage | undefined, - b: ABCIQueryResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ABCIQueryResponse, a, b); - } -} - -/** - * ProofOp defines an operation used for calculating Merkle root. The data could - * be arbitrary format, providing necessary data for example neighbouring node - * hash. - * - * Note: This type is a duplicate of the ProofOp proto type defined in Tendermint. - * - * @generated from message cosmos.base.tendermint.v1beta1.ProofOp - */ -export class ProofOp extends Message { - /** - * @generated from field: string type = 1; - */ - type = ''; - - /** - * @generated from field: bytes key = 2; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.ProofOp'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'type', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: 'data', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ProofOp { - return new ProofOp().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ProofOp { - return new ProofOp().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ProofOp { - return new ProofOp().fromJsonString(jsonString, options); - } - - static equals( - a: ProofOp | PlainMessage | undefined, - b: ProofOp | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ProofOp, a, b); - } -} - -/** - * ProofOps is Merkle proof defined by the list of ProofOps. - * - * Note: This type is a duplicate of the ProofOps proto type defined in Tendermint. - * - * @generated from message cosmos.base.tendermint.v1beta1.ProofOps - */ -export class ProofOps extends Message { - /** - * @generated from field: repeated cosmos.base.tendermint.v1beta1.ProofOp ops = 1; - */ - ops: ProofOp[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.ProofOps'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'ops', kind: 'message', T: ProofOp, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ProofOps { - return new ProofOps().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ProofOps { - return new ProofOps().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ProofOps { - return new ProofOps().fromJsonString(jsonString, options); - } - - static equals( - a: ProofOps | PlainMessage | undefined, - b: ProofOps | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ProofOps, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/types_pb.ts b/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/types_pb.ts deleted file mode 100644 index a7d2d4fcd..000000000 --- a/packages/es/src/protobufs/cosmos/base/tendermint/v1beta1/types_pb.ts +++ /dev/null @@ -1,265 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/tendermint/v1beta1/types.proto (package cosmos.base.tendermint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, Timestamp, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { EvidenceList } from '../../../../tendermint/types/evidence_pb.js'; -import { BlockID, Commit, Data } from '../../../../tendermint/types/types_pb.js'; -import { Consensus } from '../../../../tendermint/version/types_pb.js'; - -/** - * Block is tendermint type Block, with the Header proposer address - * field converted to bech32 string. - * - * @generated from message cosmos.base.tendermint.v1beta1.Block - */ -export class Block extends Message { - /** - * @generated from field: cosmos.base.tendermint.v1beta1.Header header = 1; - */ - header?: Header; - - /** - * @generated from field: tendermint.types.Data data = 2; - */ - data?: Data; - - /** - * @generated from field: tendermint.types.EvidenceList evidence = 3; - */ - evidence?: EvidenceList; - - /** - * @generated from field: tendermint.types.Commit last_commit = 4; - */ - lastCommit?: Commit; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.Block'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'header', kind: 'message', T: Header }, - { no: 2, name: 'data', kind: 'message', T: Data }, - { no: 3, name: 'evidence', kind: 'message', T: EvidenceList }, - { no: 4, name: 'last_commit', kind: 'message', T: Commit }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Block { - return new Block().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Block { - return new Block().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Block { - return new Block().fromJsonString(jsonString, options); - } - - static equals( - a: Block | PlainMessage | undefined, - b: Block | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Block, a, b); - } -} - -/** - * Header defines the structure of a Tendermint block header. - * - * @generated from message cosmos.base.tendermint.v1beta1.Header - */ -export class Header extends Message
{ - /** - * basic block info - * - * @generated from field: tendermint.version.Consensus version = 1; - */ - version?: Consensus; - - /** - * @generated from field: string chain_id = 2; - */ - chainId = ''; - - /** - * @generated from field: int64 height = 3; - */ - height = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Timestamp time = 4; - */ - time?: Timestamp; - - /** - * prev block info - * - * @generated from field: tendermint.types.BlockID last_block_id = 5; - */ - lastBlockId?: BlockID; - - /** - * hashes of block data - * - * commit from validators from the last block - * - * @generated from field: bytes last_commit_hash = 6; - */ - lastCommitHash = new Uint8Array(0); - - /** - * transactions - * - * @generated from field: bytes data_hash = 7; - */ - dataHash = new Uint8Array(0); - - /** - * hashes from the app output from the prev block - * - * validators for the current block - * - * @generated from field: bytes validators_hash = 8; - */ - validatorsHash = new Uint8Array(0); - - /** - * validators for the next block - * - * @generated from field: bytes next_validators_hash = 9; - */ - nextValidatorsHash = new Uint8Array(0); - - /** - * consensus params for current block - * - * @generated from field: bytes consensus_hash = 10; - */ - consensusHash = new Uint8Array(0); - - /** - * state after txs from the previous block - * - * @generated from field: bytes app_hash = 11; - */ - appHash = new Uint8Array(0); - - /** - * root hash of all results from the txs from the previous block - * - * @generated from field: bytes last_results_hash = 12; - */ - lastResultsHash = new Uint8Array(0); - - /** - * consensus info - * - * evidence included in the block - * - * @generated from field: bytes evidence_hash = 13; - */ - evidenceHash = new Uint8Array(0); - - /** - * proposer_address is the original block proposer address, formatted as a Bech32 string. - * In Tendermint, this type is `bytes`, but in the SDK, we convert it to a Bech32 string - * for better UX. - * - * original proposer of the block - * - * @generated from field: string proposer_address = 14; - */ - proposerAddress = ''; - - constructor(data?: PartialMessage
) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.tendermint.v1beta1.Header'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'version', kind: 'message', T: Consensus }, - { no: 2, name: 'chain_id', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 3, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: 'time', kind: 'message', T: Timestamp }, - { no: 5, name: 'last_block_id', kind: 'message', T: BlockID }, - { - no: 6, - name: 'last_commit_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { no: 7, name: 'data_hash', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { - no: 8, - name: 'validators_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { - no: 9, - name: 'next_validators_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { - no: 10, - name: 'consensus_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { no: 11, name: 'app_hash', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { - no: 12, - name: 'last_results_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { - no: 13, - name: 'evidence_hash', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { - no: 14, - name: 'proposer_address', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Header { - return new Header().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Header { - return new Header().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Header { - return new Header().fromJsonString(jsonString, options); - } - - static equals( - a: Header | PlainMessage
| undefined, - b: Header | PlainMessage
| undefined - ): boolean { - return proto3.util.equals(Header, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/base/v1beta1/coin_pb.ts b/packages/es/src/protobufs/cosmos/base/v1beta1/coin_pb.ts deleted file mode 100644 index a1461d7f8..000000000 --- a/packages/es/src/protobufs/cosmos/base/v1beta1/coin_pb.ts +++ /dev/null @@ -1,202 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/base/v1beta1/coin.proto (package cosmos.base.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * Coin defines a token with a denomination and an amount. - * - * NOTE: The amount field is an Int which implements the custom method - * signatures required by gogoproto. - * - * @generated from message cosmos.base.v1beta1.Coin - */ -export class Coin extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ''; - - /** - * @generated from field: string amount = 2; - */ - amount = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.v1beta1.Coin'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'denom', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'amount', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Coin { - return new Coin().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Coin { - return new Coin().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Coin { - return new Coin().fromJsonString(jsonString, options); - } - - static equals( - a: Coin | PlainMessage | undefined, - b: Coin | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Coin, a, b); - } -} - -/** - * DecCoin defines a token with a denomination and a decimal amount. - * - * NOTE: The amount field is an Dec which implements the custom method - * signatures required by gogoproto. - * - * @generated from message cosmos.base.v1beta1.DecCoin - */ -export class DecCoin extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ''; - - /** - * @generated from field: string amount = 2; - */ - amount = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.v1beta1.DecCoin'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'denom', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'amount', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DecCoin { - return new DecCoin().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DecCoin { - return new DecCoin().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DecCoin { - return new DecCoin().fromJsonString(jsonString, options); - } - - static equals( - a: DecCoin | PlainMessage | undefined, - b: DecCoin | PlainMessage | undefined - ): boolean { - return proto3.util.equals(DecCoin, a, b); - } -} - -/** - * IntProto defines a Protobuf wrapper around an Int object. - * Deprecated: Prefer to use math.Int directly. It supports binary Marshal and Unmarshal. - * - * @generated from message cosmos.base.v1beta1.IntProto - */ -export class IntProto extends Message { - /** - * @generated from field: string int = 1; - */ - int = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.v1beta1.IntProto'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'int', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IntProto { - return new IntProto().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IntProto { - return new IntProto().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IntProto { - return new IntProto().fromJsonString(jsonString, options); - } - - static equals( - a: IntProto | PlainMessage | undefined, - b: IntProto | PlainMessage | undefined - ): boolean { - return proto3.util.equals(IntProto, a, b); - } -} - -/** - * DecProto defines a Protobuf wrapper around a Dec object. - * Deprecated: Prefer to use math.LegacyDec directly. It supports binary Marshal and Unmarshal. - * - * @generated from message cosmos.base.v1beta1.DecProto - */ -export class DecProto extends Message { - /** - * @generated from field: string dec = 1; - */ - dec = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.base.v1beta1.DecProto'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'dec', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DecProto { - return new DecProto().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DecProto { - return new DecProto().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DecProto { - return new DecProto().fromJsonString(jsonString, options); - } - - static equals( - a: DecProto | PlainMessage | undefined, - b: DecProto | PlainMessage | undefined - ): boolean { - return proto3.util.equals(DecProto, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/ed25519/keys_pb.ts b/packages/es/src/protobufs/cosmos/crypto/ed25519/keys_pb.ts deleted file mode 100644 index cf1f8d585..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/ed25519/keys_pb.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/ed25519/keys.proto (package cosmos.crypto.ed25519, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * PubKey is an ed25519 public key for handling Tendermint keys in SDK. - * It's needed for Any serialization and SDK compatibility. - * It must not be used in a non Tendermint key context because it doesn't implement - * ADR-28. Nevertheless, you will like to use ed25519 in app user level - * then you must create a new proto message and follow ADR-28 for Address construction. - * - * @generated from message cosmos.crypto.ed25519.PubKey - */ -export class PubKey extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.ed25519.PubKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PubKey { - return new PubKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PubKey { - return new PubKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PubKey { - return new PubKey().fromJsonString(jsonString, options); - } - - static equals( - a: PubKey | PlainMessage | undefined, - b: PubKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PubKey, a, b); - } -} - -/** - * PrivKey defines a ed25519 private key. - * NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context. - * - * @generated from message cosmos.crypto.ed25519.PrivKey - */ -export class PrivKey extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.ed25519.PrivKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PrivKey { - return new PrivKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PrivKey { - return new PrivKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PrivKey { - return new PrivKey().fromJsonString(jsonString, options); - } - - static equals( - a: PrivKey | PlainMessage | undefined, - b: PrivKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PrivKey, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/hd/v1/hd_pb.ts b/packages/es/src/protobufs/cosmos/crypto/hd/v1/hd_pb.ts deleted file mode 100644 index fea28f859..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/hd/v1/hd_pb.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Since: cosmos-sdk 0.46 - -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/hd/v1/hd.proto (package cosmos.crypto.hd.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * BIP44Params is used as path field in ledger item in Record. - * - * @generated from message cosmos.crypto.hd.v1.BIP44Params - */ -export class BIP44Params extends Message { - /** - * purpose is a constant set to 44' (or 0x8000002C) following the BIP43 recommendation - * - * @generated from field: uint32 purpose = 1; - */ - purpose = 0; - - /** - * coin_type is a constant that improves privacy - * - * @generated from field: uint32 coin_type = 2; - */ - coinType = 0; - - /** - * account splits the key space into independent user identities - * - * @generated from field: uint32 account = 3; - */ - account = 0; - - /** - * change is a constant used for public derivation. Constant 0 is used for external chain and constant 1 for internal - * chain. - * - * @generated from field: bool change = 4; - */ - change = false; - - /** - * address_index is used as child index in BIP32 derivation - * - * @generated from field: uint32 address_index = 5; - */ - addressIndex = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.hd.v1.BIP44Params'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'purpose', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: 'coin_type', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: 'account', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: 'change', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - { - no: 5, - name: 'address_index', - kind: 'scalar', - T: 13 /* ScalarType.UINT32 */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BIP44Params { - return new BIP44Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BIP44Params { - return new BIP44Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BIP44Params { - return new BIP44Params().fromJsonString(jsonString, options); - } - - static equals( - a: BIP44Params | PlainMessage | undefined, - b: BIP44Params | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BIP44Params, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/keyring/v1/record_pb.ts b/packages/es/src/protobufs/cosmos/crypto/keyring/v1/record_pb.ts deleted file mode 100644 index 54d65c295..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/keyring/v1/record_pb.ts +++ /dev/null @@ -1,278 +0,0 @@ -// Since: cosmos-sdk 0.46 - -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/keyring/v1/record.proto (package cosmos.crypto.keyring.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3 } from '@bufbuild/protobuf'; -import { BIP44Params } from '../../hd/v1/hd_pb.js'; - -/** - * Record is used for representing a key in the keyring. - * - * @generated from message cosmos.crypto.keyring.v1.Record - */ -export class Record extends Message { - /** - * name represents a name of Record - * - * @generated from field: string name = 1; - */ - name = ''; - - /** - * pub_key represents a public key in any format - * - * @generated from field: google.protobuf.Any pub_key = 2; - */ - pubKey?: Any; - - /** - * Record contains one of the following items - * - * @generated from oneof cosmos.crypto.keyring.v1.Record.item - */ - item: - | { - /** - * local stores the private key locally. - * - * @generated from field: cosmos.crypto.keyring.v1.Record.Local local = 3; - */ - value: Record_Local; - case: 'local'; - } - | { - /** - * ledger stores the information about a Ledger key. - * - * @generated from field: cosmos.crypto.keyring.v1.Record.Ledger ledger = 4; - */ - value: Record_Ledger; - case: 'ledger'; - } - | { - /** - * Multi does not store any other information. - * - * @generated from field: cosmos.crypto.keyring.v1.Record.Multi multi = 5; - */ - value: Record_Multi; - case: 'multi'; - } - | { - /** - * Offline does not store any other information. - * - * @generated from field: cosmos.crypto.keyring.v1.Record.Offline offline = 6; - */ - value: Record_Offline; - case: 'offline'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.keyring.v1.Record'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'pub_key', kind: 'message', T: Any }, - { no: 3, name: 'local', kind: 'message', T: Record_Local, oneof: 'item' }, - { no: 4, name: 'ledger', kind: 'message', T: Record_Ledger, oneof: 'item' }, - { no: 5, name: 'multi', kind: 'message', T: Record_Multi, oneof: 'item' }, - { - no: 6, - name: 'offline', - kind: 'message', - T: Record_Offline, - oneof: 'item', - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record { - return new Record().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record { - return new Record().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record { - return new Record().fromJsonString(jsonString, options); - } - - static equals( - a: Record | PlainMessage | undefined, - b: Record | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Record, a, b); - } -} - -/** - * Item is a keyring item stored in a keyring backend. - * Local item - * - * @generated from message cosmos.crypto.keyring.v1.Record.Local - */ -export class Record_Local extends Message { - /** - * @generated from field: google.protobuf.Any priv_key = 1; - */ - privKey?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.keyring.v1.Record.Local'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'priv_key', kind: 'message', T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record_Local { - return new Record_Local().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record_Local { - return new Record_Local().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record_Local { - return new Record_Local().fromJsonString(jsonString, options); - } - - static equals( - a: Record_Local | PlainMessage | undefined, - b: Record_Local | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Record_Local, a, b); - } -} - -/** - * Ledger item - * - * @generated from message cosmos.crypto.keyring.v1.Record.Ledger - */ -export class Record_Ledger extends Message { - /** - * @generated from field: cosmos.crypto.hd.v1.BIP44Params path = 1; - */ - path?: BIP44Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.keyring.v1.Record.Ledger'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'path', kind: 'message', T: BIP44Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record_Ledger { - return new Record_Ledger().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record_Ledger { - return new Record_Ledger().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record_Ledger { - return new Record_Ledger().fromJsonString(jsonString, options); - } - - static equals( - a: Record_Ledger | PlainMessage | undefined, - b: Record_Ledger | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Record_Ledger, a, b); - } -} - -/** - * Multi item - * - * @generated from message cosmos.crypto.keyring.v1.Record.Multi - */ -export class Record_Multi extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.keyring.v1.Record.Multi'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record_Multi { - return new Record_Multi().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record_Multi { - return new Record_Multi().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record_Multi { - return new Record_Multi().fromJsonString(jsonString, options); - } - - static equals( - a: Record_Multi | PlainMessage | undefined, - b: Record_Multi | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Record_Multi, a, b); - } -} - -/** - * Offline item - * - * @generated from message cosmos.crypto.keyring.v1.Record.Offline - */ -export class Record_Offline extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.keyring.v1.Record.Offline'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record_Offline { - return new Record_Offline().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record_Offline { - return new Record_Offline().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record_Offline { - return new Record_Offline().fromJsonString(jsonString, options); - } - - static equals( - a: Record_Offline | PlainMessage | undefined, - b: Record_Offline | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Record_Offline, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/multisig/keys_pb.ts b/packages/es/src/protobufs/cosmos/crypto/multisig/keys_pb.ts deleted file mode 100644 index 1d9f67f22..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/multisig/keys_pb.ts +++ /dev/null @@ -1,64 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/multisig/keys.proto (package cosmos.crypto.multisig, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3 } from '@bufbuild/protobuf'; - -/** - * LegacyAminoPubKey specifies a public key type - * which nests multiple public keys and a threshold, - * it uses legacy amino address rules. - * - * @generated from message cosmos.crypto.multisig.LegacyAminoPubKey - */ -export class LegacyAminoPubKey extends Message { - /** - * @generated from field: uint32 threshold = 1; - */ - threshold = 0; - - /** - * @generated from field: repeated google.protobuf.Any public_keys = 2; - */ - publicKeys: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.multisig.LegacyAminoPubKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'threshold', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: 'public_keys', kind: 'message', T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LegacyAminoPubKey { - return new LegacyAminoPubKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LegacyAminoPubKey { - return new LegacyAminoPubKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LegacyAminoPubKey { - return new LegacyAminoPubKey().fromJsonString(jsonString, options); - } - - static equals( - a: LegacyAminoPubKey | PlainMessage | undefined, - b: LegacyAminoPubKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(LegacyAminoPubKey, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/multisig/v1beta1/multisig_pb.ts b/packages/es/src/protobufs/cosmos/crypto/multisig/v1beta1/multisig_pb.ts deleted file mode 100644 index 43e18fb72..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/multisig/v1beta1/multisig_pb.ts +++ /dev/null @@ -1,120 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/multisig/v1beta1/multisig.proto (package cosmos.crypto.multisig.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * MultiSignature wraps the signatures from a multisig.LegacyAminoPubKey. - * See cosmos.tx.v1betata1.ModeInfo.Multi for how to specify which signers - * signed and with which modes. - * - * @generated from message cosmos.crypto.multisig.v1beta1.MultiSignature - */ -export class MultiSignature extends Message { - /** - * @generated from field: repeated bytes signatures = 1; - */ - signatures: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.multisig.v1beta1.MultiSignature'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'signatures', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MultiSignature { - return new MultiSignature().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MultiSignature { - return new MultiSignature().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MultiSignature { - return new MultiSignature().fromJsonString(jsonString, options); - } - - static equals( - a: MultiSignature | PlainMessage | undefined, - b: MultiSignature | PlainMessage | undefined - ): boolean { - return proto3.util.equals(MultiSignature, a, b); - } -} - -/** - * CompactBitArray is an implementation of a space efficient bit array. - * This is used to ensure that the encoded data takes up a minimal amount of - * space after proto encoding. - * This is not thread safe, and is not intended for concurrent usage. - * - * @generated from message cosmos.crypto.multisig.v1beta1.CompactBitArray - */ -export class CompactBitArray extends Message { - /** - * @generated from field: uint32 extra_bits_stored = 1; - */ - extraBitsStored = 0; - - /** - * @generated from field: bytes elems = 2; - */ - elems = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.multisig.v1beta1.CompactBitArray'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'extra_bits_stored', - kind: 'scalar', - T: 13 /* ScalarType.UINT32 */, - }, - { no: 2, name: 'elems', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CompactBitArray { - return new CompactBitArray().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CompactBitArray { - return new CompactBitArray().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CompactBitArray { - return new CompactBitArray().fromJsonString(jsonString, options); - } - - static equals( - a: CompactBitArray | PlainMessage | undefined, - b: CompactBitArray | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CompactBitArray, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/secp256k1/keys_pb.ts b/packages/es/src/protobufs/cosmos/crypto/secp256k1/keys_pb.ts deleted file mode 100644 index 0f1e7d2e0..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/secp256k1/keys_pb.ts +++ /dev/null @@ -1,102 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/secp256k1/keys.proto (package cosmos.crypto.secp256k1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * PubKey defines a secp256k1 public key - * Key is the compressed form of the pubkey. The first byte depends is a 0x02 byte - * if the y-coordinate is the lexicographically largest of the two associated with - * the x-coordinate. Otherwise the first byte is a 0x03. - * This prefix is followed with the x-coordinate. - * - * @generated from message cosmos.crypto.secp256k1.PubKey - */ -export class PubKey extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.secp256k1.PubKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PubKey { - return new PubKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PubKey { - return new PubKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PubKey { - return new PubKey().fromJsonString(jsonString, options); - } - - static equals( - a: PubKey | PlainMessage | undefined, - b: PubKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PubKey, a, b); - } -} - -/** - * PrivKey defines a secp256k1 private key. - * - * @generated from message cosmos.crypto.secp256k1.PrivKey - */ -export class PrivKey extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.secp256k1.PrivKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PrivKey { - return new PrivKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PrivKey { - return new PrivKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PrivKey { - return new PrivKey().fromJsonString(jsonString, options); - } - - static equals( - a: PrivKey | PlainMessage | undefined, - b: PrivKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PrivKey, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/crypto/secp256r1/keys_pb.ts b/packages/es/src/protobufs/cosmos/crypto/secp256r1/keys_pb.ts deleted file mode 100644 index 6a928b603..000000000 --- a/packages/es/src/protobufs/cosmos/crypto/secp256r1/keys_pb.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Since: cosmos-sdk 0.43 - -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/crypto/secp256r1/keys.proto (package cosmos.crypto.secp256r1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * PubKey defines a secp256r1 ECDSA public key. - * - * @generated from message cosmos.crypto.secp256r1.PubKey - */ -export class PubKey extends Message { - /** - * Point on secp256r1 curve in a compressed representation as specified in section - * 4.3.6 of ANSI X9.62: https://webstore.ansi.org/standards/ascx9/ansix9621998 - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.secp256r1.PubKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PubKey { - return new PubKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PubKey { - return new PubKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PubKey { - return new PubKey().fromJsonString(jsonString, options); - } - - static equals( - a: PubKey | PlainMessage | undefined, - b: PubKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PubKey, a, b); - } -} - -/** - * PrivKey defines a secp256r1 ECDSA private key. - * - * @generated from message cosmos.crypto.secp256r1.PrivKey - */ -export class PrivKey extends Message { - /** - * secret number serialized using big-endian encoding - * - * @generated from field: bytes secret = 1; - */ - secret = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.crypto.secp256r1.PrivKey'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'secret', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PrivKey { - return new PrivKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PrivKey { - return new PrivKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PrivKey { - return new PrivKey().fromJsonString(jsonString, options); - } - - static equals( - a: PrivKey | PlainMessage | undefined, - b: PrivKey | PlainMessage | undefined - ): boolean { - return proto3.util.equals(PrivKey, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/ics23/v1/proofs_pb.ts b/packages/es/src/protobufs/cosmos/ics23/v1/proofs_pb.ts deleted file mode 100644 index 3b28a28a3..000000000 --- a/packages/es/src/protobufs/cosmos/ics23/v1/proofs_pb.ts +++ /dev/null @@ -1,1149 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/ics23/v1/proofs.proto (package cosmos.ics23.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * @generated from enum cosmos.ics23.v1.HashOp - */ -export enum HashOp { - /** - * NO_HASH is the default if no data passed. Note this is an illegal argument some places. - * - * @generated from enum value: NO_HASH = 0; - */ - NO_HASH = 0, - - /** - * @generated from enum value: SHA256 = 1; - */ - SHA256 = 1, - - /** - * @generated from enum value: SHA512 = 2; - */ - SHA512 = 2, - - /** - * @generated from enum value: KECCAK256 = 3; - */ - KECCAK256 = 3, - - /** - * @generated from enum value: RIPEMD160 = 4; - */ - RIPEMD160 = 4, - - /** - * ripemd160(sha256(x)) - * - * @generated from enum value: BITCOIN = 5; - */ - BITCOIN = 5, - - /** - * @generated from enum value: SHA512_256 = 6; - */ - SHA512_256 = 6, - - /** - * @generated from enum value: BLAKE2B_512 = 7; - */ - BLAKE2B_512 = 7, - - /** - * @generated from enum value: BLAKE2S_256 = 8; - */ - BLAKE2S_256 = 8, - - /** - * @generated from enum value: BLAKE3 = 9; - */ - BLAKE3 = 9, -} -// Retrieve enum metadata with: proto3.getEnumType(HashOp) -proto3.util.setEnumType(HashOp, 'cosmos.ics23.v1.HashOp', [ - { no: 0, name: 'NO_HASH' }, - { no: 1, name: 'SHA256' }, - { no: 2, name: 'SHA512' }, - { no: 3, name: 'KECCAK256' }, - { no: 4, name: 'RIPEMD160' }, - { no: 5, name: 'BITCOIN' }, - { no: 6, name: 'SHA512_256' }, - { no: 7, name: 'BLAKE2B_512' }, - { no: 8, name: 'BLAKE2S_256' }, - { no: 9, name: 'BLAKE3' }, -]); - -/** - * * - * LengthOp defines how to process the key and value of the LeafOp - * to include length information. After encoding the length with the given - * algorithm, the length will be prepended to the key and value bytes. - * (Each one with it's own encoded length) - * - * @generated from enum cosmos.ics23.v1.LengthOp - */ -export enum LengthOp { - /** - * NO_PREFIX don't include any length info - * - * @generated from enum value: NO_PREFIX = 0; - */ - NO_PREFIX = 0, - - /** - * VAR_PROTO uses protobuf (and go-amino) varint encoding of the length - * - * @generated from enum value: VAR_PROTO = 1; - */ - VAR_PROTO = 1, - - /** - * VAR_RLP uses rlp int encoding of the length - * - * @generated from enum value: VAR_RLP = 2; - */ - VAR_RLP = 2, - - /** - * FIXED32_BIG uses big-endian encoding of the length as a 32 bit integer - * - * @generated from enum value: FIXED32_BIG = 3; - */ - FIXED32_BIG = 3, - - /** - * FIXED32_LITTLE uses little-endian encoding of the length as a 32 bit integer - * - * @generated from enum value: FIXED32_LITTLE = 4; - */ - FIXED32_LITTLE = 4, - - /** - * FIXED64_BIG uses big-endian encoding of the length as a 64 bit integer - * - * @generated from enum value: FIXED64_BIG = 5; - */ - FIXED64_BIG = 5, - - /** - * FIXED64_LITTLE uses little-endian encoding of the length as a 64 bit integer - * - * @generated from enum value: FIXED64_LITTLE = 6; - */ - FIXED64_LITTLE = 6, - - /** - * REQUIRE_32_BYTES is like NONE, but will fail if the input is not exactly 32 bytes (sha256 output) - * - * @generated from enum value: REQUIRE_32_BYTES = 7; - */ - REQUIRE_32_BYTES = 7, - - /** - * REQUIRE_64_BYTES is like NONE, but will fail if the input is not exactly 64 bytes (sha512 output) - * - * @generated from enum value: REQUIRE_64_BYTES = 8; - */ - REQUIRE_64_BYTES = 8, -} -// Retrieve enum metadata with: proto3.getEnumType(LengthOp) -proto3.util.setEnumType(LengthOp, 'cosmos.ics23.v1.LengthOp', [ - { no: 0, name: 'NO_PREFIX' }, - { no: 1, name: 'VAR_PROTO' }, - { no: 2, name: 'VAR_RLP' }, - { no: 3, name: 'FIXED32_BIG' }, - { no: 4, name: 'FIXED32_LITTLE' }, - { no: 5, name: 'FIXED64_BIG' }, - { no: 6, name: 'FIXED64_LITTLE' }, - { no: 7, name: 'REQUIRE_32_BYTES' }, - { no: 8, name: 'REQUIRE_64_BYTES' }, -]); - -/** - * * - * ExistenceProof takes a key and a value and a set of steps to perform on it. - * The result of peforming all these steps will provide a "root hash", which can - * be compared to the value in a header. - * - * Since it is computationally infeasible to produce a hash collission for any of the used - * cryptographic hash functions, if someone can provide a series of operations to transform - * a given key and value into a root hash that matches some trusted root, these key and values - * must be in the referenced merkle tree. - * - * The only possible issue is maliablity in LeafOp, such as providing extra prefix data, - * which should be controlled by a spec. Eg. with lengthOp as NONE, - * prefix = FOO, key = BAR, value = CHOICE - * and - * prefix = F, key = OOBAR, value = CHOICE - * would produce the same value. - * - * With LengthOp this is tricker but not impossible. Which is why the "leafPrefixEqual" field - * in the ProofSpec is valuable to prevent this mutability. And why all trees should - * length-prefix the data before hashing it. - * - * @generated from message cosmos.ics23.v1.ExistenceProof - */ -export class ExistenceProof extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - /** - * @generated from field: cosmos.ics23.v1.LeafOp leaf = 3; - */ - leaf?: LeafOp; - - /** - * @generated from field: repeated cosmos.ics23.v1.InnerOp path = 4; - */ - path: InnerOp[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.ExistenceProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: 'leaf', kind: 'message', T: LeafOp }, - { no: 4, name: 'path', kind: 'message', T: InnerOp, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExistenceProof { - return new ExistenceProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExistenceProof { - return new ExistenceProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExistenceProof { - return new ExistenceProof().fromJsonString(jsonString, options); - } - - static equals( - a: ExistenceProof | PlainMessage | undefined, - b: ExistenceProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ExistenceProof, a, b); - } -} - -/** - * - * NonExistenceProof takes a proof of two neighbors, one left of the desired key, - * one right of the desired key. If both proofs are valid AND they are neighbors, - * then there is no valid proof for the given key. - * - * @generated from message cosmos.ics23.v1.NonExistenceProof - */ -export class NonExistenceProof extends Message { - /** - * TODO: remove this as unnecessary??? we prove a range - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: cosmos.ics23.v1.ExistenceProof left = 2; - */ - left?: ExistenceProof; - - /** - * @generated from field: cosmos.ics23.v1.ExistenceProof right = 3; - */ - right?: ExistenceProof; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.NonExistenceProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'left', kind: 'message', T: ExistenceProof }, - { no: 3, name: 'right', kind: 'message', T: ExistenceProof }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NonExistenceProof { - return new NonExistenceProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NonExistenceProof { - return new NonExistenceProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NonExistenceProof { - return new NonExistenceProof().fromJsonString(jsonString, options); - } - - static equals( - a: NonExistenceProof | PlainMessage | undefined, - b: NonExistenceProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(NonExistenceProof, a, b); - } -} - -/** - * - * CommitmentProof is either an ExistenceProof or a NonExistenceProof, or a Batch of such messages - * - * @generated from message cosmos.ics23.v1.CommitmentProof - */ -export class CommitmentProof extends Message { - /** - * @generated from oneof cosmos.ics23.v1.CommitmentProof.proof - */ - proof: - | { - /** - * @generated from field: cosmos.ics23.v1.ExistenceProof exist = 1; - */ - value: ExistenceProof; - case: 'exist'; - } - | { - /** - * @generated from field: cosmos.ics23.v1.NonExistenceProof nonexist = 2; - */ - value: NonExistenceProof; - case: 'nonexist'; - } - | { - /** - * @generated from field: cosmos.ics23.v1.BatchProof batch = 3; - */ - value: BatchProof; - case: 'batch'; - } - | { - /** - * @generated from field: cosmos.ics23.v1.CompressedBatchProof compressed = 4; - */ - value: CompressedBatchProof; - case: 'compressed'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.CommitmentProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'exist', - kind: 'message', - T: ExistenceProof, - oneof: 'proof', - }, - { - no: 2, - name: 'nonexist', - kind: 'message', - T: NonExistenceProof, - oneof: 'proof', - }, - { no: 3, name: 'batch', kind: 'message', T: BatchProof, oneof: 'proof' }, - { - no: 4, - name: 'compressed', - kind: 'message', - T: CompressedBatchProof, - oneof: 'proof', - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CommitmentProof { - return new CommitmentProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CommitmentProof { - return new CommitmentProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CommitmentProof { - return new CommitmentProof().fromJsonString(jsonString, options); - } - - static equals( - a: CommitmentProof | PlainMessage | undefined, - b: CommitmentProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CommitmentProof, a, b); - } -} - -/** - * * - * LeafOp represents the raw key-value data we wish to prove, and - * must be flexible to represent the internal transformation from - * the original key-value pairs into the basis hash, for many existing - * merkle trees. - * - * key and value are passed in. So that the signature of this operation is: - * leafOp(key, value) -> output - * - * To process this, first prehash the keys and values if needed (ANY means no hash in this case): - * hkey = prehashKey(key) - * hvalue = prehashValue(value) - * - * Then combine the bytes, and hash it - * output = hash(prefix || length(hkey) || hkey || length(hvalue) || hvalue) - * - * @generated from message cosmos.ics23.v1.LeafOp - */ -export class LeafOp extends Message { - /** - * @generated from field: cosmos.ics23.v1.HashOp hash = 1; - */ - hash = HashOp.NO_HASH; - - /** - * @generated from field: cosmos.ics23.v1.HashOp prehash_key = 2; - */ - prehashKey = HashOp.NO_HASH; - - /** - * @generated from field: cosmos.ics23.v1.HashOp prehash_value = 3; - */ - prehashValue = HashOp.NO_HASH; - - /** - * @generated from field: cosmos.ics23.v1.LengthOp length = 4; - */ - length = LengthOp.NO_PREFIX; - - /** - * prefix is a fixed bytes that may optionally be included at the beginning to differentiate - * a leaf node from an inner node. - * - * @generated from field: bytes prefix = 5; - */ - prefix = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.LeafOp'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'hash', kind: 'enum', T: proto3.getEnumType(HashOp) }, - { no: 2, name: 'prehash_key', kind: 'enum', T: proto3.getEnumType(HashOp) }, - { - no: 3, - name: 'prehash_value', - kind: 'enum', - T: proto3.getEnumType(HashOp), - }, - { no: 4, name: 'length', kind: 'enum', T: proto3.getEnumType(LengthOp) }, - { no: 5, name: 'prefix', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LeafOp { - return new LeafOp().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LeafOp { - return new LeafOp().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LeafOp { - return new LeafOp().fromJsonString(jsonString, options); - } - - static equals( - a: LeafOp | PlainMessage | undefined, - b: LeafOp | PlainMessage | undefined - ): boolean { - return proto3.util.equals(LeafOp, a, b); - } -} - -/** - * * - * InnerOp represents a merkle-proof step that is not a leaf. - * It represents concatenating two children and hashing them to provide the next result. - * - * The result of the previous step is passed in, so the signature of this op is: - * innerOp(child) -> output - * - * The result of applying InnerOp should be: - * output = op.hash(op.prefix || child || op.suffix) - * - * where the || operator is concatenation of binary data, - * and child is the result of hashing all the tree below this step. - * - * Any special data, like prepending child with the length, or prepending the entire operation with - * some value to differentiate from leaf nodes, should be included in prefix and suffix. - * If either of prefix or suffix is empty, we just treat it as an empty string - * - * @generated from message cosmos.ics23.v1.InnerOp - */ -export class InnerOp extends Message { - /** - * @generated from field: cosmos.ics23.v1.HashOp hash = 1; - */ - hash = HashOp.NO_HASH; - - /** - * @generated from field: bytes prefix = 2; - */ - prefix = new Uint8Array(0); - - /** - * @generated from field: bytes suffix = 3; - */ - suffix = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.InnerOp'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'hash', kind: 'enum', T: proto3.getEnumType(HashOp) }, - { no: 2, name: 'prefix', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: 'suffix', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InnerOp { - return new InnerOp().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InnerOp { - return new InnerOp().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InnerOp { - return new InnerOp().fromJsonString(jsonString, options); - } - - static equals( - a: InnerOp | PlainMessage | undefined, - b: InnerOp | PlainMessage | undefined - ): boolean { - return proto3.util.equals(InnerOp, a, b); - } -} - -/** - * * - * ProofSpec defines what the expected parameters are for a given proof type. - * This can be stored in the client and used to validate any incoming proofs. - * - * verify(ProofSpec, Proof) -> Proof | Error - * - * As demonstrated in tests, if we don't fix the algorithm used to calculate the - * LeafHash for a given tree, there are many possible key-value pairs that can - * generate a given hash (by interpretting the preimage differently). - * We need this for proper security, requires client knows a priori what - * tree format server uses. But not in code, rather a configuration object. - * - * @generated from message cosmos.ics23.v1.ProofSpec - */ -export class ProofSpec extends Message { - /** - * any field in the ExistenceProof must be the same as in this spec. - * except Prefix, which is just the first bytes of prefix (spec can be longer) - * - * @generated from field: cosmos.ics23.v1.LeafOp leaf_spec = 1; - */ - leafSpec?: LeafOp; - - /** - * @generated from field: cosmos.ics23.v1.InnerSpec inner_spec = 2; - */ - innerSpec?: InnerSpec; - - /** - * max_depth (if > 0) is the maximum number of InnerOps allowed (mainly for fixed-depth tries) - * the max_depth is interpreted as 128 if set to 0 - * - * @generated from field: int32 max_depth = 3; - */ - maxDepth = 0; - - /** - * min_depth (if > 0) is the minimum number of InnerOps allowed (mainly for fixed-depth tries) - * - * @generated from field: int32 min_depth = 4; - */ - minDepth = 0; - - /** - * prehash_key_before_comparison is a flag that indicates whether to use the - * prehash_key specified by LeafOp to compare lexical ordering of keys for - * non-existence proofs. - * - * @generated from field: bool prehash_key_before_comparison = 5; - */ - prehashKeyBeforeComparison = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.ProofSpec'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'leaf_spec', kind: 'message', T: LeafOp }, - { no: 2, name: 'inner_spec', kind: 'message', T: InnerSpec }, - { no: 3, name: 'max_depth', kind: 'scalar', T: 5 /* ScalarType.INT32 */ }, - { no: 4, name: 'min_depth', kind: 'scalar', T: 5 /* ScalarType.INT32 */ }, - { - no: 5, - name: 'prehash_key_before_comparison', - kind: 'scalar', - T: 8 /* ScalarType.BOOL */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ProofSpec { - return new ProofSpec().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ProofSpec { - return new ProofSpec().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ProofSpec { - return new ProofSpec().fromJsonString(jsonString, options); - } - - static equals( - a: ProofSpec | PlainMessage | undefined, - b: ProofSpec | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ProofSpec, a, b); - } -} - -/** - * - * InnerSpec contains all store-specific structure info to determine if two proofs from a - * given store are neighbors. - * - * This enables: - * - * isLeftMost(spec: InnerSpec, op: InnerOp) - * isRightMost(spec: InnerSpec, op: InnerOp) - * isLeftNeighbor(spec: InnerSpec, left: InnerOp, right: InnerOp) - * - * @generated from message cosmos.ics23.v1.InnerSpec - */ -export class InnerSpec extends Message { - /** - * Child order is the ordering of the children node, must count from 0 - * iavl tree is [0, 1] (left then right) - * merk is [0, 2, 1] (left, right, here) - * - * @generated from field: repeated int32 child_order = 1; - */ - childOrder: number[] = []; - - /** - * @generated from field: int32 child_size = 2; - */ - childSize = 0; - - /** - * @generated from field: int32 min_prefix_length = 3; - */ - minPrefixLength = 0; - - /** - * the max prefix length must be less than the minimum prefix length + child size - * - * @generated from field: int32 max_prefix_length = 4; - */ - maxPrefixLength = 0; - - /** - * empty child is the prehash image that is used when one child is nil (eg. 20 bytes of 0) - * - * @generated from field: bytes empty_child = 5; - */ - emptyChild = new Uint8Array(0); - - /** - * hash is the algorithm that must be used for each InnerOp - * - * @generated from field: cosmos.ics23.v1.HashOp hash = 6; - */ - hash = HashOp.NO_HASH; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.InnerSpec'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'child_order', - kind: 'scalar', - T: 5 /* ScalarType.INT32 */, - repeated: true, - }, - { no: 2, name: 'child_size', kind: 'scalar', T: 5 /* ScalarType.INT32 */ }, - { - no: 3, - name: 'min_prefix_length', - kind: 'scalar', - T: 5 /* ScalarType.INT32 */, - }, - { - no: 4, - name: 'max_prefix_length', - kind: 'scalar', - T: 5 /* ScalarType.INT32 */, - }, - { - no: 5, - name: 'empty_child', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { no: 6, name: 'hash', kind: 'enum', T: proto3.getEnumType(HashOp) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InnerSpec { - return new InnerSpec().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InnerSpec { - return new InnerSpec().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InnerSpec { - return new InnerSpec().fromJsonString(jsonString, options); - } - - static equals( - a: InnerSpec | PlainMessage | undefined, - b: InnerSpec | PlainMessage | undefined - ): boolean { - return proto3.util.equals(InnerSpec, a, b); - } -} - -/** - * - * BatchProof is a group of multiple proof types than can be compressed - * - * @generated from message cosmos.ics23.v1.BatchProof - */ -export class BatchProof extends Message { - /** - * @generated from field: repeated cosmos.ics23.v1.BatchEntry entries = 1; - */ - entries: BatchEntry[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.BatchProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'entries', kind: 'message', T: BatchEntry, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BatchProof { - return new BatchProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BatchProof { - return new BatchProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BatchProof { - return new BatchProof().fromJsonString(jsonString, options); - } - - static equals( - a: BatchProof | PlainMessage | undefined, - b: BatchProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BatchProof, a, b); - } -} - -/** - * Use BatchEntry not CommitmentProof, to avoid recursion - * - * @generated from message cosmos.ics23.v1.BatchEntry - */ -export class BatchEntry extends Message { - /** - * @generated from oneof cosmos.ics23.v1.BatchEntry.proof - */ - proof: - | { - /** - * @generated from field: cosmos.ics23.v1.ExistenceProof exist = 1; - */ - value: ExistenceProof; - case: 'exist'; - } - | { - /** - * @generated from field: cosmos.ics23.v1.NonExistenceProof nonexist = 2; - */ - value: NonExistenceProof; - case: 'nonexist'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.BatchEntry'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'exist', - kind: 'message', - T: ExistenceProof, - oneof: 'proof', - }, - { - no: 2, - name: 'nonexist', - kind: 'message', - T: NonExistenceProof, - oneof: 'proof', - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BatchEntry { - return new BatchEntry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BatchEntry { - return new BatchEntry().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BatchEntry { - return new BatchEntry().fromJsonString(jsonString, options); - } - - static equals( - a: BatchEntry | PlainMessage | undefined, - b: BatchEntry | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BatchEntry, a, b); - } -} - -/** - * @generated from message cosmos.ics23.v1.CompressedBatchProof - */ -export class CompressedBatchProof extends Message { - /** - * @generated from field: repeated cosmos.ics23.v1.CompressedBatchEntry entries = 1; - */ - entries: CompressedBatchEntry[] = []; - - /** - * @generated from field: repeated cosmos.ics23.v1.InnerOp lookup_inners = 2; - */ - lookupInners: InnerOp[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.CompressedBatchProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'entries', - kind: 'message', - T: CompressedBatchEntry, - repeated: true, - }, - { - no: 2, - name: 'lookup_inners', - kind: 'message', - T: InnerOp, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CompressedBatchProof { - return new CompressedBatchProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CompressedBatchProof { - return new CompressedBatchProof().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): CompressedBatchProof { - return new CompressedBatchProof().fromJsonString(jsonString, options); - } - - static equals( - a: CompressedBatchProof | PlainMessage | undefined, - b: CompressedBatchProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CompressedBatchProof, a, b); - } -} - -/** - * Use BatchEntry not CommitmentProof, to avoid recursion - * - * @generated from message cosmos.ics23.v1.CompressedBatchEntry - */ -export class CompressedBatchEntry extends Message { - /** - * @generated from oneof cosmos.ics23.v1.CompressedBatchEntry.proof - */ - proof: - | { - /** - * @generated from field: cosmos.ics23.v1.CompressedExistenceProof exist = 1; - */ - value: CompressedExistenceProof; - case: 'exist'; - } - | { - /** - * @generated from field: cosmos.ics23.v1.CompressedNonExistenceProof nonexist = 2; - */ - value: CompressedNonExistenceProof; - case: 'nonexist'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.CompressedBatchEntry'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'exist', - kind: 'message', - T: CompressedExistenceProof, - oneof: 'proof', - }, - { - no: 2, - name: 'nonexist', - kind: 'message', - T: CompressedNonExistenceProof, - oneof: 'proof', - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CompressedBatchEntry { - return new CompressedBatchEntry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CompressedBatchEntry { - return new CompressedBatchEntry().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): CompressedBatchEntry { - return new CompressedBatchEntry().fromJsonString(jsonString, options); - } - - static equals( - a: CompressedBatchEntry | PlainMessage | undefined, - b: CompressedBatchEntry | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CompressedBatchEntry, a, b); - } -} - -/** - * @generated from message cosmos.ics23.v1.CompressedExistenceProof - */ -export class CompressedExistenceProof extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - /** - * @generated from field: cosmos.ics23.v1.LeafOp leaf = 3; - */ - leaf?: LeafOp; - - /** - * these are indexes into the lookup_inners table in CompressedBatchProof - * - * @generated from field: repeated int32 path = 4; - */ - path: number[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.CompressedExistenceProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: 'leaf', kind: 'message', T: LeafOp }, - { - no: 4, - name: 'path', - kind: 'scalar', - T: 5 /* ScalarType.INT32 */, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): CompressedExistenceProof { - return new CompressedExistenceProof().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): CompressedExistenceProof { - return new CompressedExistenceProof().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): CompressedExistenceProof { - return new CompressedExistenceProof().fromJsonString(jsonString, options); - } - - static equals( - a: CompressedExistenceProof | PlainMessage | undefined, - b: CompressedExistenceProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CompressedExistenceProof, a, b); - } -} - -/** - * @generated from message cosmos.ics23.v1.CompressedNonExistenceProof - */ -export class CompressedNonExistenceProof extends Message { - /** - * TODO: remove this as unnecessary??? we prove a range - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: cosmos.ics23.v1.CompressedExistenceProof left = 2; - */ - left?: CompressedExistenceProof; - - /** - * @generated from field: cosmos.ics23.v1.CompressedExistenceProof right = 3; - */ - right?: CompressedExistenceProof; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.ics23.v1.CompressedNonExistenceProof'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'left', kind: 'message', T: CompressedExistenceProof }, - { no: 3, name: 'right', kind: 'message', T: CompressedExistenceProof }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): CompressedNonExistenceProof { - return new CompressedNonExistenceProof().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): CompressedNonExistenceProof { - return new CompressedNonExistenceProof().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): CompressedNonExistenceProof { - return new CompressedNonExistenceProof().fromJsonString(jsonString, options); - } - - static equals( - a: CompressedNonExistenceProof | PlainMessage | undefined, - b: CompressedNonExistenceProof | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CompressedNonExistenceProof, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/reflection/v1/reflection_cosmes.ts b/packages/es/src/protobufs/cosmos/reflection/v1/reflection_cosmes.ts deleted file mode 100644 index 699d3c881..000000000 --- a/packages/es/src/protobufs/cosmos/reflection/v1/reflection_cosmes.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/reflection/v1/reflection.proto (package cosmos.reflection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { FileDescriptorsRequest, FileDescriptorsResponse } from './reflection_pb.js'; - -const TYPE_NAME = 'cosmos.reflection.v1.ReflectionService'; - -/** - * FileDescriptors queries all the file descriptors in the app in order - * to enable easier generation of dynamic clients. - * - * @generated from rpc cosmos.reflection.v1.ReflectionService.FileDescriptors - */ -export const ReflectionServiceFileDescriptorsService = { - typeName: TYPE_NAME, - method: 'FileDescriptors', - Request: FileDescriptorsRequest, - Response: FileDescriptorsResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/reflection/v1/reflection_pb.ts b/packages/es/src/protobufs/cosmos/reflection/v1/reflection_pb.ts deleted file mode 100644 index 8a1591854..000000000 --- a/packages/es/src/protobufs/cosmos/reflection/v1/reflection_pb.ts +++ /dev/null @@ -1,117 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/reflection/v1/reflection.proto (package cosmos.reflection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { FileDescriptorProto, Message, proto3 } from '@bufbuild/protobuf'; - -/** - * FileDescriptorsRequest is the Query/FileDescriptors request type. - * - * @generated from message cosmos.reflection.v1.FileDescriptorsRequest - */ -export class FileDescriptorsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.reflection.v1.FileDescriptorsRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): FileDescriptorsRequest { - return new FileDescriptorsRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): FileDescriptorsRequest { - return new FileDescriptorsRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): FileDescriptorsRequest { - return new FileDescriptorsRequest().fromJsonString(jsonString, options); - } - - static equals( - a: FileDescriptorsRequest | PlainMessage | undefined, - b: FileDescriptorsRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(FileDescriptorsRequest, a, b); - } -} - -/** - * FileDescriptorsResponse is the Query/FileDescriptors response type. - * - * @generated from message cosmos.reflection.v1.FileDescriptorsResponse - */ -export class FileDescriptorsResponse extends Message { - /** - * files is the file descriptors. - * - * @generated from field: repeated google.protobuf.FileDescriptorProto files = 1; - */ - files: FileDescriptorProto[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.reflection.v1.FileDescriptorsResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'files', - kind: 'message', - T: FileDescriptorProto, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): FileDescriptorsResponse { - return new FileDescriptorsResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): FileDescriptorsResponse { - return new FileDescriptorsResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): FileDescriptorsResponse { - return new FileDescriptorsResponse().fromJsonString(jsonString, options); - } - - static equals( - a: FileDescriptorsResponse | PlainMessage | undefined, - b: FileDescriptorsResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(FileDescriptorsResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/store/internal/kv/v1beta1/kv_pb.ts b/packages/es/src/protobufs/cosmos/store/internal/kv/v1beta1/kv_pb.ts deleted file mode 100644 index 1340ea239..000000000 --- a/packages/es/src/protobufs/cosmos/store/internal/kv/v1beta1/kv_pb.ts +++ /dev/null @@ -1,104 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/store/internal/kv/v1beta1/kv.proto (package cosmos.store.internal.kv.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * Pairs defines a repeated slice of Pair objects. - * - * @generated from message cosmos.store.internal.kv.v1beta1.Pairs - */ -export class Pairs extends Message { - /** - * @generated from field: repeated cosmos.store.internal.kv.v1beta1.Pair pairs = 1; - */ - pairs: Pair[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.internal.kv.v1beta1.Pairs'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'pairs', kind: 'message', T: Pair, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Pairs { - return new Pairs().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Pairs { - return new Pairs().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Pairs { - return new Pairs().fromJsonString(jsonString, options); - } - - static equals( - a: Pairs | PlainMessage | undefined, - b: Pairs | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Pairs, a, b); - } -} - -/** - * Pair defines a key/value bytes tuple. - * - * @generated from message cosmos.store.internal.kv.v1beta1.Pair - */ -export class Pair extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.internal.kv.v1beta1.Pair'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Pair { - return new Pair().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Pair { - return new Pair().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Pair { - return new Pair().fromJsonString(jsonString, options); - } - - static equals( - a: Pair | PlainMessage | undefined, - b: Pair | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Pair, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/store/snapshots/v1/snapshot_pb.ts b/packages/es/src/protobufs/cosmos/store/snapshots/v1/snapshot_pb.ts deleted file mode 100644 index d93b5bae3..000000000 --- a/packages/es/src/protobufs/cosmos/store/snapshots/v1/snapshot_pb.ts +++ /dev/null @@ -1,451 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/store/snapshots/v1/snapshot.proto (package cosmos.store.snapshots.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3, protoInt64 } from '@bufbuild/protobuf'; - -/** - * Snapshot contains Tendermint state sync snapshot info. - * - * @generated from message cosmos.store.snapshots.v1.Snapshot - */ -export class Snapshot extends Message { - /** - * @generated from field: uint64 height = 1; - */ - height = protoInt64.zero; - - /** - * @generated from field: uint32 format = 2; - */ - format = 0; - - /** - * @generated from field: uint32 chunks = 3; - */ - chunks = 0; - - /** - * @generated from field: bytes hash = 4; - */ - hash = new Uint8Array(0); - - /** - * @generated from field: cosmos.store.snapshots.v1.Metadata metadata = 5; - */ - metadata?: Metadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.Snapshot'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'height', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: 'format', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: 'chunks', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: 'hash', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: 'metadata', kind: 'message', T: Metadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Snapshot { - return new Snapshot().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Snapshot { - return new Snapshot().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Snapshot { - return new Snapshot().fromJsonString(jsonString, options); - } - - static equals( - a: Snapshot | PlainMessage | undefined, - b: Snapshot | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Snapshot, a, b); - } -} - -/** - * Metadata contains SDK-specific snapshot metadata. - * - * @generated from message cosmos.store.snapshots.v1.Metadata - */ -export class Metadata extends Message { - /** - * SHA-256 chunk hashes - * - * @generated from field: repeated bytes chunk_hashes = 1; - */ - chunkHashes: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.Metadata'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'chunk_hashes', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Metadata { - return new Metadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Metadata { - return new Metadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Metadata { - return new Metadata().fromJsonString(jsonString, options); - } - - static equals( - a: Metadata | PlainMessage | undefined, - b: Metadata | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Metadata, a, b); - } -} - -/** - * SnapshotItem is an item contained in a rootmulti.Store snapshot. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.store.snapshots.v1.SnapshotItem - */ -export class SnapshotItem extends Message { - /** - * item is the specific type of snapshot item. - * - * @generated from oneof cosmos.store.snapshots.v1.SnapshotItem.item - */ - item: - | { - /** - * @generated from field: cosmos.store.snapshots.v1.SnapshotStoreItem store = 1; - */ - value: SnapshotStoreItem; - case: 'store'; - } - | { - /** - * @generated from field: cosmos.store.snapshots.v1.SnapshotIAVLItem iavl = 2; - */ - value: SnapshotIAVLItem; - case: 'iavl'; - } - | { - /** - * @generated from field: cosmos.store.snapshots.v1.SnapshotExtensionMeta extension = 3; - */ - value: SnapshotExtensionMeta; - case: 'extension'; - } - | { - /** - * @generated from field: cosmos.store.snapshots.v1.SnapshotExtensionPayload extension_payload = 4; - */ - value: SnapshotExtensionPayload; - case: 'extensionPayload'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.SnapshotItem'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'store', - kind: 'message', - T: SnapshotStoreItem, - oneof: 'item', - }, - { - no: 2, - name: 'iavl', - kind: 'message', - T: SnapshotIAVLItem, - oneof: 'item', - }, - { - no: 3, - name: 'extension', - kind: 'message', - T: SnapshotExtensionMeta, - oneof: 'item', - }, - { - no: 4, - name: 'extension_payload', - kind: 'message', - T: SnapshotExtensionPayload, - oneof: 'item', - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SnapshotItem { - return new SnapshotItem().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SnapshotItem { - return new SnapshotItem().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SnapshotItem { - return new SnapshotItem().fromJsonString(jsonString, options); - } - - static equals( - a: SnapshotItem | PlainMessage | undefined, - b: SnapshotItem | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SnapshotItem, a, b); - } -} - -/** - * SnapshotStoreItem contains metadata about a snapshotted store. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.store.snapshots.v1.SnapshotStoreItem - */ -export class SnapshotStoreItem extends Message { - /** - * @generated from field: string name = 1; - */ - name = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.SnapshotStoreItem'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SnapshotStoreItem { - return new SnapshotStoreItem().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SnapshotStoreItem { - return new SnapshotStoreItem().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SnapshotStoreItem { - return new SnapshotStoreItem().fromJsonString(jsonString, options); - } - - static equals( - a: SnapshotStoreItem | PlainMessage | undefined, - b: SnapshotStoreItem | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SnapshotStoreItem, a, b); - } -} - -/** - * SnapshotIAVLItem is an exported IAVL node. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.store.snapshots.v1.SnapshotIAVLItem - */ -export class SnapshotIAVLItem extends Message { - /** - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - /** - * version is block height - * - * @generated from field: int64 version = 3; - */ - version = protoInt64.zero; - - /** - * height is depth of the tree. - * - * @generated from field: int32 height = 4; - */ - height = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.SnapshotIAVLItem'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: 'version', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: 'height', kind: 'scalar', T: 5 /* ScalarType.INT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SnapshotIAVLItem { - return new SnapshotIAVLItem().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SnapshotIAVLItem { - return new SnapshotIAVLItem().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SnapshotIAVLItem { - return new SnapshotIAVLItem().fromJsonString(jsonString, options); - } - - static equals( - a: SnapshotIAVLItem | PlainMessage | undefined, - b: SnapshotIAVLItem | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SnapshotIAVLItem, a, b); - } -} - -/** - * SnapshotExtensionMeta contains metadata about an external snapshotter. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.store.snapshots.v1.SnapshotExtensionMeta - */ -export class SnapshotExtensionMeta extends Message { - /** - * @generated from field: string name = 1; - */ - name = ''; - - /** - * @generated from field: uint32 format = 2; - */ - format = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.SnapshotExtensionMeta'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'format', kind: 'scalar', T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SnapshotExtensionMeta { - return new SnapshotExtensionMeta().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SnapshotExtensionMeta { - return new SnapshotExtensionMeta().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SnapshotExtensionMeta { - return new SnapshotExtensionMeta().fromJsonString(jsonString, options); - } - - static equals( - a: SnapshotExtensionMeta | PlainMessage | undefined, - b: SnapshotExtensionMeta | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SnapshotExtensionMeta, a, b); - } -} - -/** - * SnapshotExtensionPayload contains payloads of an external snapshotter. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.store.snapshots.v1.SnapshotExtensionPayload - */ -export class SnapshotExtensionPayload extends Message { - /** - * @generated from field: bytes payload = 1; - */ - payload = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.snapshots.v1.SnapshotExtensionPayload'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'payload', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SnapshotExtensionPayload { - return new SnapshotExtensionPayload().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): SnapshotExtensionPayload { - return new SnapshotExtensionPayload().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SnapshotExtensionPayload { - return new SnapshotExtensionPayload().fromJsonString(jsonString, options); - } - - static equals( - a: SnapshotExtensionPayload | PlainMessage | undefined, - b: SnapshotExtensionPayload | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SnapshotExtensionPayload, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_cosmes.ts b/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_cosmes.ts deleted file mode 100644 index 53909ba81..000000000 --- a/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_cosmes.ts +++ /dev/null @@ -1,37 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/store/streaming/abci/grpc.proto (package cosmos.store.streaming.abci, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { - ListenCommitRequest, - ListenCommitResponse, - ListenFinalizeBlockRequest, - ListenFinalizeBlockResponse, -} from './grpc_pb.js'; - -const TYPE_NAME = 'cosmos.store.streaming.abci.ABCIListenerService'; - -/** - * ListenFinalizeBlock is the corresponding endpoint for ABCIListener.ListenEndBlock - * - * @generated from rpc cosmos.store.streaming.abci.ABCIListenerService.ListenFinalizeBlock - */ -export const ABCIListenerServiceListenFinalizeBlockService = { - typeName: TYPE_NAME, - method: 'ListenFinalizeBlock', - Request: ListenFinalizeBlockRequest, - Response: ListenFinalizeBlockResponse, -} as const; - -/** - * ListenCommit is the corresponding endpoint for ABCIListener.ListenCommit - * - * @generated from rpc cosmos.store.streaming.abci.ABCIListenerService.ListenCommit - */ -export const ABCIListenerServiceListenCommitService = { - typeName: TYPE_NAME, - method: 'ListenCommit', - Request: ListenCommitRequest, - Response: ListenCommitResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_pb.ts b/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_pb.ts deleted file mode 100644 index 913261d3b..000000000 --- a/packages/es/src/protobufs/cosmos/store/streaming/abci/grpc_pb.ts +++ /dev/null @@ -1,229 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/store/streaming/abci/grpc.proto (package cosmos.store.streaming.abci, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { - RequestFinalizeBlock, - ResponseCommit, - ResponseFinalizeBlock, -} from '../../../../tendermint/abci/types_pb.js'; -import { StoreKVPair } from '../../v1beta1/listening_pb.js'; - -/** - * ListenEndBlockRequest is the request type for the ListenEndBlock RPC method - * - * @generated from message cosmos.store.streaming.abci.ListenFinalizeBlockRequest - */ -export class ListenFinalizeBlockRequest extends Message { - /** - * @generated from field: tendermint.abci.RequestFinalizeBlock req = 1; - */ - req?: RequestFinalizeBlock; - - /** - * @generated from field: tendermint.abci.ResponseFinalizeBlock res = 2; - */ - res?: ResponseFinalizeBlock; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.streaming.abci.ListenFinalizeBlockRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'req', kind: 'message', T: RequestFinalizeBlock }, - { no: 2, name: 'res', kind: 'message', T: ResponseFinalizeBlock }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListenFinalizeBlockRequest { - return new ListenFinalizeBlockRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListenFinalizeBlockRequest { - return new ListenFinalizeBlockRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListenFinalizeBlockRequest { - return new ListenFinalizeBlockRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ListenFinalizeBlockRequest | PlainMessage | undefined, - b: ListenFinalizeBlockRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListenFinalizeBlockRequest, a, b); - } -} - -/** - * ListenEndBlockResponse is the response type for the ListenEndBlock RPC method - * - * @generated from message cosmos.store.streaming.abci.ListenFinalizeBlockResponse - */ -export class ListenFinalizeBlockResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.streaming.abci.ListenFinalizeBlockResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): ListenFinalizeBlockResponse { - return new ListenFinalizeBlockResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): ListenFinalizeBlockResponse { - return new ListenFinalizeBlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListenFinalizeBlockResponse { - return new ListenFinalizeBlockResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ListenFinalizeBlockResponse | PlainMessage | undefined, - b: ListenFinalizeBlockResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListenFinalizeBlockResponse, a, b); - } -} - -/** - * ListenCommitRequest is the request type for the ListenCommit RPC method - * - * @generated from message cosmos.store.streaming.abci.ListenCommitRequest - */ -export class ListenCommitRequest extends Message { - /** - * explicitly pass in block height as ResponseCommit does not contain this info - * - * @generated from field: int64 block_height = 1; - */ - blockHeight = protoInt64.zero; - - /** - * @generated from field: tendermint.abci.ResponseCommit res = 2; - */ - res?: ResponseCommit; - - /** - * @generated from field: repeated cosmos.store.v1beta1.StoreKVPair change_set = 3; - */ - changeSet: StoreKVPair[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.streaming.abci.ListenCommitRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'block_height', - kind: 'scalar', - T: 3 /* ScalarType.INT64 */, - }, - { no: 2, name: 'res', kind: 'message', T: ResponseCommit }, - { - no: 3, - name: 'change_set', - kind: 'message', - T: StoreKVPair, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ListenCommitRequest { - return new ListenCommitRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ListenCommitRequest { - return new ListenCommitRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListenCommitRequest { - return new ListenCommitRequest().fromJsonString(jsonString, options); - } - - static equals( - a: ListenCommitRequest | PlainMessage | undefined, - b: ListenCommitRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListenCommitRequest, a, b); - } -} - -/** - * ListenCommitResponse is the response type for the ListenCommit RPC method - * - * @generated from message cosmos.store.streaming.abci.ListenCommitResponse - */ -export class ListenCommitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.streaming.abci.ListenCommitResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => []); - - static fromBinary(bytes: Uint8Array, options?: Partial): ListenCommitResponse { - return new ListenCommitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ListenCommitResponse { - return new ListenCommitResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): ListenCommitResponse { - return new ListenCommitResponse().fromJsonString(jsonString, options); - } - - static equals( - a: ListenCommitResponse | PlainMessage | undefined, - b: ListenCommitResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ListenCommitResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/store/v1beta1/commit_info_pb.ts b/packages/es/src/protobufs/cosmos/store/v1beta1/commit_info_pb.ts deleted file mode 100644 index 6bcad00c2..000000000 --- a/packages/es/src/protobufs/cosmos/store/v1beta1/commit_info_pb.ts +++ /dev/null @@ -1,173 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/store/v1beta1/commit_info.proto (package cosmos.store.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, Timestamp, proto3, protoInt64 } from '@bufbuild/protobuf'; - -/** - * CommitInfo defines commit information used by the multi-store when committing - * a version/height. - * - * @generated from message cosmos.store.v1beta1.CommitInfo - */ -export class CommitInfo extends Message { - /** - * @generated from field: int64 version = 1; - */ - version = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.store.v1beta1.StoreInfo store_infos = 2; - */ - storeInfos: StoreInfo[] = []; - - /** - * @generated from field: google.protobuf.Timestamp timestamp = 3; - */ - timestamp?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.v1beta1.CommitInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'version', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { - no: 2, - name: 'store_infos', - kind: 'message', - T: StoreInfo, - repeated: true, - }, - { no: 3, name: 'timestamp', kind: 'message', T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CommitInfo { - return new CommitInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CommitInfo { - return new CommitInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CommitInfo { - return new CommitInfo().fromJsonString(jsonString, options); - } - - static equals( - a: CommitInfo | PlainMessage | undefined, - b: CommitInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CommitInfo, a, b); - } -} - -/** - * StoreInfo defines store-specific commit information. It contains a reference - * between a store name and the commit ID. - * - * @generated from message cosmos.store.v1beta1.StoreInfo - */ -export class StoreInfo extends Message { - /** - * @generated from field: string name = 1; - */ - name = ''; - - /** - * @generated from field: cosmos.store.v1beta1.CommitID commit_id = 2; - */ - commitId?: CommitID; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.v1beta1.StoreInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'name', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'commit_id', kind: 'message', T: CommitID }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreInfo { - return new StoreInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreInfo { - return new StoreInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreInfo { - return new StoreInfo().fromJsonString(jsonString, options); - } - - static equals( - a: StoreInfo | PlainMessage | undefined, - b: StoreInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StoreInfo, a, b); - } -} - -/** - * CommitID defines the commitment information when a specific store is - * committed. - * - * @generated from message cosmos.store.v1beta1.CommitID - */ -export class CommitID extends Message { - /** - * @generated from field: int64 version = 1; - */ - version = protoInt64.zero; - - /** - * @generated from field: bytes hash = 2; - */ - hash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.v1beta1.CommitID'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'version', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: 'hash', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CommitID { - return new CommitID().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CommitID { - return new CommitID().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CommitID { - return new CommitID().fromJsonString(jsonString, options); - } - - static equals( - a: CommitID | PlainMessage | undefined, - b: CommitID | PlainMessage | undefined - ): boolean { - return proto3.util.equals(CommitID, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/store/v1beta1/listening_pb.ts b/packages/es/src/protobufs/cosmos/store/v1beta1/listening_pb.ts deleted file mode 100644 index b20e4e670..000000000 --- a/packages/es/src/protobufs/cosmos/store/v1beta1/listening_pb.ts +++ /dev/null @@ -1,154 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/store/v1beta1/listening.proto (package cosmos.store.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; -import { - RequestFinalizeBlock, - ResponseCommit, - ResponseFinalizeBlock, -} from '../../../tendermint/abci/types_pb.js'; - -/** - * StoreKVPair is a KVStore KVPair used for listening to state changes (Sets and Deletes) - * It optionally includes the StoreKey for the originating KVStore and a Boolean flag to distinguish between Sets and - * Deletes - * - * Since: cosmos-sdk 0.43 - * - * @generated from message cosmos.store.v1beta1.StoreKVPair - */ -export class StoreKVPair extends Message { - /** - * the store key for the KVStore this pair originates from - * - * @generated from field: string store_key = 1; - */ - storeKey = ''; - - /** - * true indicates a delete operation, false indicates a set operation - * - * @generated from field: bool delete = 2; - */ - delete = false; - - /** - * @generated from field: bytes key = 3; - */ - key = new Uint8Array(0); - - /** - * @generated from field: bytes value = 4; - */ - value = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.v1beta1.StoreKVPair'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'store_key', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'delete', kind: 'scalar', T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: 'key', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: 'value', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreKVPair { - return new StoreKVPair().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreKVPair { - return new StoreKVPair().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreKVPair { - return new StoreKVPair().fromJsonString(jsonString, options); - } - - static equals( - a: StoreKVPair | PlainMessage | undefined, - b: StoreKVPair | PlainMessage | undefined - ): boolean { - return proto3.util.equals(StoreKVPair, a, b); - } -} - -/** - * BlockMetadata contains all the abci event data of a block - * the file streamer dump them into files together with the state changes. - * - * @generated from message cosmos.store.v1beta1.BlockMetadata - */ -export class BlockMetadata extends Message { - /** - * @generated from field: tendermint.abci.ResponseCommit response_commit = 6; - */ - responseCommit?: ResponseCommit; - - /** - * @generated from field: tendermint.abci.RequestFinalizeBlock request_finalize_block = 7; - */ - requestFinalizeBlock?: RequestFinalizeBlock; - - /** - * TODO: should we renumber this? - * - * @generated from field: tendermint.abci.ResponseFinalizeBlock response_finalize_block = 8; - */ - responseFinalizeBlock?: ResponseFinalizeBlock; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.store.v1beta1.BlockMetadata'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 6, name: 'response_commit', kind: 'message', T: ResponseCommit }, - { - no: 7, - name: 'request_finalize_block', - kind: 'message', - T: RequestFinalizeBlock, - }, - { - no: 8, - name: 'response_finalize_block', - kind: 'message', - T: ResponseFinalizeBlock, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BlockMetadata { - return new BlockMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BlockMetadata { - return new BlockMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BlockMetadata { - return new BlockMetadata().fromJsonString(jsonString, options); - } - - static equals( - a: BlockMetadata | PlainMessage | undefined, - b: BlockMetadata | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BlockMetadata, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/tx/config/v1/config_pb.ts b/packages/es/src/protobufs/cosmos/tx/config/v1/config_pb.ts deleted file mode 100644 index 32aad7d23..000000000 --- a/packages/es/src/protobufs/cosmos/tx/config/v1/config_pb.ts +++ /dev/null @@ -1,78 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/tx/config/v1/config.proto (package cosmos.tx.config.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3 } from '@bufbuild/protobuf'; - -/** - * Config is the config object of the x/auth/tx package. - * - * @generated from message cosmos.tx.config.v1.Config - */ -export class Config extends Message { - /** - * skip_ante_handler defines whether the ante handler registration should be skipped in case an app wants to override - * this functionality. - * - * @generated from field: bool skip_ante_handler = 1; - */ - skipAnteHandler = false; - - /** - * skip_post_handler defines whether the post handler registration should be skipped in case an app wants to override - * this functionality. - * - * @generated from field: bool skip_post_handler = 2; - */ - skipPostHandler = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.config.v1.Config'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'skip_ante_handler', - kind: 'scalar', - T: 8 /* ScalarType.BOOL */, - }, - { - no: 2, - name: 'skip_post_handler', - kind: 'scalar', - T: 8 /* ScalarType.BOOL */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Config { - return new Config().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Config { - return new Config().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Config { - return new Config().fromJsonString(jsonString, options); - } - - static equals( - a: Config | PlainMessage | undefined, - b: Config | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Config, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/tx/signing/v1beta1/signing_pb.ts b/packages/es/src/protobufs/cosmos/tx/signing/v1beta1/signing_pb.ts deleted file mode 100644 index d80410251..000000000 --- a/packages/es/src/protobufs/cosmos/tx/signing/v1beta1/signing_pb.ts +++ /dev/null @@ -1,432 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/tx/signing/v1beta1/signing.proto (package cosmos.tx.signing.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { CompactBitArray } from '../../../crypto/multisig/v1beta1/multisig_pb.js'; - -/** - * SignMode represents a signing mode with its own security guarantees. - * - * This enum should be considered a registry of all known sign modes - * in the Cosmos ecosystem. Apps are not expected to support all known - * sign modes. Apps that would like to support custom sign modes are - * encouraged to open a small PR against this file to add a new case - * to this SignMode enum describing their sign mode so that different - * apps have a consistent version of this enum. - * - * @generated from enum cosmos.tx.signing.v1beta1.SignMode - */ -export enum SignMode { - /** - * SIGN_MODE_UNSPECIFIED specifies an unknown signing mode and will be - * rejected. - * - * @generated from enum value: SIGN_MODE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * SIGN_MODE_DIRECT specifies a signing mode which uses SignDoc and is - * verified with raw bytes from Tx. - * - * @generated from enum value: SIGN_MODE_DIRECT = 1; - */ - DIRECT = 1, - - /** - * SIGN_MODE_TEXTUAL is a future signing mode that will verify some - * human-readable textual representation on top of the binary representation - * from SIGN_MODE_DIRECT. - * - * Since: cosmos-sdk 0.50 - * - * @generated from enum value: SIGN_MODE_TEXTUAL = 2; - */ - TEXTUAL = 2, - - /** - * SIGN_MODE_DIRECT_AUX specifies a signing mode which uses - * SignDocDirectAux. As opposed to SIGN_MODE_DIRECT, this sign mode does not - * require signers signing over other signers' `signer_info`. - * - * Since: cosmos-sdk 0.46 - * - * @generated from enum value: SIGN_MODE_DIRECT_AUX = 3; - */ - DIRECT_AUX = 3, - - /** - * SIGN_MODE_LEGACY_AMINO_JSON is a backwards compatibility mode which uses - * Amino JSON and will be removed in the future. - * - * @generated from enum value: SIGN_MODE_LEGACY_AMINO_JSON = 127; - */ - LEGACY_AMINO_JSON = 127, - - /** - * SIGN_MODE_EIP_191 specifies the sign mode for EIP 191 signing on the Cosmos - * SDK. Ref: https://eips.ethereum.org/EIPS/eip-191 - * - * Currently, SIGN_MODE_EIP_191 is registered as a SignMode enum variant, - * but is not implemented on the SDK by default. To enable EIP-191, you need - * to pass a custom `TxConfig` that has an implementation of - * `SignModeHandler` for EIP-191. The SDK may decide to fully support - * EIP-191 in the future. - * - * Since: cosmos-sdk 0.45.2 - * - * @generated from enum value: SIGN_MODE_EIP_191 = 191; - */ - EIP_191 = 191, -} -// Retrieve enum metadata with: proto3.getEnumType(SignMode) -proto3.util.setEnumType(SignMode, 'cosmos.tx.signing.v1beta1.SignMode', [ - { no: 0, name: 'SIGN_MODE_UNSPECIFIED' }, - { no: 1, name: 'SIGN_MODE_DIRECT' }, - { no: 2, name: 'SIGN_MODE_TEXTUAL' }, - { no: 3, name: 'SIGN_MODE_DIRECT_AUX' }, - { no: 127, name: 'SIGN_MODE_LEGACY_AMINO_JSON' }, - { no: 191, name: 'SIGN_MODE_EIP_191' }, -]); - -/** - * SignatureDescriptors wraps multiple SignatureDescriptor's. - * - * @generated from message cosmos.tx.signing.v1beta1.SignatureDescriptors - */ -export class SignatureDescriptors extends Message { - /** - * signatures are the signature descriptors - * - * @generated from field: repeated cosmos.tx.signing.v1beta1.SignatureDescriptor signatures = 1; - */ - signatures: SignatureDescriptor[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.signing.v1beta1.SignatureDescriptors'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'signatures', - kind: 'message', - T: SignatureDescriptor, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignatureDescriptors { - return new SignatureDescriptors().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignatureDescriptors { - return new SignatureDescriptors().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SignatureDescriptors { - return new SignatureDescriptors().fromJsonString(jsonString, options); - } - - static equals( - a: SignatureDescriptors | PlainMessage | undefined, - b: SignatureDescriptors | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignatureDescriptors, a, b); - } -} - -/** - * SignatureDescriptor is a convenience type which represents the full data for - * a signature including the public key of the signer, signing modes and the - * signature itself. It is primarily used for coordinating signatures between - * clients. - * - * @generated from message cosmos.tx.signing.v1beta1.SignatureDescriptor - */ -export class SignatureDescriptor extends Message { - /** - * public_key is the public key of the signer - * - * @generated from field: google.protobuf.Any public_key = 1; - */ - publicKey?: Any; - - /** - * @generated from field: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data data = 2; - */ - data?: SignatureDescriptor_Data; - - /** - * sequence is the sequence of the account, which describes the - * number of committed transactions signed by a given address. It is used to prevent - * replay attacks. - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.signing.v1beta1.SignatureDescriptor'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'public_key', kind: 'message', T: Any }, - { no: 2, name: 'data', kind: 'message', T: SignatureDescriptor_Data }, - { no: 3, name: 'sequence', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignatureDescriptor { - return new SignatureDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignatureDescriptor { - return new SignatureDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SignatureDescriptor { - return new SignatureDescriptor().fromJsonString(jsonString, options); - } - - static equals( - a: SignatureDescriptor | PlainMessage | undefined, - b: SignatureDescriptor | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignatureDescriptor, a, b); - } -} - -/** - * Data represents signature data - * - * @generated from message cosmos.tx.signing.v1beta1.SignatureDescriptor.Data - */ -export class SignatureDescriptor_Data extends Message { - /** - * sum is the oneof that specifies whether this represents single or multi-signature data - * - * @generated from oneof cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.sum - */ - sum: - | { - /** - * single represents a single signer - * - * @generated from field: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single single = 1; - */ - value: SignatureDescriptor_Data_Single; - case: 'single'; - } - | { - /** - * multi represents a multisig signer - * - * @generated from field: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi multi = 2; - */ - value: SignatureDescriptor_Data_Multi; - case: 'multi'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.signing.v1beta1.SignatureDescriptor.Data'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'single', - kind: 'message', - T: SignatureDescriptor_Data_Single, - oneof: 'sum', - }, - { - no: 2, - name: 'multi', - kind: 'message', - T: SignatureDescriptor_Data_Multi, - oneof: 'sum', - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SignatureDescriptor_Data { - return new SignatureDescriptor_Data().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): SignatureDescriptor_Data { - return new SignatureDescriptor_Data().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SignatureDescriptor_Data { - return new SignatureDescriptor_Data().fromJsonString(jsonString, options); - } - - static equals( - a: SignatureDescriptor_Data | PlainMessage | undefined, - b: SignatureDescriptor_Data | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignatureDescriptor_Data, a, b); - } -} - -/** - * Single is the signature data for a single signer - * - * @generated from message cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single - */ -export class SignatureDescriptor_Data_Single extends Message { - /** - * mode is the signing mode of the single signer - * - * @generated from field: cosmos.tx.signing.v1beta1.SignMode mode = 1; - */ - mode = SignMode.UNSPECIFIED; - - /** - * signature is the raw signature bytes - * - * @generated from field: bytes signature = 2; - */ - signature = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'mode', kind: 'enum', T: proto3.getEnumType(SignMode) }, - { no: 2, name: 'signature', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SignatureDescriptor_Data_Single { - return new SignatureDescriptor_Data_Single().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): SignatureDescriptor_Data_Single { - return new SignatureDescriptor_Data_Single().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SignatureDescriptor_Data_Single { - return new SignatureDescriptor_Data_Single().fromJsonString(jsonString, options); - } - - static equals( - a: SignatureDescriptor_Data_Single | PlainMessage | undefined, - b: SignatureDescriptor_Data_Single | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignatureDescriptor_Data_Single, a, b); - } -} - -/** - * Multi is the signature data for a multisig public key - * - * @generated from message cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi - */ -export class SignatureDescriptor_Data_Multi extends Message { - /** - * bitarray specifies which keys within the multisig are signing - * - * @generated from field: cosmos.crypto.multisig.v1beta1.CompactBitArray bitarray = 1; - */ - bitarray?: CompactBitArray; - - /** - * signatures is the signatures of the multi-signature - * - * @generated from field: repeated cosmos.tx.signing.v1beta1.SignatureDescriptor.Data signatures = 2; - */ - signatures: SignatureDescriptor_Data[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'bitarray', kind: 'message', T: CompactBitArray }, - { - no: 2, - name: 'signatures', - kind: 'message', - T: SignatureDescriptor_Data, - repeated: true, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): SignatureDescriptor_Data_Multi { - return new SignatureDescriptor_Data_Multi().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): SignatureDescriptor_Data_Multi { - return new SignatureDescriptor_Data_Multi().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): SignatureDescriptor_Data_Multi { - return new SignatureDescriptor_Data_Multi().fromJsonString(jsonString, options); - } - - static equals( - a: SignatureDescriptor_Data_Multi | PlainMessage | undefined, - b: SignatureDescriptor_Data_Multi | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignatureDescriptor_Data_Multi, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/tx/v1beta1/service_cosmes.ts b/packages/es/src/protobufs/cosmos/tx/v1beta1/service_cosmes.ts deleted file mode 100644 index 5c16ba731..000000000 --- a/packages/es/src/protobufs/cosmos/tx/v1beta1/service_cosmes.ts +++ /dev/null @@ -1,145 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmos/tx/v1beta1/service.proto (package cosmos.tx.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { - BroadcastTxRequest, - BroadcastTxResponse, - GetBlockWithTxsRequest, - GetBlockWithTxsResponse, - GetTxRequest, - GetTxResponse, - GetTxsEventRequest, - GetTxsEventResponse, - SimulateRequest, - SimulateResponse, - TxDecodeAminoRequest, - TxDecodeAminoResponse, - TxDecodeRequest, - TxDecodeResponse, - TxEncodeAminoRequest, - TxEncodeAminoResponse, - TxEncodeRequest, - TxEncodeResponse, -} from './service_pb.js'; - -const TYPE_NAME = 'cosmos.tx.v1beta1.Service'; - -/** - * Simulate simulates executing a transaction for estimating gas usage. - * - * @generated from rpc cosmos.tx.v1beta1.Service.Simulate - */ -export const ServiceSimulateService = { - typeName: TYPE_NAME, - method: 'Simulate', - Request: SimulateRequest, - Response: SimulateResponse, -} as const; - -/** - * GetTx fetches a tx by hash. - * - * @generated from rpc cosmos.tx.v1beta1.Service.GetTx - */ -export const ServiceGetTxService = { - typeName: TYPE_NAME, - method: 'GetTx', - Request: GetTxRequest, - Response: GetTxResponse, -} as const; - -/** - * BroadcastTx broadcast transaction. - * - * @generated from rpc cosmos.tx.v1beta1.Service.BroadcastTx - */ -export const ServiceBroadcastTxService = { - typeName: TYPE_NAME, - method: 'BroadcastTx', - Request: BroadcastTxRequest, - Response: BroadcastTxResponse, -} as const; - -/** - * GetTxsEvent fetches txs by event. - * - * @generated from rpc cosmos.tx.v1beta1.Service.GetTxsEvent - */ -export const ServiceGetTxsEventService = { - typeName: TYPE_NAME, - method: 'GetTxsEvent', - Request: GetTxsEventRequest, - Response: GetTxsEventResponse, -} as const; - -/** - * GetBlockWithTxs fetches a block with decoded txs. - * - * Since: cosmos-sdk 0.45.2 - * - * @generated from rpc cosmos.tx.v1beta1.Service.GetBlockWithTxs - */ -export const ServiceGetBlockWithTxsService = { - typeName: TYPE_NAME, - method: 'GetBlockWithTxs', - Request: GetBlockWithTxsRequest, - Response: GetBlockWithTxsResponse, -} as const; - -/** - * TxDecode decodes the transaction. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc cosmos.tx.v1beta1.Service.TxDecode - */ -export const ServiceTxDecodeService = { - typeName: TYPE_NAME, - method: 'TxDecode', - Request: TxDecodeRequest, - Response: TxDecodeResponse, -} as const; - -/** - * TxEncode encodes the transaction. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc cosmos.tx.v1beta1.Service.TxEncode - */ -export const ServiceTxEncodeService = { - typeName: TYPE_NAME, - method: 'TxEncode', - Request: TxEncodeRequest, - Response: TxEncodeResponse, -} as const; - -/** - * TxEncodeAmino encodes an Amino transaction from JSON to encoded bytes. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc cosmos.tx.v1beta1.Service.TxEncodeAmino - */ -export const ServiceTxEncodeAminoService = { - typeName: TYPE_NAME, - method: 'TxEncodeAmino', - Request: TxEncodeAminoRequest, - Response: TxEncodeAminoResponse, -} as const; - -/** - * TxDecodeAmino decodes an Amino transaction from encoded bytes to JSON. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc cosmos.tx.v1beta1.Service.TxDecodeAmino - */ -export const ServiceTxDecodeAminoService = { - typeName: TYPE_NAME, - method: 'TxDecodeAmino', - Request: TxDecodeAminoRequest, - Response: TxDecodeAminoResponse, -} as const; diff --git a/packages/es/src/protobufs/cosmos/tx/v1beta1/service_pb.ts b/packages/es/src/protobufs/cosmos/tx/v1beta1/service_pb.ts deleted file mode 100644 index 41dc2a9c5..000000000 --- a/packages/es/src/protobufs/cosmos/tx/v1beta1/service_pb.ts +++ /dev/null @@ -1,1128 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/tx/v1beta1/service.proto (package cosmos.tx.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { Block } from '../../../tendermint/types/block_pb.js'; -import { BlockID } from '../../../tendermint/types/types_pb.js'; -import { GasInfo, Result, TxResponse } from '../../base/abci/v1beta1/abci_pb.js'; -import { PageRequest, PageResponse } from '../../base/query/v1beta1/pagination_pb.js'; -import { Tx } from './tx_pb.js'; - -/** - * OrderBy defines the sorting order - * - * @generated from enum cosmos.tx.v1beta1.OrderBy - */ -export enum OrderBy { - /** - * ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults - * to ASC in this case. - * - * @generated from enum value: ORDER_BY_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * ORDER_BY_ASC defines ascending order - * - * @generated from enum value: ORDER_BY_ASC = 1; - */ - ASC = 1, - - /** - * ORDER_BY_DESC defines descending order - * - * @generated from enum value: ORDER_BY_DESC = 2; - */ - DESC = 2, -} -// Retrieve enum metadata with: proto3.getEnumType(OrderBy) -proto3.util.setEnumType(OrderBy, 'cosmos.tx.v1beta1.OrderBy', [ - { no: 0, name: 'ORDER_BY_UNSPECIFIED' }, - { no: 1, name: 'ORDER_BY_ASC' }, - { no: 2, name: 'ORDER_BY_DESC' }, -]); - -/** - * BroadcastMode specifies the broadcast mode for the TxService.Broadcast RPC - * method. - * - * @generated from enum cosmos.tx.v1beta1.BroadcastMode - */ -export enum BroadcastMode { - /** - * zero-value for mode ordering - * - * @generated from enum value: BROADCAST_MODE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * DEPRECATED: use BROADCAST_MODE_SYNC instead, - * BROADCAST_MODE_BLOCK is not supported by the SDK from v0.47.x onwards. - * - * @generated from enum value: BROADCAST_MODE_BLOCK = 1 [deprecated = true]; - * @deprecated - */ - BLOCK = 1, - - /** - * BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits - * for a CheckTx execution response only. - * - * @generated from enum value: BROADCAST_MODE_SYNC = 2; - */ - SYNC = 2, - - /** - * BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client - * returns immediately. - * - * @generated from enum value: BROADCAST_MODE_ASYNC = 3; - */ - ASYNC = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(BroadcastMode) -proto3.util.setEnumType(BroadcastMode, 'cosmos.tx.v1beta1.BroadcastMode', [ - { no: 0, name: 'BROADCAST_MODE_UNSPECIFIED' }, - { no: 1, name: 'BROADCAST_MODE_BLOCK' }, - { no: 2, name: 'BROADCAST_MODE_SYNC' }, - { no: 3, name: 'BROADCAST_MODE_ASYNC' }, -]); - -/** - * GetTxsEventRequest is the request type for the Service.TxsByEvents - * RPC method. - * - * @generated from message cosmos.tx.v1beta1.GetTxsEventRequest - */ -export class GetTxsEventRequest extends Message { - /** - * events is the list of transaction event type. - * Deprecated post v0.47.x: use query instead, which should contain a valid - * events query. - * - * @generated from field: repeated string events = 1 [deprecated = true]; - * @deprecated - */ - events: string[] = []; - - /** - * pagination defines a pagination for the request. - * Deprecated post v0.46.x: use page and limit instead. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2 [deprecated = true]; - * @deprecated - */ - pagination?: PageRequest; - - /** - * @generated from field: cosmos.tx.v1beta1.OrderBy order_by = 3; - */ - orderBy = OrderBy.UNSPECIFIED; - - /** - * page is the page number to query, starts at 1. If not provided, will - * default to first page. - * - * @generated from field: uint64 page = 4; - */ - page = protoInt64.zero; - - /** - * limit is the total number of results to be returned in the result page. - * If left empty it will default to a value to be set by each app. - * - * @generated from field: uint64 limit = 5; - */ - limit = protoInt64.zero; - - /** - * query defines the transaction event query that is proxied to Tendermint's - * TxSearch RPC method. The query must be valid. - * - * Since cosmos-sdk 0.50 - * - * @generated from field: string query = 6; - */ - query = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetTxsEventRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'events', - kind: 'scalar', - T: 9 /* ScalarType.STRING */, - repeated: true, - }, - { no: 2, name: 'pagination', kind: 'message', T: PageRequest }, - { no: 3, name: 'order_by', kind: 'enum', T: proto3.getEnumType(OrderBy) }, - { no: 4, name: 'page', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: 'limit', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: 'query', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTxsEventRequest { - return new GetTxsEventRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTxsEventRequest { - return new GetTxsEventRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetTxsEventRequest { - return new GetTxsEventRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxsEventRequest | PlainMessage | undefined, - b: GetTxsEventRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxsEventRequest, a, b); - } -} - -/** - * GetTxsEventResponse is the response type for the Service.TxsByEvents - * RPC method. - * - * @generated from message cosmos.tx.v1beta1.GetTxsEventResponse - */ -export class GetTxsEventResponse extends Message { - /** - * txs is the list of queried transactions. - * - * @generated from field: repeated cosmos.tx.v1beta1.Tx txs = 1; - */ - txs: Tx[] = []; - - /** - * tx_responses is the list of queried TxResponses. - * - * @generated from field: repeated cosmos.base.abci.v1beta1.TxResponse tx_responses = 2; - */ - txResponses: TxResponse[] = []; - - /** - * pagination defines a pagination for the response. - * Deprecated post v0.46.x: use total instead. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 3 [deprecated = true]; - * @deprecated - */ - pagination?: PageResponse; - - /** - * total is total number of results available - * - * @generated from field: uint64 total = 4; - */ - total = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetTxsEventResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'txs', kind: 'message', T: Tx, repeated: true }, - { - no: 2, - name: 'tx_responses', - kind: 'message', - T: TxResponse, - repeated: true, - }, - { no: 3, name: 'pagination', kind: 'message', T: PageResponse }, - { no: 4, name: 'total', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTxsEventResponse { - return new GetTxsEventResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTxsEventResponse { - return new GetTxsEventResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetTxsEventResponse { - return new GetTxsEventResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxsEventResponse | PlainMessage | undefined, - b: GetTxsEventResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxsEventResponse, a, b); - } -} - -/** - * BroadcastTxRequest is the request type for the Service.BroadcastTxRequest - * RPC method. - * - * @generated from message cosmos.tx.v1beta1.BroadcastTxRequest - */ -export class BroadcastTxRequest extends Message { - /** - * tx_bytes is the raw transaction. - * - * @generated from field: bytes tx_bytes = 1; - */ - txBytes = new Uint8Array(0); - - /** - * @generated from field: cosmos.tx.v1beta1.BroadcastMode mode = 2; - */ - mode = BroadcastMode.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.BroadcastTxRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'mode', kind: 'enum', T: proto3.getEnumType(BroadcastMode) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BroadcastTxRequest { - return new BroadcastTxRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BroadcastTxRequest { - return new BroadcastTxRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): BroadcastTxRequest { - return new BroadcastTxRequest().fromJsonString(jsonString, options); - } - - static equals( - a: BroadcastTxRequest | PlainMessage | undefined, - b: BroadcastTxRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BroadcastTxRequest, a, b); - } -} - -/** - * BroadcastTxResponse is the response type for the - * Service.BroadcastTx method. - * - * @generated from message cosmos.tx.v1beta1.BroadcastTxResponse - */ -export class BroadcastTxResponse extends Message { - /** - * tx_response is the queried TxResponses. - * - * @generated from field: cosmos.base.abci.v1beta1.TxResponse tx_response = 1; - */ - txResponse?: TxResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.BroadcastTxResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx_response', kind: 'message', T: TxResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BroadcastTxResponse { - return new BroadcastTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BroadcastTxResponse { - return new BroadcastTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): BroadcastTxResponse { - return new BroadcastTxResponse().fromJsonString(jsonString, options); - } - - static equals( - a: BroadcastTxResponse | PlainMessage | undefined, - b: BroadcastTxResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(BroadcastTxResponse, a, b); - } -} - -/** - * SimulateRequest is the request type for the Service.Simulate - * RPC method. - * - * @generated from message cosmos.tx.v1beta1.SimulateRequest - */ -export class SimulateRequest extends Message { - /** - * tx is the transaction to simulate. - * Deprecated. Send raw tx bytes instead. - * - * @generated from field: cosmos.tx.v1beta1.Tx tx = 1 [deprecated = true]; - * @deprecated - */ - tx?: Tx; - - /** - * tx_bytes is the raw transaction. - * - * Since: cosmos-sdk 0.43 - * - * @generated from field: bytes tx_bytes = 2; - */ - txBytes = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.SimulateRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: Tx }, - { no: 2, name: 'tx_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SimulateRequest { - return new SimulateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SimulateRequest { - return new SimulateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SimulateRequest { - return new SimulateRequest().fromJsonString(jsonString, options); - } - - static equals( - a: SimulateRequest | PlainMessage | undefined, - b: SimulateRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SimulateRequest, a, b); - } -} - -/** - * SimulateResponse is the response type for the - * Service.SimulateRPC method. - * - * @generated from message cosmos.tx.v1beta1.SimulateResponse - */ -export class SimulateResponse extends Message { - /** - * gas_info is the information about gas used in the simulation. - * - * @generated from field: cosmos.base.abci.v1beta1.GasInfo gas_info = 1; - */ - gasInfo?: GasInfo; - - /** - * result is the result of the simulation. - * - * @generated from field: cosmos.base.abci.v1beta1.Result result = 2; - */ - result?: Result; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.SimulateResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'gas_info', kind: 'message', T: GasInfo }, - { no: 2, name: 'result', kind: 'message', T: Result }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SimulateResponse { - return new SimulateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SimulateResponse { - return new SimulateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SimulateResponse { - return new SimulateResponse().fromJsonString(jsonString, options); - } - - static equals( - a: SimulateResponse | PlainMessage | undefined, - b: SimulateResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SimulateResponse, a, b); - } -} - -/** - * GetTxRequest is the request type for the Service.GetTx - * RPC method. - * - * @generated from message cosmos.tx.v1beta1.GetTxRequest - */ -export class GetTxRequest extends Message { - /** - * hash is the tx hash to query, encoded as a hex string. - * - * @generated from field: string hash = 1; - */ - hash = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetTxRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'hash', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTxRequest { - return new GetTxRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTxRequest { - return new GetTxRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTxRequest { - return new GetTxRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxRequest | PlainMessage | undefined, - b: GetTxRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxRequest, a, b); - } -} - -/** - * GetTxResponse is the response type for the Service.GetTx method. - * - * @generated from message cosmos.tx.v1beta1.GetTxResponse - */ -export class GetTxResponse extends Message { - /** - * tx is the queried transaction. - * - * @generated from field: cosmos.tx.v1beta1.Tx tx = 1; - */ - tx?: Tx; - - /** - * tx_response is the queried TxResponses. - * - * @generated from field: cosmos.base.abci.v1beta1.TxResponse tx_response = 2; - */ - txResponse?: TxResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetTxResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: Tx }, - { no: 2, name: 'tx_response', kind: 'message', T: TxResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTxResponse { - return new GetTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTxResponse { - return new GetTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTxResponse { - return new GetTxResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetTxResponse | PlainMessage | undefined, - b: GetTxResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetTxResponse, a, b); - } -} - -/** - * GetBlockWithTxsRequest is the request type for the Service.GetBlockWithTxs - * RPC method. - * - * Since: cosmos-sdk 0.45.2 - * - * @generated from message cosmos.tx.v1beta1.GetBlockWithTxsRequest - */ -export class GetBlockWithTxsRequest extends Message { - /** - * height is the height of the block to query. - * - * @generated from field: int64 height = 1; - */ - height = protoInt64.zero; - - /** - * pagination defines a pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetBlockWithTxsRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'height', kind: 'scalar', T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: 'pagination', kind: 'message', T: PageRequest }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetBlockWithTxsRequest { - return new GetBlockWithTxsRequest().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetBlockWithTxsRequest { - return new GetBlockWithTxsRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetBlockWithTxsRequest { - return new GetBlockWithTxsRequest().fromJsonString(jsonString, options); - } - - static equals( - a: GetBlockWithTxsRequest | PlainMessage | undefined, - b: GetBlockWithTxsRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetBlockWithTxsRequest, a, b); - } -} - -/** - * GetBlockWithTxsResponse is the response type for the Service.GetBlockWithTxs - * method. - * - * Since: cosmos-sdk 0.45.2 - * - * @generated from message cosmos.tx.v1beta1.GetBlockWithTxsResponse - */ -export class GetBlockWithTxsResponse extends Message { - /** - * txs are the transactions in the block. - * - * @generated from field: repeated cosmos.tx.v1beta1.Tx txs = 1; - */ - txs: Tx[] = []; - - /** - * @generated from field: tendermint.types.BlockID block_id = 2; - */ - blockId?: BlockID; - - /** - * @generated from field: tendermint.types.Block block = 3; - */ - block?: Block; - - /** - * pagination defines a pagination for the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 4; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.GetBlockWithTxsResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'txs', kind: 'message', T: Tx, repeated: true }, - { no: 2, name: 'block_id', kind: 'message', T: BlockID }, - { no: 3, name: 'block', kind: 'message', T: Block }, - { no: 4, name: 'pagination', kind: 'message', T: PageResponse }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): GetBlockWithTxsResponse { - return new GetBlockWithTxsResponse().fromBinary(bytes, options); - } - - static fromJson( - jsonValue: JsonValue, - options?: Partial - ): GetBlockWithTxsResponse { - return new GetBlockWithTxsResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): GetBlockWithTxsResponse { - return new GetBlockWithTxsResponse().fromJsonString(jsonString, options); - } - - static equals( - a: GetBlockWithTxsResponse | PlainMessage | undefined, - b: GetBlockWithTxsResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(GetBlockWithTxsResponse, a, b); - } -} - -/** - * TxDecodeRequest is the request type for the Service.TxDecode - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxDecodeRequest - */ -export class TxDecodeRequest extends Message { - /** - * tx_bytes is the raw transaction. - * - * @generated from field: bytes tx_bytes = 1; - */ - txBytes = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxDecodeRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxDecodeRequest { - return new TxDecodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxDecodeRequest { - return new TxDecodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxDecodeRequest { - return new TxDecodeRequest().fromJsonString(jsonString, options); - } - - static equals( - a: TxDecodeRequest | PlainMessage | undefined, - b: TxDecodeRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxDecodeRequest, a, b); - } -} - -/** - * TxDecodeResponse is the response type for the - * Service.TxDecode method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxDecodeResponse - */ -export class TxDecodeResponse extends Message { - /** - * tx is the decoded transaction. - * - * @generated from field: cosmos.tx.v1beta1.Tx tx = 1; - */ - tx?: Tx; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxDecodeResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: Tx }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxDecodeResponse { - return new TxDecodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxDecodeResponse { - return new TxDecodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxDecodeResponse { - return new TxDecodeResponse().fromJsonString(jsonString, options); - } - - static equals( - a: TxDecodeResponse | PlainMessage | undefined, - b: TxDecodeResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxDecodeResponse, a, b); - } -} - -/** - * TxEncodeRequest is the request type for the Service.TxEncode - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxEncodeRequest - */ -export class TxEncodeRequest extends Message { - /** - * tx is the transaction to encode. - * - * @generated from field: cosmos.tx.v1beta1.Tx tx = 1; - */ - tx?: Tx; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxEncodeRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx', kind: 'message', T: Tx }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxEncodeRequest { - return new TxEncodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxEncodeRequest { - return new TxEncodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxEncodeRequest { - return new TxEncodeRequest().fromJsonString(jsonString, options); - } - - static equals( - a: TxEncodeRequest | PlainMessage | undefined, - b: TxEncodeRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxEncodeRequest, a, b); - } -} - -/** - * TxEncodeResponse is the response type for the - * Service.TxEncode method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxEncodeResponse - */ -export class TxEncodeResponse extends Message { - /** - * tx_bytes is the encoded transaction bytes. - * - * @generated from field: bytes tx_bytes = 1; - */ - txBytes = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxEncodeResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'tx_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxEncodeResponse { - return new TxEncodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxEncodeResponse { - return new TxEncodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxEncodeResponse { - return new TxEncodeResponse().fromJsonString(jsonString, options); - } - - static equals( - a: TxEncodeResponse | PlainMessage | undefined, - b: TxEncodeResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxEncodeResponse, a, b); - } -} - -/** - * TxEncodeAminoRequest is the request type for the Service.TxEncodeAmino - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxEncodeAminoRequest - */ -export class TxEncodeAminoRequest extends Message { - /** - * @generated from field: string amino_json = 1; - */ - aminoJson = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxEncodeAminoRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'amino_json', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxEncodeAminoRequest { - return new TxEncodeAminoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxEncodeAminoRequest { - return new TxEncodeAminoRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): TxEncodeAminoRequest { - return new TxEncodeAminoRequest().fromJsonString(jsonString, options); - } - - static equals( - a: TxEncodeAminoRequest | PlainMessage | undefined, - b: TxEncodeAminoRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxEncodeAminoRequest, a, b); - } -} - -/** - * TxEncodeAminoResponse is the response type for the Service.TxEncodeAmino - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxEncodeAminoResponse - */ -export class TxEncodeAminoResponse extends Message { - /** - * @generated from field: bytes amino_binary = 1; - */ - aminoBinary = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxEncodeAminoResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'amino_binary', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): TxEncodeAminoResponse { - return new TxEncodeAminoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxEncodeAminoResponse { - return new TxEncodeAminoResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): TxEncodeAminoResponse { - return new TxEncodeAminoResponse().fromJsonString(jsonString, options); - } - - static equals( - a: TxEncodeAminoResponse | PlainMessage | undefined, - b: TxEncodeAminoResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxEncodeAminoResponse, a, b); - } -} - -/** - * TxDecodeAminoRequest is the request type for the Service.TxDecodeAmino - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxDecodeAminoRequest - */ -export class TxDecodeAminoRequest extends Message { - /** - * @generated from field: bytes amino_binary = 1; - */ - aminoBinary = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxDecodeAminoRequest'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'amino_binary', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxDecodeAminoRequest { - return new TxDecodeAminoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxDecodeAminoRequest { - return new TxDecodeAminoRequest().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): TxDecodeAminoRequest { - return new TxDecodeAminoRequest().fromJsonString(jsonString, options); - } - - static equals( - a: TxDecodeAminoRequest | PlainMessage | undefined, - b: TxDecodeAminoRequest | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxDecodeAminoRequest, a, b); - } -} - -/** - * TxDecodeAminoResponse is the response type for the Service.TxDecodeAmino - * RPC method. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message cosmos.tx.v1beta1.TxDecodeAminoResponse - */ -export class TxDecodeAminoResponse extends Message { - /** - * @generated from field: string amino_json = 1; - */ - aminoJson = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxDecodeAminoResponse'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'amino_json', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary( - bytes: Uint8Array, - options?: Partial - ): TxDecodeAminoResponse { - return new TxDecodeAminoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxDecodeAminoResponse { - return new TxDecodeAminoResponse().fromJson(jsonValue, options); - } - - static fromJsonString( - jsonString: string, - options?: Partial - ): TxDecodeAminoResponse { - return new TxDecodeAminoResponse().fromJsonString(jsonString, options); - } - - static equals( - a: TxDecodeAminoResponse | PlainMessage | undefined, - b: TxDecodeAminoResponse | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxDecodeAminoResponse, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmos/tx/v1beta1/tx_pb.ts b/packages/es/src/protobufs/cosmos/tx/v1beta1/tx_pb.ts deleted file mode 100644 index 14ecd651d..000000000 --- a/packages/es/src/protobufs/cosmos/tx/v1beta1/tx_pb.ts +++ /dev/null @@ -1,971 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmos/tx/v1beta1/tx.proto (package cosmos.tx.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { - BinaryReadOptions, - FieldList, - JsonReadOptions, - JsonValue, - PartialMessage, - PlainMessage, -} from '@bufbuild/protobuf'; -import { Any, Message, proto3, protoInt64 } from '@bufbuild/protobuf'; -import { Coin } from '../../base/v1beta1/coin_pb.js'; -import { CompactBitArray } from '../../crypto/multisig/v1beta1/multisig_pb.js'; -import { SignMode } from '../signing/v1beta1/signing_pb.js'; - -/** - * Tx is the standard type used for broadcasting transactions. - * - * @generated from message cosmos.tx.v1beta1.Tx - */ -export class Tx extends Message { - /** - * body is the processable content of the transaction - * - * @generated from field: cosmos.tx.v1beta1.TxBody body = 1; - */ - body?: TxBody; - - /** - * auth_info is the authorization related content of the transaction, - * specifically signers, signer modes and fee - * - * @generated from field: cosmos.tx.v1beta1.AuthInfo auth_info = 2; - */ - authInfo?: AuthInfo; - - /** - * signatures is a list of signatures that matches the length and order of - * AuthInfo's signer_infos to allow connecting signature meta information like - * public key and signing mode by position. - * - * @generated from field: repeated bytes signatures = 3; - */ - signatures: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.Tx'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'body', kind: 'message', T: TxBody }, - { no: 2, name: 'auth_info', kind: 'message', T: AuthInfo }, - { - no: 3, - name: 'signatures', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Tx { - return new Tx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Tx { - return new Tx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Tx { - return new Tx().fromJsonString(jsonString, options); - } - - static equals( - a: Tx | PlainMessage | undefined, - b: Tx | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Tx, a, b); - } -} - -/** - * TxRaw is a variant of Tx that pins the signer's exact binary representation - * of body and auth_info. This is used for signing, broadcasting and - * verification. The binary `serialize(tx: TxRaw)` is stored in Tendermint and - * the hash `sha256(serialize(tx: TxRaw))` becomes the "txhash", commonly used - * as the transaction ID. - * - * @generated from message cosmos.tx.v1beta1.TxRaw - */ -export class TxRaw extends Message { - /** - * body_bytes is a protobuf serialization of a TxBody that matches the - * representation in SignDoc. - * - * @generated from field: bytes body_bytes = 1; - */ - bodyBytes = new Uint8Array(0); - - /** - * auth_info_bytes is a protobuf serialization of an AuthInfo that matches the - * representation in SignDoc. - * - * @generated from field: bytes auth_info_bytes = 2; - */ - authInfoBytes = new Uint8Array(0); - - /** - * signatures is a list of signatures that matches the length and order of - * AuthInfo's signer_infos to allow connecting signature meta information like - * public key and signing mode by position. - * - * @generated from field: repeated bytes signatures = 3; - */ - signatures: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxRaw'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'body_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { - no: 2, - name: 'auth_info_bytes', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { - no: 3, - name: 'signatures', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxRaw { - return new TxRaw().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxRaw { - return new TxRaw().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxRaw { - return new TxRaw().fromJsonString(jsonString, options); - } - - static equals( - a: TxRaw | PlainMessage | undefined, - b: TxRaw | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxRaw, a, b); - } -} - -/** - * SignDoc is the type used for generating sign bytes for SIGN_MODE_DIRECT. - * - * @generated from message cosmos.tx.v1beta1.SignDoc - */ -export class SignDoc extends Message { - /** - * body_bytes is protobuf serialization of a TxBody that matches the - * representation in TxRaw. - * - * @generated from field: bytes body_bytes = 1; - */ - bodyBytes = new Uint8Array(0); - - /** - * auth_info_bytes is a protobuf serialization of an AuthInfo that matches the - * representation in TxRaw. - * - * @generated from field: bytes auth_info_bytes = 2; - */ - authInfoBytes = new Uint8Array(0); - - /** - * chain_id is the unique identifier of the chain this transaction targets. - * It prevents signed transactions from being used on another chain by an - * attacker - * - * @generated from field: string chain_id = 3; - */ - chainId = ''; - - /** - * account_number is the account number of the account in state - * - * @generated from field: uint64 account_number = 4; - */ - accountNumber = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.SignDoc'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'body_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { - no: 2, - name: 'auth_info_bytes', - kind: 'scalar', - T: 12 /* ScalarType.BYTES */, - }, - { no: 3, name: 'chain_id', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 4, - name: 'account_number', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignDoc { - return new SignDoc().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignDoc { - return new SignDoc().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignDoc { - return new SignDoc().fromJsonString(jsonString, options); - } - - static equals( - a: SignDoc | PlainMessage | undefined, - b: SignDoc | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignDoc, a, b); - } -} - -/** - * SignDocDirectAux is the type used for generating sign bytes for - * SIGN_MODE_DIRECT_AUX. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.tx.v1beta1.SignDocDirectAux - */ -export class SignDocDirectAux extends Message { - /** - * body_bytes is protobuf serialization of a TxBody that matches the - * representation in TxRaw. - * - * @generated from field: bytes body_bytes = 1; - */ - bodyBytes = new Uint8Array(0); - - /** - * public_key is the public key of the signing account. - * - * @generated from field: google.protobuf.Any public_key = 2; - */ - publicKey?: Any; - - /** - * chain_id is the identifier of the chain this transaction targets. - * It prevents signed transactions from being used on another chain by an - * attacker. - * - * @generated from field: string chain_id = 3; - */ - chainId = ''; - - /** - * account_number is the account number of the account in state. - * - * @generated from field: uint64 account_number = 4; - */ - accountNumber = protoInt64.zero; - - /** - * sequence is the sequence number of the signing account. - * - * @generated from field: uint64 sequence = 5; - */ - sequence = protoInt64.zero; - - /** - * tips have been depreacted and should not be used - * - * @generated from field: cosmos.tx.v1beta1.Tip tip = 6 [deprecated = true]; - * @deprecated - */ - tip?: Tip; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.SignDocDirectAux'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'body_bytes', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: 'public_key', kind: 'message', T: Any }, - { no: 3, name: 'chain_id', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 4, - name: 'account_number', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - { no: 5, name: 'sequence', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: 'tip', kind: 'message', T: Tip }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignDocDirectAux { - return new SignDocDirectAux().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignDocDirectAux { - return new SignDocDirectAux().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignDocDirectAux { - return new SignDocDirectAux().fromJsonString(jsonString, options); - } - - static equals( - a: SignDocDirectAux | PlainMessage | undefined, - b: SignDocDirectAux | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignDocDirectAux, a, b); - } -} - -/** - * TxBody is the body of a transaction that all signers sign over. - * - * @generated from message cosmos.tx.v1beta1.TxBody - */ -export class TxBody extends Message { - /** - * messages is a list of messages to be executed. The required signers of - * those messages define the number and order of elements in AuthInfo's - * signer_infos and Tx's signatures. Each required signer address is added to - * the list only the first time it occurs. - * By convention, the first required signer (usually from the first message) - * is referred to as the primary signer and pays the fee for the whole - * transaction. - * - * @generated from field: repeated google.protobuf.Any messages = 1; - */ - messages: Any[] = []; - - /** - * memo is any arbitrary note/comment to be added to the transaction. - * WARNING: in clients, any publicly exposed text should not be called memo, - * but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122). - * - * @generated from field: string memo = 2; - */ - memo = ''; - - /** - * timeout is the block height after which this transaction will not - * be processed by the chain - * - * @generated from field: uint64 timeout_height = 3; - */ - timeoutHeight = protoInt64.zero; - - /** - * extension_options are arbitrary options that can be added by chains - * when the default options are not sufficient. If any of these are present - * and can't be handled, the transaction will be rejected - * - * @generated from field: repeated google.protobuf.Any extension_options = 1023; - */ - extensionOptions: Any[] = []; - - /** - * extension_options are arbitrary options that can be added by chains - * when the default options are not sufficient. If any of these are present - * and can't be handled, they will be ignored - * - * @generated from field: repeated google.protobuf.Any non_critical_extension_options = 2047; - */ - nonCriticalExtensionOptions: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.TxBody'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'messages', kind: 'message', T: Any, repeated: true }, - { no: 2, name: 'memo', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { - no: 3, - name: 'timeout_height', - kind: 'scalar', - T: 4 /* ScalarType.UINT64 */, - }, - { - no: 1023, - name: 'extension_options', - kind: 'message', - T: Any, - repeated: true, - }, - { - no: 2047, - name: 'non_critical_extension_options', - kind: 'message', - T: Any, - repeated: true, - }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxBody { - return new TxBody().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxBody { - return new TxBody().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxBody { - return new TxBody().fromJsonString(jsonString, options); - } - - static equals( - a: TxBody | PlainMessage | undefined, - b: TxBody | PlainMessage | undefined - ): boolean { - return proto3.util.equals(TxBody, a, b); - } -} - -/** - * AuthInfo describes the fee and signer modes that are used to sign a - * transaction. - * - * @generated from message cosmos.tx.v1beta1.AuthInfo - */ -export class AuthInfo extends Message { - /** - * signer_infos defines the signing modes for the required signers. The number - * and order of elements must match the required signers from TxBody's - * messages. The first element is the primary signer and the one which pays - * the fee. - * - * @generated from field: repeated cosmos.tx.v1beta1.SignerInfo signer_infos = 1; - */ - signerInfos: SignerInfo[] = []; - - /** - * Fee is the fee and gas limit for the transaction. The first signer is the - * primary signer and the one which pays the fee. The fee can be calculated - * based on the cost of evaluating the body and doing signature verification - * of the signers. This can be estimated via simulation. - * - * @generated from field: cosmos.tx.v1beta1.Fee fee = 2; - */ - fee?: Fee; - - /** - * Tip is the optional tip used for transactions fees paid in another denom. - * - * This field is ignored if the chain didn't enable tips, i.e. didn't add the - * `TipDecorator` in its posthandler. - * - * Since: cosmos-sdk 0.46 - * - * @generated from field: cosmos.tx.v1beta1.Tip tip = 3 [deprecated = true]; - * @deprecated - */ - tip?: Tip; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.AuthInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'signer_infos', - kind: 'message', - T: SignerInfo, - repeated: true, - }, - { no: 2, name: 'fee', kind: 'message', T: Fee }, - { no: 3, name: 'tip', kind: 'message', T: Tip }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AuthInfo { - return new AuthInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AuthInfo { - return new AuthInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AuthInfo { - return new AuthInfo().fromJsonString(jsonString, options); - } - - static equals( - a: AuthInfo | PlainMessage | undefined, - b: AuthInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AuthInfo, a, b); - } -} - -/** - * SignerInfo describes the public key and signing mode of a single top-level - * signer. - * - * @generated from message cosmos.tx.v1beta1.SignerInfo - */ -export class SignerInfo extends Message { - /** - * public_key is the public key of the signer. It is optional for accounts - * that already exist in state. If unset, the verifier can use the required \ - * signer address for this position and lookup the public key. - * - * @generated from field: google.protobuf.Any public_key = 1; - */ - publicKey?: Any; - - /** - * mode_info describes the signing mode of the signer and is a nested - * structure to support nested multisig pubkey's - * - * @generated from field: cosmos.tx.v1beta1.ModeInfo mode_info = 2; - */ - modeInfo?: ModeInfo; - - /** - * sequence is the sequence of the account, which describes the - * number of committed transactions signed by a given address. It is used to - * prevent replay attacks. - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.SignerInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'public_key', kind: 'message', T: Any }, - { no: 2, name: 'mode_info', kind: 'message', T: ModeInfo }, - { no: 3, name: 'sequence', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignerInfo { - return new SignerInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignerInfo { - return new SignerInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignerInfo { - return new SignerInfo().fromJsonString(jsonString, options); - } - - static equals( - a: SignerInfo | PlainMessage | undefined, - b: SignerInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(SignerInfo, a, b); - } -} - -/** - * ModeInfo describes the signing mode of a single or nested multisig signer. - * - * @generated from message cosmos.tx.v1beta1.ModeInfo - */ -export class ModeInfo extends Message { - /** - * sum is the oneof that specifies whether this represents a single or nested - * multisig signer - * - * @generated from oneof cosmos.tx.v1beta1.ModeInfo.sum - */ - sum: - | { - /** - * single represents a single signer - * - * @generated from field: cosmos.tx.v1beta1.ModeInfo.Single single = 1; - */ - value: ModeInfo_Single; - case: 'single'; - } - | { - /** - * multi represents a nested multisig signer - * - * @generated from field: cosmos.tx.v1beta1.ModeInfo.Multi multi = 2; - */ - value: ModeInfo_Multi; - case: 'multi'; - } - | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.ModeInfo'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { - no: 1, - name: 'single', - kind: 'message', - T: ModeInfo_Single, - oneof: 'sum', - }, - { no: 2, name: 'multi', kind: 'message', T: ModeInfo_Multi, oneof: 'sum' }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModeInfo { - return new ModeInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModeInfo { - return new ModeInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModeInfo { - return new ModeInfo().fromJsonString(jsonString, options); - } - - static equals( - a: ModeInfo | PlainMessage | undefined, - b: ModeInfo | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModeInfo, a, b); - } -} - -/** - * Single is the mode info for a single signer. It is structured as a message - * to allow for additional fields such as locale for SIGN_MODE_TEXTUAL in the - * future - * - * @generated from message cosmos.tx.v1beta1.ModeInfo.Single - */ -export class ModeInfo_Single extends Message { - /** - * mode is the signing mode of the single signer - * - * @generated from field: cosmos.tx.signing.v1beta1.SignMode mode = 1; - */ - mode = SignMode.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.ModeInfo.Single'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'mode', kind: 'enum', T: proto3.getEnumType(SignMode) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModeInfo_Single { - return new ModeInfo_Single().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModeInfo_Single { - return new ModeInfo_Single().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModeInfo_Single { - return new ModeInfo_Single().fromJsonString(jsonString, options); - } - - static equals( - a: ModeInfo_Single | PlainMessage | undefined, - b: ModeInfo_Single | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModeInfo_Single, a, b); - } -} - -/** - * Multi is the mode info for a multisig public key - * - * @generated from message cosmos.tx.v1beta1.ModeInfo.Multi - */ -export class ModeInfo_Multi extends Message { - /** - * bitarray specifies which keys within the multisig are signing - * - * @generated from field: cosmos.crypto.multisig.v1beta1.CompactBitArray bitarray = 1; - */ - bitarray?: CompactBitArray; - - /** - * mode_infos is the corresponding modes of the signers of the multisig - * which could include nested multisig public keys - * - * @generated from field: repeated cosmos.tx.v1beta1.ModeInfo mode_infos = 2; - */ - modeInfos: ModeInfo[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.ModeInfo.Multi'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'bitarray', kind: 'message', T: CompactBitArray }, - { no: 2, name: 'mode_infos', kind: 'message', T: ModeInfo, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModeInfo_Multi { - return new ModeInfo_Multi().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModeInfo_Multi { - return new ModeInfo_Multi().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModeInfo_Multi { - return new ModeInfo_Multi().fromJsonString(jsonString, options); - } - - static equals( - a: ModeInfo_Multi | PlainMessage | undefined, - b: ModeInfo_Multi | PlainMessage | undefined - ): boolean { - return proto3.util.equals(ModeInfo_Multi, a, b); - } -} - -/** - * Fee includes the amount of coins paid in fees and the maximum - * gas to be used by the transaction. The ratio yields an effective "gasprice", - * which must be above some miminum to be accepted into the mempool. - * - * @generated from message cosmos.tx.v1beta1.Fee - */ -export class Fee extends Message { - /** - * amount is the amount of coins to be paid as a fee - * - * @generated from field: repeated cosmos.base.v1beta1.Coin amount = 1; - */ - amount: Coin[] = []; - - /** - * gas_limit is the maximum gas that can be used in transaction processing - * before an out of gas error occurs - * - * @generated from field: uint64 gas_limit = 2; - */ - gasLimit = protoInt64.zero; - - /** - * if unset, the first signer is responsible for paying the fees. If set, the specified account must pay the fees. - * the payer must be a tx signer (and thus have signed this field in AuthInfo). - * setting this field does *not* change the ordering of required signers for the transaction. - * - * @generated from field: string payer = 3; - */ - payer = ''; - - /** - * if set, the fee payer (either the first signer or the value of the payer field) requests that a fee grant be used - * to pay fees instead of the fee payer's own balance. If an appropriate fee grant does not exist or the chain does - * not support fee grants, this will fail - * - * @generated from field: string granter = 4; - */ - granter = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.Fee'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'amount', kind: 'message', T: Coin, repeated: true }, - { no: 2, name: 'gas_limit', kind: 'scalar', T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: 'payer', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 4, name: 'granter', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Fee { - return new Fee().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Fee { - return new Fee().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Fee { - return new Fee().fromJsonString(jsonString, options); - } - - static equals( - a: Fee | PlainMessage | undefined, - b: Fee | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Fee, a, b); - } -} - -/** - * Tip is the tip used for meta-transactions. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.tx.v1beta1.Tip - * @deprecated - */ -export class Tip extends Message { - /** - * amount is the amount of the tip - * - * @generated from field: repeated cosmos.base.v1beta1.Coin amount = 1; - */ - amount: Coin[] = []; - - /** - * tipper is the address of the account paying for the tip - * - * @generated from field: string tipper = 2; - */ - tipper = ''; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.Tip'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'amount', kind: 'message', T: Coin, repeated: true }, - { no: 2, name: 'tipper', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Tip { - return new Tip().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Tip { - return new Tip().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Tip { - return new Tip().fromJsonString(jsonString, options); - } - - static equals( - a: Tip | PlainMessage | undefined, - b: Tip | PlainMessage | undefined - ): boolean { - return proto3.util.equals(Tip, a, b); - } -} - -/** - * AuxSignerData is the intermediary format that an auxiliary signer (e.g. a - * tipper) builds and sends to the fee payer (who will build and broadcast the - * actual tx). AuxSignerData is not a valid tx in itself, and will be rejected - * by the node if sent directly as-is. - * - * Since: cosmos-sdk 0.46 - * - * @generated from message cosmos.tx.v1beta1.AuxSignerData - */ -export class AuxSignerData extends Message { - /** - * address is the bech32-encoded address of the auxiliary signer. If using - * AuxSignerData across different chains, the bech32 prefix of the target - * chain (where the final transaction is broadcasted) should be used. - * - * @generated from field: string address = 1; - */ - address = ''; - - /** - * sign_doc is the SIGN_MODE_DIRECT_AUX sign doc that the auxiliary signer - * signs. Note: we use the same sign doc even if we're signing with - * LEGACY_AMINO_JSON. - * - * @generated from field: cosmos.tx.v1beta1.SignDocDirectAux sign_doc = 2; - */ - signDoc?: SignDocDirectAux; - - /** - * mode is the signing mode of the single signer. - * - * @generated from field: cosmos.tx.signing.v1beta1.SignMode mode = 3; - */ - mode = SignMode.UNSPECIFIED; - - /** - * sig is the signature of the sign doc. - * - * @generated from field: bytes sig = 4; - */ - sig = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = 'cosmos.tx.v1beta1.AuxSignerData'; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: 'address', kind: 'scalar', T: 9 /* ScalarType.STRING */ }, - { no: 2, name: 'sign_doc', kind: 'message', T: SignDocDirectAux }, - { no: 3, name: 'mode', kind: 'enum', T: proto3.getEnumType(SignMode) }, - { no: 4, name: 'sig', kind: 'scalar', T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AuxSignerData { - return new AuxSignerData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AuxSignerData { - return new AuxSignerData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AuxSignerData { - return new AuxSignerData().fromJsonString(jsonString, options); - } - - static equals( - a: AuxSignerData | PlainMessage | undefined, - b: AuxSignerData | PlainMessage | undefined - ): boolean { - return proto3.util.equals(AuxSignerData, a, b); - } -} diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/authz_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/authz_pb.ts deleted file mode 100644 index 4097fdf57..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/authz_pb.ts +++ /dev/null @@ -1,505 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/authz.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccessConfig } from "./types_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * StoreCodeAuthorization defines authorization for wasm code upload. - * Since: wasmd 0.42 - * - * @generated from message cosmwasm.wasm.v1.StoreCodeAuthorization - */ -export class StoreCodeAuthorization extends Message { - /** - * Grants for code upload - * - * @generated from field: repeated cosmwasm.wasm.v1.CodeGrant grants = 1; - */ - grants: CodeGrant[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.StoreCodeAuthorization"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "grants", kind: "message", T: CodeGrant, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreCodeAuthorization { - return new StoreCodeAuthorization().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreCodeAuthorization { - return new StoreCodeAuthorization().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreCodeAuthorization { - return new StoreCodeAuthorization().fromJsonString(jsonString, options); - } - - static equals(a: StoreCodeAuthorization | PlainMessage | undefined, b: StoreCodeAuthorization | PlainMessage | undefined): boolean { - return proto3.util.equals(StoreCodeAuthorization, a, b); - } -} - -/** - * ContractExecutionAuthorization defines authorization for wasm execute. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.ContractExecutionAuthorization - */ -export class ContractExecutionAuthorization extends Message { - /** - * Grants for contract executions - * - * @generated from field: repeated cosmwasm.wasm.v1.ContractGrant grants = 1; - */ - grants: ContractGrant[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ContractExecutionAuthorization"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "grants", kind: "message", T: ContractGrant, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractExecutionAuthorization { - return new ContractExecutionAuthorization().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractExecutionAuthorization { - return new ContractExecutionAuthorization().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractExecutionAuthorization { - return new ContractExecutionAuthorization().fromJsonString(jsonString, options); - } - - static equals(a: ContractExecutionAuthorization | PlainMessage | undefined, b: ContractExecutionAuthorization | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractExecutionAuthorization, a, b); - } -} - -/** - * ContractMigrationAuthorization defines authorization for wasm contract - * migration. Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.ContractMigrationAuthorization - */ -export class ContractMigrationAuthorization extends Message { - /** - * Grants for contract migrations - * - * @generated from field: repeated cosmwasm.wasm.v1.ContractGrant grants = 1; - */ - grants: ContractGrant[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ContractMigrationAuthorization"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "grants", kind: "message", T: ContractGrant, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractMigrationAuthorization { - return new ContractMigrationAuthorization().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractMigrationAuthorization { - return new ContractMigrationAuthorization().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractMigrationAuthorization { - return new ContractMigrationAuthorization().fromJsonString(jsonString, options); - } - - static equals(a: ContractMigrationAuthorization | PlainMessage | undefined, b: ContractMigrationAuthorization | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractMigrationAuthorization, a, b); - } -} - -/** - * CodeGrant a granted permission for a single code - * - * @generated from message cosmwasm.wasm.v1.CodeGrant - */ -export class CodeGrant extends Message { - /** - * CodeHash is the unique identifier created by wasmvm - * Wildcard "*" is used to specify any kind of grant. - * - * @generated from field: bytes code_hash = 1; - */ - codeHash = new Uint8Array(0); - - /** - * InstantiatePermission is the superset access control to apply - * on contract creation. - * Optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 2; - */ - instantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.CodeGrant"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CodeGrant { - return new CodeGrant().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CodeGrant { - return new CodeGrant().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CodeGrant { - return new CodeGrant().fromJsonString(jsonString, options); - } - - static equals(a: CodeGrant | PlainMessage | undefined, b: CodeGrant | PlainMessage | undefined): boolean { - return proto3.util.equals(CodeGrant, a, b); - } -} - -/** - * ContractGrant a granted permission for a single contract - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.ContractGrant - */ -export class ContractGrant extends Message { - /** - * Contract is the bech32 address of the smart contract - * - * @generated from field: string contract = 1; - */ - contract = ""; - - /** - * Limit defines execution limits that are enforced and updated when the grant - * is applied. When the limit lapsed the grant is removed. - * - * @generated from field: google.protobuf.Any limit = 2; - */ - limit?: Any; - - /** - * Filter define more fine-grained control on the message payload passed - * to the contract in the operation. When no filter applies on execution, the - * operation is prohibited. - * - * @generated from field: google.protobuf.Any filter = 3; - */ - filter?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ContractGrant"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "limit", kind: "message", T: Any }, - { no: 3, name: "filter", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractGrant { - return new ContractGrant().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractGrant { - return new ContractGrant().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractGrant { - return new ContractGrant().fromJsonString(jsonString, options); - } - - static equals(a: ContractGrant | PlainMessage | undefined, b: ContractGrant | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractGrant, a, b); - } -} - -/** - * MaxCallsLimit limited number of calls to the contract. No funds transferable. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.MaxCallsLimit - */ -export class MaxCallsLimit extends Message { - /** - * Remaining number that is decremented on each execution - * - * @generated from field: uint64 remaining = 1; - */ - remaining = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MaxCallsLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "remaining", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MaxCallsLimit { - return new MaxCallsLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MaxCallsLimit { - return new MaxCallsLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MaxCallsLimit { - return new MaxCallsLimit().fromJsonString(jsonString, options); - } - - static equals(a: MaxCallsLimit | PlainMessage | undefined, b: MaxCallsLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MaxCallsLimit, a, b); - } -} - -/** - * MaxFundsLimit defines the maximal amounts that can be sent to the contract. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.MaxFundsLimit - */ -export class MaxFundsLimit extends Message { - /** - * Amounts is the maximal amount of tokens transferable to the contract. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin amounts = 1; - */ - amounts: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MaxFundsLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amounts", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MaxFundsLimit { - return new MaxFundsLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MaxFundsLimit { - return new MaxFundsLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MaxFundsLimit { - return new MaxFundsLimit().fromJsonString(jsonString, options); - } - - static equals(a: MaxFundsLimit | PlainMessage | undefined, b: MaxFundsLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MaxFundsLimit, a, b); - } -} - -/** - * CombinedLimit defines the maximal amounts that can be sent to a contract and - * the maximal number of calls executable. Both need to remain >0 to be valid. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.CombinedLimit - */ -export class CombinedLimit extends Message { - /** - * Remaining number that is decremented on each execution - * - * @generated from field: uint64 calls_remaining = 1; - */ - callsRemaining = protoInt64.zero; - - /** - * Amounts is the maximal amount of tokens transferable to the contract. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin amounts = 2; - */ - amounts: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.CombinedLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "calls_remaining", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "amounts", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CombinedLimit { - return new CombinedLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CombinedLimit { - return new CombinedLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CombinedLimit { - return new CombinedLimit().fromJsonString(jsonString, options); - } - - static equals(a: CombinedLimit | PlainMessage | undefined, b: CombinedLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(CombinedLimit, a, b); - } -} - -/** - * AllowAllMessagesFilter is a wildcard to allow any type of contract payload - * message. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.AllowAllMessagesFilter - */ -export class AllowAllMessagesFilter extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AllowAllMessagesFilter"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllowAllMessagesFilter { - return new AllowAllMessagesFilter().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllowAllMessagesFilter { - return new AllowAllMessagesFilter().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllowAllMessagesFilter { - return new AllowAllMessagesFilter().fromJsonString(jsonString, options); - } - - static equals(a: AllowAllMessagesFilter | PlainMessage | undefined, b: AllowAllMessagesFilter | PlainMessage | undefined): boolean { - return proto3.util.equals(AllowAllMessagesFilter, a, b); - } -} - -/** - * AcceptedMessageKeysFilter accept only the specific contract message keys in - * the json object to be executed. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.AcceptedMessageKeysFilter - */ -export class AcceptedMessageKeysFilter extends Message { - /** - * Messages is the list of unique keys - * - * @generated from field: repeated string keys = 1; - */ - keys: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AcceptedMessageKeysFilter"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "keys", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AcceptedMessageKeysFilter { - return new AcceptedMessageKeysFilter().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AcceptedMessageKeysFilter { - return new AcceptedMessageKeysFilter().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AcceptedMessageKeysFilter { - return new AcceptedMessageKeysFilter().fromJsonString(jsonString, options); - } - - static equals(a: AcceptedMessageKeysFilter | PlainMessage | undefined, b: AcceptedMessageKeysFilter | PlainMessage | undefined): boolean { - return proto3.util.equals(AcceptedMessageKeysFilter, a, b); - } -} - -/** - * AcceptedMessagesFilter accept only the specific raw contract messages to be - * executed. - * Since: wasmd 0.30 - * - * @generated from message cosmwasm.wasm.v1.AcceptedMessagesFilter - */ -export class AcceptedMessagesFilter extends Message { - /** - * Messages is the list of raw contract messages - * - * @generated from field: repeated bytes messages = 1; - */ - messages: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AcceptedMessagesFilter"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "messages", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AcceptedMessagesFilter { - return new AcceptedMessagesFilter().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AcceptedMessagesFilter { - return new AcceptedMessagesFilter().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AcceptedMessagesFilter { - return new AcceptedMessagesFilter().fromJsonString(jsonString, options); - } - - static equals(a: AcceptedMessagesFilter | PlainMessage | undefined, b: AcceptedMessagesFilter | PlainMessage | undefined): boolean { - return proto3.util.equals(AcceptedMessagesFilter, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/genesis_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/genesis_pb.ts deleted file mode 100644 index 66ec9d46b..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/genesis_pb.ts +++ /dev/null @@ -1,227 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/genesis.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { CodeInfo, ContractCodeHistoryEntry, ContractInfo, Model, Params } from "./types_pb.js"; - -/** - * GenesisState - genesis state of x/wasm - * - * @generated from message cosmwasm.wasm.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.Params params = 1; - */ - params?: Params; - - /** - * @generated from field: repeated cosmwasm.wasm.v1.Code codes = 2; - */ - codes: Code[] = []; - - /** - * @generated from field: repeated cosmwasm.wasm.v1.Contract contracts = 3; - */ - contracts: Contract[] = []; - - /** - * @generated from field: repeated cosmwasm.wasm.v1.Sequence sequences = 4; - */ - sequences: Sequence[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "codes", kind: "message", T: Code, repeated: true }, - { no: 3, name: "contracts", kind: "message", T: Contract, repeated: true }, - { no: 4, name: "sequences", kind: "message", T: Sequence, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Code struct encompasses CodeInfo and CodeBytes - * - * @generated from message cosmwasm.wasm.v1.Code - */ -export class Code extends Message { - /** - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * @generated from field: cosmwasm.wasm.v1.CodeInfo code_info = 2; - */ - codeInfo?: CodeInfo; - - /** - * @generated from field: bytes code_bytes = 3; - */ - codeBytes = new Uint8Array(0); - - /** - * Pinned to wasmvm cache - * - * @generated from field: bool pinned = 4; - */ - pinned = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.Code"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "code_info", kind: "message", T: CodeInfo }, - { no: 3, name: "code_bytes", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "pinned", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Code { - return new Code().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Code { - return new Code().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Code { - return new Code().fromJsonString(jsonString, options); - } - - static equals(a: Code | PlainMessage | undefined, b: Code | PlainMessage | undefined): boolean { - return proto3.util.equals(Code, a, b); - } -} - -/** - * Contract struct encompasses ContractAddress, ContractInfo, and ContractState - * - * @generated from message cosmwasm.wasm.v1.Contract - */ -export class Contract extends Message { - /** - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - /** - * @generated from field: cosmwasm.wasm.v1.ContractInfo contract_info = 2; - */ - contractInfo?: ContractInfo; - - /** - * @generated from field: repeated cosmwasm.wasm.v1.Model contract_state = 3; - */ - contractState: Model[] = []; - - /** - * @generated from field: repeated cosmwasm.wasm.v1.ContractCodeHistoryEntry contract_code_history = 4; - */ - contractCodeHistory: ContractCodeHistoryEntry[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.Contract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "contract_info", kind: "message", T: ContractInfo }, - { no: 3, name: "contract_state", kind: "message", T: Model, repeated: true }, - { no: 4, name: "contract_code_history", kind: "message", T: ContractCodeHistoryEntry, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Contract { - return new Contract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Contract { - return new Contract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Contract { - return new Contract().fromJsonString(jsonString, options); - } - - static equals(a: Contract | PlainMessage | undefined, b: Contract | PlainMessage | undefined): boolean { - return proto3.util.equals(Contract, a, b); - } -} - -/** - * Sequence key and value of an id generation counter - * - * @generated from message cosmwasm.wasm.v1.Sequence - */ -export class Sequence extends Message { - /** - * @generated from field: bytes id_key = 1; - */ - idKey = new Uint8Array(0); - - /** - * @generated from field: uint64 value = 2; - */ - value = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.Sequence"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "value", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Sequence { - return new Sequence().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Sequence { - return new Sequence().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Sequence { - return new Sequence().fromJsonString(jsonString, options); - } - - static equals(a: Sequence | PlainMessage | undefined, b: Sequence | PlainMessage | undefined): boolean { - return proto3.util.equals(Sequence, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/ibc_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/ibc_pb.ts deleted file mode 100644 index 4704b63ad..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/ibc_pb.ts +++ /dev/null @@ -1,189 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/ibc.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * MsgIBCSend - * - * @generated from message cosmwasm.wasm.v1.MsgIBCSend - */ -export class MsgIBCSend extends Message { - /** - * the channel by which the packet will be sent - * - * @generated from field: string channel = 2; - */ - channel = ""; - - /** - * Timeout height relative to the current block height. - * The timeout is disabled when set to 0. - * - * @generated from field: uint64 timeout_height = 4; - */ - timeoutHeight = protoInt64.zero; - - /** - * Timeout timestamp (in nanoseconds) relative to the current block timestamp. - * The timeout is disabled when set to 0. - * - * @generated from field: uint64 timeout_timestamp = 5; - */ - timeoutTimestamp = protoInt64.zero; - - /** - * Data is the payload to transfer. We must not make assumption what format or - * content is in here. - * - * @generated from field: bytes data = 6; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgIBCSend"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "timeout_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCSend { - return new MsgIBCSend().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCSend { - return new MsgIBCSend().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCSend { - return new MsgIBCSend().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCSend | PlainMessage | undefined, b: MsgIBCSend | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCSend, a, b); - } -} - -/** - * MsgIBCSendResponse - * - * @generated from message cosmwasm.wasm.v1.MsgIBCSendResponse - */ -export class MsgIBCSendResponse extends Message { - /** - * Sequence number of the IBC packet sent - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgIBCSendResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCSendResponse { - return new MsgIBCSendResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCSendResponse { - return new MsgIBCSendResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCSendResponse { - return new MsgIBCSendResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCSendResponse | PlainMessage | undefined, b: MsgIBCSendResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCSendResponse, a, b); - } -} - -/** - * MsgIBCWriteAcknowledgementResponse - * - * @generated from message cosmwasm.wasm.v1.MsgIBCWriteAcknowledgementResponse - */ -export class MsgIBCWriteAcknowledgementResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgIBCWriteAcknowledgementResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCWriteAcknowledgementResponse { - return new MsgIBCWriteAcknowledgementResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCWriteAcknowledgementResponse { - return new MsgIBCWriteAcknowledgementResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCWriteAcknowledgementResponse { - return new MsgIBCWriteAcknowledgementResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCWriteAcknowledgementResponse | PlainMessage | undefined, b: MsgIBCWriteAcknowledgementResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCWriteAcknowledgementResponse, a, b); - } -} - -/** - * MsgIBCCloseChannel port and channel need to be owned by the contract - * - * @generated from message cosmwasm.wasm.v1.MsgIBCCloseChannel - */ -export class MsgIBCCloseChannel extends Message { - /** - * @generated from field: string channel = 2; - */ - channel = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgIBCCloseChannel"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCCloseChannel { - return new MsgIBCCloseChannel().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCCloseChannel { - return new MsgIBCCloseChannel().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCCloseChannel { - return new MsgIBCCloseChannel().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCCloseChannel | PlainMessage | undefined, b: MsgIBCCloseChannel | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCCloseChannel, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/proposal_legacy_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/proposal_legacy_pb.ts deleted file mode 100644 index ad56b04d2..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/proposal_legacy_pb.ts +++ /dev/null @@ -1,1080 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/proposal_legacy.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccessConfig } from "./types_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit StoreCodeProposal. To submit WASM code to the system, - * a simple MsgStoreCode can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.StoreCodeProposal - * @deprecated - */ -export class StoreCodeProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * RunAs is the address that is passed to the contract's environment as sender - * - * @generated from field: string run_as = 3; - */ - runAs = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 4; - */ - wasmByteCode = new Uint8Array(0); - - /** - * InstantiatePermission to apply on contract creation, optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 7; - */ - instantiatePermission?: AccessConfig; - - /** - * UnpinCode code on upload, optional - * - * @generated from field: bool unpin_code = 8; - */ - unpinCode = false; - - /** - * Source is the URL where the code is hosted - * - * @generated from field: string source = 9; - */ - source = ""; - - /** - * Builder is the docker image used to build the code deterministically, used - * for smart contract verification - * - * @generated from field: string builder = 10; - */ - builder = ""; - - /** - * CodeHash is the SHA256 sum of the code outputted by builder, used for smart - * contract verification - * - * @generated from field: bytes code_hash = 11; - */ - codeHash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.StoreCodeProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "run_as", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "instantiate_permission", kind: "message", T: AccessConfig }, - { no: 8, name: "unpin_code", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 9, name: "source", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "builder", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "code_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreCodeProposal { - return new StoreCodeProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreCodeProposal { - return new StoreCodeProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreCodeProposal { - return new StoreCodeProposal().fromJsonString(jsonString, options); - } - - static equals(a: StoreCodeProposal | PlainMessage | undefined, b: StoreCodeProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(StoreCodeProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit InstantiateContractProposal. To instantiate a contract, - * a simple MsgInstantiateContract can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.InstantiateContractProposal - * @deprecated - */ -export class InstantiateContractProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * RunAs is the address that is passed to the contract's environment as sender - * - * @generated from field: string run_as = 3; - */ - runAs = ""; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 4; - */ - admin = ""; - - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 5; - */ - codeId = protoInt64.zero; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 6; - */ - label = ""; - - /** - * Msg json encoded message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 7; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 8; - */ - funds: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.InstantiateContractProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "run_as", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "funds", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InstantiateContractProposal { - return new InstantiateContractProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InstantiateContractProposal { - return new InstantiateContractProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InstantiateContractProposal { - return new InstantiateContractProposal().fromJsonString(jsonString, options); - } - - static equals(a: InstantiateContractProposal | PlainMessage | undefined, b: InstantiateContractProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(InstantiateContractProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit InstantiateContract2Proposal. To instantiate contract 2, - * a simple MsgInstantiateContract2 can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.InstantiateContract2Proposal - * @deprecated - */ -export class InstantiateContract2Proposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * RunAs is the address that is passed to the contract's environment as sender - * - * @generated from field: string run_as = 3; - */ - runAs = ""; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 4; - */ - admin = ""; - - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 5; - */ - codeId = protoInt64.zero; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 6; - */ - label = ""; - - /** - * Msg json encode message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 7; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 8; - */ - funds: Coin[] = []; - - /** - * Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - * - * @generated from field: bytes salt = 9; - */ - salt = new Uint8Array(0); - - /** - * FixMsg include the msg value into the hash for the predictable address. - * Default is false - * - * @generated from field: bool fix_msg = 10; - */ - fixMsg = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.InstantiateContract2Proposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "run_as", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "funds", kind: "message", T: Coin, repeated: true }, - { no: 9, name: "salt", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "fix_msg", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InstantiateContract2Proposal { - return new InstantiateContract2Proposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InstantiateContract2Proposal { - return new InstantiateContract2Proposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InstantiateContract2Proposal { - return new InstantiateContract2Proposal().fromJsonString(jsonString, options); - } - - static equals(a: InstantiateContract2Proposal | PlainMessage | undefined, b: InstantiateContract2Proposal | PlainMessage | undefined): boolean { - return proto3.util.equals(InstantiateContract2Proposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit MigrateContractProposal. To migrate a contract, - * a simple MsgMigrateContract can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.MigrateContractProposal - * @deprecated - */ -export class MigrateContractProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * Note: skipping 3 as this was previously used for unneeded run_as - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 4; - */ - contract = ""; - - /** - * CodeID references the new WASM code - * - * @generated from field: uint64 code_id = 5; - */ - codeId = protoInt64.zero; - - /** - * Msg json encoded message to be passed to the contract on migration - * - * @generated from field: bytes msg = 6; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MigrateContractProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MigrateContractProposal { - return new MigrateContractProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MigrateContractProposal { - return new MigrateContractProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MigrateContractProposal { - return new MigrateContractProposal().fromJsonString(jsonString, options); - } - - static equals(a: MigrateContractProposal | PlainMessage | undefined, b: MigrateContractProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(MigrateContractProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit SudoContractProposal. To call sudo on a contract, - * a simple MsgSudoContract can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.SudoContractProposal - * @deprecated - */ -export class SudoContractProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 3; - */ - contract = ""; - - /** - * Msg json encoded message to be passed to the contract as sudo - * - * @generated from field: bytes msg = 4; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.SudoContractProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SudoContractProposal { - return new SudoContractProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SudoContractProposal { - return new SudoContractProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SudoContractProposal { - return new SudoContractProposal().fromJsonString(jsonString, options); - } - - static equals(a: SudoContractProposal | PlainMessage | undefined, b: SudoContractProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(SudoContractProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit ExecuteContractProposal. To call execute on a contract, - * a simple MsgExecuteContract can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.ExecuteContractProposal - * @deprecated - */ -export class ExecuteContractProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * RunAs is the address that is passed to the contract's environment as sender - * - * @generated from field: string run_as = 3; - */ - runAs = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 4; - */ - contract = ""; - - /** - * Msg json encoded message to be passed to the contract as execute - * - * @generated from field: bytes msg = 5; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 6; - */ - funds: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ExecuteContractProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "run_as", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "funds", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExecuteContractProposal { - return new ExecuteContractProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExecuteContractProposal { - return new ExecuteContractProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExecuteContractProposal { - return new ExecuteContractProposal().fromJsonString(jsonString, options); - } - - static equals(a: ExecuteContractProposal | PlainMessage | undefined, b: ExecuteContractProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(ExecuteContractProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit UpdateAdminProposal. To set an admin for a contract, - * a simple MsgUpdateAdmin can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.UpdateAdminProposal - * @deprecated - */ -export class UpdateAdminProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * NewAdmin address to be set - * - * @generated from field: string new_admin = 3; - */ - newAdmin = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 4; - */ - contract = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.UpdateAdminProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "new_admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdateAdminProposal { - return new UpdateAdminProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdateAdminProposal { - return new UpdateAdminProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdateAdminProposal { - return new UpdateAdminProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdateAdminProposal | PlainMessage | undefined, b: UpdateAdminProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdateAdminProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit ClearAdminProposal. To clear the admin of a contract, - * a simple MsgClearAdmin can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.ClearAdminProposal - * @deprecated - */ -export class ClearAdminProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 3; - */ - contract = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ClearAdminProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClearAdminProposal { - return new ClearAdminProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClearAdminProposal { - return new ClearAdminProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClearAdminProposal { - return new ClearAdminProposal().fromJsonString(jsonString, options); - } - - static equals(a: ClearAdminProposal | PlainMessage | undefined, b: ClearAdminProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(ClearAdminProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit PinCodesProposal. To pin a set of code ids in the wasmvm - * cache, a simple MsgPinCodes can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.PinCodesProposal - * @deprecated - */ -export class PinCodesProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * CodeIDs references the new WASM codes - * - * @generated from field: repeated uint64 code_ids = 3; - */ - codeIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.PinCodesProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "code_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PinCodesProposal { - return new PinCodesProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PinCodesProposal { - return new PinCodesProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PinCodesProposal { - return new PinCodesProposal().fromJsonString(jsonString, options); - } - - static equals(a: PinCodesProposal | PlainMessage | undefined, b: PinCodesProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(PinCodesProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit UnpinCodesProposal. To unpin a set of code ids in the wasmvm - * cache, a simple MsgUnpinCodes can be invoked from the x/gov module via - * a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.UnpinCodesProposal - * @deprecated - */ -export class UnpinCodesProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * CodeIDs references the WASM codes - * - * @generated from field: repeated uint64 code_ids = 3; - */ - codeIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.UnpinCodesProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "code_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UnpinCodesProposal { - return new UnpinCodesProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UnpinCodesProposal { - return new UnpinCodesProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UnpinCodesProposal { - return new UnpinCodesProposal().fromJsonString(jsonString, options); - } - - static equals(a: UnpinCodesProposal | PlainMessage | undefined, b: UnpinCodesProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UnpinCodesProposal, a, b); - } -} - -/** - * AccessConfigUpdate contains the code id and the access config to be - * applied. - * - * @generated from message cosmwasm.wasm.v1.AccessConfigUpdate - */ -export class AccessConfigUpdate extends Message { - /** - * CodeID is the reference to the stored WASM code to be updated - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * InstantiatePermission to apply to the set of code ids - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 2; - */ - instantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AccessConfigUpdate"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccessConfigUpdate { - return new AccessConfigUpdate().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccessConfigUpdate { - return new AccessConfigUpdate().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccessConfigUpdate { - return new AccessConfigUpdate().fromJsonString(jsonString, options); - } - - static equals(a: AccessConfigUpdate | PlainMessage | undefined, b: AccessConfigUpdate | PlainMessage | undefined): boolean { - return proto3.util.equals(AccessConfigUpdate, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit UpdateInstantiateConfigProposal. To update instantiate config - * to a set of code ids, a simple MsgUpdateInstantiateConfig can be invoked from - * the x/gov module via a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.UpdateInstantiateConfigProposal - * @deprecated - */ -export class UpdateInstantiateConfigProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * AccessConfigUpdates contains the list of code ids and the access config - * to be applied. - * - * @generated from field: repeated cosmwasm.wasm.v1.AccessConfigUpdate access_config_updates = 3; - */ - accessConfigUpdates: AccessConfigUpdate[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.UpdateInstantiateConfigProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "access_config_updates", kind: "message", T: AccessConfigUpdate, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdateInstantiateConfigProposal { - return new UpdateInstantiateConfigProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdateInstantiateConfigProposal { - return new UpdateInstantiateConfigProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdateInstantiateConfigProposal { - return new UpdateInstantiateConfigProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdateInstantiateConfigProposal | PlainMessage | undefined, b: UpdateInstantiateConfigProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdateInstantiateConfigProposal, a, b); - } -} - -/** - * Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for - * an explicit StoreAndInstantiateContractProposal. To store and instantiate - * the contract, a simple MsgStoreAndInstantiateContract can be invoked from - * the x/gov module via a v1 governance proposal. - * - * @generated from message cosmwasm.wasm.v1.StoreAndInstantiateContractProposal - * @deprecated - */ -export class StoreAndInstantiateContractProposal extends Message { - /** - * Title is a short summary - * - * @generated from field: string title = 1; - */ - title = ""; - - /** - * Description is a human readable text - * - * @generated from field: string description = 2; - */ - description = ""; - - /** - * RunAs is the address that is passed to the contract's environment as sender - * - * @generated from field: string run_as = 3; - */ - runAs = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 4; - */ - wasmByteCode = new Uint8Array(0); - - /** - * InstantiatePermission to apply on contract creation, optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 5; - */ - instantiatePermission?: AccessConfig; - - /** - * UnpinCode code on upload, optional - * - * @generated from field: bool unpin_code = 6; - */ - unpinCode = false; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 7; - */ - admin = ""; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 8; - */ - label = ""; - - /** - * Msg json encoded message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 9; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 10; - */ - funds: Coin[] = []; - - /** - * Source is the URL where the code is hosted - * - * @generated from field: string source = 11; - */ - source = ""; - - /** - * Builder is the docker image used to build the code deterministically, used - * for smart contract verification - * - * @generated from field: string builder = 12; - */ - builder = ""; - - /** - * CodeHash is the SHA256 sum of the code outputted by builder, used for smart - * contract verification - * - * @generated from field: bytes code_hash = 13; - */ - codeHash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.StoreAndInstantiateContractProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "run_as", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "instantiate_permission", kind: "message", T: AccessConfig }, - { no: 6, name: "unpin_code", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 7, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "funds", kind: "message", T: Coin, repeated: true }, - { no: 11, name: "source", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "builder", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "code_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StoreAndInstantiateContractProposal { - return new StoreAndInstantiateContractProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StoreAndInstantiateContractProposal { - return new StoreAndInstantiateContractProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StoreAndInstantiateContractProposal { - return new StoreAndInstantiateContractProposal().fromJsonString(jsonString, options); - } - - static equals(a: StoreAndInstantiateContractProposal | PlainMessage | undefined, b: StoreAndInstantiateContractProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(StoreAndInstantiateContractProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/query_cosmes.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/query_cosmes.ts deleted file mode 100644 index 369a436c7..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/query_cosmes.ts +++ /dev/null @@ -1,178 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/query.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryAllContractStateRequest, QueryAllContractStateResponse, QueryBuildAddressRequest, QueryBuildAddressResponse, QueryCodeInfoRequest, QueryCodeInfoResponse, QueryCodeRequest, QueryCodeResponse, QueryCodesRequest, QueryCodesResponse, QueryContractHistoryRequest, QueryContractHistoryResponse, QueryContractInfoRequest, QueryContractInfoResponse, QueryContractsByCodeRequest, QueryContractsByCodeResponse, QueryContractsByCreatorRequest, QueryContractsByCreatorResponse, QueryParamsRequest, QueryParamsResponse, QueryPinnedCodesRequest, QueryPinnedCodesResponse, QueryRawContractStateRequest, QueryRawContractStateResponse, QuerySmartContractStateRequest, QuerySmartContractStateResponse, QueryWasmLimitsConfigRequest, QueryWasmLimitsConfigResponse } from "./query_pb.js"; - -const TYPE_NAME = "cosmwasm.wasm.v1.Query"; - -/** - * ContractInfo gets the contract meta data - * - * @generated from rpc cosmwasm.wasm.v1.Query.ContractInfo - */ -export const QueryContractInfoService = { - typeName: TYPE_NAME, - method: "ContractInfo", - Request: QueryContractInfoRequest, - Response: QueryContractInfoResponse, -} as const; - -/** - * ContractHistory gets the contract code history - * - * @generated from rpc cosmwasm.wasm.v1.Query.ContractHistory - */ -export const QueryContractHistoryService = { - typeName: TYPE_NAME, - method: "ContractHistory", - Request: QueryContractHistoryRequest, - Response: QueryContractHistoryResponse, -} as const; - -/** - * ContractsByCode lists all smart contracts for a code id - * - * @generated from rpc cosmwasm.wasm.v1.Query.ContractsByCode - */ -export const QueryContractsByCodeService = { - typeName: TYPE_NAME, - method: "ContractsByCode", - Request: QueryContractsByCodeRequest, - Response: QueryContractsByCodeResponse, -} as const; - -/** - * AllContractState gets all raw store data for a single contract - * - * @generated from rpc cosmwasm.wasm.v1.Query.AllContractState - */ -export const QueryAllContractStateService = { - typeName: TYPE_NAME, - method: "AllContractState", - Request: QueryAllContractStateRequest, - Response: QueryAllContractStateResponse, -} as const; - -/** - * RawContractState gets single key from the raw store data of a contract - * - * @generated from rpc cosmwasm.wasm.v1.Query.RawContractState - */ -export const QueryRawContractStateService = { - typeName: TYPE_NAME, - method: "RawContractState", - Request: QueryRawContractStateRequest, - Response: QueryRawContractStateResponse, -} as const; - -/** - * SmartContractState get smart query result from the contract - * - * @generated from rpc cosmwasm.wasm.v1.Query.SmartContractState - */ -export const QuerySmartContractStateService = { - typeName: TYPE_NAME, - method: "SmartContractState", - Request: QuerySmartContractStateRequest, - Response: QuerySmartContractStateResponse, -} as const; - -/** - * Code gets the binary code and metadata for a single wasm code - * - * @generated from rpc cosmwasm.wasm.v1.Query.Code - */ -export const QueryCodeService = { - typeName: TYPE_NAME, - method: "Code", - Request: QueryCodeRequest, - Response: QueryCodeResponse, -} as const; - -/** - * Codes gets the metadata for all stored wasm codes - * - * @generated from rpc cosmwasm.wasm.v1.Query.Codes - */ -export const QueryCodesService = { - typeName: TYPE_NAME, - method: "Codes", - Request: QueryCodesRequest, - Response: QueryCodesResponse, -} as const; - -/** - * CodeInfo gets the metadata for a single wasm code - * - * @generated from rpc cosmwasm.wasm.v1.Query.CodeInfo - */ -export const QueryCodeInfoService = { - typeName: TYPE_NAME, - method: "CodeInfo", - Request: QueryCodeInfoRequest, - Response: QueryCodeInfoResponse, -} as const; - -/** - * PinnedCodes gets the pinned code ids - * - * @generated from rpc cosmwasm.wasm.v1.Query.PinnedCodes - */ -export const QueryPinnedCodesService = { - typeName: TYPE_NAME, - method: "PinnedCodes", - Request: QueryPinnedCodesRequest, - Response: QueryPinnedCodesResponse, -} as const; - -/** - * Params gets the module params - * - * @generated from rpc cosmwasm.wasm.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * ContractsByCreator gets the contracts by creator - * - * @generated from rpc cosmwasm.wasm.v1.Query.ContractsByCreator - */ -export const QueryContractsByCreatorService = { - typeName: TYPE_NAME, - method: "ContractsByCreator", - Request: QueryContractsByCreatorRequest, - Response: QueryContractsByCreatorResponse, -} as const; - -/** - * WasmLimitsConfig gets the configured limits for static validation of Wasm - * files, encoded in JSON. - * - * @generated from rpc cosmwasm.wasm.v1.Query.WasmLimitsConfig - */ -export const QueryWasmLimitsConfigService = { - typeName: TYPE_NAME, - method: "WasmLimitsConfig", - Request: QueryWasmLimitsConfigRequest, - Response: QueryWasmLimitsConfigResponse, -} as const; - -/** - * BuildAddress builds a contract address - * - * @generated from rpc cosmwasm.wasm.v1.Query.BuildAddress - */ -export const QueryBuildAddressService = { - typeName: TYPE_NAME, - method: "BuildAddress", - Request: QueryBuildAddressRequest, - Response: QueryBuildAddressResponse, -} as const; - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/query_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/query_pb.ts deleted file mode 100644 index 87bef604a..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/query_pb.ts +++ /dev/null @@ -1,1357 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/query.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccessConfig, ContractCodeHistoryEntry, ContractInfo, Model, Params } from "./types_pb.js"; -import { PageRequest, PageResponse } from "../../../cosmos/base/query/v1beta1/pagination_pb.js"; - -/** - * QueryContractInfoRequest is the request type for the Query/ContractInfo RPC - * method - * - * @generated from message cosmwasm.wasm.v1.QueryContractInfoRequest - */ -export class QueryContractInfoRequest extends Message { - /** - * address is the address of the contract to query - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractInfoRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractInfoRequest { - return new QueryContractInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractInfoRequest { - return new QueryContractInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractInfoRequest { - return new QueryContractInfoRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractInfoRequest | PlainMessage | undefined, b: QueryContractInfoRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractInfoRequest, a, b); - } -} - -/** - * QueryContractInfoResponse is the response type for the Query/ContractInfo RPC - * method - * - * @generated from message cosmwasm.wasm.v1.QueryContractInfoResponse - */ -export class QueryContractInfoResponse extends Message { - /** - * address is the address of the contract - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: cosmwasm.wasm.v1.ContractInfo contract_info = 2; - */ - contractInfo?: ContractInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "contract_info", kind: "message", T: ContractInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractInfoResponse { - return new QueryContractInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractInfoResponse { - return new QueryContractInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractInfoResponse { - return new QueryContractInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractInfoResponse | PlainMessage | undefined, b: QueryContractInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractInfoResponse, a, b); - } -} - -/** - * QueryContractHistoryRequest is the request type for the Query/ContractHistory - * RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryContractHistoryRequest - */ -export class QueryContractHistoryRequest extends Message { - /** - * address is the address of the contract to query - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractHistoryRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractHistoryRequest { - return new QueryContractHistoryRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractHistoryRequest { - return new QueryContractHistoryRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractHistoryRequest { - return new QueryContractHistoryRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractHistoryRequest | PlainMessage | undefined, b: QueryContractHistoryRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractHistoryRequest, a, b); - } -} - -/** - * QueryContractHistoryResponse is the response type for the - * Query/ContractHistory RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryContractHistoryResponse - */ -export class QueryContractHistoryResponse extends Message { - /** - * @generated from field: repeated cosmwasm.wasm.v1.ContractCodeHistoryEntry entries = 1; - */ - entries: ContractCodeHistoryEntry[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractHistoryResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "entries", kind: "message", T: ContractCodeHistoryEntry, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractHistoryResponse { - return new QueryContractHistoryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractHistoryResponse { - return new QueryContractHistoryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractHistoryResponse { - return new QueryContractHistoryResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractHistoryResponse | PlainMessage | undefined, b: QueryContractHistoryResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractHistoryResponse, a, b); - } -} - -/** - * QueryContractsByCodeRequest is the request type for the Query/ContractsByCode - * RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryContractsByCodeRequest - */ -export class QueryContractsByCodeRequest extends Message { - /** - * grpc-gateway_out does not support Go style CodeID - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractsByCodeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractsByCodeRequest { - return new QueryContractsByCodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractsByCodeRequest { - return new QueryContractsByCodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractsByCodeRequest { - return new QueryContractsByCodeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractsByCodeRequest | PlainMessage | undefined, b: QueryContractsByCodeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractsByCodeRequest, a, b); - } -} - -/** - * QueryContractsByCodeResponse is the response type for the - * Query/ContractsByCode RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryContractsByCodeResponse - */ -export class QueryContractsByCodeResponse extends Message { - /** - * contracts are a set of contract addresses - * - * @generated from field: repeated string contracts = 1; - */ - contracts: string[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractsByCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contracts", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractsByCodeResponse { - return new QueryContractsByCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractsByCodeResponse { - return new QueryContractsByCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractsByCodeResponse { - return new QueryContractsByCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractsByCodeResponse | PlainMessage | undefined, b: QueryContractsByCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractsByCodeResponse, a, b); - } -} - -/** - * QueryAllContractStateRequest is the request type for the - * Query/AllContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryAllContractStateRequest - */ -export class QueryAllContractStateRequest extends Message { - /** - * address is the address of the contract - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryAllContractStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllContractStateRequest { - return new QueryAllContractStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllContractStateRequest { - return new QueryAllContractStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllContractStateRequest { - return new QueryAllContractStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllContractStateRequest | PlainMessage | undefined, b: QueryAllContractStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllContractStateRequest, a, b); - } -} - -/** - * QueryAllContractStateResponse is the response type for the - * Query/AllContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryAllContractStateResponse - */ -export class QueryAllContractStateResponse extends Message { - /** - * @generated from field: repeated cosmwasm.wasm.v1.Model models = 1; - */ - models: Model[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryAllContractStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "models", kind: "message", T: Model, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllContractStateResponse { - return new QueryAllContractStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllContractStateResponse { - return new QueryAllContractStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllContractStateResponse { - return new QueryAllContractStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllContractStateResponse | PlainMessage | undefined, b: QueryAllContractStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllContractStateResponse, a, b); - } -} - -/** - * QueryRawContractStateRequest is the request type for the - * Query/RawContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryRawContractStateRequest - */ -export class QueryRawContractStateRequest extends Message { - /** - * address is the address of the contract - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: bytes query_data = 2; - */ - queryData = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryRawContractStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "query_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRawContractStateRequest { - return new QueryRawContractStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRawContractStateRequest { - return new QueryRawContractStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRawContractStateRequest { - return new QueryRawContractStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRawContractStateRequest | PlainMessage | undefined, b: QueryRawContractStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRawContractStateRequest, a, b); - } -} - -/** - * QueryRawContractStateResponse is the response type for the - * Query/RawContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryRawContractStateResponse - */ -export class QueryRawContractStateResponse extends Message { - /** - * Data contains the raw store data - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryRawContractStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRawContractStateResponse { - return new QueryRawContractStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRawContractStateResponse { - return new QueryRawContractStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRawContractStateResponse { - return new QueryRawContractStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRawContractStateResponse | PlainMessage | undefined, b: QueryRawContractStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRawContractStateResponse, a, b); - } -} - -/** - * QuerySmartContractStateRequest is the request type for the - * Query/SmartContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QuerySmartContractStateRequest - */ -export class QuerySmartContractStateRequest extends Message { - /** - * address is the address of the contract - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * QueryData contains the query data passed to the contract - * - * @generated from field: bytes query_data = 2; - */ - queryData = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QuerySmartContractStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "query_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySmartContractStateRequest { - return new QuerySmartContractStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySmartContractStateRequest { - return new QuerySmartContractStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySmartContractStateRequest { - return new QuerySmartContractStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QuerySmartContractStateRequest | PlainMessage | undefined, b: QuerySmartContractStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySmartContractStateRequest, a, b); - } -} - -/** - * QuerySmartContractStateResponse is the response type for the - * Query/SmartContractState RPC method - * - * @generated from message cosmwasm.wasm.v1.QuerySmartContractStateResponse - */ -export class QuerySmartContractStateResponse extends Message { - /** - * Data contains the json data returned from the smart contract - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QuerySmartContractStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySmartContractStateResponse { - return new QuerySmartContractStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySmartContractStateResponse { - return new QuerySmartContractStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySmartContractStateResponse { - return new QuerySmartContractStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QuerySmartContractStateResponse | PlainMessage | undefined, b: QuerySmartContractStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySmartContractStateResponse, a, b); - } -} - -/** - * QueryCodeRequest is the request type for the Query/Code RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodeRequest - */ -export class QueryCodeRequest extends Message { - /** - * grpc-gateway_out does not support Go style CodeID - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeRequest | PlainMessage | undefined, b: QueryCodeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeRequest, a, b); - } -} - -/** - * QueryCodeInfoRequest is the request type for the Query/CodeInfo RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodeInfoRequest - */ -export class QueryCodeInfoRequest extends Message { - /** - * grpc-gateway_out does not support Go style CodeID - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodeInfoRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeInfoRequest { - return new QueryCodeInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeInfoRequest { - return new QueryCodeInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeInfoRequest { - return new QueryCodeInfoRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeInfoRequest | PlainMessage | undefined, b: QueryCodeInfoRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeInfoRequest, a, b); - } -} - -/** - * QueryCodeInfoResponse is the response type for the Query/CodeInfo RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodeInfoResponse - */ -export class QueryCodeInfoResponse extends Message { - /** - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * @generated from field: string creator = 2; - */ - creator = ""; - - /** - * @generated from field: bytes checksum = 3; - */ - checksum = new Uint8Array(0); - - /** - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 4; - */ - instantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodeInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeInfoResponse { - return new QueryCodeInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeInfoResponse { - return new QueryCodeInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeInfoResponse { - return new QueryCodeInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeInfoResponse | PlainMessage | undefined, b: QueryCodeInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeInfoResponse, a, b); - } -} - -/** - * CodeInfoResponse contains code meta data from CodeInfo - * - * @generated from message cosmwasm.wasm.v1.CodeInfoResponse - */ -export class CodeInfoResponse extends Message { - /** - * id for legacy support - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * @generated from field: string creator = 2; - */ - creator = ""; - - /** - * @generated from field: bytes data_hash = 3; - */ - dataHash = new Uint8Array(0); - - /** - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 6; - */ - instantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.CodeInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "data_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CodeInfoResponse { - return new CodeInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CodeInfoResponse { - return new CodeInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CodeInfoResponse { - return new CodeInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: CodeInfoResponse | PlainMessage | undefined, b: CodeInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(CodeInfoResponse, a, b); - } -} - -/** - * QueryCodeResponse is the response type for the Query/Code RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodeResponse - */ -export class QueryCodeResponse extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.CodeInfoResponse code_info = 1; - */ - codeInfo?: CodeInfoResponse; - - /** - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_info", kind: "message", T: CodeInfoResponse }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeResponse | PlainMessage | undefined, b: QueryCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeResponse, a, b); - } -} - -/** - * QueryCodesRequest is the request type for the Query/Codes RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodesRequest - */ -export class QueryCodesRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodesRequest { - return new QueryCodesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodesRequest { - return new QueryCodesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodesRequest { - return new QueryCodesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodesRequest | PlainMessage | undefined, b: QueryCodesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodesRequest, a, b); - } -} - -/** - * QueryCodesResponse is the response type for the Query/Codes RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryCodesResponse - */ -export class QueryCodesResponse extends Message { - /** - * @generated from field: repeated cosmwasm.wasm.v1.CodeInfoResponse code_infos = 1; - */ - codeInfos: CodeInfoResponse[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryCodesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_infos", kind: "message", T: CodeInfoResponse, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodesResponse { - return new QueryCodesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodesResponse { - return new QueryCodesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodesResponse { - return new QueryCodesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodesResponse | PlainMessage | undefined, b: QueryCodesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodesResponse, a, b); - } -} - -/** - * QueryPinnedCodesRequest is the request type for the Query/PinnedCodes - * RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryPinnedCodesRequest - */ -export class QueryPinnedCodesRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryPinnedCodesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPinnedCodesRequest { - return new QueryPinnedCodesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPinnedCodesRequest { - return new QueryPinnedCodesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPinnedCodesRequest { - return new QueryPinnedCodesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPinnedCodesRequest | PlainMessage | undefined, b: QueryPinnedCodesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPinnedCodesRequest, a, b); - } -} - -/** - * QueryPinnedCodesResponse is the response type for the - * Query/PinnedCodes RPC method - * - * @generated from message cosmwasm.wasm.v1.QueryPinnedCodesResponse - */ -export class QueryPinnedCodesResponse extends Message { - /** - * @generated from field: repeated uint64 code_ids = 1; - */ - codeIds: bigint[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryPinnedCodesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPinnedCodesResponse { - return new QueryPinnedCodesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPinnedCodesResponse { - return new QueryPinnedCodesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPinnedCodesResponse { - return new QueryPinnedCodesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPinnedCodesResponse | PlainMessage | undefined, b: QueryPinnedCodesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPinnedCodesResponse, a, b); - } -} - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message cosmwasm.wasm.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message cosmwasm.wasm.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: cosmwasm.wasm.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryContractsByCreatorRequest is the request type for the - * Query/ContractsByCreator RPC method. - * - * @generated from message cosmwasm.wasm.v1.QueryContractsByCreatorRequest - */ -export class QueryContractsByCreatorRequest extends Message { - /** - * CreatorAddress is the address of contract creator - * - * @generated from field: string creator_address = 1; - */ - creatorAddress = ""; - - /** - * Pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractsByCreatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractsByCreatorRequest { - return new QueryContractsByCreatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractsByCreatorRequest { - return new QueryContractsByCreatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractsByCreatorRequest { - return new QueryContractsByCreatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractsByCreatorRequest | PlainMessage | undefined, b: QueryContractsByCreatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractsByCreatorRequest, a, b); - } -} - -/** - * QueryContractsByCreatorResponse is the response type for the - * Query/ContractsByCreator RPC method. - * - * @generated from message cosmwasm.wasm.v1.QueryContractsByCreatorResponse - */ -export class QueryContractsByCreatorResponse extends Message { - /** - * ContractAddresses result set - * - * @generated from field: repeated string contract_addresses = 1; - */ - contractAddresses: string[] = []; - - /** - * Pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryContractsByCreatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryContractsByCreatorResponse { - return new QueryContractsByCreatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryContractsByCreatorResponse { - return new QueryContractsByCreatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryContractsByCreatorResponse { - return new QueryContractsByCreatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryContractsByCreatorResponse | PlainMessage | undefined, b: QueryContractsByCreatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryContractsByCreatorResponse, a, b); - } -} - -/** - * QueryWasmLimitsConfigRequest is the request type for the - * Query/WasmLimitsConfig RPC method. - * - * @generated from message cosmwasm.wasm.v1.QueryWasmLimitsConfigRequest - */ -export class QueryWasmLimitsConfigRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryWasmLimitsConfigRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryWasmLimitsConfigRequest { - return new QueryWasmLimitsConfigRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryWasmLimitsConfigRequest { - return new QueryWasmLimitsConfigRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryWasmLimitsConfigRequest { - return new QueryWasmLimitsConfigRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryWasmLimitsConfigRequest | PlainMessage | undefined, b: QueryWasmLimitsConfigRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryWasmLimitsConfigRequest, a, b); - } -} - -/** - * QueryWasmLimitsConfigResponse is the response type for the - * Query/WasmLimitsConfig RPC method. It contains the JSON encoded limits for - * static validation of Wasm files. - * - * @generated from message cosmwasm.wasm.v1.QueryWasmLimitsConfigResponse - */ -export class QueryWasmLimitsConfigResponse extends Message { - /** - * @generated from field: string config = 1; - */ - config = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryWasmLimitsConfigResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "config", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryWasmLimitsConfigResponse { - return new QueryWasmLimitsConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryWasmLimitsConfigResponse { - return new QueryWasmLimitsConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryWasmLimitsConfigResponse { - return new QueryWasmLimitsConfigResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryWasmLimitsConfigResponse | PlainMessage | undefined, b: QueryWasmLimitsConfigResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryWasmLimitsConfigResponse, a, b); - } -} - -/** - * QueryBuildAddressRequest is the request type for the Query/BuildAddress RPC - * method. - * - * @generated from message cosmwasm.wasm.v1.QueryBuildAddressRequest - */ -export class QueryBuildAddressRequest extends Message { - /** - * CodeHash is the hash of the code - * - * @generated from field: string code_hash = 1; - */ - codeHash = ""; - - /** - * CreatorAddress is the address of the contract instantiator - * - * @generated from field: string creator_address = 2; - */ - creatorAddress = ""; - - /** - * Salt is a hex encoded salt - * - * @generated from field: string salt = 3; - */ - salt = ""; - - /** - * InitArgs are optional json encoded init args to be used in contract address - * building if provided - * - * @generated from field: bytes init_args = 4; - */ - initArgs = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryBuildAddressRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "creator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "salt", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "init_args", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBuildAddressRequest { - return new QueryBuildAddressRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBuildAddressRequest { - return new QueryBuildAddressRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBuildAddressRequest { - return new QueryBuildAddressRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBuildAddressRequest | PlainMessage | undefined, b: QueryBuildAddressRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBuildAddressRequest, a, b); - } -} - -/** - * QueryBuildAddressResponse is the response type for the Query/BuildAddress RPC - * method. - * - * @generated from message cosmwasm.wasm.v1.QueryBuildAddressResponse - */ -export class QueryBuildAddressResponse extends Message { - /** - * Address is the contract address - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.QueryBuildAddressResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBuildAddressResponse { - return new QueryBuildAddressResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBuildAddressResponse { - return new QueryBuildAddressResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBuildAddressResponse { - return new QueryBuildAddressResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBuildAddressResponse | PlainMessage | undefined, b: QueryBuildAddressResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBuildAddressResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_cosmes.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_cosmes.ts deleted file mode 100644 index 5a68dcee4..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_cosmes.ts +++ /dev/null @@ -1,239 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/tx.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddCodeUploadParamsAddresses, MsgAddCodeUploadParamsAddressesResponse, MsgClearAdmin, MsgClearAdminResponse, MsgExecuteContract, MsgExecuteContractResponse, MsgInstantiateContract, MsgInstantiateContract2, MsgInstantiateContract2Response, MsgInstantiateContractResponse, MsgMigrateContract, MsgMigrateContractResponse, MsgPinCodes, MsgPinCodesResponse, MsgRemoveCodeUploadParamsAddresses, MsgRemoveCodeUploadParamsAddressesResponse, MsgStoreAndInstantiateContract, MsgStoreAndInstantiateContractResponse, MsgStoreAndMigrateContract, MsgStoreAndMigrateContractResponse, MsgStoreCode, MsgStoreCodeResponse, MsgSudoContract, MsgSudoContractResponse, MsgUnpinCodes, MsgUnpinCodesResponse, MsgUpdateAdmin, MsgUpdateAdminResponse, MsgUpdateContractLabel, MsgUpdateContractLabelResponse, MsgUpdateInstantiateConfig, MsgUpdateInstantiateConfigResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "cosmwasm.wasm.v1.Msg"; - -/** - * StoreCode to submit Wasm code to the system - * - * @generated from rpc cosmwasm.wasm.v1.Msg.StoreCode - */ -export const MsgStoreCodeService = { - typeName: TYPE_NAME, - method: "StoreCode", - Request: MsgStoreCode, - Response: MsgStoreCodeResponse, -} as const; - -/** - * InstantiateContract creates a new smart contract instance for the given - * code id. - * - * @generated from rpc cosmwasm.wasm.v1.Msg.InstantiateContract - */ -export const MsgInstantiateContractService = { - typeName: TYPE_NAME, - method: "InstantiateContract", - Request: MsgInstantiateContract, - Response: MsgInstantiateContractResponse, -} as const; - -/** - * InstantiateContract2 creates a new smart contract instance for the given - * code id with a predictable address - * - * @generated from rpc cosmwasm.wasm.v1.Msg.InstantiateContract2 - */ -export const MsgInstantiateContract2Service = { - typeName: TYPE_NAME, - method: "InstantiateContract2", - Request: MsgInstantiateContract2, - Response: MsgInstantiateContract2Response, -} as const; - -/** - * Execute submits the given message data to a smart contract - * - * @generated from rpc cosmwasm.wasm.v1.Msg.ExecuteContract - */ -export const MsgExecuteContractService = { - typeName: TYPE_NAME, - method: "ExecuteContract", - Request: MsgExecuteContract, - Response: MsgExecuteContractResponse, -} as const; - -/** - * Migrate runs a code upgrade/ downgrade for a smart contract - * - * @generated from rpc cosmwasm.wasm.v1.Msg.MigrateContract - */ -export const MsgMigrateContractService = { - typeName: TYPE_NAME, - method: "MigrateContract", - Request: MsgMigrateContract, - Response: MsgMigrateContractResponse, -} as const; - -/** - * UpdateAdmin sets a new admin for a smart contract - * - * @generated from rpc cosmwasm.wasm.v1.Msg.UpdateAdmin - */ -export const MsgUpdateAdminService = { - typeName: TYPE_NAME, - method: "UpdateAdmin", - Request: MsgUpdateAdmin, - Response: MsgUpdateAdminResponse, -} as const; - -/** - * ClearAdmin removes any admin stored for a smart contract - * - * @generated from rpc cosmwasm.wasm.v1.Msg.ClearAdmin - */ -export const MsgClearAdminService = { - typeName: TYPE_NAME, - method: "ClearAdmin", - Request: MsgClearAdmin, - Response: MsgClearAdminResponse, -} as const; - -/** - * UpdateInstantiateConfig updates instantiate config for a smart contract - * - * @generated from rpc cosmwasm.wasm.v1.Msg.UpdateInstantiateConfig - */ -export const MsgUpdateInstantiateConfigService = { - typeName: TYPE_NAME, - method: "UpdateInstantiateConfig", - Request: MsgUpdateInstantiateConfig, - Response: MsgUpdateInstantiateConfigResponse, -} as const; - -/** - * UpdateParams defines a governance operation for updating the x/wasm - * module parameters. The authority is defined in the keeper. - * - * Since: 0.40 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * SudoContract defines a governance operation for calling sudo - * on a contract. The authority is defined in the keeper. - * - * Since: 0.40 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.SudoContract - */ -export const MsgSudoContractService = { - typeName: TYPE_NAME, - method: "SudoContract", - Request: MsgSudoContract, - Response: MsgSudoContractResponse, -} as const; - -/** - * PinCodes defines a governance operation for pinning a set of - * code ids in the wasmvm cache. The authority is defined in the keeper. - * - * Since: 0.40 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.PinCodes - */ -export const MsgPinCodesService = { - typeName: TYPE_NAME, - method: "PinCodes", - Request: MsgPinCodes, - Response: MsgPinCodesResponse, -} as const; - -/** - * UnpinCodes defines a governance operation for unpinning a set of - * code ids in the wasmvm cache. The authority is defined in the keeper. - * - * Since: 0.40 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.UnpinCodes - */ -export const MsgUnpinCodesService = { - typeName: TYPE_NAME, - method: "UnpinCodes", - Request: MsgUnpinCodes, - Response: MsgUnpinCodesResponse, -} as const; - -/** - * StoreAndInstantiateContract defines a governance operation for storing - * and instantiating the contract. The authority is defined in the keeper. - * - * Since: 0.40 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.StoreAndInstantiateContract - */ -export const MsgStoreAndInstantiateContractService = { - typeName: TYPE_NAME, - method: "StoreAndInstantiateContract", - Request: MsgStoreAndInstantiateContract, - Response: MsgStoreAndInstantiateContractResponse, -} as const; - -/** - * RemoveCodeUploadParamsAddresses defines a governance operation for - * removing addresses from code upload params. - * The authority is defined in the keeper. - * - * @generated from rpc cosmwasm.wasm.v1.Msg.RemoveCodeUploadParamsAddresses - */ -export const MsgRemoveCodeUploadParamsAddressesService = { - typeName: TYPE_NAME, - method: "RemoveCodeUploadParamsAddresses", - Request: MsgRemoveCodeUploadParamsAddresses, - Response: MsgRemoveCodeUploadParamsAddressesResponse, -} as const; - -/** - * AddCodeUploadParamsAddresses defines a governance operation for - * adding addresses to code upload params. - * The authority is defined in the keeper. - * - * @generated from rpc cosmwasm.wasm.v1.Msg.AddCodeUploadParamsAddresses - */ -export const MsgAddCodeUploadParamsAddressesService = { - typeName: TYPE_NAME, - method: "AddCodeUploadParamsAddresses", - Request: MsgAddCodeUploadParamsAddresses, - Response: MsgAddCodeUploadParamsAddressesResponse, -} as const; - -/** - * StoreAndMigrateContract defines a governance operation for storing - * and migrating the contract. The authority is defined in the keeper. - * - * Since: 0.42 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.StoreAndMigrateContract - */ -export const MsgStoreAndMigrateContractService = { - typeName: TYPE_NAME, - method: "StoreAndMigrateContract", - Request: MsgStoreAndMigrateContract, - Response: MsgStoreAndMigrateContractResponse, -} as const; - -/** - * UpdateContractLabel sets a new label for a smart contract - * - * Since: 0.43 - * - * @generated from rpc cosmwasm.wasm.v1.Msg.UpdateContractLabel - */ -export const MsgUpdateContractLabelService = { - typeName: TYPE_NAME, - method: "UpdateContractLabel", - Request: MsgUpdateContractLabel, - Response: MsgUpdateContractLabelResponse, -} as const; - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_pb.ts deleted file mode 100644 index f55caac89..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/tx_pb.ts +++ /dev/null @@ -1,1807 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/tx.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccessConfig, Params } from "./types_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * MsgStoreCode submit Wasm code to the system - * - * @generated from message cosmwasm.wasm.v1.MsgStoreCode - */ -export class MsgStoreCode extends Message { - /** - * Sender is the actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 2; - */ - wasmByteCode = new Uint8Array(0); - - /** - * InstantiatePermission access control to apply on contract creation, - * optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 5; - */ - instantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreCode"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreCode | PlainMessage | undefined, b: MsgStoreCode | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreCode, a, b); - } -} - -/** - * MsgStoreCodeResponse returns store result data. - * - * @generated from message cosmwasm.wasm.v1.MsgStoreCodeResponse - */ -export class MsgStoreCodeResponse extends Message { - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * Checksum is the sha256 hash of the stored code - * - * @generated from field: bytes checksum = 2; - */ - checksum = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreCodeResponse | PlainMessage | undefined, b: MsgStoreCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreCodeResponse, a, b); - } -} - -/** - * MsgInstantiateContract create a new smart contract instance for the given - * code id. - * - * @generated from message cosmwasm.wasm.v1.MsgInstantiateContract - */ -export class MsgInstantiateContract extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 2; - */ - admin = ""; - - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 3; - */ - codeId = protoInt64.zero; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 4; - */ - label = ""; - - /** - * Msg json encoded message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 5; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 6; - */ - funds: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgInstantiateContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "funds", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInstantiateContract { - return new MsgInstantiateContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInstantiateContract { - return new MsgInstantiateContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInstantiateContract { - return new MsgInstantiateContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgInstantiateContract | PlainMessage | undefined, b: MsgInstantiateContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInstantiateContract, a, b); - } -} - -/** - * MsgInstantiateContractResponse return instantiation result data - * - * @generated from message cosmwasm.wasm.v1.MsgInstantiateContractResponse - */ -export class MsgInstantiateContractResponse extends Message { - /** - * Address is the bech32 address of the new contract instance. - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgInstantiateContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInstantiateContractResponse { - return new MsgInstantiateContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInstantiateContractResponse { - return new MsgInstantiateContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInstantiateContractResponse { - return new MsgInstantiateContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgInstantiateContractResponse | PlainMessage | undefined, b: MsgInstantiateContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInstantiateContractResponse, a, b); - } -} - -/** - * MsgInstantiateContract2 create a new smart contract instance for the given - * code id with a predictable address. - * - * @generated from message cosmwasm.wasm.v1.MsgInstantiateContract2 - */ -export class MsgInstantiateContract2 extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 2; - */ - admin = ""; - - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 3; - */ - codeId = protoInt64.zero; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 4; - */ - label = ""; - - /** - * Msg json encoded message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 5; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 6; - */ - funds: Coin[] = []; - - /** - * Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - * - * @generated from field: bytes salt = 7; - */ - salt = new Uint8Array(0); - - /** - * FixMsg include the msg value into the hash for the predictable address. - * Default is false - * - * @generated from field: bool fix_msg = 8; - */ - fixMsg = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgInstantiateContract2"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "funds", kind: "message", T: Coin, repeated: true }, - { no: 7, name: "salt", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "fix_msg", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInstantiateContract2 { - return new MsgInstantiateContract2().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInstantiateContract2 { - return new MsgInstantiateContract2().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInstantiateContract2 { - return new MsgInstantiateContract2().fromJsonString(jsonString, options); - } - - static equals(a: MsgInstantiateContract2 | PlainMessage | undefined, b: MsgInstantiateContract2 | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInstantiateContract2, a, b); - } -} - -/** - * MsgInstantiateContract2Response return instantiation result data - * - * @generated from message cosmwasm.wasm.v1.MsgInstantiateContract2Response - */ -export class MsgInstantiateContract2Response extends Message { - /** - * Address is the bech32 address of the new contract instance. - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgInstantiateContract2Response"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInstantiateContract2Response { - return new MsgInstantiateContract2Response().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInstantiateContract2Response { - return new MsgInstantiateContract2Response().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInstantiateContract2Response { - return new MsgInstantiateContract2Response().fromJsonString(jsonString, options); - } - - static equals(a: MsgInstantiateContract2Response | PlainMessage | undefined, b: MsgInstantiateContract2Response | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInstantiateContract2Response, a, b); - } -} - -/** - * MsgExecuteContract submits the given message data to a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgExecuteContract - */ -export class MsgExecuteContract extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 2; - */ - contract = ""; - - /** - * Msg json encoded message to be passed to the contract - * - * @generated from field: bytes msg = 3; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred to the contract on execution - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 5; - */ - funds: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgExecuteContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "funds", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExecuteContract { - return new MsgExecuteContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExecuteContract { - return new MsgExecuteContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExecuteContract { - return new MsgExecuteContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgExecuteContract | PlainMessage | undefined, b: MsgExecuteContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExecuteContract, a, b); - } -} - -/** - * MsgExecuteContractResponse returns execution result data. - * - * @generated from message cosmwasm.wasm.v1.MsgExecuteContractResponse - */ -export class MsgExecuteContractResponse extends Message { - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgExecuteContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExecuteContractResponse { - return new MsgExecuteContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExecuteContractResponse { - return new MsgExecuteContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExecuteContractResponse { - return new MsgExecuteContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExecuteContractResponse | PlainMessage | undefined, b: MsgExecuteContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExecuteContractResponse, a, b); - } -} - -/** - * MsgMigrateContract runs a code upgrade/ downgrade for a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgMigrateContract - */ -export class MsgMigrateContract extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 2; - */ - contract = ""; - - /** - * CodeID references the new WASM code - * - * @generated from field: uint64 code_id = 3; - */ - codeId = protoInt64.zero; - - /** - * Msg json encoded message to be passed to the contract on migration - * - * @generated from field: bytes msg = 4; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgMigrateContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgMigrateContract | PlainMessage | undefined, b: MsgMigrateContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMigrateContract, a, b); - } -} - -/** - * MsgMigrateContractResponse returns contract migration result data. - * - * @generated from message cosmwasm.wasm.v1.MsgMigrateContractResponse - */ -export class MsgMigrateContractResponse extends Message { - /** - * Data contains same raw bytes returned as data from the wasm contract. - * (May be empty) - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgMigrateContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgMigrateContractResponse | PlainMessage | undefined, b: MsgMigrateContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMigrateContractResponse, a, b); - } -} - -/** - * MsgUpdateAdmin sets a new admin for a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateAdmin - */ -export class MsgUpdateAdmin extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * NewAdmin address to be set - * - * @generated from field: string new_admin = 2; - */ - newAdmin = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 3; - */ - contract = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateAdmin"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "new_admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateAdmin { - return new MsgUpdateAdmin().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateAdmin { - return new MsgUpdateAdmin().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateAdmin { - return new MsgUpdateAdmin().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateAdmin | PlainMessage | undefined, b: MsgUpdateAdmin | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateAdmin, a, b); - } -} - -/** - * MsgUpdateAdminResponse returns empty data - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateAdminResponse - */ -export class MsgUpdateAdminResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateAdminResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateAdminResponse { - return new MsgUpdateAdminResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateAdminResponse { - return new MsgUpdateAdminResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateAdminResponse { - return new MsgUpdateAdminResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateAdminResponse | PlainMessage | undefined, b: MsgUpdateAdminResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateAdminResponse, a, b); - } -} - -/** - * MsgClearAdmin removes any admin stored for a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgClearAdmin - */ -export class MsgClearAdmin extends Message { - /** - * Sender is the actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 3; - */ - contract = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgClearAdmin"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgClearAdmin { - return new MsgClearAdmin().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgClearAdmin { - return new MsgClearAdmin().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgClearAdmin { - return new MsgClearAdmin().fromJsonString(jsonString, options); - } - - static equals(a: MsgClearAdmin | PlainMessage | undefined, b: MsgClearAdmin | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgClearAdmin, a, b); - } -} - -/** - * MsgClearAdminResponse returns empty data - * - * @generated from message cosmwasm.wasm.v1.MsgClearAdminResponse - */ -export class MsgClearAdminResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgClearAdminResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgClearAdminResponse { - return new MsgClearAdminResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgClearAdminResponse { - return new MsgClearAdminResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgClearAdminResponse { - return new MsgClearAdminResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgClearAdminResponse | PlainMessage | undefined, b: MsgClearAdminResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgClearAdminResponse, a, b); - } -} - -/** - * MsgUpdateInstantiateConfig updates instantiate config for a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateInstantiateConfig - */ -export class MsgUpdateInstantiateConfig extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * CodeID references the stored WASM code - * - * @generated from field: uint64 code_id = 2; - */ - codeId = protoInt64.zero; - - /** - * NewInstantiatePermission is the new access control - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig new_instantiate_permission = 3; - */ - newInstantiatePermission?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateInstantiateConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "new_instantiate_permission", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateInstantiateConfig { - return new MsgUpdateInstantiateConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateInstantiateConfig { - return new MsgUpdateInstantiateConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateInstantiateConfig { - return new MsgUpdateInstantiateConfig().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateInstantiateConfig | PlainMessage | undefined, b: MsgUpdateInstantiateConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateInstantiateConfig, a, b); - } -} - -/** - * MsgUpdateInstantiateConfigResponse returns empty data - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateInstantiateConfigResponse - */ -export class MsgUpdateInstantiateConfigResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateInstantiateConfigResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateInstantiateConfigResponse { - return new MsgUpdateInstantiateConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateInstantiateConfigResponse { - return new MsgUpdateInstantiateConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateInstantiateConfigResponse { - return new MsgUpdateInstantiateConfigResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateInstantiateConfigResponse | PlainMessage | undefined, b: MsgUpdateInstantiateConfigResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateInstantiateConfigResponse, a, b); - } -} - -/** - * MsgUpdateParams is the MsgUpdateParams request type. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the x/wasm parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: cosmwasm.wasm.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgSudoContract is the MsgSudoContract request type. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgSudoContract - */ -export class MsgSudoContract extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 2; - */ - contract = ""; - - /** - * Msg json encoded message to be passed to the contract as sudo - * - * @generated from field: bytes msg = 3; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgSudoContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSudoContract { - return new MsgSudoContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSudoContract { - return new MsgSudoContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSudoContract { - return new MsgSudoContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgSudoContract | PlainMessage | undefined, b: MsgSudoContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSudoContract, a, b); - } -} - -/** - * MsgSudoContractResponse defines the response structure for executing a - * MsgSudoContract message. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgSudoContractResponse - */ -export class MsgSudoContractResponse extends Message { - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgSudoContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSudoContractResponse { - return new MsgSudoContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSudoContractResponse { - return new MsgSudoContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSudoContractResponse { - return new MsgSudoContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSudoContractResponse | PlainMessage | undefined, b: MsgSudoContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSudoContractResponse, a, b); - } -} - -/** - * MsgPinCodes is the MsgPinCodes request type. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgPinCodes - */ -export class MsgPinCodes extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * CodeIDs references the new WASM codes - * - * @generated from field: repeated uint64 code_ids = 2; - */ - codeIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgPinCodes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPinCodes { - return new MsgPinCodes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPinCodes { - return new MsgPinCodes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPinCodes { - return new MsgPinCodes().fromJsonString(jsonString, options); - } - - static equals(a: MsgPinCodes | PlainMessage | undefined, b: MsgPinCodes | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPinCodes, a, b); - } -} - -/** - * MsgPinCodesResponse defines the response structure for executing a - * MsgPinCodes message. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgPinCodesResponse - */ -export class MsgPinCodesResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgPinCodesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPinCodesResponse { - return new MsgPinCodesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPinCodesResponse { - return new MsgPinCodesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPinCodesResponse { - return new MsgPinCodesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgPinCodesResponse | PlainMessage | undefined, b: MsgPinCodesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPinCodesResponse, a, b); - } -} - -/** - * MsgUnpinCodes is the MsgUnpinCodes request type. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgUnpinCodes - */ -export class MsgUnpinCodes extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * CodeIDs references the WASM codes - * - * @generated from field: repeated uint64 code_ids = 2; - */ - codeIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUnpinCodes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnpinCodes { - return new MsgUnpinCodes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnpinCodes { - return new MsgUnpinCodes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnpinCodes { - return new MsgUnpinCodes().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnpinCodes | PlainMessage | undefined, b: MsgUnpinCodes | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnpinCodes, a, b); - } -} - -/** - * MsgUnpinCodesResponse defines the response structure for executing a - * MsgUnpinCodes message. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgUnpinCodesResponse - */ -export class MsgUnpinCodesResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUnpinCodesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnpinCodesResponse { - return new MsgUnpinCodesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnpinCodesResponse { - return new MsgUnpinCodesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnpinCodesResponse { - return new MsgUnpinCodesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnpinCodesResponse | PlainMessage | undefined, b: MsgUnpinCodesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnpinCodesResponse, a, b); - } -} - -/** - * MsgStoreAndInstantiateContract is the MsgStoreAndInstantiateContract - * request type. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgStoreAndInstantiateContract - */ -export class MsgStoreAndInstantiateContract extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 3; - */ - wasmByteCode = new Uint8Array(0); - - /** - * InstantiatePermission to apply on contract creation, optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 4; - */ - instantiatePermission?: AccessConfig; - - /** - * UnpinCode code on upload, optional. As default the uploaded contract is - * pinned to cache. - * - * @generated from field: bool unpin_code = 5; - */ - unpinCode = false; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 6; - */ - admin = ""; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 7; - */ - label = ""; - - /** - * Msg json encoded message to be passed to the contract on instantiation - * - * @generated from field: bytes msg = 8; - */ - msg = new Uint8Array(0); - - /** - * Funds coins that are transferred from the authority account to the contract - * on instantiation - * - * @generated from field: repeated cosmos.base.v1beta1.Coin funds = 9; - */ - funds: Coin[] = []; - - /** - * Source is the URL where the code is hosted - * - * @generated from field: string source = 10; - */ - source = ""; - - /** - * Builder is the docker image used to build the code deterministically, used - * for smart contract verification - * - * @generated from field: string builder = 11; - */ - builder = ""; - - /** - * CodeHash is the SHA256 sum of the code outputted by builder, used for smart - * contract verification - * - * @generated from field: bytes code_hash = 12; - */ - codeHash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreAndInstantiateContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "instantiate_permission", kind: "message", T: AccessConfig }, - { no: 5, name: "unpin_code", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "funds", kind: "message", T: Coin, repeated: true }, - { no: 10, name: "source", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "builder", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "code_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreAndInstantiateContract { - return new MsgStoreAndInstantiateContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreAndInstantiateContract { - return new MsgStoreAndInstantiateContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreAndInstantiateContract { - return new MsgStoreAndInstantiateContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreAndInstantiateContract | PlainMessage | undefined, b: MsgStoreAndInstantiateContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreAndInstantiateContract, a, b); - } -} - -/** - * MsgStoreAndInstantiateContractResponse defines the response structure - * for executing a MsgStoreAndInstantiateContract message. - * - * Since: 0.40 - * - * @generated from message cosmwasm.wasm.v1.MsgStoreAndInstantiateContractResponse - */ -export class MsgStoreAndInstantiateContractResponse extends Message { - /** - * Address is the bech32 address of the new contract instance. - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreAndInstantiateContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreAndInstantiateContractResponse { - return new MsgStoreAndInstantiateContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreAndInstantiateContractResponse { - return new MsgStoreAndInstantiateContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreAndInstantiateContractResponse { - return new MsgStoreAndInstantiateContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreAndInstantiateContractResponse | PlainMessage | undefined, b: MsgStoreAndInstantiateContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreAndInstantiateContractResponse, a, b); - } -} - -/** - * MsgAddCodeUploadParamsAddresses is the - * MsgAddCodeUploadParamsAddresses request type. - * - * @generated from message cosmwasm.wasm.v1.MsgAddCodeUploadParamsAddresses - */ -export class MsgAddCodeUploadParamsAddresses extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * @generated from field: repeated string addresses = 2; - */ - addresses: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgAddCodeUploadParamsAddresses"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddCodeUploadParamsAddresses { - return new MsgAddCodeUploadParamsAddresses().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddCodeUploadParamsAddresses { - return new MsgAddCodeUploadParamsAddresses().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddCodeUploadParamsAddresses { - return new MsgAddCodeUploadParamsAddresses().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddCodeUploadParamsAddresses | PlainMessage | undefined, b: MsgAddCodeUploadParamsAddresses | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddCodeUploadParamsAddresses, a, b); - } -} - -/** - * MsgAddCodeUploadParamsAddressesResponse defines the response - * structure for executing a MsgAddCodeUploadParamsAddresses message. - * - * @generated from message cosmwasm.wasm.v1.MsgAddCodeUploadParamsAddressesResponse - */ -export class MsgAddCodeUploadParamsAddressesResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgAddCodeUploadParamsAddressesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddCodeUploadParamsAddressesResponse { - return new MsgAddCodeUploadParamsAddressesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddCodeUploadParamsAddressesResponse { - return new MsgAddCodeUploadParamsAddressesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddCodeUploadParamsAddressesResponse { - return new MsgAddCodeUploadParamsAddressesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddCodeUploadParamsAddressesResponse | PlainMessage | undefined, b: MsgAddCodeUploadParamsAddressesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddCodeUploadParamsAddressesResponse, a, b); - } -} - -/** - * MsgRemoveCodeUploadParamsAddresses is the - * MsgRemoveCodeUploadParamsAddresses request type. - * - * @generated from message cosmwasm.wasm.v1.MsgRemoveCodeUploadParamsAddresses - */ -export class MsgRemoveCodeUploadParamsAddresses extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * @generated from field: repeated string addresses = 2; - */ - addresses: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgRemoveCodeUploadParamsAddresses"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveCodeUploadParamsAddresses { - return new MsgRemoveCodeUploadParamsAddresses().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveCodeUploadParamsAddresses { - return new MsgRemoveCodeUploadParamsAddresses().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveCodeUploadParamsAddresses { - return new MsgRemoveCodeUploadParamsAddresses().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveCodeUploadParamsAddresses | PlainMessage | undefined, b: MsgRemoveCodeUploadParamsAddresses | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveCodeUploadParamsAddresses, a, b); - } -} - -/** - * MsgRemoveCodeUploadParamsAddressesResponse defines the response - * structure for executing a MsgRemoveCodeUploadParamsAddresses message. - * - * @generated from message cosmwasm.wasm.v1.MsgRemoveCodeUploadParamsAddressesResponse - */ -export class MsgRemoveCodeUploadParamsAddressesResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgRemoveCodeUploadParamsAddressesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveCodeUploadParamsAddressesResponse { - return new MsgRemoveCodeUploadParamsAddressesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveCodeUploadParamsAddressesResponse { - return new MsgRemoveCodeUploadParamsAddressesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveCodeUploadParamsAddressesResponse { - return new MsgRemoveCodeUploadParamsAddressesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveCodeUploadParamsAddressesResponse | PlainMessage | undefined, b: MsgRemoveCodeUploadParamsAddressesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveCodeUploadParamsAddressesResponse, a, b); - } -} - -/** - * MsgStoreAndMigrateContract is the MsgStoreAndMigrateContract - * request type. - * - * Since: 0.42 - * - * @generated from message cosmwasm.wasm.v1.MsgStoreAndMigrateContract - */ -export class MsgStoreAndMigrateContract extends Message { - /** - * Authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 2; - */ - wasmByteCode = new Uint8Array(0); - - /** - * InstantiatePermission to apply on contract creation, optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_permission = 3; - */ - instantiatePermission?: AccessConfig; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 4; - */ - contract = ""; - - /** - * Msg json encoded message to be passed to the contract on migration - * - * @generated from field: bytes msg = 5; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreAndMigrateContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "instantiate_permission", kind: "message", T: AccessConfig }, - { no: 4, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreAndMigrateContract { - return new MsgStoreAndMigrateContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreAndMigrateContract { - return new MsgStoreAndMigrateContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreAndMigrateContract { - return new MsgStoreAndMigrateContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreAndMigrateContract | PlainMessage | undefined, b: MsgStoreAndMigrateContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreAndMigrateContract, a, b); - } -} - -/** - * MsgStoreAndMigrateContractResponse defines the response structure - * for executing a MsgStoreAndMigrateContract message. - * - * Since: 0.42 - * - * @generated from message cosmwasm.wasm.v1.MsgStoreAndMigrateContractResponse - */ -export class MsgStoreAndMigrateContractResponse extends Message { - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * Checksum is the sha256 hash of the stored code - * - * @generated from field: bytes checksum = 2; - */ - checksum = new Uint8Array(0); - - /** - * Data contains bytes to returned from the contract - * - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgStoreAndMigrateContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreAndMigrateContractResponse { - return new MsgStoreAndMigrateContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreAndMigrateContractResponse { - return new MsgStoreAndMigrateContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreAndMigrateContractResponse { - return new MsgStoreAndMigrateContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreAndMigrateContractResponse | PlainMessage | undefined, b: MsgStoreAndMigrateContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreAndMigrateContractResponse, a, b); - } -} - -/** - * MsgUpdateContractLabel sets a new label for a smart contract - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateContractLabel - */ -export class MsgUpdateContractLabel extends Message { - /** - * Sender is the that actor that signed the messages - * - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * NewLabel string to be set - * - * @generated from field: string new_label = 2; - */ - newLabel = ""; - - /** - * Contract is the address of the smart contract - * - * @generated from field: string contract = 3; - */ - contract = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateContractLabel"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "new_label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "contract", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateContractLabel { - return new MsgUpdateContractLabel().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateContractLabel { - return new MsgUpdateContractLabel().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateContractLabel { - return new MsgUpdateContractLabel().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateContractLabel | PlainMessage | undefined, b: MsgUpdateContractLabel | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateContractLabel, a, b); - } -} - -/** - * MsgUpdateContractLabelResponse returns empty data - * - * @generated from message cosmwasm.wasm.v1.MsgUpdateContractLabelResponse - */ -export class MsgUpdateContractLabelResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.MsgUpdateContractLabelResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateContractLabelResponse { - return new MsgUpdateContractLabelResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateContractLabelResponse { - return new MsgUpdateContractLabelResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateContractLabelResponse { - return new MsgUpdateContractLabelResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateContractLabelResponse | PlainMessage | undefined, b: MsgUpdateContractLabelResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateContractLabelResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/cosmwasm/wasm/v1/types_pb.ts b/packages/es/src/protobufs/cosmwasm/wasm/v1/types_pb.ts deleted file mode 100644 index 45b377e6b..000000000 --- a/packages/es/src/protobufs/cosmwasm/wasm/v1/types_pb.ts +++ /dev/null @@ -1,533 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file cosmwasm/wasm/v1/types.proto (package cosmwasm.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * AccessType permission types - * - * @generated from enum cosmwasm.wasm.v1.AccessType - */ -export enum AccessType { - /** - * AccessTypeUnspecified placeholder for empty value - * - * @generated from enum value: ACCESS_TYPE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * AccessTypeNobody forbidden - * - * @generated from enum value: ACCESS_TYPE_NOBODY = 1; - */ - NOBODY = 1, - - /** - * AccessTypeEverybody unrestricted - * - * @generated from enum value: ACCESS_TYPE_EVERYBODY = 3; - */ - EVERYBODY = 3, - - /** - * AccessTypeAnyOfAddresses allow any of the addresses - * - * @generated from enum value: ACCESS_TYPE_ANY_OF_ADDRESSES = 4; - */ - ANY_OF_ADDRESSES = 4, -} -// Retrieve enum metadata with: proto3.getEnumType(AccessType) -proto3.util.setEnumType(AccessType, "cosmwasm.wasm.v1.AccessType", [ - { no: 0, name: "ACCESS_TYPE_UNSPECIFIED" }, - { no: 1, name: "ACCESS_TYPE_NOBODY" }, - { no: 3, name: "ACCESS_TYPE_EVERYBODY" }, - { no: 4, name: "ACCESS_TYPE_ANY_OF_ADDRESSES" }, -]); - -/** - * ContractCodeHistoryOperationType actions that caused a code change - * - * @generated from enum cosmwasm.wasm.v1.ContractCodeHistoryOperationType - */ -export enum ContractCodeHistoryOperationType { - /** - * ContractCodeHistoryOperationTypeUnspecified placeholder for empty value - * - * @generated from enum value: CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * ContractCodeHistoryOperationTypeInit on chain contract instantiation - * - * @generated from enum value: CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT = 1; - */ - INIT = 1, - - /** - * ContractCodeHistoryOperationTypeMigrate code migration - * - * @generated from enum value: CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE = 2; - */ - MIGRATE = 2, - - /** - * ContractCodeHistoryOperationTypeGenesis based on genesis data - * - * @generated from enum value: CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS = 3; - */ - GENESIS = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(ContractCodeHistoryOperationType) -proto3.util.setEnumType(ContractCodeHistoryOperationType, "cosmwasm.wasm.v1.ContractCodeHistoryOperationType", [ - { no: 0, name: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED" }, - { no: 1, name: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT" }, - { no: 2, name: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE" }, - { no: 3, name: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS" }, -]); - -/** - * AccessTypeParam - * - * @generated from message cosmwasm.wasm.v1.AccessTypeParam - */ -export class AccessTypeParam extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.AccessType value = 1; - */ - value = AccessType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AccessTypeParam"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "value", kind: "enum", T: proto3.getEnumType(AccessType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccessTypeParam { - return new AccessTypeParam().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccessTypeParam { - return new AccessTypeParam().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccessTypeParam { - return new AccessTypeParam().fromJsonString(jsonString, options); - } - - static equals(a: AccessTypeParam | PlainMessage | undefined, b: AccessTypeParam | PlainMessage | undefined): boolean { - return proto3.util.equals(AccessTypeParam, a, b); - } -} - -/** - * AccessConfig access control type. - * - * @generated from message cosmwasm.wasm.v1.AccessConfig - */ -export class AccessConfig extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.AccessType permission = 1; - */ - permission = AccessType.UNSPECIFIED; - - /** - * @generated from field: repeated string addresses = 3; - */ - addresses: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AccessConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permission", kind: "enum", T: proto3.getEnumType(AccessType) }, - { no: 3, name: "addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccessConfig { - return new AccessConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccessConfig { - return new AccessConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccessConfig { - return new AccessConfig().fromJsonString(jsonString, options); - } - - static equals(a: AccessConfig | PlainMessage | undefined, b: AccessConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(AccessConfig, a, b); - } -} - -/** - * Params defines the set of wasm parameters. - * - * @generated from message cosmwasm.wasm.v1.Params - */ -export class Params extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.AccessConfig code_upload_access = 1; - */ - codeUploadAccess?: AccessConfig; - - /** - * @generated from field: cosmwasm.wasm.v1.AccessType instantiate_default_permission = 2; - */ - instantiateDefaultPermission = AccessType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_upload_access", kind: "message", T: AccessConfig }, - { no: 2, name: "instantiate_default_permission", kind: "enum", T: proto3.getEnumType(AccessType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * CodeInfo is data for the uploaded contract WASM code - * - * @generated from message cosmwasm.wasm.v1.CodeInfo - */ -export class CodeInfo extends Message { - /** - * CodeHash is the unique identifier created by wasmvm - * - * @generated from field: bytes code_hash = 1; - */ - codeHash = new Uint8Array(0); - - /** - * Creator address who initially stored the code - * - * @generated from field: string creator = 2; - */ - creator = ""; - - /** - * InstantiateConfig access control to apply on contract creation, optional - * - * @generated from field: cosmwasm.wasm.v1.AccessConfig instantiate_config = 5; - */ - instantiateConfig?: AccessConfig; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.CodeInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "instantiate_config", kind: "message", T: AccessConfig }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CodeInfo { - return new CodeInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CodeInfo { - return new CodeInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CodeInfo { - return new CodeInfo().fromJsonString(jsonString, options); - } - - static equals(a: CodeInfo | PlainMessage | undefined, b: CodeInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(CodeInfo, a, b); - } -} - -/** - * ContractInfo stores a WASM contract instance - * - * @generated from message cosmwasm.wasm.v1.ContractInfo - */ -export class ContractInfo extends Message { - /** - * CodeID is the reference to the stored Wasm code - * - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * Creator address who initially instantiated the contract - * - * @generated from field: string creator = 2; - */ - creator = ""; - - /** - * Admin is an optional address that can execute migrations - * - * @generated from field: string admin = 3; - */ - admin = ""; - - /** - * Label is optional metadata to be stored with a contract instance. - * - * @generated from field: string label = 4; - */ - label = ""; - - /** - * Created Tx position when the contract was instantiated. - * - * @generated from field: cosmwasm.wasm.v1.AbsoluteTxPosition created = 5; - */ - created?: AbsoluteTxPosition; - - /** - * @generated from field: string ibc_port_id = 6; - */ - ibcPortId = ""; - - /** - * @generated from field: string ibc2_port_id = 7; - */ - ibc2PortId = ""; - - /** - * Extension is an extension point to store custom metadata within the - * persistence model. - * - * @generated from field: google.protobuf.Any extension = 8; - */ - extension?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ContractInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "label", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "created", kind: "message", T: AbsoluteTxPosition }, - { no: 6, name: "ibc_port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "ibc2_port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "extension", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractInfo { - return new ContractInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractInfo { - return new ContractInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractInfo { - return new ContractInfo().fromJsonString(jsonString, options); - } - - static equals(a: ContractInfo | PlainMessage | undefined, b: ContractInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractInfo, a, b); - } -} - -/** - * ContractCodeHistoryEntry metadata to a contract. - * - * @generated from message cosmwasm.wasm.v1.ContractCodeHistoryEntry - */ -export class ContractCodeHistoryEntry extends Message { - /** - * @generated from field: cosmwasm.wasm.v1.ContractCodeHistoryOperationType operation = 1; - */ - operation = ContractCodeHistoryOperationType.UNSPECIFIED; - - /** - * CodeID is the reference to the stored WASM code - * - * @generated from field: uint64 code_id = 2; - */ - codeId = protoInt64.zero; - - /** - * Updated Tx position when the operation was executed. - * - * @generated from field: cosmwasm.wasm.v1.AbsoluteTxPosition updated = 3; - */ - updated?: AbsoluteTxPosition; - - /** - * @generated from field: bytes msg = 4; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.ContractCodeHistoryEntry"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "operation", kind: "enum", T: proto3.getEnumType(ContractCodeHistoryOperationType) }, - { no: 2, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "updated", kind: "message", T: AbsoluteTxPosition }, - { no: 4, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractCodeHistoryEntry { - return new ContractCodeHistoryEntry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractCodeHistoryEntry { - return new ContractCodeHistoryEntry().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractCodeHistoryEntry { - return new ContractCodeHistoryEntry().fromJsonString(jsonString, options); - } - - static equals(a: ContractCodeHistoryEntry | PlainMessage | undefined, b: ContractCodeHistoryEntry | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractCodeHistoryEntry, a, b); - } -} - -/** - * AbsoluteTxPosition is a unique transaction position that allows for global - * ordering of transactions. - * - * @generated from message cosmwasm.wasm.v1.AbsoluteTxPosition - */ -export class AbsoluteTxPosition extends Message { - /** - * BlockHeight is the block the contract was created at - * - * @generated from field: uint64 block_height = 1; - */ - blockHeight = protoInt64.zero; - - /** - * TxIndex is a monotonic counter within the block (actual transaction index, - * or gas consumed) - * - * @generated from field: uint64 tx_index = 2; - */ - txIndex = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.AbsoluteTxPosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "tx_index", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AbsoluteTxPosition { - return new AbsoluteTxPosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AbsoluteTxPosition { - return new AbsoluteTxPosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AbsoluteTxPosition { - return new AbsoluteTxPosition().fromJsonString(jsonString, options); - } - - static equals(a: AbsoluteTxPosition | PlainMessage | undefined, b: AbsoluteTxPosition | PlainMessage | undefined): boolean { - return proto3.util.equals(AbsoluteTxPosition, a, b); - } -} - -/** - * Model is a struct that holds a KV pair - * - * @generated from message cosmwasm.wasm.v1.Model - */ -export class Model extends Message { - /** - * hex-encode key to read it better (this is often ascii) - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * base64-encode raw value - * - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "cosmwasm.wasm.v1.Model"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Model { - return new Model().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Model { - return new Model().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Model { - return new Model().fromJsonString(jsonString, options); - } - - static equals(a: Model | PlainMessage | undefined, b: Model | PlainMessage | undefined): boolean { - return proto3.util.equals(Model, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/module/v1/module_pb.ts b/packages/es/src/protobufs/dex/module/v1/module_pb.ts deleted file mode 100644 index 934b7243d..000000000 --- a/packages/es/src/protobufs/dex/module/v1/module_pb.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/module/v1/module.proto (package dex.module.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Module is the app config object of the module. - * Learn more: https://docs.cosmos.network/main/building-modules/depinject - * - * @generated from message dex.module.v1.Module - */ -export class Module extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.module.v1.Module"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals(a: Module | PlainMessage | undefined, b: Module | PlainMessage | undefined): boolean { - return proto3.util.equals(Module, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/v1/events_pb.ts b/packages/es/src/protobufs/dex/v1/events_pb.ts deleted file mode 100644 index 0c2715fe0..000000000 --- a/packages/es/src/protobufs/dex/v1/events_pb.ts +++ /dev/null @@ -1,698 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/v1/events.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * EventDEXAccountRegistered is emitted when a new DEX account is registered - * - * @generated from message dex.v1.EventDEXAccountRegistered - */ -export class EventDEXAccountRegistered extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Generated port ID - * - * @generated from field: string port_id = 3; - */ - portId = ""; - - /** - * Remote account address (when available) - * - * @generated from field: string account_address = 4; - */ - accountAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventDEXAccountRegistered"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "account_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDEXAccountRegistered { - return new EventDEXAccountRegistered().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDEXAccountRegistered { - return new EventDEXAccountRegistered().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDEXAccountRegistered { - return new EventDEXAccountRegistered().fromJsonString(jsonString, options); - } - - static equals(a: EventDEXAccountRegistered | PlainMessage | undefined, b: EventDEXAccountRegistered | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDEXAccountRegistered, a, b); - } -} - -/** - * EventSwapExecuted is emitted when a swap is executed - * - * @generated from message dex.v1.EventSwapExecuted - */ -export class EventSwapExecuted extends Message { - /** - * DID of the trader - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Source token and amount - * - * @generated from field: cosmos.base.v1beta1.Coin source = 3; - */ - source?: Coin; - - /** - * Target token and amount received - * - * @generated from field: cosmos.base.v1beta1.Coin target = 4; - */ - target?: Coin; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 5; - */ - txHash = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 6; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventSwapExecuted"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "source", kind: "message", T: Coin }, - { no: 4, name: "target", kind: "message", T: Coin }, - { no: 5, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventSwapExecuted { - return new EventSwapExecuted().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventSwapExecuted { - return new EventSwapExecuted().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventSwapExecuted { - return new EventSwapExecuted().fromJsonString(jsonString, options); - } - - static equals(a: EventSwapExecuted | PlainMessage | undefined, b: EventSwapExecuted | PlainMessage | undefined): boolean { - return proto3.util.equals(EventSwapExecuted, a, b); - } -} - -/** - * EventLiquidityProvided is emitted when liquidity is added - * - * @generated from message dex.v1.EventLiquidityProvided - */ -export class EventLiquidityProvided extends Message { - /** - * DID of the liquidity provider - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Pool ID - * - * @generated from field: string pool_id = 3; - */ - poolId = ""; - - /** - * Assets provided - * - * @generated from field: repeated cosmos.base.v1beta1.Coin assets = 4; - */ - assets: Coin[] = []; - - /** - * Shares received - * - * @generated from field: string shares_received = 5; - */ - sharesReceived = ""; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 6; - */ - txHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventLiquidityProvided"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "assets", kind: "message", T: Coin, repeated: true }, - { no: 5, name: "shares_received", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventLiquidityProvided { - return new EventLiquidityProvided().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventLiquidityProvided { - return new EventLiquidityProvided().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventLiquidityProvided { - return new EventLiquidityProvided().fromJsonString(jsonString, options); - } - - static equals(a: EventLiquidityProvided | PlainMessage | undefined, b: EventLiquidityProvided | PlainMessage | undefined): boolean { - return proto3.util.equals(EventLiquidityProvided, a, b); - } -} - -/** - * EventLiquidityRemoved is emitted when liquidity is removed - * - * @generated from message dex.v1.EventLiquidityRemoved - */ -export class EventLiquidityRemoved extends Message { - /** - * DID of the liquidity provider - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Pool ID - * - * @generated from field: string pool_id = 3; - */ - poolId = ""; - - /** - * Shares removed - * - * @generated from field: string shares_removed = 4; - */ - sharesRemoved = ""; - - /** - * Assets received - * - * @generated from field: repeated cosmos.base.v1beta1.Coin assets = 5; - */ - assets: Coin[] = []; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 6; - */ - txHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventLiquidityRemoved"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "shares_removed", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "assets", kind: "message", T: Coin, repeated: true }, - { no: 6, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventLiquidityRemoved { - return new EventLiquidityRemoved().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventLiquidityRemoved { - return new EventLiquidityRemoved().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventLiquidityRemoved { - return new EventLiquidityRemoved().fromJsonString(jsonString, options); - } - - static equals(a: EventLiquidityRemoved | PlainMessage | undefined, b: EventLiquidityRemoved | PlainMessage | undefined): boolean { - return proto3.util.equals(EventLiquidityRemoved, a, b); - } -} - -/** - * EventOrderCreated is emitted when a limit order is created - * - * @generated from message dex.v1.EventOrderCreated - */ -export class EventOrderCreated extends Message { - /** - * DID of the trader - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Order ID on remote chain - * - * @generated from field: string order_id = 3; - */ - orderId = ""; - - /** - * Order details - * - * @generated from field: string sell_denom = 4; - */ - sellDenom = ""; - - /** - * @generated from field: string buy_denom = 5; - */ - buyDenom = ""; - - /** - * @generated from field: string amount = 6; - */ - amount = ""; - - /** - * @generated from field: string price = 7; - */ - price = ""; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 8; - */ - txHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventOrderCreated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "sell_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "buy_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventOrderCreated { - return new EventOrderCreated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventOrderCreated { - return new EventOrderCreated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventOrderCreated { - return new EventOrderCreated().fromJsonString(jsonString, options); - } - - static equals(a: EventOrderCreated | PlainMessage | undefined, b: EventOrderCreated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventOrderCreated, a, b); - } -} - -/** - * EventOrderCancelled is emitted when an order is cancelled - * - * @generated from message dex.v1.EventOrderCancelled - */ -export class EventOrderCancelled extends Message { - /** - * DID of the trader - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Order ID that was cancelled - * - * @generated from field: string order_id = 3; - */ - orderId = ""; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 4; - */ - txHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventOrderCancelled"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventOrderCancelled { - return new EventOrderCancelled().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventOrderCancelled { - return new EventOrderCancelled().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventOrderCancelled { - return new EventOrderCancelled().fromJsonString(jsonString, options); - } - - static equals(a: EventOrderCancelled | PlainMessage | undefined, b: EventOrderCancelled | PlainMessage | undefined): boolean { - return proto3.util.equals(EventOrderCancelled, a, b); - } -} - -/** - * EventOrderFilled is emitted when an order is filled - * - * @generated from message dex.v1.EventOrderFilled - */ -export class EventOrderFilled extends Message { - /** - * DID of the trader - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Order ID that was filled - * - * @generated from field: string order_id = 3; - */ - orderId = ""; - - /** - * Fill details - * - * @generated from field: string fill_amount = 4; - */ - fillAmount = ""; - - /** - * @generated from field: string fill_price = 5; - */ - fillPrice = ""; - - /** - * Transaction hash on remote chain - * - * @generated from field: string tx_hash = 6; - */ - txHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventOrderFilled"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "fill_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "fill_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventOrderFilled { - return new EventOrderFilled().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventOrderFilled { - return new EventOrderFilled().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventOrderFilled { - return new EventOrderFilled().fromJsonString(jsonString, options); - } - - static equals(a: EventOrderFilled | PlainMessage | undefined, b: EventOrderFilled | PlainMessage | undefined): boolean { - return proto3.util.equals(EventOrderFilled, a, b); - } -} - -/** - * EventICAPacketSent is emitted when an ICA packet is sent - * - * @generated from message dex.v1.EventICAPacketSent - */ -export class EventICAPacketSent extends Message { - /** - * DID of the sender - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Packet type (swap, liquidity, order, etc.) - * - * @generated from field: string packet_type = 3; - */ - packetType = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 4; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventICAPacketSent"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "packet_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventICAPacketSent { - return new EventICAPacketSent().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventICAPacketSent { - return new EventICAPacketSent().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventICAPacketSent { - return new EventICAPacketSent().fromJsonString(jsonString, options); - } - - static equals(a: EventICAPacketSent | PlainMessage | undefined, b: EventICAPacketSent | PlainMessage | undefined): boolean { - return proto3.util.equals(EventICAPacketSent, a, b); - } -} - -/** - * EventICAPacketAcknowledged is emitted when an ICA packet is acknowledged - * - * @generated from message dex.v1.EventICAPacketAcknowledged - */ -export class EventICAPacketAcknowledged extends Message { - /** - * DID of the sender - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Packet type - * - * @generated from field: string packet_type = 3; - */ - packetType = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 4; - */ - sequence = protoInt64.zero; - - /** - * Success status - * - * @generated from field: bool success = 5; - */ - success = false; - - /** - * Error message if failed - * - * @generated from field: string error = 6; - */ - error = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.EventICAPacketAcknowledged"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "packet_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "error", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventICAPacketAcknowledged { - return new EventICAPacketAcknowledged().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventICAPacketAcknowledged { - return new EventICAPacketAcknowledged().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventICAPacketAcknowledged { - return new EventICAPacketAcknowledged().fromJsonString(jsonString, options); - } - - static equals(a: EventICAPacketAcknowledged | PlainMessage | undefined, b: EventICAPacketAcknowledged | PlainMessage | undefined): boolean { - return proto3.util.equals(EventICAPacketAcknowledged, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/v1/genesis_pb.ts b/packages/es/src/protobufs/dex/v1/genesis_pb.ts deleted file mode 100644 index 92774aab5..000000000 --- a/packages/es/src/protobufs/dex/v1/genesis_pb.ts +++ /dev/null @@ -1,293 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/v1/genesis.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { InterchainDEXAccount } from "./ica_pb.js"; - -/** - * GenesisState defines the DEX module's genesis state - * - * @generated from message dex.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * Module parameters - * - * @generated from field: dex.v1.Params params = 1; - */ - params?: Params; - - /** - * IBC port ID for the module - * - * @generated from field: string port_id = 2; - */ - portId = ""; - - /** - * Registered DEX accounts - * - * @generated from field: repeated dex.v1.InterchainDEXAccount accounts = 3; - */ - accounts: InterchainDEXAccount[] = []; - - /** - * Account sequence counter - * - * @generated from field: uint64 account_sequence = 4; - */ - accountSequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "accounts", kind: "message", T: InterchainDEXAccount, repeated: true }, - { no: 4, name: "account_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Params defines the parameters for the DEX module - * - * @generated from message dex.v1.Params - */ -export class Params extends Message { - /** - * Enable/disable the module - * - * @generated from field: bool enabled = 1; - */ - enabled = false; - - /** - * Maximum accounts per DID - * - * @generated from field: uint32 max_accounts_per_did = 2; - */ - maxAccountsPerDid = 0; - - /** - * Default timeout for ICA operations (in seconds) - * - * @generated from field: uint64 default_timeout_seconds = 3; - */ - defaultTimeoutSeconds = protoInt64.zero; - - /** - * Allowed DEX connections - * - * @generated from field: repeated string allowed_connections = 4; - */ - allowedConnections: string[] = []; - - /** - * Minimum swap amount (in base denom) - * - * @generated from field: string min_swap_amount = 5; - */ - minSwapAmount = ""; - - /** - * Maximum daily volume per DID (in USD equivalent) - * - * @generated from field: string max_daily_volume = 6; - */ - maxDailyVolume = ""; - - /** - * Rate limit parameters - * - * @generated from field: dex.v1.RateLimitParams rate_limits = 7; - */ - rateLimits?: RateLimitParams; - - /** - * Fee parameters - * - * @generated from field: dex.v1.FeeParams fees = 8; - */ - fees?: FeeParams; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "max_accounts_per_did", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "default_timeout_seconds", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "allowed_connections", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "min_swap_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "max_daily_volume", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "rate_limits", kind: "message", T: RateLimitParams }, - { no: 8, name: "fees", kind: "message", T: FeeParams }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * RateLimitParams defines rate limiting parameters - * - * @generated from message dex.v1.RateLimitParams - */ -export class RateLimitParams extends Message { - /** - * Maximum operations per block - * - * @generated from field: uint32 max_ops_per_block = 1; - */ - maxOpsPerBlock = 0; - - /** - * Maximum operations per DID per day - * - * @generated from field: uint32 max_ops_per_did_per_day = 2; - */ - maxOpsPerDidPerDay = 0; - - /** - * Cooldown period between operations (in blocks) - * - * @generated from field: uint32 cooldown_blocks = 3; - */ - cooldownBlocks = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.RateLimitParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_ops_per_block", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: "max_ops_per_did_per_day", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "cooldown_blocks", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RateLimitParams { - return new RateLimitParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RateLimitParams { - return new RateLimitParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RateLimitParams { - return new RateLimitParams().fromJsonString(jsonString, options); - } - - static equals(a: RateLimitParams | PlainMessage | undefined, b: RateLimitParams | PlainMessage | undefined): boolean { - return proto3.util.equals(RateLimitParams, a, b); - } -} - -/** - * FeeParams defines fee parameters for DEX operations - * - * @generated from message dex.v1.FeeParams - */ -export class FeeParams extends Message { - /** - * Platform fee for swaps (basis points, e.g., 30 = 0.3%) - * - * @generated from field: uint32 swap_fee_bps = 1; - */ - swapFeeBps = 0; - - /** - * Platform fee for liquidity operations - * - * @generated from field: uint32 liquidity_fee_bps = 2; - */ - liquidityFeeBps = 0; - - /** - * Platform fee for orders - * - * @generated from field: uint32 order_fee_bps = 3; - */ - orderFeeBps = 0; - - /** - * Fee collector address - * - * @generated from field: string fee_collector = 4; - */ - feeCollector = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.FeeParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "swap_fee_bps", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: "liquidity_fee_bps", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "order_fee_bps", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: "fee_collector", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FeeParams { - return new FeeParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FeeParams { - return new FeeParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FeeParams { - return new FeeParams().fromJsonString(jsonString, options); - } - - static equals(a: FeeParams | PlainMessage | undefined, b: FeeParams | PlainMessage | undefined): boolean { - return proto3.util.equals(FeeParams, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/v1/ica_pb.ts b/packages/es/src/protobufs/dex/v1/ica_pb.ts deleted file mode 100644 index 757376ad0..000000000 --- a/packages/es/src/protobufs/dex/v1/ica_pb.ts +++ /dev/null @@ -1,311 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/v1/ica.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * AccountStatus defines the status of an ICA account - * - * @generated from enum dex.v1.AccountStatus - */ -export enum AccountStatus { - /** - * Account is pending creation - * - * @generated from enum value: ACCOUNT_STATUS_PENDING = 0; - */ - PENDING = 0, - - /** - * Account is active and ready - * - * @generated from enum value: ACCOUNT_STATUS_ACTIVE = 1; - */ - ACTIVE = 1, - - /** - * Account is temporarily disabled - * - * @generated from enum value: ACCOUNT_STATUS_DISABLED = 2; - */ - DISABLED = 2, - - /** - * Account creation failed - * - * @generated from enum value: ACCOUNT_STATUS_FAILED = 3; - */ - FAILED = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(AccountStatus) -proto3.util.setEnumType(AccountStatus, "dex.v1.AccountStatus", [ - { no: 0, name: "ACCOUNT_STATUS_PENDING" }, - { no: 1, name: "ACCOUNT_STATUS_ACTIVE" }, - { no: 2, name: "ACCOUNT_STATUS_DISABLED" }, - { no: 3, name: "ACCOUNT_STATUS_FAILED" }, -]); - -/** - * DEXFeatures defines available features for DEX accounts - * - * @generated from enum dex.v1.DEXFeatures - */ -export enum DEXFeatures { - /** - * Basic swap functionality - * - * @generated from enum value: DEX_FEATURE_SWAP = 0; - */ - DEX_FEATURE_SWAP = 0, - - /** - * Liquidity provision - * - * @generated from enum value: DEX_FEATURE_LIQUIDITY = 1; - */ - DEX_FEATURE_LIQUIDITY = 1, - - /** - * Limit orders - * - * @generated from enum value: DEX_FEATURE_ORDERS = 2; - */ - DEX_FEATURE_ORDERS = 2, - - /** - * Staking operations - * - * @generated from enum value: DEX_FEATURE_STAKING = 3; - */ - DEX_FEATURE_STAKING = 3, - - /** - * Governance participation - * - * @generated from enum value: DEX_FEATURE_GOVERNANCE = 4; - */ - DEX_FEATURE_GOVERNANCE = 4, -} -// Retrieve enum metadata with: proto3.getEnumType(DEXFeatures) -proto3.util.setEnumType(DEXFeatures, "dex.v1.DEXFeatures", [ - { no: 0, name: "DEX_FEATURE_SWAP" }, - { no: 1, name: "DEX_FEATURE_LIQUIDITY" }, - { no: 2, name: "DEX_FEATURE_ORDERS" }, - { no: 3, name: "DEX_FEATURE_STAKING" }, - { no: 4, name: "DEX_FEATURE_GOVERNANCE" }, -]); - -/** - * InterchainDEXAccount represents a DEX account on a remote chain - * - * @generated from message dex.v1.InterchainDEXAccount - */ -export class InterchainDEXAccount extends Message { - /** - * DID controller of this account - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to the remote chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Remote chain ID (e.g., osmosis-1) - * - * @generated from field: string host_chain_id = 3; - */ - hostChainId = ""; - - /** - * Account address on the remote chain - * - * @generated from field: string account_address = 4; - */ - accountAddress = ""; - - /** - * ICA port ID for this account - * - * @generated from field: string port_id = 5; - */ - portId = ""; - - /** - * Account creation timestamp - * - * @generated from field: google.protobuf.Timestamp created_at = 6; - */ - createdAt?: Timestamp; - - /** - * Enabled features for this account - * - * @generated from field: repeated string enabled_features = 7; - */ - enabledFeatures: string[] = []; - - /** - * Account status - * - * @generated from field: dex.v1.AccountStatus status = 8; - */ - status = AccountStatus.PENDING; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.InterchainDEXAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "host_chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "account_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "created_at", kind: "message", T: Timestamp }, - { no: 7, name: "enabled_features", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 8, name: "status", kind: "enum", T: proto3.getEnumType(AccountStatus) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InterchainDEXAccount { - return new InterchainDEXAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InterchainDEXAccount { - return new InterchainDEXAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InterchainDEXAccount { - return new InterchainDEXAccount().fromJsonString(jsonString, options); - } - - static equals(a: InterchainDEXAccount | PlainMessage | undefined, b: InterchainDEXAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(InterchainDEXAccount, a, b); - } -} - -/** - * DEXActivity represents a DEX operation activity record - * - * @generated from message dex.v1.DEXActivity - */ -export class DEXActivity extends Message { - /** - * Type of activity (swap, provide_liquidity, remove_liquidity, create_order, cancel_order) - * - * @generated from field: string type = 1; - */ - type = ""; - - /** - * DID that performed the activity - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * Connection ID where the activity occurred - * - * @generated from field: string connection_id = 3; - */ - connectionId = ""; - - /** - * Transaction hash of the activity - * - * @generated from field: string tx_hash = 4; - */ - txHash = ""; - - /** - * Block height when the activity occurred - * - * @generated from field: int64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - /** - * Timestamp of the activity - * - * @generated from field: google.protobuf.Timestamp timestamp = 6; - */ - timestamp?: Timestamp; - - /** - * Activity-specific details (JSON encoded) - * - * @generated from field: string details = 7; - */ - details = ""; - - /** - * Status of the activity (pending, success, failed) - * - * @generated from field: string status = 8; - */ - status = ""; - - /** - * Amount involved in the activity (if applicable) - * - * @generated from field: repeated cosmos.base.v1beta1.Coin amount = 9; - */ - amount: Coin[] = []; - - /** - * Gas used for the activity - * - * @generated from field: uint64 gas_used = 10; - */ - gasUsed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.DEXActivity"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "block_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "timestamp", kind: "message", T: Timestamp }, - { no: 7, name: "details", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "amount", kind: "message", T: Coin, repeated: true }, - { no: 10, name: "gas_used", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DEXActivity { - return new DEXActivity().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DEXActivity { - return new DEXActivity().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DEXActivity { - return new DEXActivity().fromJsonString(jsonString, options); - } - - static equals(a: DEXActivity | PlainMessage | undefined, b: DEXActivity | PlainMessage | undefined): boolean { - return proto3.util.equals(DEXActivity, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/v1/query_cosmes.ts b/packages/es/src/protobufs/dex/v1/query_cosmes.ts deleted file mode 100644 index ab5995888..000000000 --- a/packages/es/src/protobufs/dex/v1/query_cosmes.ts +++ /dev/null @@ -1,128 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file dex/v1/query.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryAccountRequest, QueryAccountResponse, QueryAccountsRequest, QueryAccountsResponse, QueryBalanceRequest, QueryBalanceResponse, QueryHistoryRequest, QueryHistoryResponse, QueryOrdersRequest, QueryOrdersResponse, QueryParamsRequest, QueryParamsResponse, QueryPoolRequest, QueryPoolResponse } from "./query_pb.js"; - -const TYPE_NAME = "dex.v1.Query"; - -/** - * Params queries the parameters of the module - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * Account queries a DEX account by DID and connection - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Account - */ -export const QueryAccountService = { - typeName: TYPE_NAME, - method: "Account", - Request: QueryAccountRequest, - Response: QueryAccountResponse, -} as const; - -/** - * Accounts queries all DEX accounts for a DID - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Accounts - */ -export const QueryAccountsService = { - typeName: TYPE_NAME, - method: "Accounts", - Request: QueryAccountsRequest, - Response: QueryAccountsResponse, -} as const; - -/** - * Balance queries remote chain balance - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Balance - */ -export const QueryBalanceService = { - typeName: TYPE_NAME, - method: "Balance", - Request: QueryBalanceRequest, - Response: QueryBalanceResponse, -} as const; - -/** - * Pool queries pool information - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Pool - */ -export const QueryPoolService = { - typeName: TYPE_NAME, - method: "Pool", - Request: QueryPoolRequest, - Response: QueryPoolResponse, -} as const; - -/** - * Orders queries orders for a DID - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.Orders - */ -export const QueryOrdersService = { - typeName: TYPE_NAME, - method: "Orders", - Request: QueryOrdersRequest, - Response: QueryOrdersResponse, -} as const; - -/** - * History queries transaction history - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_query_docs.md"}} - * - * @generated from rpc dex.v1.Query.History - */ -export const QueryHistoryService = { - typeName: TYPE_NAME, - method: "History", - Request: QueryHistoryRequest, - Response: QueryHistoryResponse, -} as const; - diff --git a/packages/es/src/protobufs/dex/v1/query_pb.ts b/packages/es/src/protobufs/dex/v1/query_pb.ts deleted file mode 100644 index ffd9a2862..000000000 --- a/packages/es/src/protobufs/dex/v1/query_pb.ts +++ /dev/null @@ -1,933 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/v1/query.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { InterchainDEXAccount } from "./ica_pb.js"; -import { PageRequest, PageResponse } from "../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * QueryParamsRequest is request type for Query/Params RPC method - * - * @generated from message dex.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is response type for Query/Params RPC method - * - * @generated from message dex.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params holds all the parameters of this module - * - * @generated from field: dex.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryAccountRequest is request type for Query/Account RPC method - * - * @generated from message dex.v1.QueryAccountRequest - */ -export class QueryAccountRequest extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountRequest | PlainMessage | undefined, b: QueryAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountRequest, a, b); - } -} - -/** - * QueryAccountResponse is response type for Query/Account RPC method - * - * @generated from message dex.v1.QueryAccountResponse - */ -export class QueryAccountResponse extends Message { - /** - * The DEX account - * - * @generated from field: dex.v1.InterchainDEXAccount account = 1; - */ - account?: InterchainDEXAccount; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account", kind: "message", T: InterchainDEXAccount }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountResponse | PlainMessage | undefined, b: QueryAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountResponse, a, b); - } -} - -/** - * QueryAccountsRequest is request type for Query/Accounts RPC method - * - * @generated from message dex.v1.QueryAccountsRequest - */ -export class QueryAccountsRequest extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * pagination defines optional pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryAccountsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountsRequest { - return new QueryAccountsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountsRequest { - return new QueryAccountsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountsRequest { - return new QueryAccountsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountsRequest | PlainMessage | undefined, b: QueryAccountsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountsRequest, a, b); - } -} - -/** - * QueryAccountsResponse is response type for Query/Accounts RPC method - * - * @generated from message dex.v1.QueryAccountsResponse - */ -export class QueryAccountsResponse extends Message { - /** - * List of DEX accounts - * - * @generated from field: repeated dex.v1.InterchainDEXAccount accounts = 1; - */ - accounts: InterchainDEXAccount[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryAccountsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "accounts", kind: "message", T: InterchainDEXAccount, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountsResponse { - return new QueryAccountsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountsResponse { - return new QueryAccountsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountsResponse { - return new QueryAccountsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountsResponse | PlainMessage | undefined, b: QueryAccountsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountsResponse, a, b); - } -} - -/** - * QueryBalanceRequest is request type for Query/Balance RPC method - * - * @generated from message dex.v1.QueryBalanceRequest - */ -export class QueryBalanceRequest extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Optional specific denom to query - * - * @generated from field: string denom = 3; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryBalanceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBalanceRequest | PlainMessage | undefined, b: QueryBalanceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBalanceRequest, a, b); - } -} - -/** - * QueryBalanceResponse is response type for Query/Balance RPC method - * - * @generated from message dex.v1.QueryBalanceResponse - */ -export class QueryBalanceResponse extends Message { - /** - * Balances on the remote chain - * - * @generated from field: repeated cosmos.base.v1beta1.Coin balances = 1; - */ - balances: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryBalanceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balances", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBalanceResponse | PlainMessage | undefined, b: QueryBalanceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBalanceResponse, a, b); - } -} - -/** - * QueryPoolRequest is request type for Query/Pool RPC method - * - * @generated from message dex.v1.QueryPoolRequest - */ -export class QueryPoolRequest extends Message { - /** - * IBC connection ID - * - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * Pool ID to query - * - * @generated from field: string pool_id = 2; - */ - poolId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryPoolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolRequest | PlainMessage | undefined, b: QueryPoolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolRequest, a, b); - } -} - -/** - * QueryPoolResponse is response type for Query/Pool RPC method - * - * @generated from message dex.v1.QueryPoolResponse - */ -export class QueryPoolResponse extends Message { - /** - * Pool information - * - * @generated from field: dex.v1.PoolInfo pool = 1; - */ - pool?: PoolInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool", kind: "message", T: PoolInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolResponse | PlainMessage | undefined, b: QueryPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolResponse, a, b); - } -} - -/** - * PoolInfo contains pool information - * - * @generated from message dex.v1.PoolInfo - */ -export class PoolInfo extends Message { - /** - * Pool ID - * - * @generated from field: string pool_id = 1; - */ - poolId = ""; - - /** - * Pool assets - * - * @generated from field: repeated cosmos.base.v1beta1.Coin assets = 2; - */ - assets: Coin[] = []; - - /** - * Total shares - * - * @generated from field: string total_shares = 3; - */ - totalShares = ""; - - /** - * Swap fee - * - * @generated from field: string swap_fee = 4; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.PoolInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "assets", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "total_shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolInfo { - return new PoolInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolInfo { - return new PoolInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolInfo { - return new PoolInfo().fromJsonString(jsonString, options); - } - - static equals(a: PoolInfo | PlainMessage | undefined, b: PoolInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolInfo, a, b); - } -} - -/** - * QueryOrdersRequest is request type for Query/Orders RPC method - * - * @generated from message dex.v1.QueryOrdersRequest - */ -export class QueryOrdersRequest extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection ID - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Filter by status (optional) - * - * @generated from field: string status = 3; - */ - status = ""; - - /** - * pagination defines optional pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 4; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryOrdersRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryOrdersRequest { - return new QueryOrdersRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryOrdersRequest { - return new QueryOrdersRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryOrdersRequest { - return new QueryOrdersRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryOrdersRequest | PlainMessage | undefined, b: QueryOrdersRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryOrdersRequest, a, b); - } -} - -/** - * QueryOrdersResponse is response type for Query/Orders RPC method - * - * @generated from message dex.v1.QueryOrdersResponse - */ -export class QueryOrdersResponse extends Message { - /** - * List of orders - * - * @generated from field: repeated dex.v1.Order orders = 1; - */ - orders: Order[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryOrdersResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "orders", kind: "message", T: Order, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryOrdersResponse { - return new QueryOrdersResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryOrdersResponse { - return new QueryOrdersResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryOrdersResponse { - return new QueryOrdersResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryOrdersResponse | PlainMessage | undefined, b: QueryOrdersResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryOrdersResponse, a, b); - } -} - -/** - * Order represents a DEX order - * - * @generated from message dex.v1.Order - */ -export class Order extends Message { - /** - * Order ID - * - * @generated from field: string order_id = 1; - */ - orderId = ""; - - /** - * Order type - * - * @generated from field: string order_type = 2; - */ - orderType = ""; - - /** - * Sell token - * - * @generated from field: string sell_denom = 3; - */ - sellDenom = ""; - - /** - * Buy token - * - * @generated from field: string buy_denom = 4; - */ - buyDenom = ""; - - /** - * Amount - * - * @generated from field: string amount = 5; - */ - amount = ""; - - /** - * Price - * - * @generated from field: string price = 6; - */ - price = ""; - - /** - * Status - * - * @generated from field: string status = 7; - */ - status = ""; - - /** - * Creation time - * - * @generated from field: string created_at = 8; - */ - createdAt = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.Order"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "order_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sell_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "buy_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "created_at", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Order { - return new Order().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Order { - return new Order().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Order { - return new Order().fromJsonString(jsonString, options); - } - - static equals(a: Order | PlainMessage | undefined, b: Order | PlainMessage | undefined): boolean { - return proto3.util.equals(Order, a, b); - } -} - -/** - * QueryHistoryRequest is request type for Query/History RPC method - * - * @generated from message dex.v1.QueryHistoryRequest - */ -export class QueryHistoryRequest extends Message { - /** - * DID of the account owner - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Optional connection filter - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Optional operation type filter - * - * @generated from field: string operation_type = 3; - */ - operationType = ""; - - /** - * pagination defines optional pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 4; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryHistoryRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "operation_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryHistoryRequest { - return new QueryHistoryRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryHistoryRequest { - return new QueryHistoryRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryHistoryRequest { - return new QueryHistoryRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryHistoryRequest | PlainMessage | undefined, b: QueryHistoryRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryHistoryRequest, a, b); - } -} - -/** - * QueryHistoryResponse is response type for Query/History RPC method - * - * @generated from message dex.v1.QueryHistoryResponse - */ -export class QueryHistoryResponse extends Message { - /** - * List of historical transactions - * - * @generated from field: repeated dex.v1.Transaction transactions = 1; - */ - transactions: Transaction[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.QueryHistoryResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "transactions", kind: "message", T: Transaction, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryHistoryResponse { - return new QueryHistoryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryHistoryResponse { - return new QueryHistoryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryHistoryResponse { - return new QueryHistoryResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryHistoryResponse | PlainMessage | undefined, b: QueryHistoryResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryHistoryResponse, a, b); - } -} - -/** - * Transaction represents a historical transaction - * - * @generated from message dex.v1.Transaction - */ -export class Transaction extends Message { - /** - * Transaction ID - * - * @generated from field: string tx_id = 1; - */ - txId = ""; - - /** - * Operation type (swap, provide_liquidity, etc.) - * - * @generated from field: string operation_type = 2; - */ - operationType = ""; - - /** - * Connection ID - * - * @generated from field: string connection_id = 3; - */ - connectionId = ""; - - /** - * Transaction details (JSON) - * - * @generated from field: string details = 4; - */ - details = ""; - - /** - * Status - * - * @generated from field: string status = 5; - */ - status = ""; - - /** - * Timestamp - * - * @generated from field: string timestamp = 6; - */ - timestamp = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.Transaction"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "operation_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "details", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "timestamp", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Transaction { - return new Transaction().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Transaction { - return new Transaction().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Transaction { - return new Transaction().fromJsonString(jsonString, options); - } - - static equals(a: Transaction | PlainMessage | undefined, b: Transaction | PlainMessage | undefined): boolean { - return proto3.util.equals(Transaction, a, b); - } -} - diff --git a/packages/es/src/protobufs/dex/v1/tx_cosmes.ts b/packages/es/src/protobufs/dex/v1/tx_cosmes.ts deleted file mode 100644 index c0faf81f2..000000000 --- a/packages/es/src/protobufs/dex/v1/tx_cosmes.ts +++ /dev/null @@ -1,111 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file dex/v1/tx.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCancelOrder, MsgCancelOrderResponse, MsgCreateLimitOrder, MsgCreateLimitOrderResponse, MsgExecuteSwap, MsgExecuteSwapResponse, MsgProvideLiquidity, MsgProvideLiquidityResponse, MsgRegisterDEXAccount, MsgRegisterDEXAccountResponse, MsgRemoveLiquidity, MsgRemoveLiquidityResponse } from "./tx_pb.js"; - -const TYPE_NAME = "dex.v1.Msg"; - -/** - * RegisterDEXAccount creates a new ICA account for DEX operations - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.RegisterDEXAccount - */ -export const MsgRegisterDEXAccountService = { - typeName: TYPE_NAME, - method: "RegisterDEXAccount", - Request: MsgRegisterDEXAccount, - Response: MsgRegisterDEXAccountResponse, -} as const; - -/** - * ExecuteSwap performs a token swap on a remote chain - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.ExecuteSwap - */ -export const MsgExecuteSwapService = { - typeName: TYPE_NAME, - method: "ExecuteSwap", - Request: MsgExecuteSwap, - Response: MsgExecuteSwapResponse, -} as const; - -/** - * ProvideLiquidity adds liquidity to a pool - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.ProvideLiquidity - */ -export const MsgProvideLiquidityService = { - typeName: TYPE_NAME, - method: "ProvideLiquidity", - Request: MsgProvideLiquidity, - Response: MsgProvideLiquidityResponse, -} as const; - -/** - * RemoveLiquidity removes liquidity from a pool - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.RemoveLiquidity - */ -export const MsgRemoveLiquidityService = { - typeName: TYPE_NAME, - method: "RemoveLiquidity", - Request: MsgRemoveLiquidity, - Response: MsgRemoveLiquidityResponse, -} as const; - -/** - * CreateLimitOrder creates a limit order - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.CreateLimitOrder - */ -export const MsgCreateLimitOrderService = { - typeName: TYPE_NAME, - method: "CreateLimitOrder", - Request: MsgCreateLimitOrder, - Response: MsgCreateLimitOrderResponse, -} as const; - -/** - * CancelOrder cancels an existing order - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dex_tx_docs.md"}} - * - * @generated from rpc dex.v1.Msg.CancelOrder - */ -export const MsgCancelOrderService = { - typeName: TYPE_NAME, - method: "CancelOrder", - Request: MsgCancelOrder, - Response: MsgCancelOrderResponse, -} as const; - diff --git a/packages/es/src/protobufs/dex/v1/tx_pb.ts b/packages/es/src/protobufs/dex/v1/tx_pb.ts deleted file mode 100644 index 9fee6c4ce..000000000 --- a/packages/es/src/protobufs/dex/v1/tx_pb.ts +++ /dev/null @@ -1,845 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dex/v1/tx.proto (package dex.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * MsgRegisterDEXAccount registers a new ICA account for DEX operations - * - * @generated from message dex.v1.MsgRegisterDEXAccount - */ -export class MsgRegisterDEXAccount extends Message { - /** - * DID controller requesting the account - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to target chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Requested features for this account - * - * @generated from field: repeated string features = 3; - */ - features: string[] = []; - - /** - * Optional metadata - * - * @generated from field: string metadata = 4; - */ - metadata = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgRegisterDEXAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "features", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "metadata", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterDEXAccount { - return new MsgRegisterDEXAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterDEXAccount { - return new MsgRegisterDEXAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterDEXAccount { - return new MsgRegisterDEXAccount().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterDEXAccount | PlainMessage | undefined, b: MsgRegisterDEXAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterDEXAccount, a, b); - } -} - -/** - * MsgRegisterDEXAccountResponse defines the response - * - * @generated from message dex.v1.MsgRegisterDEXAccountResponse - */ -export class MsgRegisterDEXAccountResponse extends Message { - /** - * Generated port ID for the account - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * Account address on remote chain (once available) - * - * @generated from field: string account_address = 2; - */ - accountAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgRegisterDEXAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "account_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterDEXAccountResponse { - return new MsgRegisterDEXAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterDEXAccountResponse { - return new MsgRegisterDEXAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterDEXAccountResponse { - return new MsgRegisterDEXAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterDEXAccountResponse | PlainMessage | undefined, b: MsgRegisterDEXAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterDEXAccountResponse, a, b); - } -} - -/** - * MsgExecuteSwap executes a token swap on a remote chain - * - * @generated from message dex.v1.MsgExecuteSwap - */ -export class MsgExecuteSwap extends Message { - /** - * DID initiating the swap - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to DEX chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Token to swap from - * - * @generated from field: string source_denom = 3; - */ - sourceDenom = ""; - - /** - * Token to swap to - * - * @generated from field: string target_denom = 4; - */ - targetDenom = ""; - - /** - * Amount to swap - * - * @generated from field: string amount = 5; - */ - amount = ""; - - /** - * Minimum amount out (slippage protection) - * - * @generated from field: string min_amount_out = 6; - */ - minAmountOut = ""; - - /** - * Optional specific route - * - * @generated from field: string route = 7; - */ - route = ""; - - /** - * UCAN authorization token - * - * @generated from field: string ucan_token = 8; - */ - ucanToken = ""; - - /** - * Timeout for the swap - * - * @generated from field: google.protobuf.Timestamp timeout = 9; - */ - timeout?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgExecuteSwap"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "source_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "target_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "min_amount_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "route", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "ucan_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "timeout", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExecuteSwap { - return new MsgExecuteSwap().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExecuteSwap { - return new MsgExecuteSwap().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExecuteSwap { - return new MsgExecuteSwap().fromJsonString(jsonString, options); - } - - static equals(a: MsgExecuteSwap | PlainMessage | undefined, b: MsgExecuteSwap | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExecuteSwap, a, b); - } -} - -/** - * MsgExecuteSwapResponse defines the response - * - * @generated from message dex.v1.MsgExecuteSwapResponse - */ -export class MsgExecuteSwapResponse extends Message { - /** - * Transaction ID on remote chain - * - * @generated from field: string tx_hash = 1; - */ - txHash = ""; - - /** - * Actual amount received - * - * @generated from field: string amount_received = 2; - */ - amountReceived = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgExecuteSwapResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount_received", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExecuteSwapResponse { - return new MsgExecuteSwapResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExecuteSwapResponse { - return new MsgExecuteSwapResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExecuteSwapResponse { - return new MsgExecuteSwapResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExecuteSwapResponse | PlainMessage | undefined, b: MsgExecuteSwapResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExecuteSwapResponse, a, b); - } -} - -/** - * MsgProvideLiquidity adds liquidity to a pool - * - * @generated from message dex.v1.MsgProvideLiquidity - */ -export class MsgProvideLiquidity extends Message { - /** - * DID providing liquidity - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to DEX chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Pool ID to add liquidity to - * - * @generated from field: string pool_id = 3; - */ - poolId = ""; - - /** - * Assets to provide - * - * @generated from field: repeated cosmos.base.v1beta1.Coin assets = 4; - */ - assets: Coin[] = []; - - /** - * Minimum shares to receive (slippage protection) - * - * @generated from field: string min_shares = 5; - */ - minShares = ""; - - /** - * UCAN authorization token - * - * @generated from field: string ucan_token = 6; - */ - ucanToken = ""; - - /** - * Timeout for the operation - * - * @generated from field: google.protobuf.Timestamp timeout = 7; - */ - timeout?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgProvideLiquidity"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "assets", kind: "message", T: Coin, repeated: true }, - { no: 5, name: "min_shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "ucan_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "timeout", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgProvideLiquidity { - return new MsgProvideLiquidity().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgProvideLiquidity { - return new MsgProvideLiquidity().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgProvideLiquidity { - return new MsgProvideLiquidity().fromJsonString(jsonString, options); - } - - static equals(a: MsgProvideLiquidity | PlainMessage | undefined, b: MsgProvideLiquidity | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgProvideLiquidity, a, b); - } -} - -/** - * MsgProvideLiquidityResponse defines the response - * - * @generated from message dex.v1.MsgProvideLiquidityResponse - */ -export class MsgProvideLiquidityResponse extends Message { - /** - * Transaction ID on remote chain - * - * @generated from field: string tx_hash = 1; - */ - txHash = ""; - - /** - * LP tokens received - * - * @generated from field: string shares_received = 2; - */ - sharesReceived = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgProvideLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "shares_received", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgProvideLiquidityResponse { - return new MsgProvideLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgProvideLiquidityResponse { - return new MsgProvideLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgProvideLiquidityResponse { - return new MsgProvideLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgProvideLiquidityResponse | PlainMessage | undefined, b: MsgProvideLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgProvideLiquidityResponse, a, b); - } -} - -/** - * MsgRemoveLiquidity removes liquidity from a pool - * - * @generated from message dex.v1.MsgRemoveLiquidity - */ -export class MsgRemoveLiquidity extends Message { - /** - * DID removing liquidity - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to DEX chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Pool ID to remove liquidity from - * - * @generated from field: string pool_id = 3; - */ - poolId = ""; - - /** - * Amount of shares to remove - * - * @generated from field: string shares = 4; - */ - shares = ""; - - /** - * Minimum assets to receive - * - * @generated from field: repeated cosmos.base.v1beta1.Coin min_amounts = 5; - */ - minAmounts: Coin[] = []; - - /** - * UCAN authorization token - * - * @generated from field: string ucan_token = 6; - */ - ucanToken = ""; - - /** - * Timeout for the operation - * - * @generated from field: google.protobuf.Timestamp timeout = 7; - */ - timeout?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgRemoveLiquidity"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "min_amounts", kind: "message", T: Coin, repeated: true }, - { no: 6, name: "ucan_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "timeout", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveLiquidity { - return new MsgRemoveLiquidity().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveLiquidity { - return new MsgRemoveLiquidity().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveLiquidity { - return new MsgRemoveLiquidity().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveLiquidity | PlainMessage | undefined, b: MsgRemoveLiquidity | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveLiquidity, a, b); - } -} - -/** - * MsgRemoveLiquidityResponse defines the response - * - * @generated from message dex.v1.MsgRemoveLiquidityResponse - */ -export class MsgRemoveLiquidityResponse extends Message { - /** - * Transaction ID on remote chain - * - * @generated from field: string tx_hash = 1; - */ - txHash = ""; - - /** - * Assets received - * - * @generated from field: repeated cosmos.base.v1beta1.Coin assets_received = 2; - */ - assetsReceived: Coin[] = []; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgRemoveLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "assets_received", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveLiquidityResponse { - return new MsgRemoveLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveLiquidityResponse { - return new MsgRemoveLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveLiquidityResponse { - return new MsgRemoveLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveLiquidityResponse | PlainMessage | undefined, b: MsgRemoveLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveLiquidityResponse, a, b); - } -} - -/** - * MsgCreateLimitOrder creates a limit order - * - * @generated from message dex.v1.MsgCreateLimitOrder - */ -export class MsgCreateLimitOrder extends Message { - /** - * DID creating the order - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to DEX chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Token to sell - * - * @generated from field: string sell_denom = 3; - */ - sellDenom = ""; - - /** - * Token to buy - * - * @generated from field: string buy_denom = 4; - */ - buyDenom = ""; - - /** - * Amount to sell - * - * @generated from field: string amount = 5; - */ - amount = ""; - - /** - * Price per unit - * - * @generated from field: string price = 6; - */ - price = ""; - - /** - * Order expiration - * - * @generated from field: google.protobuf.Timestamp expiration = 7; - */ - expiration?: Timestamp; - - /** - * UCAN authorization token - * - * @generated from field: string ucan_token = 8; - */ - ucanToken = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgCreateLimitOrder"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sell_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "buy_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "expiration", kind: "message", T: Timestamp }, - { no: 8, name: "ucan_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateLimitOrder { - return new MsgCreateLimitOrder().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateLimitOrder { - return new MsgCreateLimitOrder().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateLimitOrder { - return new MsgCreateLimitOrder().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateLimitOrder | PlainMessage | undefined, b: MsgCreateLimitOrder | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateLimitOrder, a, b); - } -} - -/** - * MsgCreateLimitOrderResponse defines the response - * - * @generated from message dex.v1.MsgCreateLimitOrderResponse - */ -export class MsgCreateLimitOrderResponse extends Message { - /** - * Order ID on remote chain - * - * @generated from field: string order_id = 1; - */ - orderId = ""; - - /** - * Transaction ID - * - * @generated from field: string tx_hash = 2; - */ - txHash = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgCreateLimitOrderResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateLimitOrderResponse { - return new MsgCreateLimitOrderResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateLimitOrderResponse { - return new MsgCreateLimitOrderResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateLimitOrderResponse { - return new MsgCreateLimitOrderResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateLimitOrderResponse | PlainMessage | undefined, b: MsgCreateLimitOrderResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateLimitOrderResponse, a, b); - } -} - -/** - * MsgCancelOrder cancels an existing order - * - * @generated from message dex.v1.MsgCancelOrder - */ -export class MsgCancelOrder extends Message { - /** - * DID canceling the order - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * IBC connection to DEX chain - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * Order ID to cancel - * - * @generated from field: string order_id = 3; - */ - orderId = ""; - - /** - * UCAN authorization token - * - * @generated from field: string ucan_token = 4; - */ - ucanToken = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgCancelOrder"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "order_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "ucan_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCancelOrder { - return new MsgCancelOrder().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCancelOrder { - return new MsgCancelOrder().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCancelOrder { - return new MsgCancelOrder().fromJsonString(jsonString, options); - } - - static equals(a: MsgCancelOrder | PlainMessage | undefined, b: MsgCancelOrder | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCancelOrder, a, b); - } -} - -/** - * MsgCancelOrderResponse defines the response - * - * @generated from message dex.v1.MsgCancelOrderResponse - */ -export class MsgCancelOrderResponse extends Message { - /** - * Transaction ID - * - * @generated from field: string tx_hash = 1; - */ - txHash = ""; - - /** - * IBC packet sequence - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dex.v1.MsgCancelOrderResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCancelOrderResponse { - return new MsgCancelOrderResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCancelOrderResponse { - return new MsgCancelOrderResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCancelOrderResponse { - return new MsgCancelOrderResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCancelOrderResponse | PlainMessage | undefined, b: MsgCancelOrderResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCancelOrderResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/module/v1/module_pb.ts b/packages/es/src/protobufs/did/module/v1/module_pb.ts deleted file mode 100644 index 9a3082c29..000000000 --- a/packages/es/src/protobufs/did/module/v1/module_pb.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/module/v1/module.proto (package did.module.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Module is the app config object of the module. - * Learn more: https://docs.cosmos.network/main/building-modules/depinject - * - * @generated from message did.module.v1.Module - */ -export class Module extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.module.v1.Module"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals(a: Module | PlainMessage | undefined, b: Module | PlainMessage | undefined): boolean { - return proto3.util.equals(Module, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/events_pb.ts b/packages/es/src/protobufs/did/v1/events_pb.ts deleted file mode 100644 index 05700f048..000000000 --- a/packages/es/src/protobufs/did/v1/events_pb.ts +++ /dev/null @@ -1,771 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/events.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * EventDIDCreated is emitted when a new DID is created - * - * @generated from message did.v1.EventDIDCreated - */ -export class EventDIDCreated extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Creator address - * - * @generated from field: string creator = 2; - */ - creator = ""; - - /** - * Public keys added - * - * @generated from field: repeated string public_keys = 3; - */ - publicKeys: string[] = []; - - /** - * Services added - * - * @generated from field: repeated string services = 4; - */ - services: string[] = []; - - /** - * Creation timestamp - * - * @generated from field: google.protobuf.Timestamp created_at = 5; - */ - createdAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 6; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventDIDCreated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "public_keys", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "services", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "created_at", kind: "message", T: Timestamp }, - { no: 6, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDIDCreated { - return new EventDIDCreated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDIDCreated { - return new EventDIDCreated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDIDCreated { - return new EventDIDCreated().fromJsonString(jsonString, options); - } - - static equals(a: EventDIDCreated | PlainMessage | undefined, b: EventDIDCreated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDIDCreated, a, b); - } -} - -/** - * EventDIDUpdated is emitted when a DID is updated - * - * @generated from message did.v1.EventDIDUpdated - */ -export class EventDIDUpdated extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Updater address - * - * @generated from field: string updater = 2; - */ - updater = ""; - - /** - * Fields that were updated - * - * @generated from field: repeated string fields_updated = 3; - */ - fieldsUpdated: string[] = []; - - /** - * Update timestamp - * - * @generated from field: google.protobuf.Timestamp updated_at = 4; - */ - updatedAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventDIDUpdated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "updater", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "fields_updated", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "updated_at", kind: "message", T: Timestamp }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDIDUpdated { - return new EventDIDUpdated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDIDUpdated { - return new EventDIDUpdated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDIDUpdated { - return new EventDIDUpdated().fromJsonString(jsonString, options); - } - - static equals(a: EventDIDUpdated | PlainMessage | undefined, b: EventDIDUpdated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDIDUpdated, a, b); - } -} - -/** - * EventDIDDeactivated is emitted when a DID is deactivated - * - * @generated from message did.v1.EventDIDDeactivated - */ -export class EventDIDDeactivated extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Deactivator address - * - * @generated from field: string deactivator = 2; - */ - deactivator = ""; - - /** - * Deactivation timestamp - * - * @generated from field: google.protobuf.Timestamp deactivated_at = 3; - */ - deactivatedAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventDIDDeactivated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "deactivator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "deactivated_at", kind: "message", T: Timestamp }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDIDDeactivated { - return new EventDIDDeactivated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDIDDeactivated { - return new EventDIDDeactivated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDIDDeactivated { - return new EventDIDDeactivated().fromJsonString(jsonString, options); - } - - static equals(a: EventDIDDeactivated | PlainMessage | undefined, b: EventDIDDeactivated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDIDDeactivated, a, b); - } -} - -/** - * EventVerificationMethodAdded is emitted when a verification method is added - * - * @generated from message did.v1.EventVerificationMethodAdded - */ -export class EventVerificationMethodAdded extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Method ID - * - * @generated from field: string method_id = 2; - */ - methodId = ""; - - /** - * Key type - * - * @generated from field: string key_type = 3; - */ - keyType = ""; - - /** - * Public key (encoded) - * - * @generated from field: string public_key = 4; - */ - publicKey = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventVerificationMethodAdded"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "key_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventVerificationMethodAdded { - return new EventVerificationMethodAdded().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventVerificationMethodAdded { - return new EventVerificationMethodAdded().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventVerificationMethodAdded { - return new EventVerificationMethodAdded().fromJsonString(jsonString, options); - } - - static equals(a: EventVerificationMethodAdded | PlainMessage | undefined, b: EventVerificationMethodAdded | PlainMessage | undefined): boolean { - return proto3.util.equals(EventVerificationMethodAdded, a, b); - } -} - -/** - * EventVerificationMethodRemoved is emitted when a verification method is removed - * - * @generated from message did.v1.EventVerificationMethodRemoved - */ -export class EventVerificationMethodRemoved extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Method ID - * - * @generated from field: string method_id = 2; - */ - methodId = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 3; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventVerificationMethodRemoved"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventVerificationMethodRemoved { - return new EventVerificationMethodRemoved().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventVerificationMethodRemoved { - return new EventVerificationMethodRemoved().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventVerificationMethodRemoved { - return new EventVerificationMethodRemoved().fromJsonString(jsonString, options); - } - - static equals(a: EventVerificationMethodRemoved | PlainMessage | undefined, b: EventVerificationMethodRemoved | PlainMessage | undefined): boolean { - return proto3.util.equals(EventVerificationMethodRemoved, a, b); - } -} - -/** - * EventServiceAdded is emitted when a service is added to a DID - * - * @generated from message did.v1.EventServiceAdded - */ -export class EventServiceAdded extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Service ID - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - /** - * Service type - * - * @generated from field: string type = 3; - */ - type = ""; - - /** - * Service endpoint - * - * @generated from field: string endpoint = 4; - */ - endpoint = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventServiceAdded"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventServiceAdded { - return new EventServiceAdded().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventServiceAdded { - return new EventServiceAdded().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventServiceAdded { - return new EventServiceAdded().fromJsonString(jsonString, options); - } - - static equals(a: EventServiceAdded | PlainMessage | undefined, b: EventServiceAdded | PlainMessage | undefined): boolean { - return proto3.util.equals(EventServiceAdded, a, b); - } -} - -/** - * EventServiceRemoved is emitted when a service is removed from a DID - * - * @generated from message did.v1.EventServiceRemoved - */ -export class EventServiceRemoved extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Service ID - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 3; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventServiceRemoved"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventServiceRemoved { - return new EventServiceRemoved().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventServiceRemoved { - return new EventServiceRemoved().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventServiceRemoved { - return new EventServiceRemoved().fromJsonString(jsonString, options); - } - - static equals(a: EventServiceRemoved | PlainMessage | undefined, b: EventServiceRemoved | PlainMessage | undefined): boolean { - return proto3.util.equals(EventServiceRemoved, a, b); - } -} - -/** - * EventCredentialIssued is emitted when a verifiable credential is issued - * - * @generated from message did.v1.EventCredentialIssued - */ -export class EventCredentialIssued extends Message { - /** - * Credential ID - * - * @generated from field: string credential_id = 1; - */ - credentialId = ""; - - /** - * Issuer DID - * - * @generated from field: string issuer = 2; - */ - issuer = ""; - - /** - * Subject DID - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * Credential type - * - * @generated from field: string type = 4; - */ - type = ""; - - /** - * Issuance timestamp - * - * @generated from field: google.protobuf.Timestamp issued_at = 5; - */ - issuedAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 6; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventCredentialIssued"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "issued_at", kind: "message", T: Timestamp }, - { no: 6, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventCredentialIssued { - return new EventCredentialIssued().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventCredentialIssued { - return new EventCredentialIssued().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventCredentialIssued { - return new EventCredentialIssued().fromJsonString(jsonString, options); - } - - static equals(a: EventCredentialIssued | PlainMessage | undefined, b: EventCredentialIssued | PlainMessage | undefined): boolean { - return proto3.util.equals(EventCredentialIssued, a, b); - } -} - -/** - * EventCredentialRevoked is emitted when a credential is revoked - * - * @generated from message did.v1.EventCredentialRevoked - */ -export class EventCredentialRevoked extends Message { - /** - * Credential ID - * - * @generated from field: string credential_id = 1; - */ - credentialId = ""; - - /** - * Revoker DID - * - * @generated from field: string revoker = 2; - */ - revoker = ""; - - /** - * Revocation reason - * - * @generated from field: string reason = 3; - */ - reason = ""; - - /** - * Revocation timestamp - * - * @generated from field: google.protobuf.Timestamp revoked_at = 4; - */ - revokedAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventCredentialRevoked"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "revoker", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "reason", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "revoked_at", kind: "message", T: Timestamp }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventCredentialRevoked { - return new EventCredentialRevoked().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventCredentialRevoked { - return new EventCredentialRevoked().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventCredentialRevoked { - return new EventCredentialRevoked().fromJsonString(jsonString, options); - } - - static equals(a: EventCredentialRevoked | PlainMessage | undefined, b: EventCredentialRevoked | PlainMessage | undefined): boolean { - return proto3.util.equals(EventCredentialRevoked, a, b); - } -} - -/** - * EventWebAuthnRegistered is emitted when a WebAuthn credential is registered - * - * @generated from message did.v1.EventWebAuthnRegistered - */ -export class EventWebAuthnRegistered extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * WebAuthn credential ID - * - * @generated from field: string credential_id = 2; - */ - credentialId = ""; - - /** - * Attestation type - * - * @generated from field: string attestation_type = 3; - */ - attestationType = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventWebAuthnRegistered"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "attestation_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventWebAuthnRegistered { - return new EventWebAuthnRegistered().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventWebAuthnRegistered { - return new EventWebAuthnRegistered().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventWebAuthnRegistered { - return new EventWebAuthnRegistered().fromJsonString(jsonString, options); - } - - static equals(a: EventWebAuthnRegistered | PlainMessage | undefined, b: EventWebAuthnRegistered | PlainMessage | undefined): boolean { - return proto3.util.equals(EventWebAuthnRegistered, a, b); - } -} - -/** - * EventExternalWalletLinked is emitted when an external wallet is linked - * - * @generated from message did.v1.EventExternalWalletLinked - */ -export class EventExternalWalletLinked extends Message { - /** - * DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * Wallet type (ethereum, bitcoin, etc.) - * - * @generated from field: string wallet_type = 2; - */ - walletType = ""; - - /** - * Wallet address - * - * @generated from field: string wallet_address = 3; - */ - walletAddress = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.EventExternalWalletLinked"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "wallet_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "wallet_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventExternalWalletLinked { - return new EventExternalWalletLinked().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventExternalWalletLinked { - return new EventExternalWalletLinked().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventExternalWalletLinked { - return new EventExternalWalletLinked().fromJsonString(jsonString, options); - } - - static equals(a: EventExternalWalletLinked | PlainMessage | undefined, b: EventExternalWalletLinked | PlainMessage | undefined): boolean { - return proto3.util.equals(EventExternalWalletLinked, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/genesis_pb.ts b/packages/es/src/protobufs/did/v1/genesis_pb.ts deleted file mode 100644 index f46a99bae..000000000 --- a/packages/es/src/protobufs/did/v1/genesis_pb.ts +++ /dev/null @@ -1,320 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/genesis.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * GenesisState defines the module genesis state - * - * @generated from message did.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * Params defines all the parameters of the module. - * - * @generated from field: did.v1.Params params = 1; - */ - params?: Params; - - /** - * Export format version for future migrations - * - * @generated from field: uint32 export_version = 2; - */ - exportVersion = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "export_version", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Params defines the set of module parameters. - * - * @generated from message did.v1.Params - */ -export class Params extends Message { - /** - * @generated from field: did.v1.DocumentParams document = 1; - */ - document?: DocumentParams; - - /** - * @generated from field: did.v1.WebauthnParams webauthn = 2; - */ - webauthn?: WebauthnParams; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "document", kind: "message", T: DocumentParams }, - { no: 2, name: "webauthn", kind: "message", T: WebauthnParams }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * DocumentParams defines the parameters for the DID module. - * - * @generated from message did.v1.DocumentParams - */ -export class DocumentParams extends Message { - /** - * AutoCreateVault enables automatic vault creation upon DID registration - * - * @generated from field: bool auto_create_vault = 1; - */ - autoCreateVault = false; - - /** - * MaxVerificationMethods limits the number of verification methods - * - * @generated from field: int32 max_verification_methods = 2; - */ - maxVerificationMethods = 0; - - /** - * MaxServiceEndpoints limits the number of service endpoints - * - * @generated from field: int32 max_service_endpoints = 3; - */ - maxServiceEndpoints = 0; - - /** - * MaxControllers limits the number of controllers per DID document - * - * @generated from field: int32 max_controllers = 4; - */ - maxControllers = 0; - - /** - * DidDocumentMaxSize limits the maximum size of a DID document in bytes - * - * @generated from field: int64 did_document_max_size = 5; - */ - didDocumentMaxSize = protoInt64.zero; - - /** - * DidResolutionTimeout is the timeout for resolution operations in seconds - * - * @generated from field: int64 did_resolution_timeout = 6; - */ - didResolutionTimeout = protoInt64.zero; - - /** - * KeyRotationInterval is the recommended interval for key rotation in seconds - * - * @generated from field: int64 key_rotation_interval = 7; - */ - keyRotationInterval = protoInt64.zero; - - /** - * CredentialLifetime is the default lifetime in seconds - * - * @generated from field: int64 credential_lifetime = 8; - */ - credentialLifetime = protoInt64.zero; - - /** - * Supported Assertion methods - * - * @generated from field: repeated string supported_assertion_methods = 9; - */ - supportedAssertionMethods: string[] = []; - - /** - * Supported Authentication methods - * - * @generated from field: repeated string supported_authentication_methods = 10; - */ - supportedAuthenticationMethods: string[] = []; - - /** - * Supported Invocation methods - * - * @generated from field: repeated string supported_invocation_methods = 11; - */ - supportedInvocationMethods: string[] = []; - - /** - * Supported Delegation methods - * - * @generated from field: repeated string supported_delegation_methods = 12; - */ - supportedDelegationMethods: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.DocumentParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "auto_create_vault", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "max_verification_methods", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 3, name: "max_service_endpoints", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 4, name: "max_controllers", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 5, name: "did_document_max_size", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "did_resolution_timeout", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "key_rotation_interval", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 8, name: "credential_lifetime", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 9, name: "supported_assertion_methods", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "supported_authentication_methods", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 11, name: "supported_invocation_methods", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 12, name: "supported_delegation_methods", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DocumentParams { - return new DocumentParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DocumentParams { - return new DocumentParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DocumentParams { - return new DocumentParams().fromJsonString(jsonString, options); - } - - static equals(a: DocumentParams | PlainMessage | undefined, b: DocumentParams | PlainMessage | undefined): boolean { - return proto3.util.equals(DocumentParams, a, b); - } -} - -/** - * WebauthnParams defines the parameters for the WebAuthn module. - * - * @generated from message did.v1.WebauthnParams - */ -export class WebauthnParams extends Message { - /** - * ChallengeTimeout is the default timeout in seconds - * - * @generated from field: int64 challenge_timeout = 1; - */ - challengeTimeout = protoInt64.zero; - - /** - * AllowedOrigins are the allowed WebAuthn origins for credential creation - * - * @generated from field: repeated string allowed_origins = 2; - */ - allowedOrigins: string[] = []; - - /** - * SupportedAlgorithms are the supported signature for WebAuthn credentials - * - * @generated from field: repeated string supported_algorithms = 3; - */ - supportedAlgorithms: string[] = []; - - /** - * RequireUserVerification enforces verification for WebAuthn credentials - * - * @generated from field: bool require_user_verification = 4; - */ - requireUserVerification = false; - - /** - * MaxCredentialsPerDID limits the number of WebAuthn credentials per DID - * - * @generated from field: int32 max_credentials_per_did = 5; - */ - maxCredentialsPerDid = 0; - - /** - * DefaultRPID is the default Relying Party ID for WebAuthn operations - * - * @generated from field: string default_rp_id = 6; - */ - defaultRpId = ""; - - /** - * DefaultRPName is the default Relying Party name for WebAuthn operations - * - * @generated from field: string default_rp_name = 7; - */ - defaultRpName = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.WebauthnParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "challenge_timeout", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: "allowed_origins", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 3, name: "supported_algorithms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "require_user_verification", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: "max_credentials_per_did", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 6, name: "default_rp_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "default_rp_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): WebauthnParams { - return new WebauthnParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): WebauthnParams { - return new WebauthnParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): WebauthnParams { - return new WebauthnParams().fromJsonString(jsonString, options); - } - - static equals(a: WebauthnParams | PlainMessage | undefined, b: WebauthnParams | PlainMessage | undefined): boolean { - return proto3.util.equals(WebauthnParams, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/query_cosmes.ts b/packages/es/src/protobufs/did/v1/query_cosmes.ts deleted file mode 100644 index 112d75db0..000000000 --- a/packages/es/src/protobufs/did/v1/query_cosmes.ts +++ /dev/null @@ -1,158 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file did/v1/query.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryGetCredentialsByDIDRequest, QueryGetCredentialsByDIDResponse, QueryGetDIDDocumentRequest, QueryGetDIDDocumentResponse, QueryGetDIDDocumentsByControllerRequest, QueryGetDIDDocumentsByControllerResponse, QueryGetServiceRequest, QueryGetServiceResponse, QueryGetVerifiableCredentialRequest, QueryGetVerifiableCredentialResponse, QueryGetVerificationMethodRequest, QueryGetVerificationMethodResponse, QueryListDIDDocumentsRequest, QueryListDIDDocumentsResponse, QueryListVerifiableCredentialsRequest, QueryListVerifiableCredentialsResponse, QueryLoginStartRequest, QueryLoginStartResponse, QueryParamsRequest, QueryParamsResponse, QueryRegisterStartRequest, QueryRegisterStartResponse, QueryResolveDIDRequest, QueryResolveDIDResponse } from "./query_pb.js"; - -const TYPE_NAME = "did.v1.Query"; - -/** - * Params queries all parameters of the module. - * - * @generated from rpc did.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * ResolveDID resolves a DID to its DID document - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "did_query_docs.md"}} - * - * @generated from rpc did.v1.Query.ResolveDID - */ -export const QueryResolveDIDService = { - typeName: TYPE_NAME, - method: "ResolveDID", - Request: QueryResolveDIDRequest, - Response: QueryResolveDIDResponse, -} as const; - -/** - * GetDIDDocument retrieves a DID document by its ID - * - * @generated from rpc did.v1.Query.GetDIDDocument - */ -export const QueryGetDIDDocumentService = { - typeName: TYPE_NAME, - method: "GetDIDDocument", - Request: QueryGetDIDDocumentRequest, - Response: QueryGetDIDDocumentResponse, -} as const; - -/** - * ListDIDDocuments lists all DID documents with pagination - * - * @generated from rpc did.v1.Query.ListDIDDocuments - */ -export const QueryListDIDDocumentsService = { - typeName: TYPE_NAME, - method: "ListDIDDocuments", - Request: QueryListDIDDocumentsRequest, - Response: QueryListDIDDocumentsResponse, -} as const; - -/** - * GetDIDDocumentsByController retrieves DID documents by controller - * - * @generated from rpc did.v1.Query.GetDIDDocumentsByController - */ -export const QueryGetDIDDocumentsByControllerService = { - typeName: TYPE_NAME, - method: "GetDIDDocumentsByController", - Request: QueryGetDIDDocumentsByControllerRequest, - Response: QueryGetDIDDocumentsByControllerResponse, -} as const; - -/** - * GetVerificationMethod retrieves a specific verification method - * - * @generated from rpc did.v1.Query.GetVerificationMethod - */ -export const QueryGetVerificationMethodService = { - typeName: TYPE_NAME, - method: "GetVerificationMethod", - Request: QueryGetVerificationMethodRequest, - Response: QueryGetVerificationMethodResponse, -} as const; - -/** - * GetService retrieves a specific service endpoint - * - * @generated from rpc did.v1.Query.GetService - */ -export const QueryGetServiceService = { - typeName: TYPE_NAME, - method: "GetService", - Request: QueryGetServiceRequest, - Response: QueryGetServiceResponse, -} as const; - -/** - * GetVerifiableCredential retrieves a verifiable credential by ID - * - * @generated from rpc did.v1.Query.GetVerifiableCredential - */ -export const QueryGetVerifiableCredentialService = { - typeName: TYPE_NAME, - method: "GetVerifiableCredential", - Request: QueryGetVerifiableCredentialRequest, - Response: QueryGetVerifiableCredentialResponse, -} as const; - -/** - * ListVerifiableCredentials lists all verifiable credentials with filtering options - * - * @generated from rpc did.v1.Query.ListVerifiableCredentials - */ -export const QueryListVerifiableCredentialsService = { - typeName: TYPE_NAME, - method: "ListVerifiableCredentials", - Request: QueryListVerifiableCredentialsRequest, - Response: QueryListVerifiableCredentialsResponse, -} as const; - -/** - * GetCredentialsByDID retrieves all credentials (verifiable and WebAuthn) associated with a DID - * - * @generated from rpc did.v1.Query.GetCredentialsByDID - */ -export const QueryGetCredentialsByDIDService = { - typeName: TYPE_NAME, - method: "GetCredentialsByDID", - Request: QueryGetCredentialsByDIDRequest, - Response: QueryGetCredentialsByDIDResponse, -} as const; - -/** - * RegisterStart represents the start of the registration process - * - * @generated from rpc did.v1.Query.RegisterStart - */ -export const QueryRegisterStartService = { - typeName: TYPE_NAME, - method: "RegisterStart", - Request: QueryRegisterStartRequest, - Response: QueryRegisterStartResponse, -} as const; - -/** - * LoginStart represents the start of the login process - * - * @generated from rpc did.v1.Query.LoginStart - */ -export const QueryLoginStartService = { - typeName: TYPE_NAME, - method: "LoginStart", - Request: QueryLoginStartRequest, - Response: QueryLoginStartResponse, -} as const; - diff --git a/packages/es/src/protobufs/did/v1/query_pb.ts b/packages/es/src/protobufs/did/v1/query_pb.ts deleted file mode 100644 index c1c865dcb..000000000 --- a/packages/es/src/protobufs/did/v1/query_pb.ts +++ /dev/null @@ -1,1240 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/query.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { DIDDocument, DIDDocumentMetadata, VerifiableCredential } from "./state_pb.js"; -import { PageRequest, PageResponse } from "../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Service, VerificationMethod, WebAuthnCredential } from "./types_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message did.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message did.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: did.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryResolveDIDRequest is the request type for the Query/ResolveDID RPC - * method. - * - * @generated from message did.v1.QueryResolveDIDRequest - */ -export class QueryResolveDIDRequest extends Message { - /** - * did is the DID to resolve - * - * @generated from field: string did = 1; - */ - did = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryResolveDIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryResolveDIDRequest { - return new QueryResolveDIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryResolveDIDRequest { - return new QueryResolveDIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryResolveDIDRequest { - return new QueryResolveDIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryResolveDIDRequest | PlainMessage | undefined, b: QueryResolveDIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryResolveDIDRequest, a, b); - } -} - -/** - * QueryResolveDIDResponse is the response type for the Query/ResolveDID RPC - * method. - * - * @generated from message did.v1.QueryResolveDIDResponse - */ -export class QueryResolveDIDResponse extends Message { - /** - * did_document is the resolved DID document - * - * @generated from field: did.v1.DIDDocument did_document = 1; - */ - didDocument?: DIDDocument; - - /** - * did_document_metadata contains metadata about the DID document - * - * @generated from field: did.v1.DIDDocumentMetadata did_document_metadata = 2; - */ - didDocumentMetadata?: DIDDocumentMetadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryResolveDIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did_document", kind: "message", T: DIDDocument }, - { no: 2, name: "did_document_metadata", kind: "message", T: DIDDocumentMetadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryResolveDIDResponse { - return new QueryResolveDIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryResolveDIDResponse { - return new QueryResolveDIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryResolveDIDResponse { - return new QueryResolveDIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryResolveDIDResponse | PlainMessage | undefined, b: QueryResolveDIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryResolveDIDResponse, a, b); - } -} - -/** - * QueryGetDIDDocumentRequest is the request type for the - * Query/GetDIDDocument RPC method. - * - * @generated from message did.v1.QueryGetDIDDocumentRequest - */ -export class QueryGetDIDDocumentRequest extends Message { - /** - * did is the DID to retrieve - * - * @generated from field: string did = 1; - */ - did = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetDIDDocumentRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetDIDDocumentRequest { - return new QueryGetDIDDocumentRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetDIDDocumentRequest { - return new QueryGetDIDDocumentRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetDIDDocumentRequest { - return new QueryGetDIDDocumentRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetDIDDocumentRequest | PlainMessage | undefined, b: QueryGetDIDDocumentRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetDIDDocumentRequest, a, b); - } -} - -/** - * QueryGetDIDDocumentResponse is the response type for the - * Query/GetDIDDocument RPC method. - * - * @generated from message did.v1.QueryGetDIDDocumentResponse - */ -export class QueryGetDIDDocumentResponse extends Message { - /** - * did_document is the retrieved DID document - * - * @generated from field: did.v1.DIDDocument did_document = 1; - */ - didDocument?: DIDDocument; - - /** - * did_document_metadata contains metadata about the DID document - * - * @generated from field: did.v1.DIDDocumentMetadata did_document_metadata = 2; - */ - didDocumentMetadata?: DIDDocumentMetadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetDIDDocumentResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did_document", kind: "message", T: DIDDocument }, - { no: 2, name: "did_document_metadata", kind: "message", T: DIDDocumentMetadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetDIDDocumentResponse { - return new QueryGetDIDDocumentResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetDIDDocumentResponse { - return new QueryGetDIDDocumentResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetDIDDocumentResponse { - return new QueryGetDIDDocumentResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetDIDDocumentResponse | PlainMessage | undefined, b: QueryGetDIDDocumentResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetDIDDocumentResponse, a, b); - } -} - -/** - * QueryListDIDDocumentsRequest is the request type for the - * Query/ListDIDDocuments RPC method. - * - * @generated from message did.v1.QueryListDIDDocumentsRequest - */ -export class QueryListDIDDocumentsRequest extends Message { - /** - * pagination defines an optional pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryListDIDDocumentsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryListDIDDocumentsRequest { - return new QueryListDIDDocumentsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryListDIDDocumentsRequest { - return new QueryListDIDDocumentsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryListDIDDocumentsRequest { - return new QueryListDIDDocumentsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryListDIDDocumentsRequest | PlainMessage | undefined, b: QueryListDIDDocumentsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryListDIDDocumentsRequest, a, b); - } -} - -/** - * QueryListDIDDocumentsResponse is the response type for the - * Query/ListDIDDocuments RPC method. - * - * @generated from message did.v1.QueryListDIDDocumentsResponse - */ -export class QueryListDIDDocumentsResponse extends Message { - /** - * did_documents is the list of DID documents - * - * @generated from field: repeated did.v1.DIDDocument did_documents = 1; - */ - didDocuments: DIDDocument[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryListDIDDocumentsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did_documents", kind: "message", T: DIDDocument, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryListDIDDocumentsResponse { - return new QueryListDIDDocumentsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryListDIDDocumentsResponse { - return new QueryListDIDDocumentsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryListDIDDocumentsResponse { - return new QueryListDIDDocumentsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryListDIDDocumentsResponse | PlainMessage | undefined, b: QueryListDIDDocumentsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryListDIDDocumentsResponse, a, b); - } -} - -/** - * QueryGetDIDDocumentsByControllerRequest is the request type for the - * Query/GetDIDDocumentsByController RPC method. - * - * @generated from message did.v1.QueryGetDIDDocumentsByControllerRequest - */ -export class QueryGetDIDDocumentsByControllerRequest extends Message { - /** - * controller is the controller to search for - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * pagination defines an optional pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetDIDDocumentsByControllerRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetDIDDocumentsByControllerRequest { - return new QueryGetDIDDocumentsByControllerRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetDIDDocumentsByControllerRequest { - return new QueryGetDIDDocumentsByControllerRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetDIDDocumentsByControllerRequest { - return new QueryGetDIDDocumentsByControllerRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetDIDDocumentsByControllerRequest | PlainMessage | undefined, b: QueryGetDIDDocumentsByControllerRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetDIDDocumentsByControllerRequest, a, b); - } -} - -/** - * QueryGetDIDDocumentsByControllerResponse is the response type for the - * Query/GetDIDDocumentsByController RPC method. - * - * @generated from message did.v1.QueryGetDIDDocumentsByControllerResponse - */ -export class QueryGetDIDDocumentsByControllerResponse extends Message { - /** - * did_documents is the list of DID documents controlled by the controller - * - * @generated from field: repeated did.v1.DIDDocument did_documents = 1; - */ - didDocuments: DIDDocument[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetDIDDocumentsByControllerResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did_documents", kind: "message", T: DIDDocument, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetDIDDocumentsByControllerResponse { - return new QueryGetDIDDocumentsByControllerResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetDIDDocumentsByControllerResponse { - return new QueryGetDIDDocumentsByControllerResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetDIDDocumentsByControllerResponse { - return new QueryGetDIDDocumentsByControllerResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetDIDDocumentsByControllerResponse | PlainMessage | undefined, b: QueryGetDIDDocumentsByControllerResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetDIDDocumentsByControllerResponse, a, b); - } -} - -/** - * QueryGetVerificationMethodRequest is the request type for the - * Query/GetVerificationMethod RPC method. - * - * @generated from message did.v1.QueryGetVerificationMethodRequest - */ -export class QueryGetVerificationMethodRequest extends Message { - /** - * did is the DID that contains the verification method - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * method_id is the ID of the verification method - * - * @generated from field: string method_id = 2; - */ - methodId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetVerificationMethodRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetVerificationMethodRequest { - return new QueryGetVerificationMethodRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetVerificationMethodRequest { - return new QueryGetVerificationMethodRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetVerificationMethodRequest { - return new QueryGetVerificationMethodRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetVerificationMethodRequest | PlainMessage | undefined, b: QueryGetVerificationMethodRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetVerificationMethodRequest, a, b); - } -} - -/** - * QueryGetVerificationMethodResponse is the response type for the - * Query/GetVerificationMethod RPC method. - * - * @generated from message did.v1.QueryGetVerificationMethodResponse - */ -export class QueryGetVerificationMethodResponse extends Message { - /** - * verification_method is the retrieved verification method - * - * @generated from field: did.v1.VerificationMethod verification_method = 1; - */ - verificationMethod?: VerificationMethod; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetVerificationMethodResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verification_method", kind: "message", T: VerificationMethod }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetVerificationMethodResponse { - return new QueryGetVerificationMethodResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetVerificationMethodResponse { - return new QueryGetVerificationMethodResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetVerificationMethodResponse { - return new QueryGetVerificationMethodResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetVerificationMethodResponse | PlainMessage | undefined, b: QueryGetVerificationMethodResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetVerificationMethodResponse, a, b); - } -} - -/** - * QueryGetServiceRequest is the request type for the Query/GetService RPC - * method. - * - * @generated from message did.v1.QueryGetServiceRequest - */ -export class QueryGetServiceRequest extends Message { - /** - * did is the DID that contains the service - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * service_id is the ID of the service - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetServiceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetServiceRequest { - return new QueryGetServiceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetServiceRequest { - return new QueryGetServiceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetServiceRequest { - return new QueryGetServiceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetServiceRequest | PlainMessage | undefined, b: QueryGetServiceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetServiceRequest, a, b); - } -} - -/** - * QueryGetServiceResponse is the response type for the Query/GetService - * RPC method. - * - * @generated from message did.v1.QueryGetServiceResponse - */ -export class QueryGetServiceResponse extends Message { - /** - * service is the retrieved service - * - * @generated from field: did.v1.Service service = 1; - */ - service?: Service; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetServiceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service", kind: "message", T: Service }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetServiceResponse { - return new QueryGetServiceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetServiceResponse { - return new QueryGetServiceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetServiceResponse { - return new QueryGetServiceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetServiceResponse | PlainMessage | undefined, b: QueryGetServiceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetServiceResponse, a, b); - } -} - -/** - * QueryGetVerifiableCredentialRequest is the request type for the - * Query/GetVerifiableCredential RPC method. - * - * @generated from message did.v1.QueryGetVerifiableCredentialRequest - */ -export class QueryGetVerifiableCredentialRequest extends Message { - /** - * credential_id is the ID of the credential to retrieve - * - * @generated from field: string credential_id = 1; - */ - credentialId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetVerifiableCredentialRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetVerifiableCredentialRequest { - return new QueryGetVerifiableCredentialRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetVerifiableCredentialRequest { - return new QueryGetVerifiableCredentialRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetVerifiableCredentialRequest { - return new QueryGetVerifiableCredentialRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetVerifiableCredentialRequest | PlainMessage | undefined, b: QueryGetVerifiableCredentialRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetVerifiableCredentialRequest, a, b); - } -} - -/** - * QueryGetVerifiableCredentialResponse is the response type for the - * Query/GetVerifiableCredential RPC method. - * - * @generated from message did.v1.QueryGetVerifiableCredentialResponse - */ -export class QueryGetVerifiableCredentialResponse extends Message { - /** - * credential is the retrieved verifiable credential - * - * @generated from field: did.v1.VerifiableCredential credential = 1; - */ - credential?: VerifiableCredential; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetVerifiableCredentialResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential", kind: "message", T: VerifiableCredential }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetVerifiableCredentialResponse { - return new QueryGetVerifiableCredentialResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetVerifiableCredentialResponse { - return new QueryGetVerifiableCredentialResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetVerifiableCredentialResponse { - return new QueryGetVerifiableCredentialResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetVerifiableCredentialResponse | PlainMessage | undefined, b: QueryGetVerifiableCredentialResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetVerifiableCredentialResponse, a, b); - } -} - -/** - * QueryListVerifiableCredentialsRequest is the request type for the - * Query/ListVerifiableCredentials RPC method. - * - * @generated from message did.v1.QueryListVerifiableCredentialsRequest - */ -export class QueryListVerifiableCredentialsRequest extends Message { - /** - * pagination defines an optional pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - /** - * issuer filters by issuer DID (optional) - * - * @generated from field: string issuer = 2; - */ - issuer = ""; - - /** - * holder filters by holder DID (optional) - * - * @generated from field: string holder = 3; - */ - holder = ""; - - /** - * include_revoked includes revoked credentials (default: false) - * - * @generated from field: bool include_revoked = 4; - */ - includeRevoked = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryListVerifiableCredentialsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - { no: 2, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "holder", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "include_revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryListVerifiableCredentialsRequest { - return new QueryListVerifiableCredentialsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryListVerifiableCredentialsRequest { - return new QueryListVerifiableCredentialsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryListVerifiableCredentialsRequest { - return new QueryListVerifiableCredentialsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryListVerifiableCredentialsRequest | PlainMessage | undefined, b: QueryListVerifiableCredentialsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryListVerifiableCredentialsRequest, a, b); - } -} - -/** - * QueryListVerifiableCredentialsResponse is the response type for the - * Query/ListVerifiableCredentials RPC method. - * - * @generated from message did.v1.QueryListVerifiableCredentialsResponse - */ -export class QueryListVerifiableCredentialsResponse extends Message { - /** - * credentials is the list of verifiable credentials - * - * @generated from field: repeated did.v1.VerifiableCredential credentials = 1; - */ - credentials: VerifiableCredential[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryListVerifiableCredentialsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credentials", kind: "message", T: VerifiableCredential, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryListVerifiableCredentialsResponse { - return new QueryListVerifiableCredentialsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryListVerifiableCredentialsResponse { - return new QueryListVerifiableCredentialsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryListVerifiableCredentialsResponse { - return new QueryListVerifiableCredentialsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryListVerifiableCredentialsResponse | PlainMessage | undefined, b: QueryListVerifiableCredentialsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryListVerifiableCredentialsResponse, a, b); - } -} - -/** - * CredentialInfo wraps credential data with vault status - * - * @generated from message did.v1.CredentialInfo - */ -export class CredentialInfo extends Message { - /** - * credential can be either verifiable or WebAuthn - * - * @generated from oneof did.v1.CredentialInfo.credential - */ - credential: { - /** - * @generated from field: did.v1.VerifiableCredential verifiable_credential = 1; - */ - value: VerifiableCredential; - case: "verifiableCredential"; - } | { - /** - * @generated from field: did.v1.WebAuthnCredential webauthn_credential = 2; - */ - value: WebAuthnCredential; - case: "webauthnCredential"; - } | { case: undefined; value?: undefined } = { case: undefined }; - - /** - * vault_id indicates if stored in vault (empty if not) - * - * @generated from field: string vault_id = 3; - */ - vaultId = ""; - - /** - * is_encrypted indicates if encrypted in vault - * - * @generated from field: bool is_encrypted = 4; - */ - isEncrypted = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.CredentialInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verifiable_credential", kind: "message", T: VerifiableCredential, oneof: "credential" }, - { no: 2, name: "webauthn_credential", kind: "message", T: WebAuthnCredential, oneof: "credential" }, - { no: 3, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "is_encrypted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CredentialInfo { - return new CredentialInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CredentialInfo { - return new CredentialInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CredentialInfo { - return new CredentialInfo().fromJsonString(jsonString, options); - } - - static equals(a: CredentialInfo | PlainMessage | undefined, b: CredentialInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(CredentialInfo, a, b); - } -} - -/** - * QueryGetCredentialsByDIDRequest is the request type for the - * Query/GetCredentialsByDID RPC method. - * - * @generated from message did.v1.QueryGetCredentialsByDIDRequest - */ -export class QueryGetCredentialsByDIDRequest extends Message { - /** - * did is the DID to retrieve all credentials for - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * include_verifiable includes verifiable credentials (default: true) - * - * @generated from field: bool include_verifiable = 2; - */ - includeVerifiable = false; - - /** - * include_webauthn includes WebAuthn credentials (default: true) - * - * @generated from field: bool include_webauthn = 3; - */ - includeWebauthn = false; - - /** - * include_revoked includes revoked credentials (default: false) - * - * @generated from field: bool include_revoked = 4; - */ - includeRevoked = false; - - /** - * pagination defines an optional pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 5; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetCredentialsByDIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "include_verifiable", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "include_webauthn", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 4, name: "include_revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetCredentialsByDIDRequest { - return new QueryGetCredentialsByDIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetCredentialsByDIDRequest { - return new QueryGetCredentialsByDIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetCredentialsByDIDRequest { - return new QueryGetCredentialsByDIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetCredentialsByDIDRequest | PlainMessage | undefined, b: QueryGetCredentialsByDIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetCredentialsByDIDRequest, a, b); - } -} - -/** - * QueryGetCredentialsByDIDResponse is the response type for the - * Query/GetCredentialsByDID RPC method. - * - * @generated from message did.v1.QueryGetCredentialsByDIDResponse - */ -export class QueryGetCredentialsByDIDResponse extends Message { - /** - * credentials is the list of all credentials associated with the DID - * - * @generated from field: repeated did.v1.CredentialInfo credentials = 1; - */ - credentials: CredentialInfo[] = []; - - /** - * pagination defines the pagination in the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryGetCredentialsByDIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credentials", kind: "message", T: CredentialInfo, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetCredentialsByDIDResponse { - return new QueryGetCredentialsByDIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetCredentialsByDIDResponse { - return new QueryGetCredentialsByDIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetCredentialsByDIDResponse { - return new QueryGetCredentialsByDIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetCredentialsByDIDResponse | PlainMessage | undefined, b: QueryGetCredentialsByDIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetCredentialsByDIDResponse, a, b); - } -} - -/** - * QueryRegisterStartRequest is the request type for the - * Query/RegisterStart RPC method. - * - * @generated from message did.v1.QueryRegisterStartRequest - */ -export class QueryRegisterStartRequest extends Message { - /** - * assertion_did is the DID to register (did:sonr:email: or did:sonr:phone:) - * - * @generated from field: string assertion_did = 1; - */ - assertionDid = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryRegisterStartRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "assertion_did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRegisterStartRequest { - return new QueryRegisterStartRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRegisterStartRequest { - return new QueryRegisterStartRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRegisterStartRequest { - return new QueryRegisterStartRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRegisterStartRequest | PlainMessage | undefined, b: QueryRegisterStartRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRegisterStartRequest, a, b); - } -} - -/** - * QueryRegisterStartResponse is the response type for the - * Query/RegisterStart RPC method. - * - * @generated from message did.v1.QueryRegisterStartResponse - */ -export class QueryRegisterStartResponse extends Message { - /** - * challenge for the attestation ceremony (32 bytes) - * - * @generated from field: bytes challenge = 1; - */ - challenge = new Uint8Array(0); - - /** - * relying_party_id identifier - * - * @generated from field: string relying_party_id = 2; - */ - relyingPartyId = ""; - - /** - * user information (id, name, displayName) - * - * @generated from field: map user = 3; - */ - user: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryRegisterStartResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "challenge", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "relying_party_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "user", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRegisterStartResponse { - return new QueryRegisterStartResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRegisterStartResponse { - return new QueryRegisterStartResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRegisterStartResponse { - return new QueryRegisterStartResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRegisterStartResponse | PlainMessage | undefined, b: QueryRegisterStartResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRegisterStartResponse, a, b); - } -} - -/** - * QueryLoginStartRequest is the request type for the - * Query/LoginStart RPC method. - * - * @generated from message did.v1.QueryLoginStartRequest - */ -export class QueryLoginStartRequest extends Message { - /** - * assertion_did is the assertion DID (did:sonr:email: or did:sonr:phone:) - * - * @generated from field: string assertion_did = 1; - */ - assertionDid = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryLoginStartRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "assertion_did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLoginStartRequest { - return new QueryLoginStartRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLoginStartRequest { - return new QueryLoginStartRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLoginStartRequest { - return new QueryLoginStartRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryLoginStartRequest | PlainMessage | undefined, b: QueryLoginStartRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLoginStartRequest, a, b); - } -} - -/** - * QueryLoginStartResponse is the response type for the - * Query/LoginStart RPC method. - * - * @generated from message did.v1.QueryLoginStartResponse - */ -export class QueryLoginStartResponse extends Message { - /** - * credential_ids associated with this assertion - * - * @generated from field: repeated string credential_ids = 1; - */ - credentialIds: string[] = []; - - /** - * challenge for the assertion ceremony (32 bytes) - * - * @generated from field: bytes challenge = 2; - */ - challenge = new Uint8Array(0); - - /** - * relying_party_id identifier - * - * @generated from field: string relying_party_id = 3; - */ - relyingPartyId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.QueryLoginStartResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_ids", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "challenge", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "relying_party_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLoginStartResponse { - return new QueryLoginStartResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLoginStartResponse { - return new QueryLoginStartResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLoginStartResponse { - return new QueryLoginStartResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryLoginStartResponse | PlainMessage | undefined, b: QueryLoginStartResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLoginStartResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/state_pb.ts b/packages/es/src/protobufs/did/v1/state_pb.ts deleted file mode 100644 index 3e462771f..000000000 --- a/packages/es/src/protobufs/did/v1/state_pb.ts +++ /dev/null @@ -1,873 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/state.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { CredentialProof, CredentialStatus, Service, VerificationMethod, VerificationMethodReference } from "./types_pb.js"; - -/** - * Authentication is the authentication method to be used by the DID. - * - * @generated from message did.v1.Authentication - */ -export class Authentication extends Message { - /** - * The unique identifier of the assertion - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * The authentication of the DID - * - * @generated from field: string controller = 2; - */ - controller = ""; - - /** - * Origin of the authentication - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * string is the verification method - * - * @generated from field: string public_key_base64 = 4; - */ - publicKeyBase64 = ""; - - /** - * AssertionKind is the assertion type - * - * @generated from field: string did_kind = 5; - */ - didKind = ""; - - /** - * CreationBlock is the block number of the creation of the authentication - * - * @generated from field: int64 creation_block = 6; - */ - creationBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Authentication"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "did_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "creation_block", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Authentication { - return new Authentication().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Authentication { - return new Authentication().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Authentication { - return new Authentication().fromJsonString(jsonString, options); - } - - static equals(a: Authentication | PlainMessage | undefined, b: Authentication | PlainMessage | undefined): boolean { - return proto3.util.equals(Authentication, a, b); - } -} - -/** - * Assertion is the assertion method to be used by the DID. - * - * @generated from message did.v1.Assertion - */ -export class Assertion extends Message { - /** - * The unique identifier of the assertion - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * The authentication of the DID - * - * @generated from field: string controller = 2; - */ - controller = ""; - - /** - * Origin of the authentication - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * string is the verification method - * - * @generated from field: string public_key_base64 = 4; - */ - publicKeyBase64 = ""; - - /** - * DIDKind is the DID type - * - * @generated from field: string did_kind = 5; - */ - didKind = ""; - - /** - * CreationBlock is the block number of the creation of the authentication - * - * @generated from field: int64 creation_block = 6; - */ - creationBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Assertion"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "did_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "creation_block", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Assertion { - return new Assertion().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Assertion { - return new Assertion().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Assertion { - return new Assertion().fromJsonString(jsonString, options); - } - - static equals(a: Assertion | PlainMessage | undefined, b: Assertion | PlainMessage | undefined): boolean { - return proto3.util.equals(Assertion, a, b); - } -} - -/** - * Controller is the controller method to be used by the DID. - * - * @generated from message did.v1.Controller - */ -export class Controller extends Message { - /** - * The unique identifier of the assertion - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * The authentication of the DID - * - * @generated from field: string address = 2; - */ - address = ""; - - /** - * Origin of the authentication - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * string is the verification method - * - * @generated from field: string public_key_base64 = 4; - */ - publicKeyBase64 = ""; - - /** - * DIDKind is the DID type - * - * @generated from field: string did_kind = 5; - */ - didKind = ""; - - /** - * CreationBlock is the block number of the creation of the authentication - * - * @generated from field: int64 creation_block = 6; - */ - creationBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Controller"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "did_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "creation_block", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Controller { - return new Controller().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Controller { - return new Controller().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Controller { - return new Controller().fromJsonString(jsonString, options); - } - - static equals(a: Controller | PlainMessage | undefined, b: Controller | PlainMessage | undefined): boolean { - return proto3.util.equals(Controller, a, b); - } -} - -/** - * Delegation is usually an external blockchain account that is used to sign - * transactions on behalf of the DID - * - * @generated from message did.v1.Delegation - */ -export class Delegation extends Message { - /** - * The unique identifier of the assertion - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * The authentication of the DID - * - * @generated from field: string controller = 2; - */ - controller = ""; - - /** - * Origin of the authentication - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * string is the verification method - * - * @generated from field: string public_key_base64 = 4; - */ - publicKeyBase64 = ""; - - /** - * DIDKind is the DID type - * - * @generated from field: string did_kind = 5; - */ - didKind = ""; - - /** - * CreationBlock is the block number of the creation of the authentication - * - * @generated from field: int64 creation_block = 6; - */ - creationBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Delegation"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "did_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "creation_block", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Delegation { - return new Delegation().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Delegation { - return new Delegation().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Delegation { - return new Delegation().fromJsonString(jsonString, options); - } - - static equals(a: Delegation | PlainMessage | undefined, b: Delegation | PlainMessage | undefined): boolean { - return proto3.util.equals(Delegation, a, b); - } -} - -/** - * Invocation is usually a smart contract that is used to sign transactions on - * behalf of the DID - * - * @generated from message did.v1.Invocation - */ -export class Invocation extends Message { - /** - * The unique identifier of the assertion - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * The authentication of the DID - * - * @generated from field: string controller = 2; - */ - controller = ""; - - /** - * Origin of the authentication - * - * @generated from field: string subject = 3; - */ - subject = ""; - - /** - * string is the verification method - * - * @generated from field: string public_key_base64 = 4; - */ - publicKeyBase64 = ""; - - /** - * DIDKind is the DID type - * - * @generated from field: string did_kind = 5; - */ - didKind = ""; - - /** - * CreationBlock is the block number of the creation of the authentication - * - * @generated from field: int64 creation_block = 6; - */ - creationBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Invocation"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "did_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "creation_block", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Invocation { - return new Invocation().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Invocation { - return new Invocation().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Invocation { - return new Invocation().fromJsonString(jsonString, options); - } - - static equals(a: Invocation | PlainMessage | undefined, b: Invocation | PlainMessage | undefined): boolean { - return proto3.util.equals(Invocation, a, b); - } -} - -/** - * DIDDocument represents a W3C compliant DID Document - * - * @generated from message did.v1.DIDDocument - */ -export class DIDDocument extends Message { - /** - * id is the DID that is the subject of this DID Document (REQUIRED) - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * primary_controller identifies the primary entity that controls the DID - * document (OPTIONAL) - * - * @generated from field: string primary_controller = 2; - */ - primaryController = ""; - - /** - * alsoKnownAs expresses other identifiers for the DID subject (OPTIONAL) - * - * @generated from field: repeated string also_known_as = 3; - */ - alsoKnownAs: string[] = []; - - /** - * verificationMethod expresses verification methods (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethod verification_method = 4; - */ - verificationMethod: VerificationMethod[] = []; - - /** - * authentication expresses authentication verification relationships - * (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethodReference authentication = 5; - */ - authentication: VerificationMethodReference[] = []; - - /** - * assertionMethod expresses assertion verification relationships (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethodReference assertion_method = 6; - */ - assertionMethod: VerificationMethodReference[] = []; - - /** - * keyAgreement expresses key agreement verification relationships (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethodReference key_agreement = 7; - */ - keyAgreement: VerificationMethodReference[] = []; - - /** - * capabilityInvocation expresses capability invocation verification - * relationships (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethodReference capability_invocation = 8; - */ - capabilityInvocation: VerificationMethodReference[] = []; - - /** - * capabilityDelegation expresses capability delegation verification - * relationships (OPTIONAL) - * - * @generated from field: repeated did.v1.VerificationMethodReference capability_delegation = 9; - */ - capabilityDelegation: VerificationMethodReference[] = []; - - /** - * service expresses service endpoints (OPTIONAL) - * - * @generated from field: repeated did.v1.Service service = 10; - */ - service: Service[] = []; - - /** - * Block height when the DID document was created - * - * @generated from field: int64 created_at = 11; - */ - createdAt = protoInt64.zero; - - /** - * Block height when the DID document was last updated - * - * @generated from field: int64 updated_at = 12; - */ - updatedAt = protoInt64.zero; - - /** - * Whether the DID document is deactivated - * - * @generated from field: bool deactivated = 13; - */ - deactivated = false; - - /** - * Version number for the DID document - * - * @generated from field: uint64 version = 14; - */ - version = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.DIDDocument"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "primary_controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "also_known_as", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "verification_method", kind: "message", T: VerificationMethod, repeated: true }, - { no: 5, name: "authentication", kind: "message", T: VerificationMethodReference, repeated: true }, - { no: 6, name: "assertion_method", kind: "message", T: VerificationMethodReference, repeated: true }, - { no: 7, name: "key_agreement", kind: "message", T: VerificationMethodReference, repeated: true }, - { no: 8, name: "capability_invocation", kind: "message", T: VerificationMethodReference, repeated: true }, - { no: 9, name: "capability_delegation", kind: "message", T: VerificationMethodReference, repeated: true }, - { no: 10, name: "service", kind: "message", T: Service, repeated: true }, - { no: 11, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "updated_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 13, name: "deactivated", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 14, name: "version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DIDDocument { - return new DIDDocument().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DIDDocument { - return new DIDDocument().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DIDDocument { - return new DIDDocument().fromJsonString(jsonString, options); - } - - static equals(a: DIDDocument | PlainMessage | undefined, b: DIDDocument | PlainMessage | undefined): boolean { - return proto3.util.equals(DIDDocument, a, b); - } -} - -/** - * DIDDocumentMetadata contains metadata about the DID document - * - * @generated from message did.v1.DIDDocumentMetadata - */ -export class DIDDocumentMetadata extends Message { - /** - * did is the DID this metadata belongs to - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * created is when the DID was created - * - * @generated from field: int64 created = 2; - */ - created = protoInt64.zero; - - /** - * updated is when the DID was last updated - * - * @generated from field: int64 updated = 3; - */ - updated = protoInt64.zero; - - /** - * deactivated is when the DID was deactivated (if applicable) - * - * @generated from field: int64 deactivated = 4; - */ - deactivated = protoInt64.zero; - - /** - * version_id is the version identifier - * - * @generated from field: string version_id = 5; - */ - versionId = ""; - - /** - * next_update is when the next update is scheduled (if applicable) - * - * @generated from field: int64 next_update = 6; - */ - nextUpdate = protoInt64.zero; - - /** - * next_version_id is the next version identifier (if applicable) - * - * @generated from field: string next_version_id = 7; - */ - nextVersionId = ""; - - /** - * equivalentId lists equivalent DIDs - * - * @generated from field: repeated string equivalent_id = 8; - */ - equivalentId: string[] = []; - - /** - * canonicalId is the canonical DID - * - * @generated from field: string canonical_id = 9; - */ - canonicalId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.DIDDocumentMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "created", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "updated", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: "deactivated", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "version_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "next_update", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "next_version_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "equivalent_id", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 9, name: "canonical_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DIDDocumentMetadata { - return new DIDDocumentMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DIDDocumentMetadata { - return new DIDDocumentMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DIDDocumentMetadata { - return new DIDDocumentMetadata().fromJsonString(jsonString, options); - } - - static equals(a: DIDDocumentMetadata | PlainMessage | undefined, b: DIDDocumentMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(DIDDocumentMetadata, a, b); - } -} - -/** - * VerifiableCredential represents a W3C Verifiable Credential - * - * @generated from message did.v1.VerifiableCredential - */ -export class VerifiableCredential extends Message { - /** - * id is the credential identifier - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * context is the JSON-LD contexts - * - * @generated from field: repeated string context = 2; - */ - context: string[] = []; - - /** - * credential_kinds is the credential types - * - * @generated from field: repeated string credential_kinds = 3; - */ - credentialKinds: string[] = []; - - /** - * issuer is the DID of the credential issuer - * - * @generated from field: string issuer = 4; - */ - issuer = ""; - - /** - * issuanceDate is when the credential was issued - * - * @generated from field: string issuance_date = 5; - */ - issuanceDate = ""; - - /** - * expirationDate is when the credential expires (optional) - * - * @generated from field: string expiration_date = 6; - */ - expirationDate = ""; - - /** - * credentialSubject contains the claims about the subject as JSON - * - * @generated from field: bytes credential_subject = 7; - */ - credentialSubject = new Uint8Array(0); - - /** - * proof contains the cryptographic proof - * - * @generated from field: repeated did.v1.CredentialProof proof = 8; - */ - proof: CredentialProof[] = []; - - /** - * credentialStatus contains information about credential revocation - * (optional) - * - * @generated from field: did.v1.CredentialStatus credential_status = 9; - */ - credentialStatus?: CredentialStatus; - - /** - * subject is the DID of the credential subject (for indexing) - * - * @generated from field: string subject = 10; - */ - subject = ""; - - /** - * Block height when issued - * - * @generated from field: int64 issued_at = 11; - */ - issuedAt = protoInt64.zero; - - /** - * Block height when expires (0 if no expiration) - * - * @generated from field: int64 expires_at = 12; - */ - expiresAt = protoInt64.zero; - - /** - * Whether the credential is revoked - * - * @generated from field: bool revoked = 13; - */ - revoked = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.VerifiableCredential"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "context", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 3, name: "credential_kinds", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "issuance_date", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "expiration_date", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "credential_subject", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "proof", kind: "message", T: CredentialProof, repeated: true }, - { no: 9, name: "credential_status", kind: "message", T: CredentialStatus }, - { no: 10, name: "subject", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "issued_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "expires_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 13, name: "revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VerifiableCredential { - return new VerifiableCredential().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VerifiableCredential { - return new VerifiableCredential().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VerifiableCredential { - return new VerifiableCredential().fromJsonString(jsonString, options); - } - - static equals(a: VerifiableCredential | PlainMessage | undefined, b: VerifiableCredential | PlainMessage | undefined): boolean { - return proto3.util.equals(VerifiableCredential, a, b); - } -} - -/** - * DIDController represents additional controllers for a DID document - * - * @generated from message did.v1.DIDController - */ -export class DIDController extends Message { - /** - * id is the auto-incrementing primary key - * - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - /** - * did is the DID this controller belongs to - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * controller_did is the controller DID - * - * @generated from field: string controller_did = 3; - */ - controllerDid = ""; - - /** - * added_at is when this controller was added - * - * @generated from field: int64 added_at = 4; - */ - addedAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.DIDController"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "controller_did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "added_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DIDController { - return new DIDController().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DIDController { - return new DIDController().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DIDController { - return new DIDController().fromJsonString(jsonString, options); - } - - static equals(a: DIDController | PlainMessage | undefined, b: DIDController | PlainMessage | undefined): boolean { - return proto3.util.equals(DIDController, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/tx_cosmes.ts b/packages/es/src/protobufs/did/v1/tx_cosmes.ts deleted file mode 100644 index c873d0ce5..000000000 --- a/packages/es/src/protobufs/did/v1/tx_cosmes.ts +++ /dev/null @@ -1,170 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file did/v1/tx.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddService, MsgAddServiceResponse, MsgAddVerificationMethod, MsgAddVerificationMethodResponse, MsgCreateDID, MsgCreateDIDResponse, MsgDeactivateDID, MsgDeactivateDIDResponse, MsgIssueVerifiableCredential, MsgIssueVerifiableCredentialResponse, MsgLinkExternalWallet, MsgLinkExternalWalletResponse, MsgRegisterWebAuthnCredential, MsgRegisterWebAuthnCredentialResponse, MsgRemoveService, MsgRemoveServiceResponse, MsgRemoveVerificationMethod, MsgRemoveVerificationMethodResponse, MsgRevokeVerifiableCredential, MsgRevokeVerifiableCredentialResponse, MsgUpdateDID, MsgUpdateDIDResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "did.v1.Msg"; - -/** - * UpdateParams defines a governance operation for updating the parameters. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc did.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * CreateDID creates a new DID document - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "did_tx_docs.md"}} - * - * @generated from rpc did.v1.Msg.CreateDID - */ -export const MsgCreateDIDService = { - typeName: TYPE_NAME, - method: "CreateDID", - Request: MsgCreateDID, - Response: MsgCreateDIDResponse, -} as const; - -/** - * UpdateDID updates an existing DID document - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "did_tx_docs.md"}} - * - * @generated from rpc did.v1.Msg.UpdateDID - */ -export const MsgUpdateDIDService = { - typeName: TYPE_NAME, - method: "UpdateDID", - Request: MsgUpdateDID, - Response: MsgUpdateDIDResponse, -} as const; - -/** - * DeactivateDID deactivates a DID document - * - * @generated from rpc did.v1.Msg.DeactivateDID - */ -export const MsgDeactivateDIDService = { - typeName: TYPE_NAME, - method: "DeactivateDID", - Request: MsgDeactivateDID, - Response: MsgDeactivateDIDResponse, -} as const; - -/** - * AddVerificationMethod adds a new verification method to a DID document - * - * @generated from rpc did.v1.Msg.AddVerificationMethod - */ -export const MsgAddVerificationMethodService = { - typeName: TYPE_NAME, - method: "AddVerificationMethod", - Request: MsgAddVerificationMethod, - Response: MsgAddVerificationMethodResponse, -} as const; - -/** - * RemoveVerificationMethod removes a verification method from a DID document - * - * @generated from rpc did.v1.Msg.RemoveVerificationMethod - */ -export const MsgRemoveVerificationMethodService = { - typeName: TYPE_NAME, - method: "RemoveVerificationMethod", - Request: MsgRemoveVerificationMethod, - Response: MsgRemoveVerificationMethodResponse, -} as const; - -/** - * AddService adds a new service endpoint to a DID document - * - * @generated from rpc did.v1.Msg.AddService - */ -export const MsgAddServiceService = { - typeName: TYPE_NAME, - method: "AddService", - Request: MsgAddService, - Response: MsgAddServiceResponse, -} as const; - -/** - * RemoveService removes a service endpoint from a DID document - * - * @generated from rpc did.v1.Msg.RemoveService - */ -export const MsgRemoveServiceService = { - typeName: TYPE_NAME, - method: "RemoveService", - Request: MsgRemoveService, - Response: MsgRemoveServiceResponse, -} as const; - -/** - * IssueVerifiableCredential issues a new verifiable credential - * - * @generated from rpc did.v1.Msg.IssueVerifiableCredential - */ -export const MsgIssueVerifiableCredentialService = { - typeName: TYPE_NAME, - method: "IssueVerifiableCredential", - Request: MsgIssueVerifiableCredential, - Response: MsgIssueVerifiableCredentialResponse, -} as const; - -/** - * RevokeVerifiableCredential revokes a verifiable credential - * - * @generated from rpc did.v1.Msg.RevokeVerifiableCredential - */ -export const MsgRevokeVerifiableCredentialService = { - typeName: TYPE_NAME, - method: "RevokeVerifiableCredential", - Request: MsgRevokeVerifiableCredential, - Response: MsgRevokeVerifiableCredentialResponse, -} as const; - -/** - * LinkExternalWallet links an external wallet as an assertion method - * - * @generated from rpc did.v1.Msg.LinkExternalWallet - */ -export const MsgLinkExternalWalletService = { - typeName: TYPE_NAME, - method: "LinkExternalWallet", - Request: MsgLinkExternalWallet, - Response: MsgLinkExternalWalletResponse, -} as const; - -/** - * RegisterWebAuthnCredential registers a new WebAuthn credential and creates a DID - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "did_tx_docs.md"}} - * - * @generated from rpc did.v1.Msg.RegisterWebAuthnCredential - */ -export const MsgRegisterWebAuthnCredentialService = { - typeName: TYPE_NAME, - method: "RegisterWebAuthnCredential", - Request: MsgRegisterWebAuthnCredential, - Response: MsgRegisterWebAuthnCredentialResponse, -} as const; - diff --git a/packages/es/src/protobufs/did/v1/tx_pb.ts b/packages/es/src/protobufs/did/v1/tx_pb.ts deleted file mode 100644 index 8063e02e1..000000000 --- a/packages/es/src/protobufs/did/v1/tx_pb.ts +++ /dev/null @@ -1,1222 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/tx.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { DIDDocument, VerifiableCredential } from "./state_pb.js"; -import { Service, VerificationMethod, WebAuthnCredential } from "./types_pb.js"; - -/** - * MsgUpdateParams is the Msg/UpdateParams request type. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message did.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: did.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message did.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgCreateDID creates a new DID document - * - * @generated from message did.v1.MsgCreateDID - */ -export class MsgCreateDID extends Message { - /** - * controller is the address creating the DID - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did_document is the DID document to create - * - * @generated from field: did.v1.DIDDocument did_document = 2; - */ - didDocument?: DIDDocument; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgCreateDID"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did_document", kind: "message", T: DIDDocument }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateDID { - return new MsgCreateDID().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateDID { - return new MsgCreateDID().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateDID { - return new MsgCreateDID().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateDID | PlainMessage | undefined, b: MsgCreateDID | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateDID, a, b); - } -} - -/** - * MsgCreateDIDResponse defines the response for MsgCreateDID - * - * @generated from message did.v1.MsgCreateDIDResponse - */ -export class MsgCreateDIDResponse extends Message { - /** - * did is the created DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * vault_id is the ID of the auto-created vault (optional) - * - * @generated from field: string vault_id = 2; - */ - vaultId = ""; - - /** - * vault_public_key is the public key of the auto-created vault (optional) - * - * @generated from field: bytes vault_public_key = 3; - */ - vaultPublicKey = new Uint8Array(0); - - /** - * enclave_id is the enclave ID of the auto-created vault (optional) - * - * @generated from field: string enclave_id = 4; - */ - enclaveId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgCreateDIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "vault_public_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "enclave_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateDIDResponse { - return new MsgCreateDIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateDIDResponse { - return new MsgCreateDIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateDIDResponse { - return new MsgCreateDIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateDIDResponse | PlainMessage | undefined, b: MsgCreateDIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateDIDResponse, a, b); - } -} - -/** - * MsgUpdateDID updates an existing DID document - * - * @generated from message did.v1.MsgUpdateDID - */ -export class MsgUpdateDID extends Message { - /** - * controller is the address updating the DID - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to update - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * did_document is the updated DID document - * - * @generated from field: did.v1.DIDDocument did_document = 3; - */ - didDocument?: DIDDocument; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgUpdateDID"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "did_document", kind: "message", T: DIDDocument }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateDID { - return new MsgUpdateDID().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateDID { - return new MsgUpdateDID().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateDID { - return new MsgUpdateDID().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateDID | PlainMessage | undefined, b: MsgUpdateDID | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateDID, a, b); - } -} - -/** - * MsgUpdateDIDResponse defines the response for MsgUpdateDID - * - * @generated from message did.v1.MsgUpdateDIDResponse - */ -export class MsgUpdateDIDResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgUpdateDIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateDIDResponse { - return new MsgUpdateDIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateDIDResponse { - return new MsgUpdateDIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateDIDResponse { - return new MsgUpdateDIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateDIDResponse | PlainMessage | undefined, b: MsgUpdateDIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateDIDResponse, a, b); - } -} - -/** - * MsgDeactivateDID deactivates a DID document - * - * @generated from message did.v1.MsgDeactivateDID - */ -export class MsgDeactivateDID extends Message { - /** - * controller is the address deactivating the DID - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to deactivate - * - * @generated from field: string did = 2; - */ - did = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgDeactivateDID"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDeactivateDID { - return new MsgDeactivateDID().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDeactivateDID { - return new MsgDeactivateDID().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDeactivateDID { - return new MsgDeactivateDID().fromJsonString(jsonString, options); - } - - static equals(a: MsgDeactivateDID | PlainMessage | undefined, b: MsgDeactivateDID | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDeactivateDID, a, b); - } -} - -/** - * MsgDeactivateDIDResponse defines the response for MsgDeactivateDID - * - * @generated from message did.v1.MsgDeactivateDIDResponse - */ -export class MsgDeactivateDIDResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgDeactivateDIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDeactivateDIDResponse { - return new MsgDeactivateDIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDeactivateDIDResponse { - return new MsgDeactivateDIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDeactivateDIDResponse { - return new MsgDeactivateDIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgDeactivateDIDResponse | PlainMessage | undefined, b: MsgDeactivateDIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDeactivateDIDResponse, a, b); - } -} - -/** - * MsgAddVerificationMethod adds a verification method to a DID document - * - * @generated from message did.v1.MsgAddVerificationMethod - */ -export class MsgAddVerificationMethod extends Message { - /** - * controller is the address adding the verification method - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to add the verification method to - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * verification_method is the verification method to add - * - * @generated from field: did.v1.VerificationMethod verification_method = 3; - */ - verificationMethod?: VerificationMethod; - - /** - * relationships specifies which verification relationships to add - * - * @generated from field: repeated string relationships = 4; - */ - relationships: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgAddVerificationMethod"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "verification_method", kind: "message", T: VerificationMethod }, - { no: 4, name: "relationships", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddVerificationMethod { - return new MsgAddVerificationMethod().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddVerificationMethod { - return new MsgAddVerificationMethod().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddVerificationMethod { - return new MsgAddVerificationMethod().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddVerificationMethod | PlainMessage | undefined, b: MsgAddVerificationMethod | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddVerificationMethod, a, b); - } -} - -/** - * MsgAddVerificationMethodResponse defines the response for - * MsgAddVerificationMethod - * - * @generated from message did.v1.MsgAddVerificationMethodResponse - */ -export class MsgAddVerificationMethodResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgAddVerificationMethodResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddVerificationMethodResponse { - return new MsgAddVerificationMethodResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddVerificationMethodResponse { - return new MsgAddVerificationMethodResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddVerificationMethodResponse { - return new MsgAddVerificationMethodResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddVerificationMethodResponse | PlainMessage | undefined, b: MsgAddVerificationMethodResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddVerificationMethodResponse, a, b); - } -} - -/** - * MsgRemoveVerificationMethod removes a verification method from a DID document - * - * @generated from message did.v1.MsgRemoveVerificationMethod - */ -export class MsgRemoveVerificationMethod extends Message { - /** - * controller is the address removing the verification method - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to remove the verification method from - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * verification_method_id is the ID of the verification method to remove - * - * @generated from field: string verification_method_id = 3; - */ - verificationMethodId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRemoveVerificationMethod"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveVerificationMethod { - return new MsgRemoveVerificationMethod().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveVerificationMethod { - return new MsgRemoveVerificationMethod().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveVerificationMethod { - return new MsgRemoveVerificationMethod().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveVerificationMethod | PlainMessage | undefined, b: MsgRemoveVerificationMethod | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveVerificationMethod, a, b); - } -} - -/** - * MsgRemoveVerificationMethodResponse defines the response for - * MsgRemoveVerificationMethod - * - * @generated from message did.v1.MsgRemoveVerificationMethodResponse - */ -export class MsgRemoveVerificationMethodResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRemoveVerificationMethodResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveVerificationMethodResponse { - return new MsgRemoveVerificationMethodResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveVerificationMethodResponse { - return new MsgRemoveVerificationMethodResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveVerificationMethodResponse { - return new MsgRemoveVerificationMethodResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveVerificationMethodResponse | PlainMessage | undefined, b: MsgRemoveVerificationMethodResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveVerificationMethodResponse, a, b); - } -} - -/** - * MsgAddService adds a service endpoint to a DID document - * - * @generated from message did.v1.MsgAddService - */ -export class MsgAddService extends Message { - /** - * controller is the address adding the service - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to add the service to - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * service is the service to add - * - * @generated from field: did.v1.Service service = 3; - */ - service?: Service; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgAddService"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "service", kind: "message", T: Service }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddService { - return new MsgAddService().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddService { - return new MsgAddService().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddService { - return new MsgAddService().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddService | PlainMessage | undefined, b: MsgAddService | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddService, a, b); - } -} - -/** - * MsgAddServiceResponse defines the response for MsgAddService - * - * @generated from message did.v1.MsgAddServiceResponse - */ -export class MsgAddServiceResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgAddServiceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddServiceResponse { - return new MsgAddServiceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddServiceResponse { - return new MsgAddServiceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddServiceResponse { - return new MsgAddServiceResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddServiceResponse | PlainMessage | undefined, b: MsgAddServiceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddServiceResponse, a, b); - } -} - -/** - * MsgRemoveService removes a service endpoint from a DID document - * - * @generated from message did.v1.MsgRemoveService - */ -export class MsgRemoveService extends Message { - /** - * controller is the address removing the service - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to remove the service from - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * service_id is the ID of the service to remove - * - * @generated from field: string service_id = 3; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRemoveService"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveService { - return new MsgRemoveService().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveService { - return new MsgRemoveService().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveService { - return new MsgRemoveService().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveService | PlainMessage | undefined, b: MsgRemoveService | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveService, a, b); - } -} - -/** - * MsgRemoveServiceResponse defines the response for MsgRemoveService - * - * @generated from message did.v1.MsgRemoveServiceResponse - */ -export class MsgRemoveServiceResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRemoveServiceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveServiceResponse { - return new MsgRemoveServiceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveServiceResponse { - return new MsgRemoveServiceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveServiceResponse { - return new MsgRemoveServiceResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveServiceResponse | PlainMessage | undefined, b: MsgRemoveServiceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveServiceResponse, a, b); - } -} - -/** - * MsgIssueVerifiableCredential issues a new verifiable credential - * - * @generated from message did.v1.MsgIssueVerifiableCredential - */ -export class MsgIssueVerifiableCredential extends Message { - /** - * issuer is the address issuing the credential - * - * @generated from field: string issuer = 1; - */ - issuer = ""; - - /** - * credential is the verifiable credential to issue - * - * @generated from field: did.v1.VerifiableCredential credential = 2; - */ - credential?: VerifiableCredential; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgIssueVerifiableCredential"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "credential", kind: "message", T: VerifiableCredential }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIssueVerifiableCredential { - return new MsgIssueVerifiableCredential().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIssueVerifiableCredential { - return new MsgIssueVerifiableCredential().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIssueVerifiableCredential { - return new MsgIssueVerifiableCredential().fromJsonString(jsonString, options); - } - - static equals(a: MsgIssueVerifiableCredential | PlainMessage | undefined, b: MsgIssueVerifiableCredential | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIssueVerifiableCredential, a, b); - } -} - -/** - * MsgIssueVerifiableCredentialResponse defines the response for - * MsgIssueVerifiableCredential - * - * @generated from message did.v1.MsgIssueVerifiableCredentialResponse - */ -export class MsgIssueVerifiableCredentialResponse extends Message { - /** - * credential_id is the ID of the issued credential - * - * @generated from field: string credential_id = 1; - */ - credentialId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgIssueVerifiableCredentialResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIssueVerifiableCredentialResponse { - return new MsgIssueVerifiableCredentialResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIssueVerifiableCredentialResponse { - return new MsgIssueVerifiableCredentialResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIssueVerifiableCredentialResponse { - return new MsgIssueVerifiableCredentialResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgIssueVerifiableCredentialResponse | PlainMessage | undefined, b: MsgIssueVerifiableCredentialResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIssueVerifiableCredentialResponse, a, b); - } -} - -/** - * MsgRevokeVerifiableCredential revokes a verifiable credential - * - * @generated from message did.v1.MsgRevokeVerifiableCredential - */ -export class MsgRevokeVerifiableCredential extends Message { - /** - * issuer is the address revoking the credential - * - * @generated from field: string issuer = 1; - */ - issuer = ""; - - /** - * credential_id is the ID of the credential to revoke - * - * @generated from field: string credential_id = 2; - */ - credentialId = ""; - - /** - * revocation_reason is the reason for revocation - * - * @generated from field: string revocation_reason = 3; - */ - revocationReason = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRevokeVerifiableCredential"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "revocation_reason", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRevokeVerifiableCredential { - return new MsgRevokeVerifiableCredential().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRevokeVerifiableCredential { - return new MsgRevokeVerifiableCredential().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRevokeVerifiableCredential { - return new MsgRevokeVerifiableCredential().fromJsonString(jsonString, options); - } - - static equals(a: MsgRevokeVerifiableCredential | PlainMessage | undefined, b: MsgRevokeVerifiableCredential | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRevokeVerifiableCredential, a, b); - } -} - -/** - * MsgRevokeVerifiableCredentialResponse defines the response for - * MsgRevokeVerifiableCredential - * - * @generated from message did.v1.MsgRevokeVerifiableCredentialResponse - */ -export class MsgRevokeVerifiableCredentialResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRevokeVerifiableCredentialResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRevokeVerifiableCredentialResponse { - return new MsgRevokeVerifiableCredentialResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRevokeVerifiableCredentialResponse { - return new MsgRevokeVerifiableCredentialResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRevokeVerifiableCredentialResponse { - return new MsgRevokeVerifiableCredentialResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRevokeVerifiableCredentialResponse | PlainMessage | undefined, b: MsgRevokeVerifiableCredentialResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRevokeVerifiableCredentialResponse, a, b); - } -} - -/** - * MsgLinkExternalWallet links an external wallet to a DID as an assertion method - * - * @generated from message did.v1.MsgLinkExternalWallet - */ -export class MsgLinkExternalWallet extends Message { - /** - * controller is the address that controls the DID - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * did is the DID to link the wallet to - * - * @generated from field: string did = 2; - */ - did = ""; - - /** - * wallet_address is the external wallet address - * - * @generated from field: string wallet_address = 3; - */ - walletAddress = ""; - - /** - * chain_id identifies the blockchain (e.g., "1" for Ethereum mainnet, "cosmoshub-4") - * - * @generated from field: string wallet_chain_id = 4; - */ - walletChainId = ""; - - /** - * wallet_type specifies the wallet type ("ethereum", "cosmos") - * - * @generated from field: string wallet_type = 5; - */ - walletType = ""; - - /** - * ownership_proof is the signature proving ownership of the wallet - * - * @generated from field: bytes ownership_proof = 6; - */ - ownershipProof = new Uint8Array(0); - - /** - * challenge is the message that was signed to create the ownership_proof - * - * @generated from field: bytes challenge = 7; - */ - challenge = new Uint8Array(0); - - /** - * verification_method_id is the ID for the new verification method - * - * @generated from field: string verification_method_id = 8; - */ - verificationMethodId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgLinkExternalWallet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "wallet_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "wallet_chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "wallet_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "ownership_proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "challenge", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLinkExternalWallet { - return new MsgLinkExternalWallet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLinkExternalWallet { - return new MsgLinkExternalWallet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLinkExternalWallet { - return new MsgLinkExternalWallet().fromJsonString(jsonString, options); - } - - static equals(a: MsgLinkExternalWallet | PlainMessage | undefined, b: MsgLinkExternalWallet | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLinkExternalWallet, a, b); - } -} - -/** - * MsgLinkExternalWalletResponse defines the response for MsgLinkExternalWallet - * - * @generated from message did.v1.MsgLinkExternalWalletResponse - */ -export class MsgLinkExternalWalletResponse extends Message { - /** - * verification_method_id is the ID of the created verification method - * - * @generated from field: string verification_method_id = 1; - */ - verificationMethodId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgLinkExternalWalletResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLinkExternalWalletResponse { - return new MsgLinkExternalWalletResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLinkExternalWalletResponse { - return new MsgLinkExternalWalletResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLinkExternalWalletResponse { - return new MsgLinkExternalWalletResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgLinkExternalWalletResponse | PlainMessage | undefined, b: MsgLinkExternalWalletResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLinkExternalWalletResponse, a, b); - } -} - -/** - * MsgRegisterWebAuthnCredential registers a new WebAuthn credential and creates a DID - * - * @generated from message did.v1.MsgRegisterWebAuthnCredential - */ -export class MsgRegisterWebAuthnCredential extends Message { - /** - * controller is the address that will control the created DID - * - * @generated from field: string controller = 1; - */ - controller = ""; - - /** - * username is the human-readable identifier for the DID - * - * @generated from field: string username = 2; - */ - username = ""; - - /** - * webauthn_credential contains the WebAuthn credential data - * - * @generated from field: did.v1.WebAuthnCredential webauthn_credential = 3; - */ - webauthnCredential?: WebAuthnCredential; - - /** - * verification_method_id is the ID for the WebAuthn verification method - * - * @generated from field: string verification_method_id = 4; - */ - verificationMethodId = ""; - - /** - * auto_create_vault indicates whether to automatically create a vault - * - * @generated from field: bool auto_create_vault = 5; - */ - autoCreateVault = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRegisterWebAuthnCredential"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "username", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "webauthn_credential", kind: "message", T: WebAuthnCredential }, - { no: 4, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "auto_create_vault", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterWebAuthnCredential { - return new MsgRegisterWebAuthnCredential().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterWebAuthnCredential { - return new MsgRegisterWebAuthnCredential().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterWebAuthnCredential { - return new MsgRegisterWebAuthnCredential().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterWebAuthnCredential | PlainMessage | undefined, b: MsgRegisterWebAuthnCredential | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterWebAuthnCredential, a, b); - } -} - -/** - * MsgRegisterWebAuthnCredentialResponse defines the response for MsgRegisterWebAuthnCredential - * - * @generated from message did.v1.MsgRegisterWebAuthnCredentialResponse - */ -export class MsgRegisterWebAuthnCredentialResponse extends Message { - /** - * did is the created DID identifier - * - * @generated from field: string did = 1; - */ - did = ""; - - /** - * verification_method_id is the ID of the created verification method - * - * @generated from field: string verification_method_id = 2; - */ - verificationMethodId = ""; - - /** - * vault_id is the ID of the auto-created vault (if requested) - * - * @generated from field: string vault_id = 3; - */ - vaultId = ""; - - /** - * vault_public_key is the public key of the auto-created vault (if requested) - * - * @generated from field: bytes vault_public_key = 4; - */ - vaultPublicKey = new Uint8Array(0); - - /** - * enclave_id is the enclave ID of the auto-created vault (if requested) - * - * @generated from field: string enclave_id = 5; - */ - enclaveId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.MsgRegisterWebAuthnCredentialResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "did", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "vault_public_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "enclave_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterWebAuthnCredentialResponse { - return new MsgRegisterWebAuthnCredentialResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterWebAuthnCredentialResponse { - return new MsgRegisterWebAuthnCredentialResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterWebAuthnCredentialResponse { - return new MsgRegisterWebAuthnCredentialResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterWebAuthnCredentialResponse | PlainMessage | undefined, b: MsgRegisterWebAuthnCredentialResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterWebAuthnCredentialResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/did/v1/types_pb.ts b/packages/es/src/protobufs/did/v1/types_pb.ts deleted file mode 100644 index 6e9a97af8..000000000 --- a/packages/es/src/protobufs/did/v1/types_pb.ts +++ /dev/null @@ -1,586 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file did/v1/types.proto (package did.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * VerificationMethod represents a verification method in a DID document - * - * @generated from message did.v1.VerificationMethod - */ -export class VerificationMethod extends Message { - /** - * id is the verification method identifier (REQUIRED) - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * verification_method_kind is the verification method type (REQUIRED) - * - * @generated from field: string verification_method_kind = 2; - */ - verificationMethodKind = ""; - - /** - * controller is the DID that controls this verification method (REQUIRED) - * - * @generated from field: string controller = 3; - */ - controller = ""; - - /** - * Public key material (optional, only one should be set) - * publicKeyJwk represents the public key as a JSON Web Key - * - * @generated from field: string public_key_jwk = 4; - */ - publicKeyJwk = ""; - - /** - * publicKeyMultibase represents the public key as multibase - * - * @generated from field: string public_key_multibase = 5; - */ - publicKeyMultibase = ""; - - /** - * publicKeyBase58 represents the public key in Base58 (legacy) - * - * @generated from field: string public_key_base58 = 6; - */ - publicKeyBase58 = ""; - - /** - * publicKeyBase64 represents the public key in Base64 (legacy) - * - * @generated from field: string public_key_base64 = 7; - */ - publicKeyBase64 = ""; - - /** - * publicKeyPem represents the public key in PEM format (legacy) - * - * @generated from field: string public_key_pem = 8; - */ - publicKeyPem = ""; - - /** - * publicKeyHex represents the public key in hexadecimal (legacy) - * - * @generated from field: string public_key_hex = 9; - */ - publicKeyHex = ""; - - /** - * WebAuthn credential information (for WebAuthn integration) - * - * @generated from field: did.v1.WebAuthnCredential webauthn_credential = 10; - */ - webauthnCredential?: WebAuthnCredential; - - /** - * blockchain_account_id for external wallet linking (CAIP-10 format) - * Format: "eip155:1:0x89a932207c485f85226d86f7cd486a89a24fcc12" for Ethereum - * Format: "cosmos:cosmoshub-4:cosmos1..." for Cosmos chains - * - * @generated from field: string blockchain_account_id = 11; - */ - blockchainAccountId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.VerificationMethod"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "verification_method_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "public_key_jwk", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "public_key_multibase", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "public_key_base58", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "public_key_base64", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "public_key_pem", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "public_key_hex", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "webauthn_credential", kind: "message", T: WebAuthnCredential }, - { no: 11, name: "blockchain_account_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VerificationMethod { - return new VerificationMethod().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VerificationMethod { - return new VerificationMethod().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VerificationMethod { - return new VerificationMethod().fromJsonString(jsonString, options); - } - - static equals(a: VerificationMethod | PlainMessage | undefined, b: VerificationMethod | PlainMessage | undefined): boolean { - return proto3.util.equals(VerificationMethod, a, b); - } -} - -/** - * VerificationMethodReference can be either an embedded verification method - * or a reference - * - * @generated from message did.v1.VerificationMethodReference - */ -export class VerificationMethodReference extends Message { - /** - * verification_method_id is a reference to a verification method by ID (optional) - * - * @generated from field: string verification_method_id = 1; - */ - verificationMethodId = ""; - - /** - * embedded_verification_method is an embedded verification method (optional) - * - * @generated from field: did.v1.VerificationMethod embedded_verification_method = 2; - */ - embeddedVerificationMethod?: VerificationMethod; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.VerificationMethodReference"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verification_method_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "embedded_verification_method", kind: "message", T: VerificationMethod }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VerificationMethodReference { - return new VerificationMethodReference().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VerificationMethodReference { - return new VerificationMethodReference().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VerificationMethodReference { - return new VerificationMethodReference().fromJsonString(jsonString, options); - } - - static equals(a: VerificationMethodReference | PlainMessage | undefined, b: VerificationMethodReference | PlainMessage | undefined): boolean { - return proto3.util.equals(VerificationMethodReference, a, b); - } -} - -/** - * Service represents a service endpoint in a DID document - * - * @generated from message did.v1.Service - */ -export class Service extends Message { - /** - * id is the service identifier (REQUIRED) - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * service_kind is the service type (REQUIRED) - * - * @generated from field: string service_kind = 2; - */ - serviceKind = ""; - - /** - * single_endpoint for a single URL - * - * @generated from field: string single_endpoint = 3; - */ - singleEndpoint = ""; - - /** - * multiple_endpoints for multiple URLs - * - * @generated from field: did.v1.ServiceEndpoints multiple_endpoints = 4; - */ - multipleEndpoints?: ServiceEndpoints; - - /** - * complex_endpoint for complex endpoint objects as JSON - * - * @generated from field: bytes complex_endpoint = 5; - */ - complexEndpoint = new Uint8Array(0); - - /** - * Additional properties for the service - * - * @generated from field: map properties = 6; - */ - properties: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.Service"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "single_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "multiple_endpoints", kind: "message", T: ServiceEndpoints }, - { no: 5, name: "complex_endpoint", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "properties", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Service { - return new Service().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Service { - return new Service().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Service { - return new Service().fromJsonString(jsonString, options); - } - - static equals(a: Service | PlainMessage | undefined, b: Service | PlainMessage | undefined): boolean { - return proto3.util.equals(Service, a, b); - } -} - -/** - * ServiceEndpoints represents multiple service endpoints - * - * @generated from message did.v1.ServiceEndpoints - */ -export class ServiceEndpoints extends Message { - /** - * @generated from field: repeated string endpoints = 1; - */ - endpoints: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.ServiceEndpoints"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "endpoints", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ServiceEndpoints { - return new ServiceEndpoints().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ServiceEndpoints { - return new ServiceEndpoints().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ServiceEndpoints { - return new ServiceEndpoints().fromJsonString(jsonString, options); - } - - static equals(a: ServiceEndpoints | PlainMessage | undefined, b: ServiceEndpoints | PlainMessage | undefined): boolean { - return proto3.util.equals(ServiceEndpoints, a, b); - } -} - -/** - * WebAuthnCredential represents WebAuthn credential information - * - * @generated from message did.v1.WebAuthnCredential - */ -export class WebAuthnCredential extends Message { - /** - * credential_id is the WebAuthn credential ID - * - * @generated from field: string credential_id = 1; - */ - credentialId = ""; - - /** - * public_key is the WebAuthn public key - * - * @generated from field: bytes public_key = 2; - */ - publicKey = new Uint8Array(0); - - /** - * algorithm is the signing algorithm - * - * @generated from field: int32 algorithm = 3; - */ - algorithm = 0; - - /** - * attestation_type is the attestation type - * - * @generated from field: string attestation_type = 4; - */ - attestationType = ""; - - /** - * origin is the origin where the credential was created - * - * @generated from field: string origin = 5; - */ - origin = ""; - - /** - * created_at is when the credential was created - * - * @generated from field: int64 created_at = 6; - */ - createdAt = protoInt64.zero; - - /** - * rp_id is the Relying Party ID - * - * @generated from field: string rp_id = 7; - */ - rpId = ""; - - /** - * rp_name is the Relying Party Name - * - * @generated from field: string rp_name = 8; - */ - rpName = ""; - - /** - * transports are the authenticator transports - * - * @generated from field: repeated string transports = 9; - */ - transports: string[] = []; - - /** - * user_verified indicates whether user verification was performed - * - * @generated from field: bool user_verified = 10; - */ - userVerified = false; - - /** - * signature_algorithm provides detailed algorithm information - * - * @generated from field: string signature_algorithm = 11; - */ - signatureAlgorithm = ""; - - /** - * raw_id is the base64url encoded raw credential ID - * - * @generated from field: string raw_id = 12; - */ - rawId = ""; - - /** - * client_data_json is the base64url encoded client data JSON - * - * @generated from field: string client_data_json = 13; - */ - clientDataJson = ""; - - /** - * attestation_object is the base64url encoded attestation object - * - * @generated from field: string attestation_object = 14; - */ - attestationObject = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.WebAuthnCredential"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "credential_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "public_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "algorithm", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 4, name: "attestation_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "origin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "rp_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "rp_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "transports", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "user_verified", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 11, name: "signature_algorithm", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "raw_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "client_data_json", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 14, name: "attestation_object", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): WebAuthnCredential { - return new WebAuthnCredential().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): WebAuthnCredential { - return new WebAuthnCredential().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): WebAuthnCredential { - return new WebAuthnCredential().fromJsonString(jsonString, options); - } - - static equals(a: WebAuthnCredential | PlainMessage | undefined, b: WebAuthnCredential | PlainMessage | undefined): boolean { - return proto3.util.equals(WebAuthnCredential, a, b); - } -} - -/** - * CredentialProof represents a cryptographic proof for a verifiable - * credential - * - * @generated from message did.v1.CredentialProof - */ -export class CredentialProof extends Message { - /** - * proof_kind is the proof type - * - * @generated from field: string proof_kind = 1; - */ - proofKind = ""; - - /** - * created is when the proof was created - * - * @generated from field: string created = 2; - */ - created = ""; - - /** - * verificationMethod is the verification method used - * - * @generated from field: string verification_method = 3; - */ - verificationMethod = ""; - - /** - * proofPurpose is the purpose of the proof - * - * @generated from field: string proof_purpose = 4; - */ - proofPurpose = ""; - - /** - * signature is the cryptographic signature - * - * @generated from field: string signature = 5; - */ - signature = ""; - - /** - * Additional proof properties - * - * @generated from field: map properties = 6; - */ - properties: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.CredentialProof"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "proof_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "created", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "verification_method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "proof_purpose", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "signature", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "properties", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CredentialProof { - return new CredentialProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CredentialProof { - return new CredentialProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CredentialProof { - return new CredentialProof().fromJsonString(jsonString, options); - } - - static equals(a: CredentialProof | PlainMessage | undefined, b: CredentialProof | PlainMessage | undefined): boolean { - return proto3.util.equals(CredentialProof, a, b); - } -} - -/** - * CredentialStatus represents the revocation status of a credential - * - * @generated from message did.v1.CredentialStatus - */ -export class CredentialStatus extends Message { - /** - * id is the status identifier - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * status_kind is the status type - * - * @generated from field: string status_kind = 2; - */ - statusKind = ""; - - /** - * Additional status properties - * - * @generated from field: map properties = 3; - */ - properties: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "did.v1.CredentialStatus"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "status_kind", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "properties", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CredentialStatus { - return new CredentialStatus().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CredentialStatus { - return new CredentialStatus().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CredentialStatus { - return new CredentialStatus().fromJsonString(jsonString, options); - } - - static equals(a: CredentialStatus | PlainMessage | undefined, b: CredentialStatus | PlainMessage | undefined): boolean { - return proto3.util.equals(CredentialStatus, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/module/v1/module_pb.ts b/packages/es/src/protobufs/dwn/module/v1/module_pb.ts deleted file mode 100644 index e1731a5c5..000000000 --- a/packages/es/src/protobufs/dwn/module/v1/module_pb.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/module/v1/module.proto (package dwn.module.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Module is the app config object of the module. - * Learn more: https://docs.cosmos.network/main/building-modules/depinject - * - * @generated from message dwn.module.v1.Module - */ -export class Module extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.module.v1.Module"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals(a: Module | PlainMessage | undefined, b: Module | PlainMessage | undefined): boolean { - return proto3.util.equals(Module, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/v1/events_pb.ts b/packages/es/src/protobufs/dwn/v1/events_pb.ts deleted file mode 100644 index 81ad33c91..000000000 --- a/packages/es/src/protobufs/dwn/v1/events_pb.ts +++ /dev/null @@ -1,600 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/v1/events.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * EventRecordWritten is emitted when a record is written to DWN - * - * @generated from message dwn.v1.EventRecordWritten - */ -export class EventRecordWritten extends Message { - /** - * Record ID - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * Target DID - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Protocol URI - * - * @generated from field: string protocol = 3; - */ - protocol = ""; - - /** - * Schema URI - * - * @generated from field: string schema = 4; - */ - schema = ""; - - /** - * Data CID - * - * @generated from field: string data_cid = 5; - */ - dataCid = ""; - - /** - * Data size in bytes - * - * @generated from field: uint64 data_size = 6; - */ - dataSize = protoInt64.zero; - - /** - * Whether data is encrypted - * - * @generated from field: bool encrypted = 7; - */ - encrypted = false; - - /** - * Block height - * - * @generated from field: uint64 block_height = 8; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventRecordWritten"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "schema", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "data_cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "data_size", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "encrypted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 8, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventRecordWritten { - return new EventRecordWritten().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventRecordWritten { - return new EventRecordWritten().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventRecordWritten { - return new EventRecordWritten().fromJsonString(jsonString, options); - } - - static equals(a: EventRecordWritten | PlainMessage | undefined, b: EventRecordWritten | PlainMessage | undefined): boolean { - return proto3.util.equals(EventRecordWritten, a, b); - } -} - -/** - * EventRecordDeleted is emitted when a record is deleted from DWN - * - * @generated from message dwn.v1.EventRecordDeleted - */ -export class EventRecordDeleted extends Message { - /** - * Record ID - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * Target DID - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Deleter address - * - * @generated from field: string deleter = 3; - */ - deleter = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventRecordDeleted"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "deleter", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventRecordDeleted { - return new EventRecordDeleted().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventRecordDeleted { - return new EventRecordDeleted().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventRecordDeleted { - return new EventRecordDeleted().fromJsonString(jsonString, options); - } - - static equals(a: EventRecordDeleted | PlainMessage | undefined, b: EventRecordDeleted | PlainMessage | undefined): boolean { - return proto3.util.equals(EventRecordDeleted, a, b); - } -} - -/** - * EventProtocolConfigured is emitted when a protocol is configured - * - * @generated from message dwn.v1.EventProtocolConfigured - */ -export class EventProtocolConfigured extends Message { - /** - * Target DID - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Protocol URI - * - * @generated from field: string protocol_uri = 2; - */ - protocolUri = ""; - - /** - * Whether protocol is published - * - * @generated from field: bool published = 3; - */ - published = false; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventProtocolConfigured"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "protocol_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "published", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventProtocolConfigured { - return new EventProtocolConfigured().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventProtocolConfigured { - return new EventProtocolConfigured().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventProtocolConfigured { - return new EventProtocolConfigured().fromJsonString(jsonString, options); - } - - static equals(a: EventProtocolConfigured | PlainMessage | undefined, b: EventProtocolConfigured | PlainMessage | undefined): boolean { - return proto3.util.equals(EventProtocolConfigured, a, b); - } -} - -/** - * EventPermissionGranted is emitted when a permission is granted - * - * @generated from message dwn.v1.EventPermissionGranted - */ -export class EventPermissionGranted extends Message { - /** - * Permission ID - * - * @generated from field: string permission_id = 1; - */ - permissionId = ""; - - /** - * Grantor DID - * - * @generated from field: string grantor = 2; - */ - grantor = ""; - - /** - * Grantee DID - * - * @generated from field: string grantee = 3; - */ - grantee = ""; - - /** - * Interface name - * - * @generated from field: string interface_name = 4; - */ - interfaceName = ""; - - /** - * Method name - * - * @generated from field: string method = 5; - */ - method = ""; - - /** - * Expiration timestamp - * - * @generated from field: google.protobuf.Timestamp expires_at = 6; - */ - expiresAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 7; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventPermissionGranted"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permission_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "grantor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "grantee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "interface_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "expires_at", kind: "message", T: Timestamp }, - { no: 7, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventPermissionGranted { - return new EventPermissionGranted().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventPermissionGranted { - return new EventPermissionGranted().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventPermissionGranted { - return new EventPermissionGranted().fromJsonString(jsonString, options); - } - - static equals(a: EventPermissionGranted | PlainMessage | undefined, b: EventPermissionGranted | PlainMessage | undefined): boolean { - return proto3.util.equals(EventPermissionGranted, a, b); - } -} - -/** - * EventPermissionRevoked is emitted when a permission is revoked - * - * @generated from message dwn.v1.EventPermissionRevoked - */ -export class EventPermissionRevoked extends Message { - /** - * Permission ID - * - * @generated from field: string permission_id = 1; - */ - permissionId = ""; - - /** - * Revoker DID - * - * @generated from field: string revoker = 2; - */ - revoker = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 3; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventPermissionRevoked"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permission_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "revoker", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventPermissionRevoked { - return new EventPermissionRevoked().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventPermissionRevoked { - return new EventPermissionRevoked().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventPermissionRevoked { - return new EventPermissionRevoked().fromJsonString(jsonString, options); - } - - static equals(a: EventPermissionRevoked | PlainMessage | undefined, b: EventPermissionRevoked | PlainMessage | undefined): boolean { - return proto3.util.equals(EventPermissionRevoked, a, b); - } -} - -/** - * EventVaultCreated is emitted when a vault is created - * - * @generated from message dwn.v1.EventVaultCreated - */ -export class EventVaultCreated extends Message { - /** - * Vault ID - * - * @generated from field: string vault_id = 1; - */ - vaultId = ""; - - /** - * Owner DID - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * Vault public key - * - * @generated from field: string public_key = 3; - */ - publicKey = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventVaultCreated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "public_key", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventVaultCreated { - return new EventVaultCreated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventVaultCreated { - return new EventVaultCreated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventVaultCreated { - return new EventVaultCreated().fromJsonString(jsonString, options); - } - - static equals(a: EventVaultCreated | PlainMessage | undefined, b: EventVaultCreated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventVaultCreated, a, b); - } -} - -/** - * EventVaultKeysRotated is emitted when vault keys are rotated - * - * @generated from message dwn.v1.EventVaultKeysRotated - */ -export class EventVaultKeysRotated extends Message { - /** - * Vault ID - * - * @generated from field: string vault_id = 1; - */ - vaultId = ""; - - /** - * Owner DID - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * New public key - * - * @generated from field: string new_public_key = 3; - */ - newPublicKey = ""; - - /** - * Rotation height - * - * @generated from field: uint64 rotation_height = 4; - */ - rotationHeight = protoInt64.zero; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventVaultKeysRotated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "new_public_key", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "rotation_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventVaultKeysRotated { - return new EventVaultKeysRotated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventVaultKeysRotated { - return new EventVaultKeysRotated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventVaultKeysRotated { - return new EventVaultKeysRotated().fromJsonString(jsonString, options); - } - - static equals(a: EventVaultKeysRotated | PlainMessage | undefined, b: EventVaultKeysRotated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventVaultKeysRotated, a, b); - } -} - -/** - * EventKeyRotation is emitted when encryption keys are rotated - * - * @generated from message dwn.v1.EventKeyRotation - */ -export class EventKeyRotation extends Message { - /** - * Previous key version (0 if first rotation) - * - * @generated from field: uint64 old_key_version = 1; - */ - oldKeyVersion = protoInt64.zero; - - /** - * New key version - * - * @generated from field: uint64 new_key_version = 2; - */ - newKeyVersion = protoInt64.zero; - - /** - * Reason for rotation - * - * @generated from field: string reason = 3; - */ - reason = ""; - - /** - * Block height when rotation occurred - * - * @generated from field: uint64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - /** - * Whether running in single node mode - * - * @generated from field: bool single_node_mode = 5; - */ - singleNodeMode = false; - - /** - * Number of validators at time of rotation - * - * @generated from field: uint32 validator_count = 6; - */ - validatorCount = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EventKeyRotation"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "old_key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "new_key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "reason", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "single_node_mode", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "validator_count", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventKeyRotation { - return new EventKeyRotation().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventKeyRotation { - return new EventKeyRotation().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventKeyRotation { - return new EventKeyRotation().fromJsonString(jsonString, options); - } - - static equals(a: EventKeyRotation | PlainMessage | undefined, b: EventKeyRotation | PlainMessage | undefined): boolean { - return proto3.util.equals(EventKeyRotation, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/v1/genesis_pb.ts b/packages/es/src/protobufs/dwn/v1/genesis_pb.ts deleted file mode 100644 index 88efee652..000000000 --- a/packages/es/src/protobufs/dwn/v1/genesis_pb.ts +++ /dev/null @@ -1,258 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/v1/genesis.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { DWNPermission, DWNProtocol, DWNRecord, VaultState } from "./state_pb.js"; - -/** - * GenesisState defines the module genesis state - * - * @generated from message dwn.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * Params defines all the parameters of the module. - * - * @generated from field: dwn.v1.Params params = 1; - */ - params?: Params; - - /** - * DWN Records - * - * @generated from field: repeated dwn.v1.DWNRecord records = 2; - */ - records: DWNRecord[] = []; - - /** - * DWN Protocols - * - * @generated from field: repeated dwn.v1.DWNProtocol protocols = 3; - */ - protocols: DWNProtocol[] = []; - - /** - * DWN Permissions - * - * @generated from field: repeated dwn.v1.DWNPermission permissions = 4; - */ - permissions: DWNPermission[] = []; - - /** - * Vaults - * - * @generated from field: repeated dwn.v1.VaultState vaults = 5; - */ - vaults: VaultState[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "records", kind: "message", T: DWNRecord, repeated: true }, - { no: 3, name: "protocols", kind: "message", T: DWNProtocol, repeated: true }, - { no: 4, name: "permissions", kind: "message", T: DWNPermission, repeated: true }, - { no: 5, name: "vaults", kind: "message", T: VaultState, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Params defines the set of module parameters. - * - * @generated from message dwn.v1.Params - */ -export class Params extends Message { - /** - * Maximum size for DWN record data in bytes - * - * @generated from field: uint64 max_record_size = 1; - */ - maxRecordSize = protoInt64.zero; - - /** - * Maximum number of protocols per DWN - * - * @generated from field: uint32 max_protocols_per_dwn = 2; - */ - maxProtocolsPerDwn = 0; - - /** - * Maximum number of permissions per DWN - * - * @generated from field: uint32 max_permissions_per_dwn = 3; - */ - maxPermissionsPerDwn = 0; - - /** - * Enable vault creation - * - * @generated from field: bool vault_creation_enabled = 4; - */ - vaultCreationEnabled = false; - - /** - * Minimum vault refresh interval in blocks - * - * @generated from field: uint64 min_vault_refresh_interval = 5; - */ - minVaultRefreshInterval = protoInt64.zero; - - /** - * Encryption configuration - * - * @generated from field: bool encryption_enabled = 6; - */ - encryptionEnabled = false; - - /** - * Key rotation interval in days - * - * @generated from field: uint32 key_rotation_days = 7; - */ - keyRotationDays = 0; - - /** - * Minimum validators required for key generation (percentage of active set) - * - * @generated from field: uint32 min_validators_for_key_gen = 8; - */ - minValidatorsForKeyGen = 0; - - /** - * Protocols that require encryption - * - * @generated from field: repeated string encrypted_protocols = 9; - */ - encryptedProtocols: string[] = []; - - /** - * Schemas that require encryption - * - * @generated from field: repeated string encrypted_schemas = 10; - */ - encryptedSchemas: string[] = []; - - /** - * Enable single-node fallback for development - * - * @generated from field: bool single_node_fallback = 11; - */ - singleNodeFallback = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_record_size", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "max_protocols_per_dwn", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "max_permissions_per_dwn", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: "vault_creation_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: "min_vault_refresh_interval", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "encryption_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 7, name: "key_rotation_days", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 8, name: "min_validators_for_key_gen", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 9, name: "encrypted_protocols", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "encrypted_schemas", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 11, name: "single_node_fallback", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * @generated from message dwn.v1.IPFSStatus - */ -export class IPFSStatus extends Message { - /** - * @generated from field: string peer_id = 1; - */ - peerId = ""; - - /** - * @generated from field: string peer_name = 2; - */ - peerName = ""; - - /** - * @generated from field: string peer_type = 3; - */ - peerType = ""; - - /** - * @generated from field: string version = 4; - */ - version = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.IPFSStatus"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "peer_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "peer_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "peer_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IPFSStatus { - return new IPFSStatus().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IPFSStatus { - return new IPFSStatus().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IPFSStatus { - return new IPFSStatus().fromJsonString(jsonString, options); - } - - static equals(a: IPFSStatus | PlainMessage | undefined, b: IPFSStatus | PlainMessage | undefined): boolean { - return proto3.util.equals(IPFSStatus, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/v1/query_cosmes.ts b/packages/es/src/protobufs/dwn/v1/query_cosmes.ts deleted file mode 100644 index b66eaa91c..000000000 --- a/packages/es/src/protobufs/dwn/v1/query_cosmes.ts +++ /dev/null @@ -1,170 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file dwn/v1/query.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryCIDRequest, QueryCIDResponse, QueryEncryptedRecordRequest, QueryEncryptedRecordResponse, QueryEncryptionStatusRequest, QueryEncryptionStatusResponse, QueryIPFSRequest, QueryIPFSResponse, QueryParamsRequest, QueryParamsResponse, QueryPermissionsRequest, QueryPermissionsResponse, QueryProtocolRequest, QueryProtocolResponse, QueryProtocolsRequest, QueryProtocolsResponse, QueryRecordRequest, QueryRecordResponse, QueryRecordsRequest, QueryRecordsResponse, QueryVaultRequest, QueryVaultResponse, QueryVaultsRequest, QueryVaultsResponse, QueryVRFContributionsRequest, QueryVRFContributionsResponse } from "./query_pb.js"; - -const TYPE_NAME = "dwn.v1.Query"; - -/** - * Params queries all parameters of the module. - * - * @generated from rpc dwn.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * IPFS queries the status of the IPFS node - * - * @generated from rpc dwn.v1.Query.IPFS - */ -export const QueryIPFSService = { - typeName: TYPE_NAME, - method: "IPFS", - Request: QueryIPFSRequest, - Response: QueryIPFSResponse, -} as const; - -/** - * CID returns the data for a given CID - * - * @generated from rpc dwn.v1.Query.CID - */ -export const QueryCIDService = { - typeName: TYPE_NAME, - method: "CID", - Request: QueryCIDRequest, - Response: QueryCIDResponse, -} as const; - -/** - * Records queries DWN records with filters - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dwn_docs.md"}} - * - * @generated from rpc dwn.v1.Query.Records - */ -export const QueryRecordsService = { - typeName: TYPE_NAME, - method: "Records", - Request: QueryRecordsRequest, - Response: QueryRecordsResponse, -} as const; - -/** - * Record queries a specific DWN record by ID - * - * @generated from rpc dwn.v1.Query.Record - */ -export const QueryRecordService = { - typeName: TYPE_NAME, - method: "Record", - Request: QueryRecordRequest, - Response: QueryRecordResponse, -} as const; - -/** - * Protocols queries DWN protocols - * - * @generated from rpc dwn.v1.Query.Protocols - */ -export const QueryProtocolsService = { - typeName: TYPE_NAME, - method: "Protocols", - Request: QueryProtocolsRequest, - Response: QueryProtocolsResponse, -} as const; - -/** - * Protocol queries a specific DWN protocol - * - * @generated from rpc dwn.v1.Query.Protocol - */ -export const QueryProtocolService = { - typeName: TYPE_NAME, - method: "Protocol", - Request: QueryProtocolRequest, - Response: QueryProtocolResponse, -} as const; - -/** - * Permissions queries DWN permissions - * - * @generated from rpc dwn.v1.Query.Permissions - */ -export const QueryPermissionsService = { - typeName: TYPE_NAME, - method: "Permissions", - Request: QueryPermissionsRequest, - Response: QueryPermissionsResponse, -} as const; - -/** - * Vault queries a specific vault - * - * @generated from rpc dwn.v1.Query.Vault - */ -export const QueryVaultService = { - typeName: TYPE_NAME, - method: "Vault", - Request: QueryVaultRequest, - Response: QueryVaultResponse, -} as const; - -/** - * Vaults queries vaults by owner - * - * @generated from rpc dwn.v1.Query.Vaults - */ -export const QueryVaultsService = { - typeName: TYPE_NAME, - method: "Vaults", - Request: QueryVaultsRequest, - Response: QueryVaultsResponse, -} as const; - -/** - * EncryptedRecord queries a specific encrypted record with automatic decryption - * - * @generated from rpc dwn.v1.Query.EncryptedRecord - */ -export const QueryEncryptedRecordService = { - typeName: TYPE_NAME, - method: "EncryptedRecord", - Request: QueryEncryptedRecordRequest, - Response: QueryEncryptedRecordResponse, -} as const; - -/** - * EncryptionStatus queries current encryption key state and version - * - * @generated from rpc dwn.v1.Query.EncryptionStatus - */ -export const QueryEncryptionStatusService = { - typeName: TYPE_NAME, - method: "EncryptionStatus", - Request: QueryEncryptionStatusRequest, - Response: QueryEncryptionStatusResponse, -} as const; - -/** - * VRFContributions lists VRF contributions for current consensus round - * - * @generated from rpc dwn.v1.Query.VRFContributions - */ -export const QueryVRFContributionsService = { - typeName: TYPE_NAME, - method: "VRFContributions", - Request: QueryVRFContributionsRequest, - Response: QueryVRFContributionsResponse, -} as const; - diff --git a/packages/es/src/protobufs/dwn/v1/query_pb.ts b/packages/es/src/protobufs/dwn/v1/query_pb.ts deleted file mode 100644 index e2063d405..000000000 --- a/packages/es/src/protobufs/dwn/v1/query_pb.ts +++ /dev/null @@ -1,1325 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/v1/query.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { IPFSStatus, Params } from "./genesis_pb.js"; -import { PageRequest, PageResponse } from "../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { DWNPermission, DWNProtocol, DWNRecord, EncryptionMetadata, VaultState, VRFConsensusRound, VRFContribution } from "./state_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message dwn.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message dwn.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: dwn.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryIPFSRequest is the request type for the Query/IPFS RPC method. - * - * @generated from message dwn.v1.QueryIPFSRequest - */ -export class QueryIPFSRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryIPFSRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryIPFSRequest { - return new QueryIPFSRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryIPFSRequest { - return new QueryIPFSRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryIPFSRequest { - return new QueryIPFSRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryIPFSRequest | PlainMessage | undefined, b: QueryIPFSRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryIPFSRequest, a, b); - } -} - -/** - * QueryIPFSResponse is the response type for the Query/IPFS RPC method. - * - * @generated from message dwn.v1.QueryIPFSResponse - */ -export class QueryIPFSResponse extends Message { - /** - * IPFS status - * - * @generated from field: dwn.v1.IPFSStatus status = 1; - */ - status?: IPFSStatus; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryIPFSResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "status", kind: "message", T: IPFSStatus }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryIPFSResponse { - return new QueryIPFSResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryIPFSResponse { - return new QueryIPFSResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryIPFSResponse { - return new QueryIPFSResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryIPFSResponse | PlainMessage | undefined, b: QueryIPFSResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryIPFSResponse, a, b); - } -} - -/** - * QueryCIDRequest is the request type for the Query/CID RPC method. - * - * @generated from message dwn.v1.QueryCIDRequest - */ -export class QueryCIDRequest extends Message { - /** - * CID to query - * - * @generated from field: string cid = 1; - */ - cid = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryCIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCIDRequest { - return new QueryCIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCIDRequest { - return new QueryCIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCIDRequest { - return new QueryCIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCIDRequest | PlainMessage | undefined, b: QueryCIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCIDRequest, a, b); - } -} - -/** - * QueryCIDResponse is the response type for the Query/CID RPC method. - * - * @generated from message dwn.v1.QueryCIDResponse - */ -export class QueryCIDResponse extends Message { - /** - * Status code - * - * @generated from field: int32 status_code = 1; - */ - statusCode = 0; - - /** - * CID data - * - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryCIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "status_code", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCIDResponse { - return new QueryCIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCIDResponse { - return new QueryCIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCIDResponse { - return new QueryCIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCIDResponse | PlainMessage | undefined, b: QueryCIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCIDResponse, a, b); - } -} - -/** - * QueryRecordsRequest is the request type for querying DWN records - * - * @generated from message dwn.v1.QueryRecordsRequest - */ -export class QueryRecordsRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Optional protocol filter - * - * @generated from field: string protocol = 2; - */ - protocol = ""; - - /** - * Optional schema filter - * - * @generated from field: string schema = 3; - */ - schema = ""; - - /** - * Optional parent ID filter - * - * @generated from field: string parent_id = 4; - */ - parentId = ""; - - /** - * Filter by published status - * - * @generated from field: bool published_only = 5; - */ - publishedOnly = false; - - /** - * Pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 6; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryRecordsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "schema", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "parent_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "published_only", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRecordsRequest { - return new QueryRecordsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRecordsRequest { - return new QueryRecordsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRecordsRequest { - return new QueryRecordsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRecordsRequest | PlainMessage | undefined, b: QueryRecordsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRecordsRequest, a, b); - } -} - -/** - * QueryRecordsResponse is the response type for querying DWN records - * - * @generated from message dwn.v1.QueryRecordsResponse - */ -export class QueryRecordsResponse extends Message { - /** - * List of records - * - * @generated from field: repeated dwn.v1.DWNRecord records = 1; - */ - records: DWNRecord[] = []; - - /** - * Pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryRecordsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "records", kind: "message", T: DWNRecord, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRecordsResponse { - return new QueryRecordsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRecordsResponse { - return new QueryRecordsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRecordsResponse { - return new QueryRecordsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRecordsResponse | PlainMessage | undefined, b: QueryRecordsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRecordsResponse, a, b); - } -} - -/** - * QueryRecordRequest is the request type for querying a specific DWN record - * - * @generated from message dwn.v1.QueryRecordRequest - */ -export class QueryRecordRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Record ID - * - * @generated from field: string record_id = 2; - */ - recordId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryRecordRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRecordRequest { - return new QueryRecordRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRecordRequest { - return new QueryRecordRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRecordRequest { - return new QueryRecordRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRecordRequest | PlainMessage | undefined, b: QueryRecordRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRecordRequest, a, b); - } -} - -/** - * QueryRecordResponse is the response type for querying a specific DWN record - * - * @generated from message dwn.v1.QueryRecordResponse - */ -export class QueryRecordResponse extends Message { - /** - * The record - * - * @generated from field: dwn.v1.DWNRecord record = 1; - */ - record?: DWNRecord; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryRecordResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record", kind: "message", T: DWNRecord }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRecordResponse { - return new QueryRecordResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRecordResponse { - return new QueryRecordResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRecordResponse { - return new QueryRecordResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRecordResponse | PlainMessage | undefined, b: QueryRecordResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRecordResponse, a, b); - } -} - -/** - * QueryProtocolsRequest is the request type for querying DWN protocols - * - * @generated from message dwn.v1.QueryProtocolsRequest - */ -export class QueryProtocolsRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Filter by published status - * - * @generated from field: bool published_only = 2; - */ - publishedOnly = false; - - /** - * Pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryProtocolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "published_only", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryProtocolsRequest { - return new QueryProtocolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryProtocolsRequest { - return new QueryProtocolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryProtocolsRequest { - return new QueryProtocolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryProtocolsRequest | PlainMessage | undefined, b: QueryProtocolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryProtocolsRequest, a, b); - } -} - -/** - * QueryProtocolsResponse is the response type for querying DWN protocols - * - * @generated from message dwn.v1.QueryProtocolsResponse - */ -export class QueryProtocolsResponse extends Message { - /** - * List of protocols - * - * @generated from field: repeated dwn.v1.DWNProtocol protocols = 1; - */ - protocols: DWNProtocol[] = []; - - /** - * Pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryProtocolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "protocols", kind: "message", T: DWNProtocol, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryProtocolsResponse { - return new QueryProtocolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryProtocolsResponse { - return new QueryProtocolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryProtocolsResponse { - return new QueryProtocolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryProtocolsResponse | PlainMessage | undefined, b: QueryProtocolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryProtocolsResponse, a, b); - } -} - -/** - * QueryProtocolRequest is the request type for querying a specific DWN protocol - * - * @generated from message dwn.v1.QueryProtocolRequest - */ -export class QueryProtocolRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Protocol URI - * - * @generated from field: string protocol_uri = 2; - */ - protocolUri = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryProtocolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "protocol_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryProtocolRequest { - return new QueryProtocolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryProtocolRequest { - return new QueryProtocolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryProtocolRequest { - return new QueryProtocolRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryProtocolRequest | PlainMessage | undefined, b: QueryProtocolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryProtocolRequest, a, b); - } -} - -/** - * QueryProtocolResponse is the response type for querying a specific DWN protocol - * - * @generated from message dwn.v1.QueryProtocolResponse - */ -export class QueryProtocolResponse extends Message { - /** - * The protocol - * - * @generated from field: dwn.v1.DWNProtocol protocol = 1; - */ - protocol?: DWNProtocol; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryProtocolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "protocol", kind: "message", T: DWNProtocol }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryProtocolResponse { - return new QueryProtocolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryProtocolResponse { - return new QueryProtocolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryProtocolResponse { - return new QueryProtocolResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryProtocolResponse | PlainMessage | undefined, b: QueryProtocolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryProtocolResponse, a, b); - } -} - -/** - * QueryPermissionsRequest is the request type for querying DWN permissions - * - * @generated from message dwn.v1.QueryPermissionsRequest - */ -export class QueryPermissionsRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Optional grantor filter - * - * @generated from field: string grantor = 2; - */ - grantor = ""; - - /** - * Optional grantee filter - * - * @generated from field: string grantee = 3; - */ - grantee = ""; - - /** - * Optional interface filter - * - * @generated from field: string interface_name = 4; - */ - interfaceName = ""; - - /** - * Optional method filter - * - * @generated from field: string method = 5; - */ - method = ""; - - /** - * Include revoked permissions - * - * @generated from field: bool include_revoked = 6; - */ - includeRevoked = false; - - /** - * Pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 7; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryPermissionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "grantor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "grantee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "interface_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "include_revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 7, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPermissionsRequest { - return new QueryPermissionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPermissionsRequest { - return new QueryPermissionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPermissionsRequest { - return new QueryPermissionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPermissionsRequest | PlainMessage | undefined, b: QueryPermissionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPermissionsRequest, a, b); - } -} - -/** - * QueryPermissionsResponse is the response type for querying DWN permissions - * - * @generated from message dwn.v1.QueryPermissionsResponse - */ -export class QueryPermissionsResponse extends Message { - /** - * List of permissions - * - * @generated from field: repeated dwn.v1.DWNPermission permissions = 1; - */ - permissions: DWNPermission[] = []; - - /** - * Pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryPermissionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permissions", kind: "message", T: DWNPermission, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPermissionsResponse { - return new QueryPermissionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPermissionsResponse { - return new QueryPermissionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPermissionsResponse { - return new QueryPermissionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPermissionsResponse | PlainMessage | undefined, b: QueryPermissionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPermissionsResponse, a, b); - } -} - -/** - * QueryVaultRequest is the request type for querying a specific vault - * - * @generated from message dwn.v1.QueryVaultRequest - */ -export class QueryVaultRequest extends Message { - /** - * Vault ID - * - * @generated from field: string vault_id = 1; - */ - vaultId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVaultRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVaultRequest { - return new QueryVaultRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVaultRequest { - return new QueryVaultRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVaultRequest { - return new QueryVaultRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryVaultRequest | PlainMessage | undefined, b: QueryVaultRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVaultRequest, a, b); - } -} - -/** - * QueryVaultResponse is the response type for querying a specific vault - * - * @generated from message dwn.v1.QueryVaultResponse - */ -export class QueryVaultResponse extends Message { - /** - * The vault - * - * @generated from field: dwn.v1.VaultState vault = 1; - */ - vault?: VaultState; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVaultResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vault", kind: "message", T: VaultState }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVaultResponse { - return new QueryVaultResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVaultResponse { - return new QueryVaultResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVaultResponse { - return new QueryVaultResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryVaultResponse | PlainMessage | undefined, b: QueryVaultResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVaultResponse, a, b); - } -} - -/** - * QueryVaultsRequest is the request type for querying vaults by owner - * - * @generated from message dwn.v1.QueryVaultsRequest - */ -export class QueryVaultsRequest extends Message { - /** - * Optional owner filter - * - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * Pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVaultsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVaultsRequest { - return new QueryVaultsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVaultsRequest { - return new QueryVaultsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVaultsRequest { - return new QueryVaultsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryVaultsRequest | PlainMessage | undefined, b: QueryVaultsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVaultsRequest, a, b); - } -} - -/** - * QueryVaultsResponse is the response type for querying vaults - * - * @generated from message dwn.v1.QueryVaultsResponse - */ -export class QueryVaultsResponse extends Message { - /** - * List of vaults - * - * @generated from field: repeated dwn.v1.VaultState vaults = 1; - */ - vaults: VaultState[] = []; - - /** - * Pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVaultsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vaults", kind: "message", T: VaultState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVaultsResponse { - return new QueryVaultsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVaultsResponse { - return new QueryVaultsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVaultsResponse { - return new QueryVaultsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryVaultsResponse | PlainMessage | undefined, b: QueryVaultsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVaultsResponse, a, b); - } -} - -/** - * QueryEncryptedRecordRequest is the request type for querying encrypted records - * - * @generated from message dwn.v1.QueryEncryptedRecordRequest - */ -export class QueryEncryptedRecordRequest extends Message { - /** - * Target DWN (DID) - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Record ID - * - * @generated from field: string record_id = 2; - */ - recordId = ""; - - /** - * Optional: return encrypted data instead of decrypting - * - * @generated from field: bool return_encrypted = 3; - */ - returnEncrypted = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryEncryptedRecordRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "return_encrypted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEncryptedRecordRequest { - return new QueryEncryptedRecordRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEncryptedRecordRequest { - return new QueryEncryptedRecordRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEncryptedRecordRequest { - return new QueryEncryptedRecordRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEncryptedRecordRequest | PlainMessage | undefined, b: QueryEncryptedRecordRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEncryptedRecordRequest, a, b); - } -} - -/** - * QueryEncryptedRecordResponse is the response type for querying encrypted records - * - * @generated from message dwn.v1.QueryEncryptedRecordResponse - */ -export class QueryEncryptedRecordResponse extends Message { - /** - * The record with decrypted data (if requested) - * - * @generated from field: dwn.v1.DWNRecord record = 1; - */ - record?: DWNRecord; - - /** - * Encryption metadata for the record - * - * @generated from field: dwn.v1.EncryptionMetadata encryption_metadata = 2; - */ - encryptionMetadata?: EncryptionMetadata; - - /** - * Whether data was decrypted - * - * @generated from field: bool was_decrypted = 3; - */ - wasDecrypted = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryEncryptedRecordResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record", kind: "message", T: DWNRecord }, - { no: 2, name: "encryption_metadata", kind: "message", T: EncryptionMetadata }, - { no: 3, name: "was_decrypted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEncryptedRecordResponse { - return new QueryEncryptedRecordResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEncryptedRecordResponse { - return new QueryEncryptedRecordResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEncryptedRecordResponse { - return new QueryEncryptedRecordResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEncryptedRecordResponse | PlainMessage | undefined, b: QueryEncryptedRecordResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEncryptedRecordResponse, a, b); - } -} - -/** - * QueryEncryptionStatusRequest is the request type for querying encryption status - * - * @generated from message dwn.v1.QueryEncryptionStatusRequest - */ -export class QueryEncryptionStatusRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryEncryptionStatusRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEncryptionStatusRequest { - return new QueryEncryptionStatusRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEncryptionStatusRequest { - return new QueryEncryptionStatusRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEncryptionStatusRequest { - return new QueryEncryptionStatusRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEncryptionStatusRequest | PlainMessage | undefined, b: QueryEncryptionStatusRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEncryptionStatusRequest, a, b); - } -} - -/** - * QueryEncryptionStatusResponse is the response type for querying encryption status - * - * @generated from message dwn.v1.QueryEncryptionStatusResponse - */ -export class QueryEncryptionStatusResponse extends Message { - /** - * Current encryption key version - * - * @generated from field: uint64 current_key_version = 1; - */ - currentKeyVersion = protoInt64.zero; - - /** - * Current validator set participating in consensus - * - * @generated from field: repeated string validator_set = 2; - */ - validatorSet: string[] = []; - - /** - * Whether running in single-node mode - * - * @generated from field: bool single_node_mode = 3; - */ - singleNodeMode = false; - - /** - * Last key rotation timestamp - * - * @generated from field: int64 last_rotation = 4; - */ - lastRotation = protoInt64.zero; - - /** - * Next scheduled rotation timestamp - * - * @generated from field: int64 next_rotation = 5; - */ - nextRotation = protoInt64.zero; - - /** - * Total encrypted records in the system - * - * @generated from field: uint64 total_encrypted_records = 6; - */ - totalEncryptedRecords = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryEncryptionStatusResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "current_key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "validator_set", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 3, name: "single_node_mode", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 4, name: "last_rotation", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "next_rotation", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "total_encrypted_records", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEncryptionStatusResponse { - return new QueryEncryptionStatusResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEncryptionStatusResponse { - return new QueryEncryptionStatusResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEncryptionStatusResponse { - return new QueryEncryptionStatusResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEncryptionStatusResponse | PlainMessage | undefined, b: QueryEncryptionStatusResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEncryptionStatusResponse, a, b); - } -} - -/** - * QueryVRFContributionsRequest is the request type for querying VRF contributions - * - * @generated from message dwn.v1.QueryVRFContributionsRequest - */ -export class QueryVRFContributionsRequest extends Message { - /** - * Optional: filter by validator address - * - * @generated from field: string validator_address = 1; - */ - validatorAddress = ""; - - /** - * Optional: filter by block height - * - * @generated from field: int64 block_height = 2; - */ - blockHeight = protoInt64.zero; - - /** - * Pagination - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVRFContributionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "block_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVRFContributionsRequest { - return new QueryVRFContributionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVRFContributionsRequest { - return new QueryVRFContributionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVRFContributionsRequest { - return new QueryVRFContributionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryVRFContributionsRequest | PlainMessage | undefined, b: QueryVRFContributionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVRFContributionsRequest, a, b); - } -} - -/** - * QueryVRFContributionsResponse is the response type for querying VRF contributions - * - * @generated from message dwn.v1.QueryVRFContributionsResponse - */ -export class QueryVRFContributionsResponse extends Message { - /** - * List of VRF contributions - * - * @generated from field: repeated dwn.v1.VRFContribution contributions = 1; - */ - contributions: VRFContribution[] = []; - - /** - * Current consensus round information - * - * @generated from field: dwn.v1.VRFConsensusRound current_round = 2; - */ - currentRound?: VRFConsensusRound; - - /** - * Pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 3; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.QueryVRFContributionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contributions", kind: "message", T: VRFContribution, repeated: true }, - { no: 2, name: "current_round", kind: "message", T: VRFConsensusRound }, - { no: 3, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVRFContributionsResponse { - return new QueryVRFContributionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVRFContributionsResponse { - return new QueryVRFContributionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVRFContributionsResponse { - return new QueryVRFContributionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryVRFContributionsResponse | PlainMessage | undefined, b: QueryVRFContributionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVRFContributionsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/v1/state_pb.ts b/packages/es/src/protobufs/dwn/v1/state_pb.ts deleted file mode 100644 index 05596f171..000000000 --- a/packages/es/src/protobufs/dwn/v1/state_pb.ts +++ /dev/null @@ -1,1277 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/v1/state.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * EncryptionMetadata contains metadata for consensus-based encryption - * - * @generated from message dwn.v1.EncryptionMetadata - */ -export class EncryptionMetadata extends Message { - /** - * Encryption algorithm used (e.g., "AES-256-GCM") - * - * @generated from field: string algorithm = 1; - */ - algorithm = ""; - - /** - * Input used for VRF consensus key derivation - * - * @generated from field: bytes consensus_input = 2; - */ - consensusInput = new Uint8Array(0); - - /** - * Nonce used for encryption - * - * @generated from field: bytes nonce = 3; - */ - nonce = new Uint8Array(0); - - /** - * Authentication tag from AES-GCM - * - * @generated from field: bytes auth_tag = 4; - */ - authTag = new Uint8Array(0); - - /** - * Block height when encryption was performed - * - * @generated from field: int64 encryption_height = 5; - */ - encryptionHeight = protoInt64.zero; - - /** - * Validator set participating in consensus - * - * @generated from field: repeated string validator_set = 6; - */ - validatorSet: string[] = []; - - /** - * Key rotation version - * - * @generated from field: uint64 key_version = 7; - */ - keyVersion = protoInt64.zero; - - /** - * Single node development mode flag - * - * @generated from field: bool single_node_mode = 8; - */ - singleNodeMode = false; - - /** - * HMAC-SHA256 authentication tag for data integrity - * - * @generated from field: bytes data_hmac = 9; - */ - dataHmac = new Uint8Array(0); - - /** - * Salt used for key derivation - * - * @generated from field: bytes key_derivation_salt = 10; - */ - keyDerivationSalt = new Uint8Array(0); - - /** - * Additional authenticated data (AAD) for AES-GCM - * - * @generated from field: bytes additional_data = 11; - */ - additionalData = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EncryptionMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "algorithm", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "consensus_input", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "nonce", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "auth_tag", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "encryption_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "validator_set", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 7, name: "key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 8, name: "single_node_mode", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 9, name: "data_hmac", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "key_derivation_salt", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 11, name: "additional_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EncryptionMetadata { - return new EncryptionMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EncryptionMetadata { - return new EncryptionMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EncryptionMetadata { - return new EncryptionMetadata().fromJsonString(jsonString, options); - } - - static equals(a: EncryptionMetadata | PlainMessage | undefined, b: EncryptionMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(EncryptionMetadata, a, b); - } -} - -/** - * EncryptionKeyState contains the current key and contributions for a given key version - * - * @generated from message dwn.v1.EncryptionKeyState - */ -export class EncryptionKeyState extends Message { - /** - * Current encryption key (stored encrypted or as reference) - * - * @generated from field: bytes current_key = 1; - */ - currentKey = new Uint8Array(0); - - /** - * Key version/epoch identifier - * - * @generated from field: uint64 key_version = 2; - */ - keyVersion = protoInt64.zero; - - /** - * Validator set participating in consensus - * - * @generated from field: repeated string validator_set = 3; - */ - validatorSet: string[] = []; - - /** - * VRF contributions for this key generation round - * - * @generated from field: repeated dwn.v1.VRFContribution contributions = 4; - */ - contributions: VRFContribution[] = []; - - /** - * Last rotation timestamp (Unix timestamp) - * - * @generated from field: int64 last_rotation = 5; - */ - lastRotation = protoInt64.zero; - - /** - * Next scheduled rotation timestamp (Unix timestamp) - * - * @generated from field: int64 next_rotation = 6; - */ - nextRotation = protoInt64.zero; - - /** - * Single node development mode flag - * - * @generated from field: bool single_node_mode = 7; - */ - singleNodeMode = false; - - /** - * Usage count for this key (for usage-based rotation) - * - * @generated from field: uint64 usage_count = 8; - */ - usageCount = protoInt64.zero; - - /** - * Maximum usage count before rotation - * - * @generated from field: uint64 max_usage_count = 9; - */ - maxUsageCount = protoInt64.zero; - - /** - * Rotation interval in seconds (for time-based rotation) - * - * @generated from field: int64 rotation_interval = 10; - */ - rotationInterval = protoInt64.zero; - - /** - * Key creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 11; - */ - createdAt = protoInt64.zero; - - /** - * Previous key version for migration support - * - * @generated from field: uint64 previous_key_version = 12; - */ - previousKeyVersion = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EncryptionKeyState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "current_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "validator_set", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "contributions", kind: "message", T: VRFContribution, repeated: true }, - { no: 5, name: "last_rotation", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "next_rotation", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "single_node_mode", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 8, name: "usage_count", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 9, name: "max_usage_count", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 10, name: "rotation_interval", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 11, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "previous_key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EncryptionKeyState { - return new EncryptionKeyState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EncryptionKeyState { - return new EncryptionKeyState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EncryptionKeyState { - return new EncryptionKeyState().fromJsonString(jsonString, options); - } - - static equals(a: EncryptionKeyState | PlainMessage | undefined, b: EncryptionKeyState | PlainMessage | undefined): boolean { - return proto3.util.equals(EncryptionKeyState, a, b); - } -} - -/** - * VRFConsensusRound tracks a specific consensus round for key generation - * - * @generated from message dwn.v1.VRFConsensusRound - */ -export class VRFConsensusRound extends Message { - /** - * Round number for this consensus round - * - * @generated from field: uint64 round_number = 1; - */ - roundNumber = protoInt64.zero; - - /** - * Key version this round is generating - * - * @generated from field: uint64 key_version = 2; - */ - keyVersion = protoInt64.zero; - - /** - * Number of contributions required for consensus - * - * @generated from field: uint32 required_contributions = 3; - */ - requiredContributions = 0; - - /** - * Number of contributions received so far - * - * @generated from field: uint32 received_contributions = 4; - */ - receivedContributions = 0; - - /** - * Current status: "waiting_for_contributions", "complete", "expired", "single_node_mode" - * - * @generated from field: string status = 5; - */ - status = ""; - - /** - * Block height when this round expires - * - * @generated from field: int64 expiry_height = 6; - */ - expiryHeight = protoInt64.zero; - - /** - * Block height when round was initiated - * - * @generated from field: int64 initiated_height = 7; - */ - initiatedHeight = protoInt64.zero; - - /** - * Consensus input used for this round - * - * @generated from field: bytes consensus_input = 8; - */ - consensusInput = new Uint8Array(0); - - /** - * Whether this round completed successfully - * - * @generated from field: bool completed = 9; - */ - completed = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.VRFConsensusRound"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "round_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "required_contributions", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: "received_contributions", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 5, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "expiry_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "initiated_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 8, name: "consensus_input", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "completed", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VRFConsensusRound { - return new VRFConsensusRound().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VRFConsensusRound { - return new VRFConsensusRound().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VRFConsensusRound { - return new VRFConsensusRound().fromJsonString(jsonString, options); - } - - static equals(a: VRFConsensusRound | PlainMessage | undefined, b: VRFConsensusRound | PlainMessage | undefined): boolean { - return proto3.util.equals(VRFConsensusRound, a, b); - } -} - -/** - * EncryptionStats contains encryption statistics for monitoring - * - * @generated from message dwn.v1.EncryptionStats - */ -export class EncryptionStats extends Message { - /** - * Total number of encrypted records - * - * @generated from field: int64 total_encrypted_records = 1; - */ - totalEncryptedRecords = protoInt64.zero; - - /** - * Total number of decryption errors - * - * @generated from field: int64 total_decryption_errors = 2; - */ - totalDecryptionErrors = protoInt64.zero; - - /** - * Last encryption height - * - * @generated from field: int64 last_encryption_height = 3; - */ - lastEncryptionHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EncryptionStats"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_encrypted_records", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: "total_decryption_errors", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "last_encryption_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EncryptionStats { - return new EncryptionStats().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EncryptionStats { - return new EncryptionStats().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EncryptionStats { - return new EncryptionStats().fromJsonString(jsonString, options); - } - - static equals(a: EncryptionStats | PlainMessage | undefined, b: EncryptionStats | PlainMessage | undefined): boolean { - return proto3.util.equals(EncryptionStats, a, b); - } -} - -/** - * SaltStore contains salt management for encryption operations - * - * @generated from message dwn.v1.SaltStore - */ -export class SaltStore extends Message { - /** - * Unique identifier for the encrypted record - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * Salt value used for key derivation - * - * @generated from field: bytes salt_value = 2; - */ - saltValue = new Uint8Array(0); - - /** - * Creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 3; - */ - createdAt = protoInt64.zero; - - /** - * Key version associated with this salt - * - * @generated from field: uint64 key_version = 4; - */ - keyVersion = protoInt64.zero; - - /** - * Algorithm used with this salt (e.g., "PBKDF2-SHA256") - * - * @generated from field: string algorithm = 5; - */ - algorithm = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.SaltStore"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "salt_value", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: "key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "algorithm", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SaltStore { - return new SaltStore().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SaltStore { - return new SaltStore().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SaltStore { - return new SaltStore().fromJsonString(jsonString, options); - } - - static equals(a: SaltStore | PlainMessage | undefined, b: SaltStore | PlainMessage | undefined): boolean { - return proto3.util.equals(SaltStore, a, b); - } -} - -/** - * VRFContribution contains a VRF contribution for a given validator - * - * @generated from message dwn.v1.VRFContribution - */ -export class VRFContribution extends Message { - /** - * Validator address - * - * @generated from field: string validator_address = 1; - */ - validatorAddress = ""; - - /** - * VRF randomness output - * - * @generated from field: bytes randomness = 2; - */ - randomness = new Uint8Array(0); - - /** - * VRF proof for verification - * - * @generated from field: bytes proof = 3; - */ - proof = new Uint8Array(0); - - /** - * Block height when contribution was made - * - * @generated from field: int64 block_height = 4; - */ - blockHeight = protoInt64.zero; - - /** - * Unix timestamp when contribution was submitted - * - * @generated from field: int64 timestamp = 5; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.VRFContribution"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "randomness", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "block_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "timestamp", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VRFContribution { - return new VRFContribution().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VRFContribution { - return new VRFContribution().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VRFContribution { - return new VRFContribution().fromJsonString(jsonString, options); - } - - static equals(a: VRFContribution | PlainMessage | undefined, b: VRFContribution | PlainMessage | undefined): boolean { - return proto3.util.equals(VRFContribution, a, b); - } -} - -/** - * EncryptedDWNRecord contains an encrypted DWN record - * - * @generated from message dwn.v1.EncryptedDWNRecord - */ -export class EncryptedDWNRecord extends Message { - /** - * Unique identifier for the record - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * Encrypted data - * - * @generated from field: bytes encrypted_data = 2; - */ - encryptedData = new Uint8Array(0); - - /** - * Nonce used for encryption - * - * @generated from field: bytes nonce = 3; - */ - nonce = new Uint8Array(0); - - /** - * Key version - * - * @generated from field: uint64 key_version = 4; - */ - keyVersion = protoInt64.zero; - - /** - * IPFS hash of the record data - * - * @generated from field: string ipfs_hash = 5; - */ - ipfsHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EncryptedDWNRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "encrypted_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "nonce", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "ipfs_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EncryptedDWNRecord { - return new EncryptedDWNRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EncryptedDWNRecord { - return new EncryptedDWNRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EncryptedDWNRecord { - return new EncryptedDWNRecord().fromJsonString(jsonString, options); - } - - static equals(a: EncryptedDWNRecord | PlainMessage | undefined, b: EncryptedDWNRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(EncryptedDWNRecord, a, b); - } -} - -/** - * EnclaveData represents encrypted private key material within a secure enclave - * - * @generated from message dwn.v1.EnclaveData - */ -export class EnclaveData extends Message { - /** - * Encrypted private key material from the WASM enclave - * - * @generated from field: bytes private_data = 1; - */ - privateData = new Uint8Array(0); - - /** - * Public key corresponding to the private key - * - * @generated from field: bytes public_key = 2; - */ - publicKey = new Uint8Array(0); - - /** - * Unique identifier for the enclave instance - * - * @generated from field: string enclave_id = 3; - */ - enclaveId = ""; - - /** - * Version number for refresh tracking - * - * @generated from field: int64 version = 4; - */ - version = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.EnclaveData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "private_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "public_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "enclave_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "version", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EnclaveData { - return new EnclaveData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EnclaveData { - return new EnclaveData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EnclaveData { - return new EnclaveData().fromJsonString(jsonString, options); - } - - static equals(a: EnclaveData | PlainMessage | undefined, b: EnclaveData | PlainMessage | undefined): boolean { - return proto3.util.equals(EnclaveData, a, b); - } -} - -/** - * DWNMessageDescriptor contains metadata about a DWN message - * - * @generated from message dwn.v1.DWNMessageDescriptor - */ -export class DWNMessageDescriptor extends Message { - /** - * Interface type (e.g., "Records", "Protocols", "Permissions") - * - * @generated from field: string interface_name = 1; - */ - interfaceName = ""; - - /** - * Method name (e.g., "Write", "Query", "Configure") - * - * @generated from field: string method = 2; - */ - method = ""; - - /** - * ISO 8601 timestamp of when the message was created - * - * @generated from field: string message_timestamp = 3; - */ - messageTimestamp = ""; - - /** - * CID of the message data - * - * @generated from field: string data_cid = 4; - */ - dataCid = ""; - - /** - * Size of the data in bytes - * - * @generated from field: int64 data_size = 5; - */ - dataSize = protoInt64.zero; - - /** - * MIME type of the data - * - * @generated from field: string data_format = 6; - */ - dataFormat = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.DWNMessageDescriptor"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "interface_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "message_timestamp", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "data_cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "data_size", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "data_format", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DWNMessageDescriptor { - return new DWNMessageDescriptor().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DWNMessageDescriptor { - return new DWNMessageDescriptor().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DWNMessageDescriptor { - return new DWNMessageDescriptor().fromJsonString(jsonString, options); - } - - static equals(a: DWNMessageDescriptor | PlainMessage | undefined, b: DWNMessageDescriptor | PlainMessage | undefined): boolean { - return proto3.util.equals(DWNMessageDescriptor, a, b); - } -} - -/** - * DWNRecord represents a record stored in a Decentralized Web Node - * - * @generated from message dwn.v1.DWNRecord - */ -export class DWNRecord extends Message { - /** - * Unique identifier for the record - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * DID of the DWN target - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 3; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT or signature - * - * @generated from field: string authorization = 4; - */ - authorization = ""; - - /** - * Record data payload - * - * @generated from field: bytes data = 5; - */ - data = new Uint8Array(0); - - /** - * Optional protocol URI this record conforms to - * - * @generated from field: string protocol = 6; - */ - protocol = ""; - - /** - * Optional protocol path - * - * @generated from field: string protocol_path = 7; - */ - protocolPath = ""; - - /** - * Optional schema URI for data validation - * - * @generated from field: string schema = 8; - */ - schema = ""; - - /** - * Optional parent record ID for threading - * - * @generated from field: string parent_id = 9; - */ - parentId = ""; - - /** - * Published flag for public visibility - * - * @generated from field: bool published = 10; - */ - published = false; - - /** - * Attestation signature - * - * @generated from field: string attestation = 11; - */ - attestation = ""; - - /** - * Encryption details (legacy field) - * - * @generated from field: string encryption = 12; - */ - encryption = ""; - - /** - * Key derivation scheme (legacy field) - * - * @generated from field: string key_derivation_scheme = 13; - */ - keyDerivationScheme = ""; - - /** - * Creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 14; - */ - createdAt = protoInt64.zero; - - /** - * Last update timestamp (Unix timestamp) - * - * @generated from field: int64 updated_at = 15; - */ - updatedAt = protoInt64.zero; - - /** - * Block height when created - * - * @generated from field: int64 created_height = 16; - */ - createdHeight = protoInt64.zero; - - /** - * Encryption metadata for consensus-based encryption - * - * @generated from field: dwn.v1.EncryptionMetadata encryption_metadata = 17; - */ - encryptionMetadata?: EncryptionMetadata; - - /** - * Flag indicating if the record is encrypted - * - * @generated from field: bool is_encrypted = 18; - */ - isEncrypted = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.DWNRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 4, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "protocol_path", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "schema", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "parent_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "published", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 11, name: "attestation", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "encryption", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "key_derivation_scheme", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 14, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 15, name: "updated_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 16, name: "created_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 17, name: "encryption_metadata", kind: "message", T: EncryptionMetadata }, - { no: 18, name: "is_encrypted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DWNRecord { - return new DWNRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DWNRecord { - return new DWNRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DWNRecord { - return new DWNRecord().fromJsonString(jsonString, options); - } - - static equals(a: DWNRecord | PlainMessage | undefined, b: DWNRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(DWNRecord, a, b); - } -} - -/** - * DWNProtocol represents a configured protocol in a DWN - * - * @generated from message dwn.v1.DWNProtocol - */ -export class DWNProtocol extends Message { - /** - * DID of the DWN target - * - * @generated from field: string target = 1; - */ - target = ""; - - /** - * Protocol URI identifier - * - * @generated from field: string protocol_uri = 2; - */ - protocolUri = ""; - - /** - * Protocol definition JSON - * - * @generated from field: bytes definition = 3; - */ - definition = new Uint8Array(0); - - /** - * Published flag for discoverability - * - * @generated from field: bool published = 4; - */ - published = false; - - /** - * Creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 5; - */ - createdAt = protoInt64.zero; - - /** - * Block height when created - * - * @generated from field: int64 created_height = 6; - */ - createdHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.DWNProtocol"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "protocol_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "definition", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "published", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "created_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DWNProtocol { - return new DWNProtocol().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DWNProtocol { - return new DWNProtocol().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DWNProtocol { - return new DWNProtocol().fromJsonString(jsonString, options); - } - - static equals(a: DWNProtocol | PlainMessage | undefined, b: DWNProtocol | PlainMessage | undefined): boolean { - return proto3.util.equals(DWNProtocol, a, b); - } -} - -/** - * DWNPermission represents a permission grant in a DWN - * - * @generated from message dwn.v1.DWNPermission - */ -export class DWNPermission extends Message { - /** - * Unique identifier for the permission - * - * @generated from field: string permission_id = 1; - */ - permissionId = ""; - - /** - * DID of the permission grantor - * - * @generated from field: string grantor = 2; - */ - grantor = ""; - - /** - * DID of the permission grantee - * - * @generated from field: string grantee = 3; - */ - grantee = ""; - - /** - * DID of the DWN target - * - * @generated from field: string target = 4; - */ - target = ""; - - /** - * Interface scope (e.g., "Records", "Protocols") - * - * @generated from field: string interface_name = 5; - */ - interfaceName = ""; - - /** - * Method scope (e.g., "Write", "Query") - * - * @generated from field: string method = 6; - */ - method = ""; - - /** - * Optional protocol scope - * - * @generated from field: string protocol = 7; - */ - protocol = ""; - - /** - * Optional record scope - * - * @generated from field: string record_id = 8; - */ - recordId = ""; - - /** - * Permission conditions JSON - * - * @generated from field: bytes conditions = 9; - */ - conditions = new Uint8Array(0); - - /** - * Expiration timestamp (Unix timestamp) - * - * @generated from field: int64 expires_at = 10; - */ - expiresAt = protoInt64.zero; - - /** - * Creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 11; - */ - createdAt = protoInt64.zero; - - /** - * Revoked flag - * - * @generated from field: bool revoked = 12; - */ - revoked = false; - - /** - * Block height when created - * - * @generated from field: int64 created_height = 13; - */ - createdHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.DWNPermission"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permission_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "grantor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "grantee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "interface_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "conditions", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "expires_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 11, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 13, name: "created_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DWNPermission { - return new DWNPermission().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DWNPermission { - return new DWNPermission().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DWNPermission { - return new DWNPermission().fromJsonString(jsonString, options); - } - - static equals(a: DWNPermission | PlainMessage | undefined, b: DWNPermission | PlainMessage | undefined): boolean { - return proto3.util.equals(DWNPermission, a, b); - } -} - -/** - * VaultState represents a vault instance for enclave-based operations - * - * @generated from message dwn.v1.VaultState - */ -export class VaultState extends Message { - /** - * Unique identifier for the vault - * - * @generated from field: string vault_id = 1; - */ - vaultId = ""; - - /** - * Owner DID or address - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * Enclave data containing encrypted keys - * - * @generated from field: dwn.v1.EnclaveData enclave_data = 3; - */ - enclaveData?: EnclaveData; - - /** - * Public key for verification - * - * @generated from field: bytes public_key = 4; - */ - publicKey = new Uint8Array(0); - - /** - * Creation timestamp (Unix timestamp) - * - * @generated from field: int64 created_at = 5; - */ - createdAt = protoInt64.zero; - - /** - * Last refresh timestamp (Unix timestamp) - * - * @generated from field: int64 last_refreshed = 6; - */ - lastRefreshed = protoInt64.zero; - - /** - * Block height when created - * - * @generated from field: int64 created_height = 7; - */ - createdHeight = protoInt64.zero; - - /** - * Encryption metadata for consensus-based encryption - * - * @generated from field: dwn.v1.EncryptionMetadata encryption_metadata = 8; - */ - encryptionMetadata?: EncryptionMetadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.VaultState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "enclave_data", kind: "message", T: EnclaveData }, - { no: 4, name: "public_key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "last_refreshed", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "created_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 8, name: "encryption_metadata", kind: "message", T: EncryptionMetadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): VaultState { - return new VaultState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): VaultState { - return new VaultState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): VaultState { - return new VaultState().fromJsonString(jsonString, options); - } - - static equals(a: VaultState | PlainMessage | undefined, b: VaultState | PlainMessage | undefined): boolean { - return proto3.util.equals(VaultState, a, b); - } -} - diff --git a/packages/es/src/protobufs/dwn/v1/tx_cosmes.ts b/packages/es/src/protobufs/dwn/v1/tx_cosmes.ts deleted file mode 100644 index aee97f76e..000000000 --- a/packages/es/src/protobufs/dwn/v1/tx_cosmes.ts +++ /dev/null @@ -1,94 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file dwn/v1/tx.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgPermissionsGrant, MsgPermissionsGrantResponse, MsgPermissionsRevoke, MsgPermissionsRevokeResponse, MsgProtocolsConfigure, MsgProtocolsConfigureResponse, MsgRecordsDelete, MsgRecordsDeleteResponse, MsgRecordsWrite, MsgRecordsWriteResponse, MsgRotateVaultKeys, MsgRotateVaultKeysResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "dwn.v1.Msg"; - -/** - * UpdateParams defines a governance operation for updating the parameters. - * - * @generated from rpc dwn.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * DWN Records Operations - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "dwn_docs.md"}} - * - * @generated from rpc dwn.v1.Msg.RecordsWrite - */ -export const MsgRecordsWriteService = { - typeName: TYPE_NAME, - method: "RecordsWrite", - Request: MsgRecordsWrite, - Response: MsgRecordsWriteResponse, -} as const; - -/** - * @generated from rpc dwn.v1.Msg.RecordsDelete - */ -export const MsgRecordsDeleteService = { - typeName: TYPE_NAME, - method: "RecordsDelete", - Request: MsgRecordsDelete, - Response: MsgRecordsDeleteResponse, -} as const; - -/** - * DWN Protocols Operations - * - * @generated from rpc dwn.v1.Msg.ProtocolsConfigure - */ -export const MsgProtocolsConfigureService = { - typeName: TYPE_NAME, - method: "ProtocolsConfigure", - Request: MsgProtocolsConfigure, - Response: MsgProtocolsConfigureResponse, -} as const; - -/** - * DWN Permissions Operations - * - * @generated from rpc dwn.v1.Msg.PermissionsGrant - */ -export const MsgPermissionsGrantService = { - typeName: TYPE_NAME, - method: "PermissionsGrant", - Request: MsgPermissionsGrant, - Response: MsgPermissionsGrantResponse, -} as const; - -/** - * @generated from rpc dwn.v1.Msg.PermissionsRevoke - */ -export const MsgPermissionsRevokeService = { - typeName: TYPE_NAME, - method: "PermissionsRevoke", - Request: MsgPermissionsRevoke, - Response: MsgPermissionsRevokeResponse, -} as const; - -/** - * DWN Vault Operations - * - * @generated from rpc dwn.v1.Msg.RotateVaultKeys - */ -export const MsgRotateVaultKeysService = { - typeName: TYPE_NAME, - method: "RotateVaultKeys", - Request: MsgRotateVaultKeys, - Response: MsgRotateVaultKeysResponse, -} as const; - diff --git a/packages/es/src/protobufs/dwn/v1/tx_pb.ts b/packages/es/src/protobufs/dwn/v1/tx_pb.ts deleted file mode 100644 index 6eec9e8de..000000000 --- a/packages/es/src/protobufs/dwn/v1/tx_pb.ts +++ /dev/null @@ -1,929 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file dwn/v1/tx.proto (package dwn.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { DWNMessageDescriptor } from "./state_pb.js"; - -/** - * MsgUpdateParams is the Msg/UpdateParams request type. - * - * @generated from message dwn.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the parameters to update. - * - * @generated from field: dwn.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * @generated from message dwn.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgRecordsWrite creates or updates a record in the DWN - * - * @generated from message dwn.v1.MsgRecordsWrite - */ -export class MsgRecordsWrite extends Message { - /** - * Author of the record (DID or cosmos address) - * - * @generated from field: string author = 1; - */ - author = ""; - - /** - * Target DWN (DID) - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 3; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT/signature - * - * @generated from field: string authorization = 4; - */ - authorization = ""; - - /** - * Record data - * - * @generated from field: bytes data = 5; - */ - data = new Uint8Array(0); - - /** - * Optional protocol URI - * - * @generated from field: string protocol = 6; - */ - protocol = ""; - - /** - * Optional protocol path - * - * @generated from field: string protocol_path = 7; - */ - protocolPath = ""; - - /** - * Optional schema URI - * - * @generated from field: string schema = 8; - */ - schema = ""; - - /** - * Optional parent record ID - * - * @generated from field: string parent_id = 9; - */ - parentId = ""; - - /** - * Published flag - * - * @generated from field: bool published = 10; - */ - published = false; - - /** - * Optional encryption details - * - * @generated from field: string encryption = 11; - */ - encryption = ""; - - /** - * Optional attestation - * - * @generated from field: string attestation = 12; - */ - attestation = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRecordsWrite"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "author", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 4, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "protocol_path", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "schema", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "parent_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "published", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 11, name: "encryption", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "attestation", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecordsWrite { - return new MsgRecordsWrite().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecordsWrite { - return new MsgRecordsWrite().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecordsWrite { - return new MsgRecordsWrite().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecordsWrite | PlainMessage | undefined, b: MsgRecordsWrite | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecordsWrite, a, b); - } -} - -/** - * MsgRecordsWriteResponse defines the response for RecordsWrite - * - * @generated from message dwn.v1.MsgRecordsWriteResponse - */ -export class MsgRecordsWriteResponse extends Message { - /** - * Record ID of the created/updated record - * - * @generated from field: string record_id = 1; - */ - recordId = ""; - - /** - * CID of the data - * - * @generated from field: string data_cid = 2; - */ - dataCid = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRecordsWriteResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "data_cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecordsWriteResponse { - return new MsgRecordsWriteResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecordsWriteResponse { - return new MsgRecordsWriteResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecordsWriteResponse { - return new MsgRecordsWriteResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecordsWriteResponse | PlainMessage | undefined, b: MsgRecordsWriteResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecordsWriteResponse, a, b); - } -} - -/** - * MsgRecordsDelete deletes a record from the DWN - * - * @generated from message dwn.v1.MsgRecordsDelete - */ -export class MsgRecordsDelete extends Message { - /** - * Author requesting deletion (DID or cosmos address) - * - * @generated from field: string author = 1; - */ - author = ""; - - /** - * Target DWN (DID) - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Record ID to delete - * - * @generated from field: string record_id = 3; - */ - recordId = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 4; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT/signature - * - * @generated from field: string authorization = 5; - */ - authorization = ""; - - /** - * Prune descendants flag - * - * @generated from field: bool prune = 6; - */ - prune = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRecordsDelete"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "author", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 5, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "prune", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecordsDelete { - return new MsgRecordsDelete().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecordsDelete { - return new MsgRecordsDelete().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecordsDelete { - return new MsgRecordsDelete().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecordsDelete | PlainMessage | undefined, b: MsgRecordsDelete | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecordsDelete, a, b); - } -} - -/** - * MsgRecordsDeleteResponse defines the response for RecordsDelete - * - * @generated from message dwn.v1.MsgRecordsDeleteResponse - */ -export class MsgRecordsDeleteResponse extends Message { - /** - * Success flag - * - * @generated from field: bool success = 1; - */ - success = false; - - /** - * Number of records deleted (including pruned) - * - * @generated from field: int32 deleted_count = 2; - */ - deletedCount = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRecordsDeleteResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "deleted_count", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecordsDeleteResponse { - return new MsgRecordsDeleteResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecordsDeleteResponse { - return new MsgRecordsDeleteResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecordsDeleteResponse { - return new MsgRecordsDeleteResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecordsDeleteResponse | PlainMessage | undefined, b: MsgRecordsDeleteResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecordsDeleteResponse, a, b); - } -} - -/** - * MsgProtocolsConfigure configures a protocol in the DWN - * - * @generated from message dwn.v1.MsgProtocolsConfigure - */ -export class MsgProtocolsConfigure extends Message { - /** - * Author configuring the protocol (DID or cosmos address) - * - * @generated from field: string author = 1; - */ - author = ""; - - /** - * Target DWN (DID) - * - * @generated from field: string target = 2; - */ - target = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 3; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT/signature - * - * @generated from field: string authorization = 4; - */ - authorization = ""; - - /** - * Protocol URI - * - * @generated from field: string protocol_uri = 5; - */ - protocolUri = ""; - - /** - * Protocol definition JSON - * - * @generated from field: bytes definition = 6; - */ - definition = new Uint8Array(0); - - /** - * Published flag - * - * @generated from field: bool published = 7; - */ - published = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgProtocolsConfigure"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "author", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 4, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "protocol_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "definition", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "published", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgProtocolsConfigure { - return new MsgProtocolsConfigure().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgProtocolsConfigure { - return new MsgProtocolsConfigure().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgProtocolsConfigure { - return new MsgProtocolsConfigure().fromJsonString(jsonString, options); - } - - static equals(a: MsgProtocolsConfigure | PlainMessage | undefined, b: MsgProtocolsConfigure | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgProtocolsConfigure, a, b); - } -} - -/** - * MsgProtocolsConfigureResponse defines the response for ProtocolsConfigure - * - * @generated from message dwn.v1.MsgProtocolsConfigureResponse - */ -export class MsgProtocolsConfigureResponse extends Message { - /** - * Protocol URI that was configured - * - * @generated from field: string protocol_uri = 1; - */ - protocolUri = ""; - - /** - * Success flag - * - * @generated from field: bool success = 2; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgProtocolsConfigureResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "protocol_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgProtocolsConfigureResponse { - return new MsgProtocolsConfigureResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgProtocolsConfigureResponse { - return new MsgProtocolsConfigureResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgProtocolsConfigureResponse { - return new MsgProtocolsConfigureResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgProtocolsConfigureResponse | PlainMessage | undefined, b: MsgProtocolsConfigureResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgProtocolsConfigureResponse, a, b); - } -} - -/** - * MsgPermissionsGrant grants permissions in the DWN - * - * @generated from message dwn.v1.MsgPermissionsGrant - */ -export class MsgPermissionsGrant extends Message { - /** - * Grantor of the permission (DID or cosmos address) - * - * @generated from field: string grantor = 1; - */ - grantor = ""; - - /** - * Grantee receiving the permission (DID) - * - * @generated from field: string grantee = 2; - */ - grantee = ""; - - /** - * Target DWN (DID) - * - * @generated from field: string target = 3; - */ - target = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 4; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT/signature - * - * @generated from field: string authorization = 5; - */ - authorization = ""; - - /** - * Interface scope - * - * @generated from field: string interface_name = 6; - */ - interfaceName = ""; - - /** - * Method scope - * - * @generated from field: string method = 7; - */ - method = ""; - - /** - * Optional protocol scope - * - * @generated from field: string protocol = 8; - */ - protocol = ""; - - /** - * Optional record scope - * - * @generated from field: string record_id = 9; - */ - recordId = ""; - - /** - * Permission conditions JSON - * - * @generated from field: bytes conditions = 10; - */ - conditions = new Uint8Array(0); - - /** - * Expiration timestamp (Unix timestamp) - * - * @generated from field: int64 expires_at = 11; - */ - expiresAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgPermissionsGrant"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "grantor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "grantee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "target", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 5, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "interface_name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "method", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "protocol", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "record_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "conditions", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 11, name: "expires_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPermissionsGrant { - return new MsgPermissionsGrant().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPermissionsGrant { - return new MsgPermissionsGrant().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPermissionsGrant { - return new MsgPermissionsGrant().fromJsonString(jsonString, options); - } - - static equals(a: MsgPermissionsGrant | PlainMessage | undefined, b: MsgPermissionsGrant | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPermissionsGrant, a, b); - } -} - -/** - * MsgPermissionsGrantResponse defines the response for PermissionsGrant - * - * @generated from message dwn.v1.MsgPermissionsGrantResponse - */ -export class MsgPermissionsGrantResponse extends Message { - /** - * Permission ID of the created grant - * - * @generated from field: string permission_id = 1; - */ - permissionId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgPermissionsGrantResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "permission_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPermissionsGrantResponse { - return new MsgPermissionsGrantResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPermissionsGrantResponse { - return new MsgPermissionsGrantResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPermissionsGrantResponse { - return new MsgPermissionsGrantResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgPermissionsGrantResponse | PlainMessage | undefined, b: MsgPermissionsGrantResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPermissionsGrantResponse, a, b); - } -} - -/** - * MsgPermissionsRevoke revokes permissions in the DWN - * - * @generated from message dwn.v1.MsgPermissionsRevoke - */ -export class MsgPermissionsRevoke extends Message { - /** - * Grantor revoking the permission (DID or cosmos address) - * - * @generated from field: string grantor = 1; - */ - grantor = ""; - - /** - * Permission ID to revoke - * - * @generated from field: string permission_id = 2; - */ - permissionId = ""; - - /** - * Message descriptor - * - * @generated from field: dwn.v1.DWNMessageDescriptor descriptor = 3; - */ - descriptor?: DWNMessageDescriptor; - - /** - * Authorization JWT/signature - * - * @generated from field: string authorization = 4; - */ - authorization = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgPermissionsRevoke"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "grantor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "permission_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "descriptor", kind: "message", T: DWNMessageDescriptor }, - { no: 4, name: "authorization", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPermissionsRevoke { - return new MsgPermissionsRevoke().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPermissionsRevoke { - return new MsgPermissionsRevoke().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPermissionsRevoke { - return new MsgPermissionsRevoke().fromJsonString(jsonString, options); - } - - static equals(a: MsgPermissionsRevoke | PlainMessage | undefined, b: MsgPermissionsRevoke | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPermissionsRevoke, a, b); - } -} - -/** - * MsgPermissionsRevokeResponse defines the response for PermissionsRevoke - * - * @generated from message dwn.v1.MsgPermissionsRevokeResponse - */ -export class MsgPermissionsRevokeResponse extends Message { - /** - * Success flag - * - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgPermissionsRevokeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgPermissionsRevokeResponse { - return new MsgPermissionsRevokeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgPermissionsRevokeResponse { - return new MsgPermissionsRevokeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgPermissionsRevokeResponse { - return new MsgPermissionsRevokeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgPermissionsRevokeResponse | PlainMessage | undefined, b: MsgPermissionsRevokeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgPermissionsRevokeResponse, a, b); - } -} - -/** - * MsgRotateVaultKeys rotates encryption keys for existing vaults - * - * @generated from message dwn.v1.MsgRotateVaultKeys - */ -export class MsgRotateVaultKeys extends Message { - /** - * Authority performing the rotation (governance or validator) - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * Vault ID to rotate keys for (empty means all vaults) - * - * @generated from field: string vault_id = 2; - */ - vaultId = ""; - - /** - * Reason for rotation - * - * @generated from field: string reason = 3; - */ - reason = ""; - - /** - * Force rotation even if not due - * - * @generated from field: bool force = 4; - */ - force = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRotateVaultKeys"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "vault_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "reason", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "force", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRotateVaultKeys { - return new MsgRotateVaultKeys().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRotateVaultKeys { - return new MsgRotateVaultKeys().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRotateVaultKeys { - return new MsgRotateVaultKeys().fromJsonString(jsonString, options); - } - - static equals(a: MsgRotateVaultKeys | PlainMessage | undefined, b: MsgRotateVaultKeys | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRotateVaultKeys, a, b); - } -} - -/** - * MsgRotateVaultKeysResponse defines the response for RotateVaultKeys - * - * @generated from message dwn.v1.MsgRotateVaultKeysResponse - */ -export class MsgRotateVaultKeysResponse extends Message { - /** - * Number of vaults affected - * - * @generated from field: uint32 vaults_rotated = 1; - */ - vaultsRotated = 0; - - /** - * New key version after rotation - * - * @generated from field: uint64 new_key_version = 2; - */ - newKeyVersion = protoInt64.zero; - - /** - * Success flag - * - * @generated from field: bool success = 3; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "dwn.v1.MsgRotateVaultKeysResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "vaults_rotated", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: "new_key_version", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRotateVaultKeysResponse { - return new MsgRotateVaultKeysResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRotateVaultKeysResponse { - return new MsgRotateVaultKeysResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRotateVaultKeysResponse { - return new MsgRotateVaultKeysResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRotateVaultKeysResponse | PlainMessage | undefined, b: MsgRotateVaultKeysResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRotateVaultKeysResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/crypto/v1/ethsecp256k1/keys_pb.ts b/packages/es/src/protobufs/ethermint/crypto/v1/ethsecp256k1/keys_pb.ts deleted file mode 100644 index 7987c8560..000000000 --- a/packages/es/src/protobufs/ethermint/crypto/v1/ethsecp256k1/keys_pb.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/crypto/v1/ethsecp256k1/keys.proto (package ethermint.crypto.v1.ethsecp256k1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * PubKey defines a type alias for an ecdsa.PublicKey that implements - * Tendermint's PubKey interface. It represents the 33-byte compressed public - * key format. - * - * @generated from message ethermint.crypto.v1.ethsecp256k1.PubKey - */ -export class PubKey extends Message { - /** - * key is the public key in byte form - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.crypto.v1.ethsecp256k1.PubKey"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PubKey { - return new PubKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PubKey { - return new PubKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PubKey { - return new PubKey().fromJsonString(jsonString, options); - } - - static equals(a: PubKey | PlainMessage | undefined, b: PubKey | PlainMessage | undefined): boolean { - return proto3.util.equals(PubKey, a, b); - } -} - -/** - * PrivKey defines a type alias for an ecdsa.PrivateKey that implements - * Tendermint's PrivateKey interface. - * - * @generated from message ethermint.crypto.v1.ethsecp256k1.PrivKey - */ -export class PrivKey extends Message { - /** - * key is the private key in byte form - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.crypto.v1.ethsecp256k1.PrivKey"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PrivKey { - return new PrivKey().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PrivKey { - return new PrivKey().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PrivKey { - return new PrivKey().fromJsonString(jsonString, options); - } - - static equals(a: PrivKey | PlainMessage | undefined, b: PrivKey | PlainMessage | undefined): boolean { - return proto3.util.equals(PrivKey, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/events_pb.ts b/packages/es/src/protobufs/ethermint/evm/v1/events_pb.ts deleted file mode 100644 index f17124921..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/events_pb.ts +++ /dev/null @@ -1,236 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/evm/v1/events.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * EventEthereumTx defines the event for an Ethereum transaction - * - * @generated from message ethermint.evm.v1.EventEthereumTx - */ -export class EventEthereumTx extends Message { - /** - * amount - * - * @generated from field: string amount = 1; - */ - amount = ""; - - /** - * eth_hash is the Ethereum hash of the transaction - * - * @generated from field: string eth_hash = 2; - */ - ethHash = ""; - - /** - * index of the transaction in the block - * - * @generated from field: string index = 3; - */ - index = ""; - - /** - * gas_used is the amount of gas used by the transaction - * - * @generated from field: string gas_used = 4; - */ - gasUsed = ""; - - /** - * hash is the Tendermint hash of the transaction - * - * @generated from field: string hash = 5; - */ - hash = ""; - - /** - * recipient of the transaction - * - * @generated from field: string recipient = 6; - */ - recipient = ""; - - /** - * eth_tx_failed contains a VM error should it occur - * - * @generated from field: string eth_tx_failed = 7; - */ - ethTxFailed = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EventEthereumTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "eth_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "index", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "gas_used", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "recipient", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "eth_tx_failed", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventEthereumTx { - return new EventEthereumTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventEthereumTx { - return new EventEthereumTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventEthereumTx { - return new EventEthereumTx().fromJsonString(jsonString, options); - } - - static equals(a: EventEthereumTx | PlainMessage | undefined, b: EventEthereumTx | PlainMessage | undefined): boolean { - return proto3.util.equals(EventEthereumTx, a, b); - } -} - -/** - * EventTxLog defines the event for an Ethereum transaction log - * - * @generated from message ethermint.evm.v1.EventTxLog - */ -export class EventTxLog extends Message { - /** - * tx_logs is an array of transaction logs - * - * @generated from field: repeated string tx_logs = 1; - */ - txLogs: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EventTxLog"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_logs", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventTxLog { - return new EventTxLog().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventTxLog { - return new EventTxLog().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventTxLog { - return new EventTxLog().fromJsonString(jsonString, options); - } - - static equals(a: EventTxLog | PlainMessage | undefined, b: EventTxLog | PlainMessage | undefined): boolean { - return proto3.util.equals(EventTxLog, a, b); - } -} - -/** - * EventMessage - * - * @generated from message ethermint.evm.v1.EventMessage - */ -export class EventMessage extends Message { - /** - * module which emits the event - * - * @generated from field: string module = 1; - */ - module = ""; - - /** - * sender of the message - * - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * tx_type is the type of the message - * - * @generated from field: string tx_type = 3; - */ - txType = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EventMessage"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "module", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "tx_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventMessage { - return new EventMessage().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventMessage { - return new EventMessage().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventMessage { - return new EventMessage().fromJsonString(jsonString, options); - } - - static equals(a: EventMessage | PlainMessage | undefined, b: EventMessage | PlainMessage | undefined): boolean { - return proto3.util.equals(EventMessage, a, b); - } -} - -/** - * EventBlockBloom defines an Ethereum block bloom filter event - * - * @generated from message ethermint.evm.v1.EventBlockBloom - */ -export class EventBlockBloom extends Message { - /** - * bloom is the bloom filter of the block - * - * @generated from field: string bloom = 1; - */ - bloom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EventBlockBloom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "bloom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventBlockBloom { - return new EventBlockBloom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventBlockBloom { - return new EventBlockBloom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventBlockBloom { - return new EventBlockBloom().fromJsonString(jsonString, options); - } - - static equals(a: EventBlockBloom | PlainMessage | undefined, b: EventBlockBloom | PlainMessage | undefined): boolean { - return proto3.util.equals(EventBlockBloom, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/evm_pb.ts b/packages/es/src/protobufs/ethermint/evm/v1/evm_pb.ts deleted file mode 100644 index ecf1c1bf0..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/evm_pb.ts +++ /dev/null @@ -1,745 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/evm/v1/evm.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Params defines the EVM module parameters - * - * @generated from message ethermint.evm.v1.Params - */ -export class Params extends Message { - /** - * evm_denom represents the token denomination used to run the EVM state - * transitions. - * - * @generated from field: string evm_denom = 1; - */ - evmDenom = ""; - - /** - * enable_create toggles state transitions that use the vm.Create function - * - * @generated from field: bool enable_create = 2; - */ - enableCreate = false; - - /** - * enable_call toggles state transitions that use the vm.Call function - * - * @generated from field: bool enable_call = 3; - */ - enableCall = false; - - /** - * extra_eips defines the additional EIPs for the vm.Config - * - * @generated from field: repeated int64 extra_eips = 4; - */ - extraEips: bigint[] = []; - - /** - * chain_config defines the EVM chain configuration parameters - * - * @generated from field: ethermint.evm.v1.ChainConfig chain_config = 5; - */ - chainConfig?: ChainConfig; - - /** - * allow_unprotected_txs defines if replay-protected (i.e non EIP155 - * signed) transactions can be executed on the state machine. - * - * @generated from field: bool allow_unprotected_txs = 6; - */ - allowUnprotectedTxs = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "evm_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "enable_create", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "enable_call", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 4, name: "extra_eips", kind: "scalar", T: 3 /* ScalarType.INT64 */, repeated: true }, - { no: 5, name: "chain_config", kind: "message", T: ChainConfig }, - { no: 6, name: "allow_unprotected_txs", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * ChainConfig defines the Ethereum ChainConfig parameters using *sdk.Int values - * instead of *big.Int. - * - * @generated from message ethermint.evm.v1.ChainConfig - */ -export class ChainConfig extends Message { - /** - * homestead_block switch (nil no fork, 0 = already homestead) - * - * @generated from field: string homestead_block = 1; - */ - homesteadBlock = ""; - - /** - * dao_fork_block corresponds to TheDAO hard-fork switch block (nil no fork) - * - * @generated from field: string dao_fork_block = 2; - */ - daoForkBlock = ""; - - /** - * dao_fork_support defines whether the nodes supports or opposes the DAO hard-fork - * - * @generated from field: bool dao_fork_support = 3; - */ - daoForkSupport = false; - - /** - * eip150_block: EIP150 implements the Gas price changes - * (https://github.com/ethereum/EIPs/issues/150) EIP150 HF block (nil no fork) - * - * @generated from field: string eip150_block = 4; - */ - eip150Block = ""; - - /** - * eip150_hash: EIP150 HF hash (needed for header only clients as only gas pricing changed) - * - * @generated from field: string eip150_hash = 5; - */ - eip150Hash = ""; - - /** - * eip155_block: EIP155Block HF block - * - * @generated from field: string eip155_block = 6; - */ - eip155Block = ""; - - /** - * eip158_block: EIP158 HF block - * - * @generated from field: string eip158_block = 7; - */ - eip158Block = ""; - - /** - * byzantium_block: Byzantium switch block (nil no fork, 0 = already on byzantium) - * - * @generated from field: string byzantium_block = 8; - */ - byzantiumBlock = ""; - - /** - * constantinople_block: Constantinople switch block (nil no fork, 0 = already activated) - * - * @generated from field: string constantinople_block = 9; - */ - constantinopleBlock = ""; - - /** - * petersburg_block: Petersburg switch block (nil same as Constantinople) - * - * @generated from field: string petersburg_block = 10; - */ - petersburgBlock = ""; - - /** - * istanbul_block: Istanbul switch block (nil no fork, 0 = already on istanbul) - * - * @generated from field: string istanbul_block = 11; - */ - istanbulBlock = ""; - - /** - * muir_glacier_block: Eip-2384 (bomb delay) switch block (nil no fork, 0 = already activated) - * - * @generated from field: string muir_glacier_block = 12; - */ - muirGlacierBlock = ""; - - /** - * berlin_block: Berlin switch block (nil = no fork, 0 = already on berlin) - * - * @generated from field: string berlin_block = 13; - */ - berlinBlock = ""; - - /** - * london_block: London switch block (nil = no fork, 0 = already on london) - * - * @generated from field: string london_block = 17; - */ - londonBlock = ""; - - /** - * arrow_glacier_block: Eip-4345 (bomb delay) switch block (nil = no fork, 0 = already activated) - * - * @generated from field: string arrow_glacier_block = 18; - */ - arrowGlacierBlock = ""; - - /** - * gray_glacier_block: EIP-5133 (bomb delay) switch block (nil = no fork, 0 = already activated) - * - * @generated from field: string gray_glacier_block = 20; - */ - grayGlacierBlock = ""; - - /** - * merge_netsplit_block: Virtual fork after The Merge to use as a network splitter - * - * @generated from field: string merge_netsplit_block = 21; - */ - mergeNetsplitBlock = ""; - - /** - * shanghai_block switch block (nil = no fork, 0 = already on shanghai) - * - * @generated from field: string shanghai_block = 22; - */ - shanghaiBlock = ""; - - /** - * cancun_block switch block (nil = no fork, 0 = already on cancun) - * - * @generated from field: string cancun_block = 23; - */ - cancunBlock = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.ChainConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "homestead_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "dao_fork_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "dao_fork_support", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 4, name: "eip150_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "eip150_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "eip155_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "eip158_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "byzantium_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "constantinople_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "petersburg_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "istanbul_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 12, name: "muir_glacier_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "berlin_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 17, name: "london_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 18, name: "arrow_glacier_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 20, name: "gray_glacier_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 21, name: "merge_netsplit_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 22, name: "shanghai_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 23, name: "cancun_block", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ChainConfig { - return new ChainConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ChainConfig { - return new ChainConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ChainConfig { - return new ChainConfig().fromJsonString(jsonString, options); - } - - static equals(a: ChainConfig | PlainMessage | undefined, b: ChainConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(ChainConfig, a, b); - } -} - -/** - * State represents a single Storage key value pair item. - * - * @generated from message ethermint.evm.v1.State - */ -export class State extends Message { - /** - * key is the stored key - * - * @generated from field: string key = 1; - */ - key = ""; - - /** - * value is the stored value for the given key - * - * @generated from field: string value = 2; - */ - value = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.State"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): State { - return new State().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): State { - return new State().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): State { - return new State().fromJsonString(jsonString, options); - } - - static equals(a: State | PlainMessage | undefined, b: State | PlainMessage | undefined): boolean { - return proto3.util.equals(State, a, b); - } -} - -/** - * TransactionLogs define the logs generated from a transaction execution - * with a given hash. It it used for import/export data as transactions are not - * persisted on blockchain state after an upgrade. - * - * @generated from message ethermint.evm.v1.TransactionLogs - */ -export class TransactionLogs extends Message { - /** - * hash of the transaction - * - * @generated from field: string hash = 1; - */ - hash = ""; - - /** - * logs is an array of Logs for the given transaction hash - * - * @generated from field: repeated ethermint.evm.v1.Log logs = 2; - */ - logs: Log[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.TransactionLogs"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "logs", kind: "message", T: Log, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TransactionLogs { - return new TransactionLogs().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TransactionLogs { - return new TransactionLogs().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TransactionLogs { - return new TransactionLogs().fromJsonString(jsonString, options); - } - - static equals(a: TransactionLogs | PlainMessage | undefined, b: TransactionLogs | PlainMessage | undefined): boolean { - return proto3.util.equals(TransactionLogs, a, b); - } -} - -/** - * Log represents an protobuf compatible Ethereum Log that defines a contract - * log event. These events are generated by the LOG opcode and stored/indexed by - * the node. - * - * NOTE: address, topics and data are consensus fields. The rest of the fields - * are derived, i.e. filled in by the nodes, but not secured by consensus. - * - * @generated from message ethermint.evm.v1.Log - */ -export class Log extends Message { - /** - * address of the contract that generated the event - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * topics is a list of topics provided by the contract. - * - * @generated from field: repeated string topics = 2; - */ - topics: string[] = []; - - /** - * data which is supplied by the contract, usually ABI-encoded - * - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - /** - * block_number of the block in which the transaction was included - * - * @generated from field: uint64 block_number = 4; - */ - blockNumber = protoInt64.zero; - - /** - * tx_hash is the transaction hash - * - * @generated from field: string tx_hash = 5; - */ - txHash = ""; - - /** - * tx_index of the transaction in the block - * - * @generated from field: uint64 tx_index = 6; - */ - txIndex = protoInt64.zero; - - /** - * block_hash of the block in which the transaction was included - * - * @generated from field: string block_hash = 7; - */ - blockHash = ""; - - /** - * index of the log in the block - * - * @generated from field: uint64 index = 8; - */ - index = protoInt64.zero; - - /** - * removed is true if this log was reverted due to a chain - * reorganisation. You must pay attention to this field if you receive logs - * through a filter query. - * - * @generated from field: bool removed = 9; - */ - removed = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.Log"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "topics", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "block_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "tx_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "tx_index", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "block_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "index", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 9, name: "removed", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Log { - return new Log().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Log { - return new Log().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Log { - return new Log().fromJsonString(jsonString, options); - } - - static equals(a: Log | PlainMessage | undefined, b: Log | PlainMessage | undefined): boolean { - return proto3.util.equals(Log, a, b); - } -} - -/** - * TxResult stores results of Tx execution. - * - * @generated from message ethermint.evm.v1.TxResult - */ -export class TxResult extends Message { - /** - * contract_address contains the ethereum address of the created contract (if - * any). If the state transition is an evm.Call, the contract address will be - * empty. - * - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - /** - * bloom represents the bloom filter bytes - * - * @generated from field: bytes bloom = 2; - */ - bloom = new Uint8Array(0); - - /** - * tx_logs contains the transaction hash and the proto-compatible ethereum - * logs. - * - * @generated from field: ethermint.evm.v1.TransactionLogs tx_logs = 3; - */ - txLogs?: TransactionLogs; - - /** - * ret defines the bytes from the execution. - * - * @generated from field: bytes ret = 4; - */ - ret = new Uint8Array(0); - - /** - * reverted flag is set to true when the call has been reverted - * - * @generated from field: bool reverted = 5; - */ - reverted = false; - - /** - * gas_used notes the amount of gas consumed while execution - * - * @generated from field: uint64 gas_used = 6; - */ - gasUsed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.TxResult"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "bloom", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "tx_logs", kind: "message", T: TransactionLogs }, - { no: 4, name: "ret", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "reverted", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "gas_used", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxResult { - return new TxResult().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxResult { - return new TxResult().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxResult { - return new TxResult().fromJsonString(jsonString, options); - } - - static equals(a: TxResult | PlainMessage | undefined, b: TxResult | PlainMessage | undefined): boolean { - return proto3.util.equals(TxResult, a, b); - } -} - -/** - * AccessTuple is the element type of an access list. - * - * @generated from message ethermint.evm.v1.AccessTuple - */ -export class AccessTuple extends Message { - /** - * address is a hex formatted ethereum address - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * storage_keys are hex formatted hashes of the storage keys - * - * @generated from field: repeated string storage_keys = 2; - */ - storageKeys: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.AccessTuple"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "storage_keys", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccessTuple { - return new AccessTuple().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccessTuple { - return new AccessTuple().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccessTuple { - return new AccessTuple().fromJsonString(jsonString, options); - } - - static equals(a: AccessTuple | PlainMessage | undefined, b: AccessTuple | PlainMessage | undefined): boolean { - return proto3.util.equals(AccessTuple, a, b); - } -} - -/** - * TraceConfig holds extra parameters to trace functions. - * - * @generated from message ethermint.evm.v1.TraceConfig - */ -export class TraceConfig extends Message { - /** - * tracer is a custom javascript tracer - * - * @generated from field: string tracer = 1; - */ - tracer = ""; - - /** - * timeout overrides the default timeout of 5 seconds for JavaScript-based tracing - * calls - * - * @generated from field: string timeout = 2; - */ - timeout = ""; - - /** - * reexec defines the number of blocks the tracer is willing to go back - * - * @generated from field: uint64 reexec = 3; - */ - reexec = protoInt64.zero; - - /** - * disable_stack switches stack capture - * - * @generated from field: bool disable_stack = 5; - */ - disableStack = false; - - /** - * disable_storage switches storage capture - * - * @generated from field: bool disable_storage = 6; - */ - disableStorage = false; - - /** - * debug can be used to print output during capture end - * - * @generated from field: bool debug = 8; - */ - debug = false; - - /** - * limit defines the maximum length of output, but zero means unlimited - * - * @generated from field: int32 limit = 9; - */ - limit = 0; - - /** - * overrides can be used to execute a trace using future fork rules - * - * @generated from field: ethermint.evm.v1.ChainConfig overrides = 10; - */ - overrides?: ChainConfig; - - /** - * enable_memory switches memory capture - * - * @generated from field: bool enable_memory = 11; - */ - enableMemory = false; - - /** - * enable_return_data switches the capture of return data - * - * @generated from field: bool enable_return_data = 12; - */ - enableReturnData = false; - - /** - * tracer_json_config configures the tracer using a JSON string - * - * @generated from field: string tracer_json_config = 13; - */ - tracerJsonConfig = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.TraceConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tracer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timeout", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "reexec", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "disable_stack", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "disable_storage", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 8, name: "debug", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 9, name: "limit", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 10, name: "overrides", kind: "message", T: ChainConfig }, - { no: 11, name: "enable_memory", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 12, name: "enable_return_data", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 13, name: "tracer_json_config", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TraceConfig { - return new TraceConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TraceConfig { - return new TraceConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TraceConfig { - return new TraceConfig().fromJsonString(jsonString, options); - } - - static equals(a: TraceConfig | PlainMessage | undefined, b: TraceConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(TraceConfig, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/genesis_pb.ts b/packages/es/src/protobufs/ethermint/evm/v1/genesis_pb.ts deleted file mode 100644 index 3b4c26393..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/genesis_pb.ts +++ /dev/null @@ -1,117 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/evm/v1/genesis.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params, State } from "./evm_pb.js"; - -/** - * GenesisState defines the evm module's genesis state. - * - * @generated from message ethermint.evm.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * accounts is an array containing the ethereum genesis accounts. - * - * @generated from field: repeated ethermint.evm.v1.GenesisAccount accounts = 1; - */ - accounts: GenesisAccount[] = []; - - /** - * params defines all the parameters of the module. - * - * @generated from field: ethermint.evm.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "accounts", kind: "message", T: GenesisAccount, repeated: true }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * GenesisAccount defines an account to be initialized in the genesis state. - * Its main difference between with Geth's GenesisAccount is that it uses a - * custom storage type and that it doesn't contain the private key field. - * - * @generated from message ethermint.evm.v1.GenesisAccount - */ -export class GenesisAccount extends Message { - /** - * address defines an ethereum hex formated address of an account - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * code defines the hex bytes of the account code. - * - * @generated from field: string code = 2; - */ - code = ""; - - /** - * storage defines the set of state key values for the account. - * - * @generated from field: repeated ethermint.evm.v1.State storage = 3; - */ - storage: State[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.GenesisAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "storage", kind: "message", T: State, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisAccount { - return new GenesisAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisAccount { - return new GenesisAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisAccount { - return new GenesisAccount().fromJsonString(jsonString, options); - } - - static equals(a: GenesisAccount | PlainMessage | undefined, b: GenesisAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisAccount, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/query_cosmes.ts b/packages/es/src/protobufs/ethermint/evm/v1/query_cosmes.ts deleted file mode 100644 index 51e453458..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/query_cosmes.ts +++ /dev/null @@ -1,157 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ethermint/evm/v1/query.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { EstimateGasResponse, EthCallRequest, QueryAccountRequest, QueryAccountResponse, QueryBalanceRequest, QueryBalanceResponse, QueryBaseFeeRequest, QueryBaseFeeResponse, QueryCodeRequest, QueryCodeResponse, QueryCosmosAccountRequest, QueryCosmosAccountResponse, QueryParamsRequest, QueryParamsResponse, QueryStorageRequest, QueryStorageResponse, QueryTraceBlockRequest, QueryTraceBlockResponse, QueryTraceTxRequest, QueryTraceTxResponse, QueryValidatorAccountRequest, QueryValidatorAccountResponse } from "./query_pb.js"; -import { MsgEthereumTxResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ethermint.evm.v1.Query"; - -/** - * Account queries an Ethereum account. - * - * @generated from rpc ethermint.evm.v1.Query.Account - */ -export const QueryAccountService = { - typeName: TYPE_NAME, - method: "Account", - Request: QueryAccountRequest, - Response: QueryAccountResponse, -} as const; - -/** - * CosmosAccount queries an Ethereum account's Cosmos Address. - * - * @generated from rpc ethermint.evm.v1.Query.CosmosAccount - */ -export const QueryCosmosAccountService = { - typeName: TYPE_NAME, - method: "CosmosAccount", - Request: QueryCosmosAccountRequest, - Response: QueryCosmosAccountResponse, -} as const; - -/** - * ValidatorAccount queries an Ethereum account's from a validator consensus - * Address. - * - * @generated from rpc ethermint.evm.v1.Query.ValidatorAccount - */ -export const QueryValidatorAccountService = { - typeName: TYPE_NAME, - method: "ValidatorAccount", - Request: QueryValidatorAccountRequest, - Response: QueryValidatorAccountResponse, -} as const; - -/** - * Balance queries the balance of a the EVM denomination for a single - * EthAccount. - * - * @generated from rpc ethermint.evm.v1.Query.Balance - */ -export const QueryBalanceService = { - typeName: TYPE_NAME, - method: "Balance", - Request: QueryBalanceRequest, - Response: QueryBalanceResponse, -} as const; - -/** - * Storage queries the balance of all coins for a single account. - * - * @generated from rpc ethermint.evm.v1.Query.Storage - */ -export const QueryStorageService = { - typeName: TYPE_NAME, - method: "Storage", - Request: QueryStorageRequest, - Response: QueryStorageResponse, -} as const; - -/** - * Code queries the balance of all coins for a single account. - * - * @generated from rpc ethermint.evm.v1.Query.Code - */ -export const QueryCodeService = { - typeName: TYPE_NAME, - method: "Code", - Request: QueryCodeRequest, - Response: QueryCodeResponse, -} as const; - -/** - * Params queries the parameters of x/evm module. - * - * @generated from rpc ethermint.evm.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * EthCall implements the `eth_call` rpc api - * - * @generated from rpc ethermint.evm.v1.Query.EthCall - */ -export const QueryEthCallService = { - typeName: TYPE_NAME, - method: "EthCall", - Request: EthCallRequest, - Response: MsgEthereumTxResponse, -} as const; - -/** - * EstimateGas implements the `eth_estimateGas` rpc api - * - * @generated from rpc ethermint.evm.v1.Query.EstimateGas - */ -export const QueryEstimateGasService = { - typeName: TYPE_NAME, - method: "EstimateGas", - Request: EthCallRequest, - Response: EstimateGasResponse, -} as const; - -/** - * TraceTx implements the `debug_traceTransaction` rpc api - * - * @generated from rpc ethermint.evm.v1.Query.TraceTx - */ -export const QueryTraceTxService = { - typeName: TYPE_NAME, - method: "TraceTx", - Request: QueryTraceTxRequest, - Response: QueryTraceTxResponse, -} as const; - -/** - * TraceBlock implements the `debug_traceBlockByNumber` and `debug_traceBlockByHash` rpc api - * - * @generated from rpc ethermint.evm.v1.Query.TraceBlock - */ -export const QueryTraceBlockService = { - typeName: TYPE_NAME, - method: "TraceBlock", - Request: QueryTraceBlockRequest, - Response: QueryTraceBlockResponse, -} as const; - -/** - * BaseFee queries the base fee of the parent block of the current block, - * it's similar to feemarket module's method, but also checks london hardfork status. - * - * @generated from rpc ethermint.evm.v1.Query.BaseFee - */ -export const QueryBaseFeeService = { - typeName: TYPE_NAME, - method: "BaseFee", - Request: QueryBaseFeeRequest, - Response: QueryBaseFeeResponse, -} as const; - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/query_pb.ts b/packages/es/src/protobufs/ethermint/evm/v1/query_pb.ts deleted file mode 100644 index 2e3a95c11..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/query_pb.ts +++ /dev/null @@ -1,1187 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/evm/v1/query.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { PageRequest, PageResponse } from "../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Log, Params, TraceConfig } from "./evm_pb.js"; -import { MsgEthereumTx } from "./tx_pb.js"; - -/** - * QueryAccountRequest is the request type for the Query/Account RPC method. - * - * @generated from message ethermint.evm.v1.QueryAccountRequest - */ -export class QueryAccountRequest extends Message { - /** - * address is the ethereum hex address to query the account for. - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountRequest { - return new QueryAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountRequest | PlainMessage | undefined, b: QueryAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountRequest, a, b); - } -} - -/** - * QueryAccountResponse is the response type for the Query/Account RPC method. - * - * @generated from message ethermint.evm.v1.QueryAccountResponse - */ -export class QueryAccountResponse extends Message { - /** - * balance is the balance of the EVM denomination. - * - * @generated from field: string balance = 1; - */ - balance = ""; - - /** - * code_hash is the hex-formatted code bytes from the EOA. - * - * @generated from field: string code_hash = 2; - */ - codeHash = ""; - - /** - * nonce is the account's sequence number. - * - * @generated from field: uint64 nonce = 3; - */ - nonce = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balance", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "nonce", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAccountResponse { - return new QueryAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAccountResponse | PlainMessage | undefined, b: QueryAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAccountResponse, a, b); - } -} - -/** - * QueryCosmosAccountRequest is the request type for the Query/CosmosAccount RPC - * method. - * - * @generated from message ethermint.evm.v1.QueryCosmosAccountRequest - */ -export class QueryCosmosAccountRequest extends Message { - /** - * address is the ethereum hex address to query the account for. - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryCosmosAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCosmosAccountRequest { - return new QueryCosmosAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCosmosAccountRequest { - return new QueryCosmosAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCosmosAccountRequest { - return new QueryCosmosAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCosmosAccountRequest | PlainMessage | undefined, b: QueryCosmosAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCosmosAccountRequest, a, b); - } -} - -/** - * QueryCosmosAccountResponse is the response type for the Query/CosmosAccount - * RPC method. - * - * @generated from message ethermint.evm.v1.QueryCosmosAccountResponse - */ -export class QueryCosmosAccountResponse extends Message { - /** - * cosmos_address is the cosmos address of the account. - * - * @generated from field: string cosmos_address = 1; - */ - cosmosAddress = ""; - - /** - * sequence is the account's sequence number. - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - /** - * account_number is the account number - * - * @generated from field: uint64 account_number = 3; - */ - accountNumber = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryCosmosAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cosmos_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "account_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCosmosAccountResponse { - return new QueryCosmosAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCosmosAccountResponse { - return new QueryCosmosAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCosmosAccountResponse { - return new QueryCosmosAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCosmosAccountResponse | PlainMessage | undefined, b: QueryCosmosAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCosmosAccountResponse, a, b); - } -} - -/** - * QueryValidatorAccountRequest is the request type for the - * Query/ValidatorAccount RPC method. - * - * @generated from message ethermint.evm.v1.QueryValidatorAccountRequest - */ -export class QueryValidatorAccountRequest extends Message { - /** - * cons_address is the validator cons address to query the account for. - * - * @generated from field: string cons_address = 1; - */ - consAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryValidatorAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cons_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryValidatorAccountRequest { - return new QueryValidatorAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryValidatorAccountRequest { - return new QueryValidatorAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryValidatorAccountRequest { - return new QueryValidatorAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryValidatorAccountRequest | PlainMessage | undefined, b: QueryValidatorAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryValidatorAccountRequest, a, b); - } -} - -/** - * QueryValidatorAccountResponse is the response type for the - * Query/ValidatorAccount RPC method. - * - * @generated from message ethermint.evm.v1.QueryValidatorAccountResponse - */ -export class QueryValidatorAccountResponse extends Message { - /** - * account_address is the cosmos address of the account in bech32 format. - * - * @generated from field: string account_address = 1; - */ - accountAddress = ""; - - /** - * sequence is the account's sequence number. - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - /** - * account_number is the account number - * - * @generated from field: uint64 account_number = 3; - */ - accountNumber = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryValidatorAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "account_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryValidatorAccountResponse { - return new QueryValidatorAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryValidatorAccountResponse { - return new QueryValidatorAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryValidatorAccountResponse { - return new QueryValidatorAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryValidatorAccountResponse | PlainMessage | undefined, b: QueryValidatorAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryValidatorAccountResponse, a, b); - } -} - -/** - * QueryBalanceRequest is the request type for the Query/Balance RPC method. - * - * @generated from message ethermint.evm.v1.QueryBalanceRequest - */ -export class QueryBalanceRequest extends Message { - /** - * address is the ethereum hex address to query the balance for. - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryBalanceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBalanceRequest { - return new QueryBalanceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBalanceRequest | PlainMessage | undefined, b: QueryBalanceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBalanceRequest, a, b); - } -} - -/** - * QueryBalanceResponse is the response type for the Query/Balance RPC method. - * - * @generated from message ethermint.evm.v1.QueryBalanceResponse - */ -export class QueryBalanceResponse extends Message { - /** - * balance is the balance of the EVM denomination. - * - * @generated from field: string balance = 1; - */ - balance = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryBalanceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balance", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBalanceResponse { - return new QueryBalanceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBalanceResponse | PlainMessage | undefined, b: QueryBalanceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBalanceResponse, a, b); - } -} - -/** - * QueryStorageRequest is the request type for the Query/Storage RPC method. - * - * @generated from message ethermint.evm.v1.QueryStorageRequest - */ -export class QueryStorageRequest extends Message { - /** - * address is the ethereum hex address to query the storage state for. - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * key defines the key of the storage state - * - * @generated from field: string key = 2; - */ - key = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryStorageRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "key", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryStorageRequest { - return new QueryStorageRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryStorageRequest { - return new QueryStorageRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryStorageRequest { - return new QueryStorageRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryStorageRequest | PlainMessage | undefined, b: QueryStorageRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryStorageRequest, a, b); - } -} - -/** - * QueryStorageResponse is the response type for the Query/Storage RPC - * method. - * - * @generated from message ethermint.evm.v1.QueryStorageResponse - */ -export class QueryStorageResponse extends Message { - /** - * value defines the storage state value hash associated with the given key. - * - * @generated from field: string value = 1; - */ - value = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryStorageResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryStorageResponse { - return new QueryStorageResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryStorageResponse { - return new QueryStorageResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryStorageResponse { - return new QueryStorageResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryStorageResponse | PlainMessage | undefined, b: QueryStorageResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryStorageResponse, a, b); - } -} - -/** - * QueryCodeRequest is the request type for the Query/Code RPC method. - * - * @generated from message ethermint.evm.v1.QueryCodeRequest - */ -export class QueryCodeRequest extends Message { - /** - * address is the ethereum hex address to query the code for. - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryCodeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeRequest | PlainMessage | undefined, b: QueryCodeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeRequest, a, b); - } -} - -/** - * QueryCodeResponse is the response type for the Query/Code RPC - * method. - * - * @generated from message ethermint.evm.v1.QueryCodeResponse - */ -export class QueryCodeResponse extends Message { - /** - * code represents the code bytes from an ethereum address. - * - * @generated from field: bytes code = 1; - */ - code = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeResponse | PlainMessage | undefined, b: QueryCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeResponse, a, b); - } -} - -/** - * QueryTxLogsRequest is the request type for the Query/TxLogs RPC method. - * - * @generated from message ethermint.evm.v1.QueryTxLogsRequest - */ -export class QueryTxLogsRequest extends Message { - /** - * hash is the ethereum transaction hex hash to query the logs for. - * - * @generated from field: string hash = 1; - */ - hash = ""; - - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTxLogsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTxLogsRequest { - return new QueryTxLogsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTxLogsRequest { - return new QueryTxLogsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTxLogsRequest { - return new QueryTxLogsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTxLogsRequest | PlainMessage | undefined, b: QueryTxLogsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTxLogsRequest, a, b); - } -} - -/** - * QueryTxLogsResponse is the response type for the Query/TxLogs RPC method. - * - * @generated from message ethermint.evm.v1.QueryTxLogsResponse - */ -export class QueryTxLogsResponse extends Message { - /** - * logs represents the ethereum logs generated from the given transaction. - * - * @generated from field: repeated ethermint.evm.v1.Log logs = 1; - */ - logs: Log[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTxLogsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "logs", kind: "message", T: Log, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTxLogsResponse { - return new QueryTxLogsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTxLogsResponse { - return new QueryTxLogsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTxLogsResponse { - return new QueryTxLogsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTxLogsResponse | PlainMessage | undefined, b: QueryTxLogsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTxLogsResponse, a, b); - } -} - -/** - * QueryParamsRequest defines the request type for querying x/evm parameters. - * - * @generated from message ethermint.evm.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse defines the response type for querying x/evm parameters. - * - * @generated from message ethermint.evm.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params define the evm module parameters. - * - * @generated from field: ethermint.evm.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * EthCallRequest defines EthCall request - * - * @generated from message ethermint.evm.v1.EthCallRequest - */ -export class EthCallRequest extends Message { - /** - * args uses the same json format as the json rpc api. - * - * @generated from field: bytes args = 1; - */ - args = new Uint8Array(0); - - /** - * gas_cap defines the default gas cap to be used - * - * @generated from field: uint64 gas_cap = 2; - */ - gasCap = protoInt64.zero; - - /** - * proposer_address of the requested block in hex format - * - * @generated from field: bytes proposer_address = 3; - */ - proposerAddress = new Uint8Array(0); - - /** - * chain_id is the eip155 chain id parsed from the requested block header - * - * @generated from field: int64 chain_id = 4; - */ - chainId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EthCallRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "args", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "gas_cap", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "proposer_address", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "chain_id", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EthCallRequest { - return new EthCallRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EthCallRequest { - return new EthCallRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EthCallRequest { - return new EthCallRequest().fromJsonString(jsonString, options); - } - - static equals(a: EthCallRequest | PlainMessage | undefined, b: EthCallRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EthCallRequest, a, b); - } -} - -/** - * EstimateGasResponse defines EstimateGas response - * - * @generated from message ethermint.evm.v1.EstimateGasResponse - */ -export class EstimateGasResponse extends Message { - /** - * gas returns the estimated gas - * - * @generated from field: uint64 gas = 1; - */ - gas = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.EstimateGasResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateGasResponse { - return new EstimateGasResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateGasResponse { - return new EstimateGasResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateGasResponse { - return new EstimateGasResponse().fromJsonString(jsonString, options); - } - - static equals(a: EstimateGasResponse | PlainMessage | undefined, b: EstimateGasResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateGasResponse, a, b); - } -} - -/** - * QueryTraceTxRequest defines TraceTx request - * - * @generated from message ethermint.evm.v1.QueryTraceTxRequest - */ -export class QueryTraceTxRequest extends Message { - /** - * msg is the MsgEthereumTx for the requested transaction - * - * @generated from field: ethermint.evm.v1.MsgEthereumTx msg = 1; - */ - msg?: MsgEthereumTx; - - /** - * trace_config holds extra parameters to trace functions. - * - * @generated from field: ethermint.evm.v1.TraceConfig trace_config = 3; - */ - traceConfig?: TraceConfig; - - /** - * predecessors is an array of transactions included in the same block - * need to be replayed first to get correct context for tracing. - * - * @generated from field: repeated ethermint.evm.v1.MsgEthereumTx predecessors = 4; - */ - predecessors: MsgEthereumTx[] = []; - - /** - * block_number of requested transaction - * - * @generated from field: int64 block_number = 5; - */ - blockNumber = protoInt64.zero; - - /** - * block_hash of requested transaction - * - * @generated from field: string block_hash = 6; - */ - blockHash = ""; - - /** - * block_time of requested transaction - * - * @generated from field: google.protobuf.Timestamp block_time = 7; - */ - blockTime?: Timestamp; - - /** - * proposer_address is the proposer of the requested block - * - * @generated from field: bytes proposer_address = 8; - */ - proposerAddress = new Uint8Array(0); - - /** - * chain_id is the the eip155 chain id parsed from the requested block header - * - * @generated from field: int64 chain_id = 9; - */ - chainId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTraceTxRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "msg", kind: "message", T: MsgEthereumTx }, - { no: 3, name: "trace_config", kind: "message", T: TraceConfig }, - { no: 4, name: "predecessors", kind: "message", T: MsgEthereumTx, repeated: true }, - { no: 5, name: "block_number", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "block_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "block_time", kind: "message", T: Timestamp }, - { no: 8, name: "proposer_address", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "chain_id", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTraceTxRequest { - return new QueryTraceTxRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTraceTxRequest { - return new QueryTraceTxRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTraceTxRequest { - return new QueryTraceTxRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTraceTxRequest | PlainMessage | undefined, b: QueryTraceTxRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTraceTxRequest, a, b); - } -} - -/** - * QueryTraceTxResponse defines TraceTx response - * - * @generated from message ethermint.evm.v1.QueryTraceTxResponse - */ -export class QueryTraceTxResponse extends Message { - /** - * data is the response serialized in bytes - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTraceTxResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTraceTxResponse { - return new QueryTraceTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTraceTxResponse { - return new QueryTraceTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTraceTxResponse { - return new QueryTraceTxResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTraceTxResponse | PlainMessage | undefined, b: QueryTraceTxResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTraceTxResponse, a, b); - } -} - -/** - * QueryTraceBlockRequest defines TraceTx request - * - * @generated from message ethermint.evm.v1.QueryTraceBlockRequest - */ -export class QueryTraceBlockRequest extends Message { - /** - * txs is an array of messages in the block - * - * @generated from field: repeated ethermint.evm.v1.MsgEthereumTx txs = 1; - */ - txs: MsgEthereumTx[] = []; - - /** - * trace_config holds extra parameters to trace functions. - * - * @generated from field: ethermint.evm.v1.TraceConfig trace_config = 3; - */ - traceConfig?: TraceConfig; - - /** - * block_number of the traced block - * - * @generated from field: int64 block_number = 5; - */ - blockNumber = protoInt64.zero; - - /** - * block_hash (hex) of the traced block - * - * @generated from field: string block_hash = 6; - */ - blockHash = ""; - - /** - * block_time of the traced block - * - * @generated from field: google.protobuf.Timestamp block_time = 7; - */ - blockTime?: Timestamp; - - /** - * proposer_address is the address of the requested block - * - * @generated from field: bytes proposer_address = 8; - */ - proposerAddress = new Uint8Array(0); - - /** - * chain_id is the eip155 chain id parsed from the requested block header - * - * @generated from field: int64 chain_id = 9; - */ - chainId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTraceBlockRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "txs", kind: "message", T: MsgEthereumTx, repeated: true }, - { no: 3, name: "trace_config", kind: "message", T: TraceConfig }, - { no: 5, name: "block_number", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "block_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "block_time", kind: "message", T: Timestamp }, - { no: 8, name: "proposer_address", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "chain_id", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTraceBlockRequest { - return new QueryTraceBlockRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTraceBlockRequest { - return new QueryTraceBlockRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTraceBlockRequest { - return new QueryTraceBlockRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTraceBlockRequest | PlainMessage | undefined, b: QueryTraceBlockRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTraceBlockRequest, a, b); - } -} - -/** - * QueryTraceBlockResponse defines TraceBlock response - * - * @generated from message ethermint.evm.v1.QueryTraceBlockResponse - */ -export class QueryTraceBlockResponse extends Message { - /** - * data is the response serialized in bytes - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryTraceBlockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTraceBlockResponse { - return new QueryTraceBlockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTraceBlockResponse { - return new QueryTraceBlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTraceBlockResponse { - return new QueryTraceBlockResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTraceBlockResponse | PlainMessage | undefined, b: QueryTraceBlockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTraceBlockResponse, a, b); - } -} - -/** - * QueryBaseFeeRequest defines the request type for querying the EIP1559 base - * fee. - * - * @generated from message ethermint.evm.v1.QueryBaseFeeRequest - */ -export class QueryBaseFeeRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryBaseFeeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseFeeRequest | PlainMessage | undefined, b: QueryBaseFeeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseFeeRequest, a, b); - } -} - -/** - * QueryBaseFeeResponse returns the EIP1559 base fee. - * - * @generated from message ethermint.evm.v1.QueryBaseFeeResponse - */ -export class QueryBaseFeeResponse extends Message { - /** - * base_fee is the EIP1559 base fee - * - * @generated from field: string base_fee = 1; - */ - baseFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.QueryBaseFeeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseFeeResponse | PlainMessage | undefined, b: QueryBaseFeeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseFeeResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/tx_cosmes.ts b/packages/es/src/protobufs/ethermint/evm/v1/tx_cosmes.ts deleted file mode 100644 index d9d5603ec..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/tx_cosmes.ts +++ /dev/null @@ -1,34 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ethermint/evm/v1/tx.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgEthereumTx, MsgEthereumTxResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ethermint.evm.v1.Msg"; - -/** - * EthereumTx defines a method submitting Ethereum transactions. - * - * @generated from rpc ethermint.evm.v1.Msg.EthereumTx - */ -export const MsgEthereumTxService = { - typeName: TYPE_NAME, - method: "EthereumTx", - Request: MsgEthereumTx, - Response: MsgEthereumTxResponse, -} as const; - -/** - * UpdateParams defined a governance operation for updating the x/evm module parameters. - * The authority is hard-coded to the Cosmos SDK x/gov module account - * - * @generated from rpc ethermint.evm.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ethermint/evm/v1/tx_pb.ts b/packages/es/src/protobufs/ethermint/evm/v1/tx_pb.ts deleted file mode 100644 index 10eb68649..000000000 --- a/packages/es/src/protobufs/ethermint/evm/v1/tx_pb.ts +++ /dev/null @@ -1,627 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/evm/v1/tx.proto (package ethermint.evm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccessTuple, Log, Params } from "./evm_pb.js"; - -/** - * MsgEthereumTx encapsulates an Ethereum transaction as an SDK message. - * - * @generated from message ethermint.evm.v1.MsgEthereumTx - */ -export class MsgEthereumTx extends Message { - /** - * data is inner transaction data of the Ethereum transaction - * - * @generated from field: google.protobuf.Any data = 1; - */ - data?: Any; - - /** - * size is the encoded storage size of the transaction (DEPRECATED) - * - * @generated from field: double size = 2; - */ - size = 0; - - /** - * hash of the transaction in hex format - * - * @generated from field: string hash = 3; - */ - hash = ""; - - /** - * from is the ethereum signer address in hex format. This address value is checked - * against the address derived from the signature (V, R, S) using the - * secp256k1 elliptic curve - * - * @generated from field: string from = 4; - */ - from = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.MsgEthereumTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Any }, - { no: 2, name: "size", kind: "scalar", T: 1 /* ScalarType.DOUBLE */ }, - { no: 3, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "from", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgEthereumTx { - return new MsgEthereumTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgEthereumTx { - return new MsgEthereumTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgEthereumTx { - return new MsgEthereumTx().fromJsonString(jsonString, options); - } - - static equals(a: MsgEthereumTx | PlainMessage | undefined, b: MsgEthereumTx | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgEthereumTx, a, b); - } -} - -/** - * LegacyTx is the transaction data of regular Ethereum transactions. - * NOTE: All non-protected transactions (i.e non EIP155 signed) will fail if the - * AllowUnprotectedTxs parameter is disabled. - * - * @generated from message ethermint.evm.v1.LegacyTx - */ -export class LegacyTx extends Message { - /** - * nonce corresponds to the account nonce (transaction sequence). - * - * @generated from field: uint64 nonce = 1; - */ - nonce = protoInt64.zero; - - /** - * gas_price defines the value for each gas unit - * - * @generated from field: string gas_price = 2; - */ - gasPrice = ""; - - /** - * gas defines the gas limit defined for the transaction. - * - * @generated from field: uint64 gas = 3; - */ - gas = protoInt64.zero; - - /** - * to is the hex formatted address of the recipient - * - * @generated from field: string to = 4; - */ - to = ""; - - /** - * value defines the unsigned integer value of the transaction amount. - * - * @generated from field: string value = 5; - */ - value = ""; - - /** - * data is the data payload bytes of the transaction. - * - * @generated from field: bytes data = 6; - */ - data = new Uint8Array(0); - - /** - * v defines the signature value - * - * @generated from field: bytes v = 7; - */ - v = new Uint8Array(0); - - /** - * r defines the signature value - * - * @generated from field: bytes r = 8; - */ - r = new Uint8Array(0); - - /** - * s define the signature value - * - * @generated from field: bytes s = 9; - */ - s = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.LegacyTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "nonce", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "gas_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "to", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "v", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "r", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "s", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LegacyTx { - return new LegacyTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LegacyTx { - return new LegacyTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LegacyTx { - return new LegacyTx().fromJsonString(jsonString, options); - } - - static equals(a: LegacyTx | PlainMessage | undefined, b: LegacyTx | PlainMessage | undefined): boolean { - return proto3.util.equals(LegacyTx, a, b); - } -} - -/** - * AccessListTx is the data of EIP-2930 access list transactions. - * - * @generated from message ethermint.evm.v1.AccessListTx - */ -export class AccessListTx extends Message { - /** - * chain_id of the destination EVM chain - * - * @generated from field: string chain_id = 1; - */ - chainId = ""; - - /** - * nonce corresponds to the account nonce (transaction sequence). - * - * @generated from field: uint64 nonce = 2; - */ - nonce = protoInt64.zero; - - /** - * gas_price defines the value for each gas unit - * - * @generated from field: string gas_price = 3; - */ - gasPrice = ""; - - /** - * gas defines the gas limit defined for the transaction. - * - * @generated from field: uint64 gas = 4; - */ - gas = protoInt64.zero; - - /** - * to is the recipient address in hex format - * - * @generated from field: string to = 5; - */ - to = ""; - - /** - * value defines the unsigned integer value of the transaction amount. - * - * @generated from field: string value = 6; - */ - value = ""; - - /** - * data is the data payload bytes of the transaction. - * - * @generated from field: bytes data = 7; - */ - data = new Uint8Array(0); - - /** - * accesses is an array of access tuples - * - * @generated from field: repeated ethermint.evm.v1.AccessTuple accesses = 8; - */ - accesses: AccessTuple[] = []; - - /** - * v defines the signature value - * - * @generated from field: bytes v = 9; - */ - v = new Uint8Array(0); - - /** - * r defines the signature value - * - * @generated from field: bytes r = 10; - */ - r = new Uint8Array(0); - - /** - * s define the signature value - * - * @generated from field: bytes s = 11; - */ - s = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.AccessListTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "nonce", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "gas_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "to", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "accesses", kind: "message", T: AccessTuple, repeated: true }, - { no: 9, name: "v", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "r", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 11, name: "s", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccessListTx { - return new AccessListTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccessListTx { - return new AccessListTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccessListTx { - return new AccessListTx().fromJsonString(jsonString, options); - } - - static equals(a: AccessListTx | PlainMessage | undefined, b: AccessListTx | PlainMessage | undefined): boolean { - return proto3.util.equals(AccessListTx, a, b); - } -} - -/** - * DynamicFeeTx is the data of EIP-1559 dinamic fee transactions. - * - * @generated from message ethermint.evm.v1.DynamicFeeTx - */ -export class DynamicFeeTx extends Message { - /** - * chain_id of the destination EVM chain - * - * @generated from field: string chain_id = 1; - */ - chainId = ""; - - /** - * nonce corresponds to the account nonce (transaction sequence). - * - * @generated from field: uint64 nonce = 2; - */ - nonce = protoInt64.zero; - - /** - * gas_tip_cap defines the max value for the gas tip - * - * @generated from field: string gas_tip_cap = 3; - */ - gasTipCap = ""; - - /** - * gas_fee_cap defines the max value for the gas fee - * - * @generated from field: string gas_fee_cap = 4; - */ - gasFeeCap = ""; - - /** - * gas defines the gas limit defined for the transaction. - * - * @generated from field: uint64 gas = 5; - */ - gas = protoInt64.zero; - - /** - * to is the hex formatted address of the recipient - * - * @generated from field: string to = 6; - */ - to = ""; - - /** - * value defines the the transaction amount. - * - * @generated from field: string value = 7; - */ - value = ""; - - /** - * data is the data payload bytes of the transaction. - * - * @generated from field: bytes data = 8; - */ - data = new Uint8Array(0); - - /** - * accesses is an array of access tuples - * - * @generated from field: repeated ethermint.evm.v1.AccessTuple accesses = 9; - */ - accesses: AccessTuple[] = []; - - /** - * v defines the signature value - * - * @generated from field: bytes v = 10; - */ - v = new Uint8Array(0); - - /** - * r defines the signature value - * - * @generated from field: bytes r = 11; - */ - r = new Uint8Array(0); - - /** - * s define the signature value - * - * @generated from field: bytes s = 12; - */ - s = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.DynamicFeeTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "nonce", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "gas_tip_cap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "gas_fee_cap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "to", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "accesses", kind: "message", T: AccessTuple, repeated: true }, - { no: 10, name: "v", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 11, name: "r", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 12, name: "s", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DynamicFeeTx { - return new DynamicFeeTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DynamicFeeTx { - return new DynamicFeeTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DynamicFeeTx { - return new DynamicFeeTx().fromJsonString(jsonString, options); - } - - static equals(a: DynamicFeeTx | PlainMessage | undefined, b: DynamicFeeTx | PlainMessage | undefined): boolean { - return proto3.util.equals(DynamicFeeTx, a, b); - } -} - -/** - * ExtensionOptionsEthereumTx is an extension option for ethereum transactions - * - * @generated from message ethermint.evm.v1.ExtensionOptionsEthereumTx - */ -export class ExtensionOptionsEthereumTx extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.ExtensionOptionsEthereumTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExtensionOptionsEthereumTx { - return new ExtensionOptionsEthereumTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExtensionOptionsEthereumTx { - return new ExtensionOptionsEthereumTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExtensionOptionsEthereumTx { - return new ExtensionOptionsEthereumTx().fromJsonString(jsonString, options); - } - - static equals(a: ExtensionOptionsEthereumTx | PlainMessage | undefined, b: ExtensionOptionsEthereumTx | PlainMessage | undefined): boolean { - return proto3.util.equals(ExtensionOptionsEthereumTx, a, b); - } -} - -/** - * MsgEthereumTxResponse defines the Msg/EthereumTx response type. - * - * @generated from message ethermint.evm.v1.MsgEthereumTxResponse - */ -export class MsgEthereumTxResponse extends Message { - /** - * hash of the ethereum transaction in hex format. This hash differs from the - * Tendermint sha256 hash of the transaction bytes. See - * https://github.com/tendermint/tendermint/issues/6539 for reference - * - * @generated from field: string hash = 1; - */ - hash = ""; - - /** - * logs contains the transaction hash and the proto-compatible ethereum - * logs. - * - * @generated from field: repeated ethermint.evm.v1.Log logs = 2; - */ - logs: Log[] = []; - - /** - * ret is the returned data from evm function (result or data supplied with revert - * opcode) - * - * @generated from field: bytes ret = 3; - */ - ret = new Uint8Array(0); - - /** - * vm_error is the error returned by vm execution - * - * @generated from field: string vm_error = 4; - */ - vmError = ""; - - /** - * gas_used specifies how much gas was consumed by the transaction - * - * @generated from field: uint64 gas_used = 5; - */ - gasUsed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.MsgEthereumTxResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "logs", kind: "message", T: Log, repeated: true }, - { no: 3, name: "ret", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "vm_error", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "gas_used", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgEthereumTxResponse { - return new MsgEthereumTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgEthereumTxResponse { - return new MsgEthereumTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgEthereumTxResponse { - return new MsgEthereumTxResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgEthereumTxResponse | PlainMessage | undefined, b: MsgEthereumTxResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgEthereumTxResponse, a, b); - } -} - -/** - * MsgUpdateParams defines a Msg for updating the x/evm module parameters. - * - * @generated from message ethermint.evm.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the x/evm parameters to update. - * NOTE: All parameters must be supplied. - * - * @generated from field: ethermint.evm.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * @generated from message ethermint.evm.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.evm.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/events_pb.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/events_pb.ts deleted file mode 100644 index 54e0797de..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/events_pb.ts +++ /dev/null @@ -1,98 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/events.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * EventFeeMarket is the event type for the fee market module - * - * @generated from message ethermint.feemarket.v1.EventFeeMarket - */ -export class EventFeeMarket extends Message { - /** - * base_fee for EIP-1559 blocks - * - * @generated from field: string base_fee = 1; - */ - baseFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.EventFeeMarket"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventFeeMarket { - return new EventFeeMarket().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventFeeMarket { - return new EventFeeMarket().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventFeeMarket { - return new EventFeeMarket().fromJsonString(jsonString, options); - } - - static equals(a: EventFeeMarket | PlainMessage | undefined, b: EventFeeMarket | PlainMessage | undefined): boolean { - return proto3.util.equals(EventFeeMarket, a, b); - } -} - -/** - * EventBlockGas defines an Ethereum block gas event - * - * @generated from message ethermint.feemarket.v1.EventBlockGas - */ -export class EventBlockGas extends Message { - /** - * height of the block - * - * @generated from field: string height = 1; - */ - height = ""; - - /** - * amount of gas wanted by the block - * - * @generated from field: string amount = 2; - */ - amount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.EventBlockGas"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "height", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventBlockGas { - return new EventBlockGas().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventBlockGas { - return new EventBlockGas().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventBlockGas { - return new EventBlockGas().fromJsonString(jsonString, options); - } - - static equals(a: EventBlockGas | PlainMessage | undefined, b: EventBlockGas | PlainMessage | undefined): boolean { - return proto3.util.equals(EventBlockGas, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/feemarket_pb.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/feemarket_pb.ts deleted file mode 100644 index dd7757cba..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/feemarket_pb.ts +++ /dev/null @@ -1,100 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/feemarket.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Params defines the EVM module parameters - * - * @generated from message ethermint.feemarket.v1.Params - */ -export class Params extends Message { - /** - * no_base_fee forces the EIP-1559 base fee to 0 (needed for 0 price calls) - * - * @generated from field: bool no_base_fee = 1; - */ - noBaseFee = false; - - /** - * base_fee_change_denominator bounds the amount the base fee can change - * between blocks. - * - * @generated from field: uint32 base_fee_change_denominator = 2; - */ - baseFeeChangeDenominator = 0; - - /** - * elasticity_multiplier bounds the maximum gas limit an EIP-1559 block may - * have. - * - * @generated from field: uint32 elasticity_multiplier = 3; - */ - elasticityMultiplier = 0; - - /** - * enable_height defines at which block height the base fee calculation is enabled. - * - * @generated from field: int64 enable_height = 5; - */ - enableHeight = protoInt64.zero; - - /** - * base_fee for EIP-1559 blocks. - * - * @generated from field: string base_fee = 6; - */ - baseFee = ""; - - /** - * min_gas_price defines the minimum gas price value for cosmos and eth transactions - * - * @generated from field: string min_gas_price = 7; - */ - minGasPrice = ""; - - /** - * min_gas_multiplier bounds the minimum gas used to be charged - * to senders based on gas limit - * - * @generated from field: string min_gas_multiplier = 8; - */ - minGasMultiplier = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "no_base_fee", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "base_fee_change_denominator", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "elasticity_multiplier", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 5, name: "enable_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "base_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "min_gas_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "min_gas_multiplier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/genesis_pb.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/genesis_pb.ts deleted file mode 100644 index 78c369a10..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/genesis_pb.ts +++ /dev/null @@ -1,59 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/genesis.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./feemarket_pb.js"; - -/** - * GenesisState defines the feemarket module's genesis state. - * - * @generated from message ethermint.feemarket.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * params defines all the parameters of the feemarket module. - * - * @generated from field: ethermint.feemarket.v1.Params params = 1; - */ - params?: Params; - - /** - * block_gas is the amount of gas wanted on the last block before the upgrade. - * Zero by default. - * - * @generated from field: uint64 block_gas = 3; - */ - blockGas = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 3, name: "block_gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/query_cosmes.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/query_cosmes.ts deleted file mode 100644 index c9bc1d00a..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/query_cosmes.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/query.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryBaseFeeRequest, QueryBaseFeeResponse, QueryBlockGasRequest, QueryBlockGasResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ethermint.feemarket.v1.Query"; - -/** - * Params queries the parameters of x/feemarket module. - * - * @generated from rpc ethermint.feemarket.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * BaseFee queries the base fee of the parent block of the current block. - * - * @generated from rpc ethermint.feemarket.v1.Query.BaseFee - */ -export const QueryBaseFeeService = { - typeName: TYPE_NAME, - method: "BaseFee", - Request: QueryBaseFeeRequest, - Response: QueryBaseFeeResponse, -} as const; - -/** - * BlockGas queries the gas used at a given block height - * - * @generated from rpc ethermint.feemarket.v1.Query.BlockGas - */ -export const QueryBlockGasService = { - typeName: TYPE_NAME, - method: "BlockGas", - Request: QueryBlockGasRequest, - Response: QueryBlockGasResponse, -} as const; - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/query_pb.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/query_pb.ts deleted file mode 100644 index e03697612..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/query_pb.ts +++ /dev/null @@ -1,233 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/query.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./feemarket_pb.js"; - -/** - * QueryParamsRequest defines the request type for querying x/evm parameters. - * - * @generated from message ethermint.feemarket.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse defines the response type for querying x/evm parameters. - * - * @generated from message ethermint.feemarket.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params define the evm module parameters. - * - * @generated from field: ethermint.feemarket.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryBaseFeeRequest defines the request type for querying the EIP1559 base - * fee. - * - * @generated from message ethermint.feemarket.v1.QueryBaseFeeRequest - */ -export class QueryBaseFeeRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryBaseFeeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseFeeRequest { - return new QueryBaseFeeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseFeeRequest | PlainMessage | undefined, b: QueryBaseFeeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseFeeRequest, a, b); - } -} - -/** - * QueryBaseFeeResponse returns the EIP1559 base fee. - * - * @generated from message ethermint.feemarket.v1.QueryBaseFeeResponse - */ -export class QueryBaseFeeResponse extends Message { - /** - * base_fee is the EIP1559 base fee - * - * @generated from field: string base_fee = 1; - */ - baseFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryBaseFeeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseFeeResponse { - return new QueryBaseFeeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseFeeResponse | PlainMessage | undefined, b: QueryBaseFeeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseFeeResponse, a, b); - } -} - -/** - * QueryBlockGasRequest defines the request type for querying the EIP1559 base - * fee. - * - * @generated from message ethermint.feemarket.v1.QueryBlockGasRequest - */ -export class QueryBlockGasRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryBlockGasRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBlockGasRequest { - return new QueryBlockGasRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBlockGasRequest { - return new QueryBlockGasRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBlockGasRequest { - return new QueryBlockGasRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBlockGasRequest | PlainMessage | undefined, b: QueryBlockGasRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBlockGasRequest, a, b); - } -} - -/** - * QueryBlockGasResponse returns block gas used for a given height. - * - * @generated from message ethermint.feemarket.v1.QueryBlockGasResponse - */ -export class QueryBlockGasResponse extends Message { - /** - * gas is the returned block gas - * - * @generated from field: int64 gas = 1; - */ - gas = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.QueryBlockGasResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gas", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBlockGasResponse { - return new QueryBlockGasResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBlockGasResponse { - return new QueryBlockGasResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBlockGasResponse { - return new QueryBlockGasResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBlockGasResponse | PlainMessage | undefined, b: QueryBlockGasResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBlockGasResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/tx_cosmes.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/tx_cosmes.ts deleted file mode 100644 index d3e260c8d..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/tx_cosmes.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/tx.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ethermint.feemarket.v1.Msg"; - -/** - * UpdateParams defined a governance operation for updating the x/feemarket module parameters. - * The authority is hard-coded to the Cosmos SDK x/gov module account - * - * @generated from rpc ethermint.feemarket.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ethermint/feemarket/v1/tx_pb.ts b/packages/es/src/protobufs/ethermint/feemarket/v1/tx_pb.ts deleted file mode 100644 index 9e99c488c..000000000 --- a/packages/es/src/protobufs/ethermint/feemarket/v1/tx_pb.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/feemarket/v1/tx.proto (package ethermint.feemarket.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./feemarket_pb.js"; - -/** - * MsgUpdateParams defines a Msg for updating the x/feemarket module parameters. - * - * @generated from message ethermint.feemarket.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the x/feemarket parameters to update. - * NOTE: All parameters must be supplied. - * - * @generated from field: ethermint.feemarket.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * @generated from message ethermint.feemarket.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.feemarket.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/types/v1/account_pb.ts b/packages/es/src/protobufs/ethermint/types/v1/account_pb.ts deleted file mode 100644 index 31e535681..000000000 --- a/packages/es/src/protobufs/ethermint/types/v1/account_pb.ts +++ /dev/null @@ -1,59 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/types/v1/account.proto (package ethermint.types.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { BaseAccount } from "../../../cosmos/auth/v1beta1/auth_pb.js"; - -/** - * EthAccount implements the authtypes.AccountI interface and embeds an - * authtypes.BaseAccount type. It is compatible with the auth AccountKeeper. - * - * @generated from message ethermint.types.v1.EthAccount - */ -export class EthAccount extends Message { - /** - * base_account is an authtypes.BaseAccount - * - * @generated from field: cosmos.auth.v1beta1.BaseAccount base_account = 1; - */ - baseAccount?: BaseAccount; - - /** - * code_hash is the hash calculated from the code contents - * - * @generated from field: string code_hash = 2; - */ - codeHash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.types.v1.EthAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_account", kind: "message", T: BaseAccount }, - { no: 2, name: "code_hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EthAccount { - return new EthAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EthAccount { - return new EthAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EthAccount { - return new EthAccount().fromJsonString(jsonString, options); - } - - static equals(a: EthAccount | PlainMessage | undefined, b: EthAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(EthAccount, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/types/v1/dynamic_fee_pb.ts b/packages/es/src/protobufs/ethermint/types/v1/dynamic_fee_pb.ts deleted file mode 100644 index 08187b205..000000000 --- a/packages/es/src/protobufs/ethermint/types/v1/dynamic_fee_pb.ts +++ /dev/null @@ -1,49 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/types/v1/dynamic_fee.proto (package ethermint.types.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * ExtensionOptionDynamicFeeTx is an extension option that specifies the maxPrioPrice for cosmos tx - * - * @generated from message ethermint.types.v1.ExtensionOptionDynamicFeeTx - */ -export class ExtensionOptionDynamicFeeTx extends Message { - /** - * max_priority_price is the same as `max_priority_fee_per_gas` in eip-1559 spec - * - * @generated from field: string max_priority_price = 1; - */ - maxPriorityPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.types.v1.ExtensionOptionDynamicFeeTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_priority_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExtensionOptionDynamicFeeTx { - return new ExtensionOptionDynamicFeeTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExtensionOptionDynamicFeeTx { - return new ExtensionOptionDynamicFeeTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExtensionOptionDynamicFeeTx { - return new ExtensionOptionDynamicFeeTx().fromJsonString(jsonString, options); - } - - static equals(a: ExtensionOptionDynamicFeeTx | PlainMessage | undefined, b: ExtensionOptionDynamicFeeTx | PlainMessage | undefined): boolean { - return proto3.util.equals(ExtensionOptionDynamicFeeTx, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/types/v1/indexer_pb.ts b/packages/es/src/protobufs/ethermint/types/v1/indexer_pb.ts deleted file mode 100644 index f5d92ecc7..000000000 --- a/packages/es/src/protobufs/ethermint/types/v1/indexer_pb.ts +++ /dev/null @@ -1,100 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/types/v1/indexer.proto (package ethermint.types.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * TxResult is the value stored in eth tx indexer - * - * @generated from message ethermint.types.v1.TxResult - */ -export class TxResult extends Message { - /** - * height of the blockchain - * - * @generated from field: int64 height = 1; - */ - height = protoInt64.zero; - - /** - * tx_index of the cosmos transaction - * - * @generated from field: uint32 tx_index = 2; - */ - txIndex = 0; - - /** - * msg_index in a batch transaction - * - * @generated from field: uint32 msg_index = 3; - */ - msgIndex = 0; - - /** - * eth_tx_index is the index in the list of valid eth tx in the block, - * aka. the transaction list returned by eth_getBlock api. - * - * @generated from field: int32 eth_tx_index = 4; - */ - ethTxIndex = 0; - - /** - * failed is true if the eth transaction did not go succeed - * - * @generated from field: bool failed = 5; - */ - failed = false; - - /** - * gas_used by the transaction. If it exceeds the block gas limit, - * it's set to gas limit, which is what's actually deducted by ante handler. - * - * @generated from field: uint64 gas_used = 6; - */ - gasUsed = protoInt64.zero; - - /** - * cumulative_gas_used specifies the cumulated amount of gas used for all - * processed messages within the current batch transaction. - * - * @generated from field: uint64 cumulative_gas_used = 7; - */ - cumulativeGasUsed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.types.v1.TxResult"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: "tx_index", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "msg_index", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: "eth_tx_index", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 5, name: "failed", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "gas_used", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "cumulative_gas_used", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxResult { - return new TxResult().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxResult { - return new TxResult().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxResult { - return new TxResult().fromJsonString(jsonString, options); - } - - static equals(a: TxResult | PlainMessage | undefined, b: TxResult | PlainMessage | undefined): boolean { - return proto3.util.equals(TxResult, a, b); - } -} - diff --git a/packages/es/src/protobufs/ethermint/types/v1/web3_pb.ts b/packages/es/src/protobufs/ethermint/types/v1/web3_pb.ts deleted file mode 100644 index 891b5fe9b..000000000 --- a/packages/es/src/protobufs/ethermint/types/v1/web3_pb.ts +++ /dev/null @@ -1,69 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ethermint/types/v1/web3.proto (package ethermint.types.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * ExtensionOptionsWeb3Tx is an extension option that specifies the typed chain id, - * the fee payer as well as its signature data. - * - * @generated from message ethermint.types.v1.ExtensionOptionsWeb3Tx - */ -export class ExtensionOptionsWeb3Tx extends Message { - /** - * typed_data_chain_id is used only in EIP712 Domain and should match - * Ethereum network ID in a Web3 provider (e.g. Metamask). - * - * @generated from field: uint64 typed_data_chain_id = 1; - */ - typedDataChainId = protoInt64.zero; - - /** - * fee_payer is an account address for the fee payer. It will be validated - * during EIP712 signature checking. - * - * @generated from field: string fee_payer = 2; - */ - feePayer = ""; - - /** - * fee_payer_sig is a signature data from the fee paying account, - * allows to perform fee delegation when using EIP712 Domain. - * - * @generated from field: bytes fee_payer_sig = 3; - */ - feePayerSig = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ethermint.types.v1.ExtensionOptionsWeb3Tx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "typed_data_chain_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "fee_payer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "fee_payer_sig", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExtensionOptionsWeb3Tx { - return new ExtensionOptionsWeb3Tx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExtensionOptionsWeb3Tx { - return new ExtensionOptionsWeb3Tx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExtensionOptionsWeb3Tx { - return new ExtensionOptionsWeb3Tx().fromJsonString(jsonString, options); - } - - static equals(a: ExtensionOptionsWeb3Tx | PlainMessage | undefined, b: ExtensionOptionsWeb3Tx | PlainMessage | undefined): boolean { - return proto3.util.equals(ExtensionOptionsWeb3Tx, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/controller_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/controller_pb.ts deleted file mode 100644 index 834316b5d..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/controller_pb.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/controller/v1/controller.proto (package ibc.applications.interchain_accounts.controller.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params defines the set of on-chain interchain accounts parameters. - * The following parameters may be used to disable the controller submodule. - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.Params - */ -export class Params extends Message { - /** - * controller_enabled enables or disables the controller submodule. - * - * @generated from field: bool controller_enabled = 1; - */ - controllerEnabled = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_cosmes.ts deleted file mode 100644 index af11d2588..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/controller/v1/query.proto (package ibc.applications.interchain_accounts.controller.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryInterchainAccountRequest, QueryInterchainAccountResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.applications.interchain_accounts.controller.v1.Query"; - -/** - * InterchainAccount returns the interchain account address for a given owner address on a given connection - * - * @generated from rpc ibc.applications.interchain_accounts.controller.v1.Query.InterchainAccount - */ -export const QueryInterchainAccountService = { - typeName: TYPE_NAME, - method: "InterchainAccount", - Request: QueryInterchainAccountRequest, - Response: QueryInterchainAccountResponse, -} as const; - -/** - * Params queries all parameters of the ICA controller submodule. - * - * @generated from rpc ibc.applications.interchain_accounts.controller.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_pb.ts deleted file mode 100644 index 9b668827a..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/query_pb.ts +++ /dev/null @@ -1,167 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/controller/v1/query.proto (package ibc.applications.interchain_accounts.controller.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./controller_pb.js"; - -/** - * QueryInterchainAccountRequest is the request type for the Query/InterchainAccount RPC method. - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.QueryInterchainAccountRequest - */ -export class QueryInterchainAccountRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.QueryInterchainAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInterchainAccountRequest { - return new QueryInterchainAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInterchainAccountRequest { - return new QueryInterchainAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInterchainAccountRequest { - return new QueryInterchainAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryInterchainAccountRequest | PlainMessage | undefined, b: QueryInterchainAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInterchainAccountRequest, a, b); - } -} - -/** - * QueryInterchainAccountResponse the response type for the Query/InterchainAccount RPC method. - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.QueryInterchainAccountResponse - */ -export class QueryInterchainAccountResponse extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.QueryInterchainAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInterchainAccountResponse { - return new QueryInterchainAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInterchainAccountResponse { - return new QueryInterchainAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInterchainAccountResponse { - return new QueryInterchainAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryInterchainAccountResponse | PlainMessage | undefined, b: QueryInterchainAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInterchainAccountResponse, a, b); - } -} - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: ibc.applications.interchain_accounts.controller.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_cosmes.ts deleted file mode 100644 index 76cc02f08..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_cosmes.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/controller/v1/tx.proto (package ibc.applications.interchain_accounts.controller.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgRegisterInterchainAccount, MsgRegisterInterchainAccountResponse, MsgSendTx, MsgSendTxResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.applications.interchain_accounts.controller.v1.Msg"; - -/** - * RegisterInterchainAccount defines a rpc handler for MsgRegisterInterchainAccount. - * - * @generated from rpc ibc.applications.interchain_accounts.controller.v1.Msg.RegisterInterchainAccount - */ -export const MsgRegisterInterchainAccountService = { - typeName: TYPE_NAME, - method: "RegisterInterchainAccount", - Request: MsgRegisterInterchainAccount, - Response: MsgRegisterInterchainAccountResponse, -} as const; - -/** - * SendTx defines a rpc handler for MsgSendTx. - * - * @generated from rpc ibc.applications.interchain_accounts.controller.v1.Msg.SendTx - */ -export const MsgSendTxService = { - typeName: TYPE_NAME, - method: "SendTx", - Request: MsgSendTx, - Response: MsgSendTxResponse, -} as const; - -/** - * UpdateParams defines a rpc handler for MsgUpdateParams. - * - * @generated from rpc ibc.applications.interchain_accounts.controller.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_pb.ts deleted file mode 100644 index 7aae1e40a..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/controller/v1/tx_pb.ts +++ /dev/null @@ -1,296 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/controller/v1/tx.proto (package ibc.applications.interchain_accounts.controller.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Order } from "../../../../core/channel/v1/channel_pb.js"; -import { InterchainAccountPacketData } from "../../v1/packet_pb.js"; -import { Params } from "./controller_pb.js"; - -/** - * MsgRegisterInterchainAccount defines the payload for Msg/RegisterAccount - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgRegisterInterchainAccount - */ -export class MsgRegisterInterchainAccount extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * @generated from field: string version = 3; - */ - version = ""; - - /** - * @generated from field: ibc.core.channel.v1.Order ordering = 4; - */ - ordering = Order.NONE_UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgRegisterInterchainAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "ordering", kind: "enum", T: proto3.getEnumType(Order) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterInterchainAccount { - return new MsgRegisterInterchainAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterInterchainAccount { - return new MsgRegisterInterchainAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterInterchainAccount { - return new MsgRegisterInterchainAccount().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterInterchainAccount | PlainMessage | undefined, b: MsgRegisterInterchainAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterInterchainAccount, a, b); - } -} - -/** - * MsgRegisterInterchainAccountResponse defines the response for Msg/RegisterAccount - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgRegisterInterchainAccountResponse - */ -export class MsgRegisterInterchainAccountResponse extends Message { - /** - * @generated from field: string channel_id = 1; - */ - channelId = ""; - - /** - * @generated from field: string port_id = 2; - */ - portId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgRegisterInterchainAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterInterchainAccountResponse { - return new MsgRegisterInterchainAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterInterchainAccountResponse { - return new MsgRegisterInterchainAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterInterchainAccountResponse { - return new MsgRegisterInterchainAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterInterchainAccountResponse | PlainMessage | undefined, b: MsgRegisterInterchainAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterInterchainAccountResponse, a, b); - } -} - -/** - * MsgSendTx defines the payload for Msg/SendTx - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgSendTx - */ -export class MsgSendTx extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * @generated from field: ibc.applications.interchain_accounts.v1.InterchainAccountPacketData packet_data = 3; - */ - packetData?: InterchainAccountPacketData; - - /** - * Relative timeout timestamp provided will be added to the current block time during transaction execution. - * The timeout timestamp must be non-zero. - * - * @generated from field: uint64 relative_timeout = 4; - */ - relativeTimeout = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgSendTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "packet_data", kind: "message", T: InterchainAccountPacketData }, - { no: 4, name: "relative_timeout", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSendTx { - return new MsgSendTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSendTx { - return new MsgSendTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSendTx { - return new MsgSendTx().fromJsonString(jsonString, options); - } - - static equals(a: MsgSendTx | PlainMessage | undefined, b: MsgSendTx | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSendTx, a, b); - } -} - -/** - * MsgSendTxResponse defines the response for MsgSendTx - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgSendTxResponse - */ -export class MsgSendTxResponse extends Message { - /** - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgSendTxResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSendTxResponse { - return new MsgSendTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSendTxResponse { - return new MsgSendTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSendTxResponse { - return new MsgSendTxResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSendTxResponse | PlainMessage | undefined, b: MsgSendTxResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSendTxResponse, a, b); - } -} - -/** - * MsgUpdateParams defines the payload for Msg/UpdateParams - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * params defines the 27-interchain-accounts/controller parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: ibc.applications.interchain_accounts.controller.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response for Msg/UpdateParams - * - * @generated from message ibc.applications.interchain_accounts.controller.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.controller.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/genesis/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/genesis/v1/genesis_pb.ts deleted file mode 100644 index 603afa037..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/genesis/v1/genesis_pb.ts +++ /dev/null @@ -1,278 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/genesis/v1/genesis.proto (package ibc.applications.interchain_accounts.genesis.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "../../controller/v1/controller_pb.js"; -import { Params as Params$1 } from "../../host/v1/host_pb.js"; - -/** - * GenesisState defines the interchain accounts genesis state - * - * @generated from message ibc.applications.interchain_accounts.genesis.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: ibc.applications.interchain_accounts.genesis.v1.ControllerGenesisState controller_genesis_state = 1; - */ - controllerGenesisState?: ControllerGenesisState; - - /** - * @generated from field: ibc.applications.interchain_accounts.genesis.v1.HostGenesisState host_genesis_state = 2; - */ - hostGenesisState?: HostGenesisState; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.genesis.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "controller_genesis_state", kind: "message", T: ControllerGenesisState }, - { no: 2, name: "host_genesis_state", kind: "message", T: HostGenesisState }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * ControllerGenesisState defines the interchain accounts controller genesis state - * - * @generated from message ibc.applications.interchain_accounts.genesis.v1.ControllerGenesisState - */ -export class ControllerGenesisState extends Message { - /** - * @generated from field: repeated ibc.applications.interchain_accounts.genesis.v1.ActiveChannel active_channels = 1; - */ - activeChannels: ActiveChannel[] = []; - - /** - * @generated from field: repeated ibc.applications.interchain_accounts.genesis.v1.RegisteredInterchainAccount interchain_accounts = 2; - */ - interchainAccounts: RegisteredInterchainAccount[] = []; - - /** - * @generated from field: repeated string ports = 3; - */ - ports: string[] = []; - - /** - * @generated from field: ibc.applications.interchain_accounts.controller.v1.Params params = 4; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.genesis.v1.ControllerGenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "active_channels", kind: "message", T: ActiveChannel, repeated: true }, - { no: 2, name: "interchain_accounts", kind: "message", T: RegisteredInterchainAccount, repeated: true }, - { no: 3, name: "ports", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ControllerGenesisState { - return new ControllerGenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ControllerGenesisState { - return new ControllerGenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ControllerGenesisState { - return new ControllerGenesisState().fromJsonString(jsonString, options); - } - - static equals(a: ControllerGenesisState | PlainMessage | undefined, b: ControllerGenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(ControllerGenesisState, a, b); - } -} - -/** - * HostGenesisState defines the interchain accounts host genesis state - * - * @generated from message ibc.applications.interchain_accounts.genesis.v1.HostGenesisState - */ -export class HostGenesisState extends Message { - /** - * @generated from field: repeated ibc.applications.interchain_accounts.genesis.v1.ActiveChannel active_channels = 1; - */ - activeChannels: ActiveChannel[] = []; - - /** - * @generated from field: repeated ibc.applications.interchain_accounts.genesis.v1.RegisteredInterchainAccount interchain_accounts = 2; - */ - interchainAccounts: RegisteredInterchainAccount[] = []; - - /** - * @generated from field: string port = 3; - */ - port = ""; - - /** - * @generated from field: ibc.applications.interchain_accounts.host.v1.Params params = 4; - */ - params?: Params$1; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.genesis.v1.HostGenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "active_channels", kind: "message", T: ActiveChannel, repeated: true }, - { no: 2, name: "interchain_accounts", kind: "message", T: RegisteredInterchainAccount, repeated: true }, - { no: 3, name: "port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "params", kind: "message", T: Params$1 }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): HostGenesisState { - return new HostGenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): HostGenesisState { - return new HostGenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): HostGenesisState { - return new HostGenesisState().fromJsonString(jsonString, options); - } - - static equals(a: HostGenesisState | PlainMessage | undefined, b: HostGenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(HostGenesisState, a, b); - } -} - -/** - * ActiveChannel contains a connection ID, port ID and associated active channel ID, as well as a boolean flag to - * indicate if the channel is middleware enabled - * - * @generated from message ibc.applications.interchain_accounts.genesis.v1.ActiveChannel - */ -export class ActiveChannel extends Message { - /** - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * @generated from field: string port_id = 2; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 3; - */ - channelId = ""; - - /** - * @generated from field: bool is_middleware_enabled = 4; - */ - isMiddlewareEnabled = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.genesis.v1.ActiveChannel"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "is_middleware_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ActiveChannel { - return new ActiveChannel().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ActiveChannel { - return new ActiveChannel().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ActiveChannel { - return new ActiveChannel().fromJsonString(jsonString, options); - } - - static equals(a: ActiveChannel | PlainMessage | undefined, b: ActiveChannel | PlainMessage | undefined): boolean { - return proto3.util.equals(ActiveChannel, a, b); - } -} - -/** - * RegisteredInterchainAccount contains a connection ID, port ID and associated interchain account address - * - * @generated from message ibc.applications.interchain_accounts.genesis.v1.RegisteredInterchainAccount - */ -export class RegisteredInterchainAccount extends Message { - /** - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * @generated from field: string port_id = 2; - */ - portId = ""; - - /** - * @generated from field: string account_address = 3; - */ - accountAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.genesis.v1.RegisteredInterchainAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "account_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RegisteredInterchainAccount { - return new RegisteredInterchainAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RegisteredInterchainAccount { - return new RegisteredInterchainAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RegisteredInterchainAccount { - return new RegisteredInterchainAccount().fromJsonString(jsonString, options); - } - - static equals(a: RegisteredInterchainAccount | PlainMessage | undefined, b: RegisteredInterchainAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(RegisteredInterchainAccount, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/host_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/host_pb.ts deleted file mode 100644 index 44daab027..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/host_pb.ts +++ /dev/null @@ -1,110 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/host/v1/host.proto (package ibc.applications.interchain_accounts.host.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params defines the set of on-chain interchain accounts parameters. - * The following parameters may be used to disable the host submodule. - * - * @generated from message ibc.applications.interchain_accounts.host.v1.Params - */ -export class Params extends Message { - /** - * host_enabled enables or disables the host submodule. - * - * @generated from field: bool host_enabled = 1; - */ - hostEnabled = false; - - /** - * allow_messages defines a list of sdk message typeURLs allowed to be executed on a host chain. - * - * @generated from field: repeated string allow_messages = 2; - */ - allowMessages: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "host_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "allow_messages", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * QueryRequest defines the parameters for a particular query request - * by an interchain account. - * - * @generated from message ibc.applications.interchain_accounts.host.v1.QueryRequest - */ -export class QueryRequest extends Message { - /** - * path defines the path of the query request as defined by ADR-021. - * https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-021-protobuf-query-encoding.md#custom-query-registration-and-routing - * - * @generated from field: string path = 1; - */ - path = ""; - - /** - * data defines the payload of the query request as defined by ADR-021. - * https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-021-protobuf-query-encoding.md#custom-query-registration-and-routing - * - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.QueryRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRequest { - return new QueryRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRequest { - return new QueryRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRequest { - return new QueryRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRequest | PlainMessage | undefined, b: QueryRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRequest, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_cosmes.ts deleted file mode 100644 index 89d601410..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_cosmes.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/host/v1/query.proto (package ibc.applications.interchain_accounts.host.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.applications.interchain_accounts.host.v1.Query"; - -/** - * Params queries all parameters of the ICA host submodule. - * - * @generated from rpc ibc.applications.interchain_accounts.host.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_pb.ts deleted file mode 100644 index 13c0f9d43..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/query_pb.ts +++ /dev/null @@ -1,83 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/host/v1/query.proto (package ibc.applications.interchain_accounts.host.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./host_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message ibc.applications.interchain_accounts.host.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message ibc.applications.interchain_accounts.host.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: ibc.applications.interchain_accounts.host.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_cosmes.ts deleted file mode 100644 index cd4fb7f59..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/host/v1/tx.proto (package ibc.applications.interchain_accounts.host.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgModuleQuerySafe, MsgModuleQuerySafeResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.applications.interchain_accounts.host.v1.Msg"; - -/** - * UpdateParams defines a rpc handler for MsgUpdateParams. - * - * @generated from rpc ibc.applications.interchain_accounts.host.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * ModuleQuerySafe defines a rpc handler for MsgModuleQuerySafe. - * - * @generated from rpc ibc.applications.interchain_accounts.host.v1.Msg.ModuleQuerySafe - */ -export const MsgModuleQuerySafeService = { - typeName: TYPE_NAME, - method: "ModuleQuerySafe", - Request: MsgModuleQuerySafe, - Response: MsgModuleQuerySafeResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_pb.ts deleted file mode 100644 index c9014c60f..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/host/v1/tx_pb.ts +++ /dev/null @@ -1,191 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/host/v1/tx.proto (package ibc.applications.interchain_accounts.host.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params, QueryRequest } from "./host_pb.js"; - -/** - * MsgUpdateParams defines the payload for Msg/UpdateParams - * - * @generated from message ibc.applications.interchain_accounts.host.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * params defines the 27-interchain-accounts/host parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: ibc.applications.interchain_accounts.host.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response for Msg/UpdateParams - * - * @generated from message ibc.applications.interchain_accounts.host.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgModuleQuerySafe defines the payload for Msg/ModuleQuerySafe - * - * @generated from message ibc.applications.interchain_accounts.host.v1.MsgModuleQuerySafe - */ -export class MsgModuleQuerySafe extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * requests defines the module safe queries to execute. - * - * @generated from field: repeated ibc.applications.interchain_accounts.host.v1.QueryRequest requests = 2; - */ - requests: QueryRequest[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.MsgModuleQuerySafe"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "requests", kind: "message", T: QueryRequest, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgModuleQuerySafe { - return new MsgModuleQuerySafe().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgModuleQuerySafe { - return new MsgModuleQuerySafe().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgModuleQuerySafe { - return new MsgModuleQuerySafe().fromJsonString(jsonString, options); - } - - static equals(a: MsgModuleQuerySafe | PlainMessage | undefined, b: MsgModuleQuerySafe | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgModuleQuerySafe, a, b); - } -} - -/** - * MsgModuleQuerySafeResponse defines the response for Msg/ModuleQuerySafe - * - * @generated from message ibc.applications.interchain_accounts.host.v1.MsgModuleQuerySafeResponse - */ -export class MsgModuleQuerySafeResponse extends Message { - /** - * height at which the responses were queried - * - * @generated from field: uint64 height = 1; - */ - height = protoInt64.zero; - - /** - * protobuf encoded responses for each query - * - * @generated from field: repeated bytes responses = 2; - */ - responses: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.host.v1.MsgModuleQuerySafeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "responses", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgModuleQuerySafeResponse { - return new MsgModuleQuerySafeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgModuleQuerySafeResponse { - return new MsgModuleQuerySafeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgModuleQuerySafeResponse { - return new MsgModuleQuerySafeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgModuleQuerySafeResponse | PlainMessage | undefined, b: MsgModuleQuerySafeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgModuleQuerySafeResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/account_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/account_pb.ts deleted file mode 100644 index 02fc1a9ae..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/account_pb.ts +++ /dev/null @@ -1,54 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/v1/account.proto (package ibc.applications.interchain_accounts.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { BaseAccount } from "../../../../cosmos/auth/v1beta1/auth_pb.js"; - -/** - * An InterchainAccount is defined as a BaseAccount & the address of the account owner on the controller chain - * - * @generated from message ibc.applications.interchain_accounts.v1.InterchainAccount - */ -export class InterchainAccount extends Message { - /** - * @generated from field: cosmos.auth.v1beta1.BaseAccount base_account = 1; - */ - baseAccount?: BaseAccount; - - /** - * @generated from field: string account_owner = 2; - */ - accountOwner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.v1.InterchainAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_account", kind: "message", T: BaseAccount }, - { no: 2, name: "account_owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InterchainAccount { - return new InterchainAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InterchainAccount { - return new InterchainAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InterchainAccount { - return new InterchainAccount().fromJsonString(jsonString, options); - } - - static equals(a: InterchainAccount | PlainMessage | undefined, b: InterchainAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(InterchainAccount, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/metadata_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/metadata_pb.ts deleted file mode 100644 index 42873d695..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/metadata_pb.ts +++ /dev/null @@ -1,91 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/v1/metadata.proto (package ibc.applications.interchain_accounts.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Metadata defines a set of protocol specific data encoded into the ICS27 channel version bytestring - * See ICS004: https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#Versioning - * - * @generated from message ibc.applications.interchain_accounts.v1.Metadata - */ -export class Metadata extends Message { - /** - * version defines the ICS27 protocol version - * - * @generated from field: string version = 1; - */ - version = ""; - - /** - * controller_connection_id is the connection identifier associated with the controller chain - * - * @generated from field: string controller_connection_id = 2; - */ - controllerConnectionId = ""; - - /** - * host_connection_id is the connection identifier associated with the host chain - * - * @generated from field: string host_connection_id = 3; - */ - hostConnectionId = ""; - - /** - * address defines the interchain account address to be fulfilled upon the OnChanOpenTry handshake step - * NOTE: the address field is empty on the OnChanOpenInit handshake step - * - * @generated from field: string address = 4; - */ - address = ""; - - /** - * encoding defines the supported codec format - * - * @generated from field: string encoding = 5; - */ - encoding = ""; - - /** - * tx_type defines the type of transactions the interchain account can execute - * - * @generated from field: string tx_type = 6; - */ - txType = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.v1.Metadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "controller_connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "host_connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "encoding", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "tx_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Metadata { - return new Metadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Metadata { - return new Metadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Metadata { - return new Metadata().fromJsonString(jsonString, options); - } - - static equals(a: Metadata | PlainMessage | undefined, b: Metadata | PlainMessage | undefined): boolean { - return proto3.util.equals(Metadata, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/packet_pb.ts b/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/packet_pb.ts deleted file mode 100644 index 5a3ac63db..000000000 --- a/packages/es/src/protobufs/ibc/applications/interchain_accounts/v1/packet_pb.ts +++ /dev/null @@ -1,125 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/interchain_accounts/v1/packet.proto (package ibc.applications.interchain_accounts.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Type defines a classification of message issued from a controller chain to its associated interchain accounts - * host - * - * @generated from enum ibc.applications.interchain_accounts.v1.Type - */ -export enum Type { - /** - * Default zero value enumeration - * - * @generated from enum value: TYPE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * Execute a transaction on an interchain accounts host chain - * - * @generated from enum value: TYPE_EXECUTE_TX = 1; - */ - EXECUTE_TX = 1, -} -// Retrieve enum metadata with: proto3.getEnumType(Type) -proto3.util.setEnumType(Type, "ibc.applications.interchain_accounts.v1.Type", [ - { no: 0, name: "TYPE_UNSPECIFIED" }, - { no: 1, name: "TYPE_EXECUTE_TX" }, -]); - -/** - * InterchainAccountPacketData is comprised of a raw transaction, type of transaction and optional memo field. - * - * @generated from message ibc.applications.interchain_accounts.v1.InterchainAccountPacketData - */ -export class InterchainAccountPacketData extends Message { - /** - * @generated from field: ibc.applications.interchain_accounts.v1.Type type = 1; - */ - type = Type.UNSPECIFIED; - - /** - * @generated from field: bytes data = 2; - */ - data = new Uint8Array(0); - - /** - * @generated from field: string memo = 3; - */ - memo = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.v1.InterchainAccountPacketData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "type", kind: "enum", T: proto3.getEnumType(Type) }, - { no: 2, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "memo", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InterchainAccountPacketData { - return new InterchainAccountPacketData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InterchainAccountPacketData { - return new InterchainAccountPacketData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InterchainAccountPacketData { - return new InterchainAccountPacketData().fromJsonString(jsonString, options); - } - - static equals(a: InterchainAccountPacketData | PlainMessage | undefined, b: InterchainAccountPacketData | PlainMessage | undefined): boolean { - return proto3.util.equals(InterchainAccountPacketData, a, b); - } -} - -/** - * CosmosTx contains a list of sdk.Msg's. It should be used when sending transactions to an SDK host chain. - * - * @generated from message ibc.applications.interchain_accounts.v1.CosmosTx - */ -export class CosmosTx extends Message { - /** - * @generated from field: repeated google.protobuf.Any messages = 1; - */ - messages: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.interchain_accounts.v1.CosmosTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "messages", kind: "message", T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CosmosTx { - return new CosmosTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CosmosTx { - return new CosmosTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CosmosTx { - return new CosmosTx().fromJsonString(jsonString, options); - } - - static equals(a: CosmosTx | PlainMessage | undefined, b: CosmosTx | PlainMessage | undefined): boolean { - return proto3.util.equals(CosmosTx, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/packet_forward_middleware/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/applications/packet_forward_middleware/v1/genesis_pb.ts deleted file mode 100644 index dcdeaeb96..000000000 --- a/packages/es/src/protobufs/ibc/applications/packet_forward_middleware/v1/genesis_pb.ts +++ /dev/null @@ -1,158 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/packet_forward_middleware/v1/genesis.proto (package ibc.applications.packet_forward_middleware.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * GenesisState defines the packetforward genesis state - * - * @generated from message ibc.applications.packet_forward_middleware.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * key - information about forwarded packet: src_channel - * (parsedReceiver.Channel), src_port (parsedReceiver.Port), sequence value - - * information about original packet for refunding if necessary: retries, - * srcPacketSender, srcPacket.DestinationChannel, srcPacket.DestinationPort - * - * @generated from field: map in_flight_packets = 2; - */ - inFlightPackets: { [key: string]: InFlightPacket } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.packet_forward_middleware.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "in_flight_packets", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "message", T: InFlightPacket} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * InFlightPacket contains information about original packet for - * writing the acknowledgement and refunding if necessary. - * - * @generated from message ibc.applications.packet_forward_middleware.v1.InFlightPacket - */ -export class InFlightPacket extends Message { - /** - * @generated from field: string original_sender_address = 1; - */ - originalSenderAddress = ""; - - /** - * @generated from field: string refund_channel_id = 2; - */ - refundChannelId = ""; - - /** - * @generated from field: string refund_port_id = 3; - */ - refundPortId = ""; - - /** - * @generated from field: string packet_src_channel_id = 4; - */ - packetSrcChannelId = ""; - - /** - * @generated from field: string packet_src_port_id = 5; - */ - packetSrcPortId = ""; - - /** - * @generated from field: uint64 packet_timeout_timestamp = 6; - */ - packetTimeoutTimestamp = protoInt64.zero; - - /** - * @generated from field: string packet_timeout_height = 7; - */ - packetTimeoutHeight = ""; - - /** - * @generated from field: bytes packet_data = 8; - */ - packetData = new Uint8Array(0); - - /** - * @generated from field: uint64 refund_sequence = 9; - */ - refundSequence = protoInt64.zero; - - /** - * @generated from field: int32 retries_remaining = 10; - */ - retriesRemaining = 0; - - /** - * @generated from field: uint64 timeout = 11; - */ - timeout = protoInt64.zero; - - /** - * @generated from field: bool nonrefundable = 12; - */ - nonrefundable = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.packet_forward_middleware.v1.InFlightPacket"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "original_sender_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "refund_channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "refund_port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "packet_src_channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "packet_src_port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "packet_timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "packet_timeout_height", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "packet_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "refund_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 10, name: "retries_remaining", kind: "scalar", T: 5 /* ScalarType.INT32 */ }, - { no: 11, name: "timeout", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 12, name: "nonrefundable", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InFlightPacket { - return new InFlightPacket().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InFlightPacket { - return new InFlightPacket().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InFlightPacket { - return new InFlightPacket().fromJsonString(jsonString, options); - } - - static equals(a: InFlightPacket | PlainMessage | undefined, b: InFlightPacket | PlainMessage | undefined): boolean { - return proto3.util.equals(InFlightPacket, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/genesis_pb.ts deleted file mode 100644 index e98314eb4..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/genesis_pb.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/genesis.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { HourEpoch, RateLimit, WhitelistedAddressPair } from "./rate_limiting_pb.js"; - -/** - * GenesisState defines the ratelimit module's genesis state. - * - * @generated from message ibc.applications.rate_limiting.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.RateLimit rate_limits = 1; - */ - rateLimits: RateLimit[] = []; - - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.WhitelistedAddressPair whitelisted_address_pairs = 2; - */ - whitelistedAddressPairs: WhitelistedAddressPair[] = []; - - /** - * @generated from field: repeated string blacklisted_denoms = 3; - */ - blacklistedDenoms: string[] = []; - - /** - * @generated from field: repeated string pending_send_packet_sequence_numbers = 4; - */ - pendingSendPacketSequenceNumbers: string[] = []; - - /** - * @generated from field: ibc.applications.rate_limiting.v1.HourEpoch hour_epoch = 5; - */ - hourEpoch?: HourEpoch; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "rate_limits", kind: "message", T: RateLimit, repeated: true }, - { no: 2, name: "whitelisted_address_pairs", kind: "message", T: WhitelistedAddressPair, repeated: true }, - { no: 3, name: "blacklisted_denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "pending_send_packet_sequence_numbers", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "hour_epoch", kind: "message", T: HourEpoch }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_cosmes.ts deleted file mode 100644 index 7ce5c4d15..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_cosmes.ts +++ /dev/null @@ -1,83 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/query.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryAllBlacklistedDenomsRequest, QueryAllBlacklistedDenomsResponse, QueryAllRateLimitsRequest, QueryAllRateLimitsResponse, QueryAllWhitelistedAddressesRequest, QueryAllWhitelistedAddressesResponse, QueryRateLimitRequest, QueryRateLimitResponse, QueryRateLimitsByChainIDRequest, QueryRateLimitsByChainIDResponse, QueryRateLimitsByChannelOrClientIDRequest, QueryRateLimitsByChannelOrClientIDResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.applications.rate_limiting.v1.Query"; - -/** - * Queries all rate limits - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.AllRateLimits - */ -export const QueryAllRateLimitsService = { - typeName: TYPE_NAME, - method: "AllRateLimits", - Request: QueryAllRateLimitsRequest, - Response: QueryAllRateLimitsResponse, -} as const; - -/** - * Queries a specific rate limit by channel ID and denom - * Ex: - * - /ratelimit/{channel_or_client_id}/by_denom?denom={denom} - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.RateLimit - */ -export const QueryRateLimitService = { - typeName: TYPE_NAME, - method: "RateLimit", - Request: QueryRateLimitRequest, - Response: QueryRateLimitResponse, -} as const; - -/** - * Queries all the rate limits for a given chain - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.RateLimitsByChainID - */ -export const QueryRateLimitsByChainIDService = { - typeName: TYPE_NAME, - method: "RateLimitsByChainID", - Request: QueryRateLimitsByChainIDRequest, - Response: QueryRateLimitsByChainIDResponse, -} as const; - -/** - * Queries all the rate limits for a given channel ID - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.RateLimitsByChannelOrClientID - */ -export const QueryRateLimitsByChannelOrClientIDService = { - typeName: TYPE_NAME, - method: "RateLimitsByChannelOrClientID", - Request: QueryRateLimitsByChannelOrClientIDRequest, - Response: QueryRateLimitsByChannelOrClientIDResponse, -} as const; - -/** - * Queries all blacklisted denoms - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.AllBlacklistedDenoms - */ -export const QueryAllBlacklistedDenomsService = { - typeName: TYPE_NAME, - method: "AllBlacklistedDenoms", - Request: QueryAllBlacklistedDenomsRequest, - Response: QueryAllBlacklistedDenomsResponse, -} as const; - -/** - * Queries all whitelisted address pairs - * - * @generated from rpc ibc.applications.rate_limiting.v1.Query.AllWhitelistedAddresses - */ -export const QueryAllWhitelistedAddressesService = { - typeName: TYPE_NAME, - method: "AllWhitelistedAddresses", - Request: QueryAllWhitelistedAddressesRequest, - Response: QueryAllWhitelistedAddressesResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_pb.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_pb.ts deleted file mode 100644 index fe82cffed..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/query_pb.ts +++ /dev/null @@ -1,465 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/query.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { RateLimit, WhitelistedAddressPair } from "./rate_limiting_pb.js"; - -/** - * Queries all rate limits - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllRateLimitsRequest - */ -export class QueryAllRateLimitsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllRateLimitsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllRateLimitsRequest { - return new QueryAllRateLimitsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllRateLimitsRequest { - return new QueryAllRateLimitsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllRateLimitsRequest { - return new QueryAllRateLimitsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllRateLimitsRequest | PlainMessage | undefined, b: QueryAllRateLimitsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllRateLimitsRequest, a, b); - } -} - -/** - * QueryAllRateLimitsResponse returns all the rate limits stored on the chain. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllRateLimitsResponse - */ -export class QueryAllRateLimitsResponse extends Message { - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.RateLimit rate_limits = 1; - */ - rateLimits: RateLimit[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllRateLimitsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "rate_limits", kind: "message", T: RateLimit, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllRateLimitsResponse { - return new QueryAllRateLimitsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllRateLimitsResponse { - return new QueryAllRateLimitsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllRateLimitsResponse { - return new QueryAllRateLimitsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllRateLimitsResponse | PlainMessage | undefined, b: QueryAllRateLimitsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllRateLimitsResponse, a, b); - } -} - -/** - * Queries a specific rate limit by channel ID and denom - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitRequest - */ -export class QueryRateLimitRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: string channel_or_client_id = 2; - */ - channelOrClientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitRequest { - return new QueryRateLimitRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitRequest { - return new QueryRateLimitRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitRequest { - return new QueryRateLimitRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitRequest | PlainMessage | undefined, b: QueryRateLimitRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitRequest, a, b); - } -} - -/** - * QueryRateLimitResponse returns a rate limit by denom and channel_or_client_id combination. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitResponse - */ -export class QueryRateLimitResponse extends Message { - /** - * @generated from field: ibc.applications.rate_limiting.v1.RateLimit rate_limit = 1; - */ - rateLimit?: RateLimit; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "rate_limit", kind: "message", T: RateLimit }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitResponse { - return new QueryRateLimitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitResponse { - return new QueryRateLimitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitResponse { - return new QueryRateLimitResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitResponse | PlainMessage | undefined, b: QueryRateLimitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitResponse, a, b); - } -} - -/** - * Queries all the rate limits for a given chain - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitsByChainIDRequest - */ -export class QueryRateLimitsByChainIDRequest extends Message { - /** - * @generated from field: string chain_id = 1; - */ - chainId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitsByChainIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitsByChainIDRequest { - return new QueryRateLimitsByChainIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitsByChainIDRequest { - return new QueryRateLimitsByChainIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitsByChainIDRequest { - return new QueryRateLimitsByChainIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitsByChainIDRequest | PlainMessage | undefined, b: QueryRateLimitsByChainIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitsByChainIDRequest, a, b); - } -} - -/** - * QueryRateLimitsByChainIDResponse returns all rate-limits by a chain. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitsByChainIDResponse - */ -export class QueryRateLimitsByChainIDResponse extends Message { - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.RateLimit rate_limits = 1; - */ - rateLimits: RateLimit[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitsByChainIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "rate_limits", kind: "message", T: RateLimit, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitsByChainIDResponse { - return new QueryRateLimitsByChainIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitsByChainIDResponse { - return new QueryRateLimitsByChainIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitsByChainIDResponse { - return new QueryRateLimitsByChainIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitsByChainIDResponse | PlainMessage | undefined, b: QueryRateLimitsByChainIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitsByChainIDResponse, a, b); - } -} - -/** - * Queries all the rate limits for a given channel or client ID - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitsByChannelOrClientIDRequest - */ -export class QueryRateLimitsByChannelOrClientIDRequest extends Message { - /** - * @generated from field: string channel_or_client_id = 1; - */ - channelOrClientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitsByChannelOrClientIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitsByChannelOrClientIDRequest { - return new QueryRateLimitsByChannelOrClientIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitsByChannelOrClientIDRequest { - return new QueryRateLimitsByChannelOrClientIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitsByChannelOrClientIDRequest { - return new QueryRateLimitsByChannelOrClientIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitsByChannelOrClientIDRequest | PlainMessage | undefined, b: QueryRateLimitsByChannelOrClientIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitsByChannelOrClientIDRequest, a, b); - } -} - -/** - * QueryRateLimitsByChannelOrClientIDResponse returns all rate-limits by a channel or client id. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryRateLimitsByChannelOrClientIDResponse - */ -export class QueryRateLimitsByChannelOrClientIDResponse extends Message { - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.RateLimit rate_limits = 1; - */ - rateLimits: RateLimit[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryRateLimitsByChannelOrClientIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "rate_limits", kind: "message", T: RateLimit, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRateLimitsByChannelOrClientIDResponse { - return new QueryRateLimitsByChannelOrClientIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRateLimitsByChannelOrClientIDResponse { - return new QueryRateLimitsByChannelOrClientIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRateLimitsByChannelOrClientIDResponse { - return new QueryRateLimitsByChannelOrClientIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRateLimitsByChannelOrClientIDResponse | PlainMessage | undefined, b: QueryRateLimitsByChannelOrClientIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRateLimitsByChannelOrClientIDResponse, a, b); - } -} - -/** - * Queries all blacklisted denoms - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllBlacklistedDenomsRequest - */ -export class QueryAllBlacklistedDenomsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllBlacklistedDenomsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllBlacklistedDenomsRequest { - return new QueryAllBlacklistedDenomsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllBlacklistedDenomsRequest { - return new QueryAllBlacklistedDenomsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllBlacklistedDenomsRequest { - return new QueryAllBlacklistedDenomsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllBlacklistedDenomsRequest | PlainMessage | undefined, b: QueryAllBlacklistedDenomsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllBlacklistedDenomsRequest, a, b); - } -} - -/** - * QueryAllBlacklistedDenomsResponse returns all the blacklisted denosm. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllBlacklistedDenomsResponse - */ -export class QueryAllBlacklistedDenomsResponse extends Message { - /** - * @generated from field: repeated string denoms = 1; - */ - denoms: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllBlacklistedDenomsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllBlacklistedDenomsResponse { - return new QueryAllBlacklistedDenomsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllBlacklistedDenomsResponse { - return new QueryAllBlacklistedDenomsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllBlacklistedDenomsResponse { - return new QueryAllBlacklistedDenomsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllBlacklistedDenomsResponse | PlainMessage | undefined, b: QueryAllBlacklistedDenomsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllBlacklistedDenomsResponse, a, b); - } -} - -/** - * Queries all whitelisted address pairs - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllWhitelistedAddressesRequest - */ -export class QueryAllWhitelistedAddressesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllWhitelistedAddressesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllWhitelistedAddressesRequest { - return new QueryAllWhitelistedAddressesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllWhitelistedAddressesRequest { - return new QueryAllWhitelistedAddressesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllWhitelistedAddressesRequest { - return new QueryAllWhitelistedAddressesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllWhitelistedAddressesRequest | PlainMessage | undefined, b: QueryAllWhitelistedAddressesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllWhitelistedAddressesRequest, a, b); - } -} - -/** - * QueryAllWhitelistedAddressesResponse returns all whitelisted pairs. - * - * @generated from message ibc.applications.rate_limiting.v1.QueryAllWhitelistedAddressesResponse - */ -export class QueryAllWhitelistedAddressesResponse extends Message { - /** - * @generated from field: repeated ibc.applications.rate_limiting.v1.WhitelistedAddressPair address_pairs = 1; - */ - addressPairs: WhitelistedAddressPair[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.QueryAllWhitelistedAddressesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address_pairs", kind: "message", T: WhitelistedAddressPair, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllWhitelistedAddressesResponse { - return new QueryAllWhitelistedAddressesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllWhitelistedAddressesResponse { - return new QueryAllWhitelistedAddressesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllWhitelistedAddressesResponse { - return new QueryAllWhitelistedAddressesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllWhitelistedAddressesResponse | PlainMessage | undefined, b: QueryAllWhitelistedAddressesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllWhitelistedAddressesResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/rate_limiting_pb.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/rate_limiting_pb.ts deleted file mode 100644 index f1a5826a8..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/rate_limiting_pb.ts +++ /dev/null @@ -1,354 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/rate_limiting.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * PacketDirection defines whether the transfer packet is being sent from - * this chain or is being received on this chain - * - * @generated from enum ibc.applications.rate_limiting.v1.PacketDirection - */ -export enum PacketDirection { - /** - * @generated from enum value: PACKET_SEND = 0; - */ - PACKET_SEND = 0, - - /** - * @generated from enum value: PACKET_RECV = 1; - */ - PACKET_RECV = 1, -} -// Retrieve enum metadata with: proto3.getEnumType(PacketDirection) -proto3.util.setEnumType(PacketDirection, "ibc.applications.rate_limiting.v1.PacketDirection", [ - { no: 0, name: "PACKET_SEND" }, - { no: 1, name: "PACKET_RECV" }, -]); - -/** - * Path holds the denom and channelID that define the rate limited route - * - * @generated from message ibc.applications.rate_limiting.v1.Path - */ -export class Path extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: string channel_or_client_id = 2; - */ - channelOrClientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.Path"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Path { - return new Path().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Path { - return new Path().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Path { - return new Path().fromJsonString(jsonString, options); - } - - static equals(a: Path | PlainMessage | undefined, b: Path | PlainMessage | undefined): boolean { - return proto3.util.equals(Path, a, b); - } -} - -/** - * Quota defines the rate limit thresholds for transfer packets - * - * @generated from message ibc.applications.rate_limiting.v1.Quota - */ -export class Quota extends Message { - /** - * MaxPercentSend defines the threshold for outflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_send = 1; - */ - maxPercentSend = ""; - - /** - * MaxPercentSend defines the threshold for inflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_recv = 2; - */ - maxPercentRecv = ""; - - /** - * DurationHours specifies the number of hours before the rate limit - * is reset (e.g. 24 indicates that the rate limit is reset each day) - * - * @generated from field: uint64 duration_hours = 3; - */ - durationHours = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.Quota"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_percent_send", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "max_percent_recv", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "duration_hours", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Quota { - return new Quota().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Quota { - return new Quota().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Quota { - return new Quota().fromJsonString(jsonString, options); - } - - static equals(a: Quota | PlainMessage | undefined, b: Quota | PlainMessage | undefined): boolean { - return proto3.util.equals(Quota, a, b); - } -} - -/** - * Flow tracks all the inflows and outflows of a channel. - * - * @generated from message ibc.applications.rate_limiting.v1.Flow - */ -export class Flow extends Message { - /** - * Inflow defines the total amount of inbound transfers for the given - * rate limit in the current window - * - * @generated from field: string inflow = 1; - */ - inflow = ""; - - /** - * Outflow defines the total amount of outbound transfers for the given - * rate limit in the current window - * - * @generated from field: string outflow = 2; - */ - outflow = ""; - - /** - * ChannelValue stores the total supply of the denom at the start of - * the rate limit. This is used as the denominator when checking - * the rate limit threshold - * The ChannelValue is fixed for the duration of the rate limit window - * - * @generated from field: string channel_value = 3; - */ - channelValue = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.Flow"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "inflow", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "outflow", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_value", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Flow { - return new Flow().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Flow { - return new Flow().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Flow { - return new Flow().fromJsonString(jsonString, options); - } - - static equals(a: Flow | PlainMessage | undefined, b: Flow | PlainMessage | undefined): boolean { - return proto3.util.equals(Flow, a, b); - } -} - -/** - * RateLimit stores all the context about a given rate limit, including - * the relevant denom and channel, rate limit thresholds, and current - * progress towards the limits - * - * @generated from message ibc.applications.rate_limiting.v1.RateLimit - */ -export class RateLimit extends Message { - /** - * @generated from field: ibc.applications.rate_limiting.v1.Path path = 1; - */ - path?: Path; - - /** - * @generated from field: ibc.applications.rate_limiting.v1.Quota quota = 2; - */ - quota?: Quota; - - /** - * @generated from field: ibc.applications.rate_limiting.v1.Flow flow = 3; - */ - flow?: Flow; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.RateLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "message", T: Path }, - { no: 2, name: "quota", kind: "message", T: Quota }, - { no: 3, name: "flow", kind: "message", T: Flow }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RateLimit { - return new RateLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RateLimit { - return new RateLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RateLimit { - return new RateLimit().fromJsonString(jsonString, options); - } - - static equals(a: RateLimit | PlainMessage | undefined, b: RateLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(RateLimit, a, b); - } -} - -/** - * WhitelistedAddressPair represents a sender-receiver combo that is - * not subject to rate limit restrictions - * - * @generated from message ibc.applications.rate_limiting.v1.WhitelistedAddressPair - */ -export class WhitelistedAddressPair extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: string receiver = 2; - */ - receiver = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.WhitelistedAddressPair"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "receiver", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): WhitelistedAddressPair { - return new WhitelistedAddressPair().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): WhitelistedAddressPair { - return new WhitelistedAddressPair().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): WhitelistedAddressPair { - return new WhitelistedAddressPair().fromJsonString(jsonString, options); - } - - static equals(a: WhitelistedAddressPair | PlainMessage | undefined, b: WhitelistedAddressPair | PlainMessage | undefined): boolean { - return proto3.util.equals(WhitelistedAddressPair, a, b); - } -} - -/** - * HourEpoch is the epoch type. - * - * @generated from message ibc.applications.rate_limiting.v1.HourEpoch - */ -export class HourEpoch extends Message { - /** - * @generated from field: uint64 epoch_number = 1; - */ - epochNumber = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - /** - * @generated from field: google.protobuf.Timestamp epoch_start_time = 3; - */ - epochStartTime?: Timestamp; - - /** - * @generated from field: int64 epoch_start_height = 4; - */ - epochStartHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.HourEpoch"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epoch_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - { no: 3, name: "epoch_start_time", kind: "message", T: Timestamp }, - { no: 4, name: "epoch_start_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): HourEpoch { - return new HourEpoch().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): HourEpoch { - return new HourEpoch().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): HourEpoch { - return new HourEpoch().fromJsonString(jsonString, options); - } - - static equals(a: HourEpoch | PlainMessage | undefined, b: HourEpoch | PlainMessage | undefined): boolean { - return proto3.util.equals(HourEpoch, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_cosmes.ts deleted file mode 100644 index acad2caf8..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_cosmes.ts +++ /dev/null @@ -1,57 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/tx.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddRateLimit, MsgAddRateLimitResponse, MsgRemoveRateLimit, MsgRemoveRateLimitResponse, MsgResetRateLimit, MsgResetRateLimitResponse, MsgUpdateRateLimit, MsgUpdateRateLimitResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.applications.rate_limiting.v1.Msg"; - -/** - * Gov tx to add a new rate limit - * - * @generated from rpc ibc.applications.rate_limiting.v1.Msg.AddRateLimit - */ -export const MsgAddRateLimitService = { - typeName: TYPE_NAME, - method: "AddRateLimit", - Request: MsgAddRateLimit, - Response: MsgAddRateLimitResponse, -} as const; - -/** - * Gov tx to update an existing rate limit - * - * @generated from rpc ibc.applications.rate_limiting.v1.Msg.UpdateRateLimit - */ -export const MsgUpdateRateLimitService = { - typeName: TYPE_NAME, - method: "UpdateRateLimit", - Request: MsgUpdateRateLimit, - Response: MsgUpdateRateLimitResponse, -} as const; - -/** - * Gov tx to remove a rate limit - * - * @generated from rpc ibc.applications.rate_limiting.v1.Msg.RemoveRateLimit - */ -export const MsgRemoveRateLimitService = { - typeName: TYPE_NAME, - method: "RemoveRateLimit", - Request: MsgRemoveRateLimit, - Response: MsgRemoveRateLimitResponse, -} as const; - -/** - * Gov tx to reset the flow on a rate limit - * - * @generated from rpc ibc.applications.rate_limiting.v1.Msg.ResetRateLimit - */ -export const MsgResetRateLimitService = { - typeName: TYPE_NAME, - method: "ResetRateLimit", - Request: MsgResetRateLimit, - Response: MsgResetRateLimitResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_pb.ts deleted file mode 100644 index 5c0e02793..000000000 --- a/packages/es/src/protobufs/ibc/applications/rate_limiting/v1/tx_pb.ts +++ /dev/null @@ -1,426 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/rate_limiting/v1/tx.proto (package ibc.applications.rate_limiting.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Gov tx to add a new rate limit - * - * @generated from message ibc.applications.rate_limiting.v1.MsgAddRateLimit - */ -export class MsgAddRateLimit extends Message { - /** - * signer defines the x/gov module account address or other authority signing the message - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * Denom for the rate limit, as it appears on the rate limited chain - * When rate limiting a non-native token, this will be an ibc denom - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * ChannelId for the rate limit, on the side of the rate limited chain - * - * @generated from field: string channel_or_client_id = 3; - */ - channelOrClientId = ""; - - /** - * MaxPercentSend defines the threshold for outflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_send = 4; - */ - maxPercentSend = ""; - - /** - * MaxPercentSend defines the threshold for inflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_recv = 5; - */ - maxPercentRecv = ""; - - /** - * DurationHours specifies the number of hours before the rate limit - * is reset (e.g. 24 indicates that the rate limit is reset each day) - * - * @generated from field: uint64 duration_hours = 6; - */ - durationHours = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgAddRateLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "max_percent_send", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "max_percent_recv", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "duration_hours", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddRateLimit { - return new MsgAddRateLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddRateLimit { - return new MsgAddRateLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddRateLimit { - return new MsgAddRateLimit().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddRateLimit | PlainMessage | undefined, b: MsgAddRateLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddRateLimit, a, b); - } -} - -/** - * MsgAddRateLimitResponse is the return type for AddRateLimit function. - * - * @generated from message ibc.applications.rate_limiting.v1.MsgAddRateLimitResponse - */ -export class MsgAddRateLimitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgAddRateLimitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddRateLimitResponse { - return new MsgAddRateLimitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddRateLimitResponse { - return new MsgAddRateLimitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddRateLimitResponse { - return new MsgAddRateLimitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddRateLimitResponse | PlainMessage | undefined, b: MsgAddRateLimitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddRateLimitResponse, a, b); - } -} - -/** - * Gov tx to update an existing rate limit - * - * @generated from message ibc.applications.rate_limiting.v1.MsgUpdateRateLimit - */ -export class MsgUpdateRateLimit extends Message { - /** - * signer defines the x/gov module account address or other authority signing the message - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * Denom for the rate limit, as it appears on the rate limited chain - * When rate limiting a non-native token, this will be an ibc denom - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * ChannelId for the rate limit, on the side of the rate limited chain - * - * @generated from field: string channel_or_client_id = 3; - */ - channelOrClientId = ""; - - /** - * MaxPercentSend defines the threshold for outflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_send = 4; - */ - maxPercentSend = ""; - - /** - * MaxPercentSend defines the threshold for inflows - * The threshold is defined as a percentage (e.g. 10 indicates 10%) - * - * @generated from field: string max_percent_recv = 5; - */ - maxPercentRecv = ""; - - /** - * DurationHours specifies the number of hours before the rate limit - * is reset (e.g. 24 indicates that the rate limit is reset each day) - * - * @generated from field: uint64 duration_hours = 6; - */ - durationHours = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgUpdateRateLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "max_percent_send", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "max_percent_recv", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "duration_hours", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateRateLimit { - return new MsgUpdateRateLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateRateLimit { - return new MsgUpdateRateLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateRateLimit { - return new MsgUpdateRateLimit().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateRateLimit | PlainMessage | undefined, b: MsgUpdateRateLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateRateLimit, a, b); - } -} - -/** - * MsgUpdateRateLimitResponse is the return type for UpdateRateLimit. - * - * @generated from message ibc.applications.rate_limiting.v1.MsgUpdateRateLimitResponse - */ -export class MsgUpdateRateLimitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgUpdateRateLimitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateRateLimitResponse { - return new MsgUpdateRateLimitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateRateLimitResponse { - return new MsgUpdateRateLimitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateRateLimitResponse { - return new MsgUpdateRateLimitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateRateLimitResponse | PlainMessage | undefined, b: MsgUpdateRateLimitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateRateLimitResponse, a, b); - } -} - -/** - * Gov tx to remove a rate limit - * - * @generated from message ibc.applications.rate_limiting.v1.MsgRemoveRateLimit - */ -export class MsgRemoveRateLimit extends Message { - /** - * signer defines the x/gov module account address or other authority signing the message - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * Denom for the rate limit, as it appears on the rate limited chain - * When rate limiting a non-native token, this will be an ibc denom - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * ChannelId for the rate limit, on the side of the rate limited chain - * - * @generated from field: string channel_or_client_id = 3; - */ - channelOrClientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgRemoveRateLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveRateLimit { - return new MsgRemoveRateLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveRateLimit { - return new MsgRemoveRateLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveRateLimit { - return new MsgRemoveRateLimit().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveRateLimit | PlainMessage | undefined, b: MsgRemoveRateLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveRateLimit, a, b); - } -} - -/** - * MsgRemoveRateLimitResponse is the response type for RemoveRateLimit - * - * @generated from message ibc.applications.rate_limiting.v1.MsgRemoveRateLimitResponse - */ -export class MsgRemoveRateLimitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgRemoveRateLimitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveRateLimitResponse { - return new MsgRemoveRateLimitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveRateLimitResponse { - return new MsgRemoveRateLimitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveRateLimitResponse { - return new MsgRemoveRateLimitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveRateLimitResponse | PlainMessage | undefined, b: MsgRemoveRateLimitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveRateLimitResponse, a, b); - } -} - -/** - * Gov tx to reset the flow on a rate limit - * - * @generated from message ibc.applications.rate_limiting.v1.MsgResetRateLimit - */ -export class MsgResetRateLimit extends Message { - /** - * signer defines the x/gov module account address or other authority signing the message - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * Denom for the rate limit, as it appears on the rate limited chain - * When rate limiting a non-native token, this will be an ibc denom - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * ChannelId for the rate limit, on the side of the rate limited chain - * - * @generated from field: string channel_or_client_id = 3; - */ - channelOrClientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgResetRateLimit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel_or_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgResetRateLimit { - return new MsgResetRateLimit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgResetRateLimit { - return new MsgResetRateLimit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgResetRateLimit { - return new MsgResetRateLimit().fromJsonString(jsonString, options); - } - - static equals(a: MsgResetRateLimit | PlainMessage | undefined, b: MsgResetRateLimit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgResetRateLimit, a, b); - } -} - -/** - * MsgResetRateLimitResponse is the response type for ResetRateLimit. - * - * @generated from message ibc.applications.rate_limiting.v1.MsgResetRateLimitResponse - */ -export class MsgResetRateLimitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.rate_limiting.v1.MsgResetRateLimitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgResetRateLimitResponse { - return new MsgResetRateLimitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgResetRateLimitResponse { - return new MsgResetRateLimitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgResetRateLimitResponse { - return new MsgResetRateLimitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgResetRateLimitResponse | PlainMessage | undefined, b: MsgResetRateLimitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgResetRateLimitResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/authz_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/authz_pb.ts deleted file mode 100644 index 93c0cd56d..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/authz_pb.ts +++ /dev/null @@ -1,125 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/authz.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Allocation defines the spend limit for a particular port and channel - * - * @generated from message ibc.applications.transfer.v1.Allocation - */ -export class Allocation extends Message { - /** - * the port on which the packet will be sent - * - * @generated from field: string source_port = 1; - */ - sourcePort = ""; - - /** - * the channel by which the packet will be sent - * - * @generated from field: string source_channel = 2; - */ - sourceChannel = ""; - - /** - * spend limitation on the channel - * - * @generated from field: repeated cosmos.base.v1beta1.Coin spend_limit = 3; - */ - spendLimit: Coin[] = []; - - /** - * allow list of receivers, an empty allow list permits any receiver address - * - * @generated from field: repeated string allow_list = 4; - */ - allowList: string[] = []; - - /** - * allow list of memo strings, an empty list prohibits all memo strings; - * a list only with "*" permits any memo string - * - * @generated from field: repeated string allowed_packet_data = 5; - */ - allowedPacketData: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.Allocation"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "source_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "source_channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "spend_limit", kind: "message", T: Coin, repeated: true }, - { no: 4, name: "allow_list", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "allowed_packet_data", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Allocation { - return new Allocation().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Allocation { - return new Allocation().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Allocation { - return new Allocation().fromJsonString(jsonString, options); - } - - static equals(a: Allocation | PlainMessage | undefined, b: Allocation | PlainMessage | undefined): boolean { - return proto3.util.equals(Allocation, a, b); - } -} - -/** - * TransferAuthorization allows the grantee to spend up to spend_limit coins from - * the granter's account for ibc transfer on a specific channel - * - * @generated from message ibc.applications.transfer.v1.TransferAuthorization - */ -export class TransferAuthorization extends Message { - /** - * port and channel amounts - * - * @generated from field: repeated ibc.applications.transfer.v1.Allocation allocations = 1; - */ - allocations: Allocation[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.TransferAuthorization"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "allocations", kind: "message", T: Allocation, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TransferAuthorization { - return new TransferAuthorization().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TransferAuthorization { - return new TransferAuthorization().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TransferAuthorization { - return new TransferAuthorization().fromJsonString(jsonString, options); - } - - static equals(a: TransferAuthorization | PlainMessage | undefined, b: TransferAuthorization | PlainMessage | undefined): boolean { - return proto3.util.equals(TransferAuthorization, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/denomtrace_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/denomtrace_pb.ts deleted file mode 100644 index 6f3afc457..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/denomtrace_pb.ts +++ /dev/null @@ -1,60 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/denomtrace.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * DenomTrace contains the base denomination for ICS20 fungible tokens and the - * source tracing information path. - * - * @generated from message ibc.applications.transfer.v1.DenomTrace - * @deprecated - */ -export class DenomTrace extends Message { - /** - * path defines the chain of port/channel identifiers used for tracing the - * source of the fungible token. - * - * @generated from field: string path = 1; - */ - path = ""; - - /** - * base denomination of the relayed fungible token. - * - * @generated from field: string base_denom = 2; - */ - baseDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.DenomTrace"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "base_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DenomTrace { - return new DenomTrace().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DenomTrace { - return new DenomTrace().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DenomTrace { - return new DenomTrace().fromJsonString(jsonString, options); - } - - static equals(a: DenomTrace | PlainMessage | undefined, b: DenomTrace | PlainMessage | undefined): boolean { - return proto3.util.equals(DenomTrace, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/genesis_pb.ts deleted file mode 100644 index f9d163121..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/genesis_pb.ts +++ /dev/null @@ -1,71 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/genesis.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Denom } from "./token_pb.js"; -import { Params } from "./transfer_pb.js"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * GenesisState defines the ibc-transfer genesis state - * - * @generated from message ibc.applications.transfer.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: repeated ibc.applications.transfer.v1.Denom denoms = 2; - */ - denoms: Denom[] = []; - - /** - * @generated from field: ibc.applications.transfer.v1.Params params = 3; - */ - params?: Params; - - /** - * total_escrowed contains the total amount of tokens escrowed - * by the transfer module - * - * @generated from field: repeated cosmos.base.v1beta1.Coin total_escrowed = 4; - */ - totalEscrowed: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denoms", kind: "message", T: Denom, repeated: true }, - { no: 3, name: "params", kind: "message", T: Params }, - { no: 4, name: "total_escrowed", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/packet_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/packet_pb.ts deleted file mode 100644 index 23844a876..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/packet_pb.ts +++ /dev/null @@ -1,83 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/packet.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * FungibleTokenPacketData defines a struct for the packet payload - * See FungibleTokenPacketData spec: - * https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures - * - * @generated from message ibc.applications.transfer.v1.FungibleTokenPacketData - */ -export class FungibleTokenPacketData extends Message { - /** - * the token denomination to be transferred - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * the token amount to be transferred - * - * @generated from field: string amount = 2; - */ - amount = ""; - - /** - * the sender address - * - * @generated from field: string sender = 3; - */ - sender = ""; - - /** - * the recipient address on the destination chain - * - * @generated from field: string receiver = 4; - */ - receiver = ""; - - /** - * optional memo - * - * @generated from field: string memo = 5; - */ - memo = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.FungibleTokenPacketData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "receiver", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "memo", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FungibleTokenPacketData { - return new FungibleTokenPacketData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FungibleTokenPacketData { - return new FungibleTokenPacketData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FungibleTokenPacketData { - return new FungibleTokenPacketData().fromJsonString(jsonString, options); - } - - static equals(a: FungibleTokenPacketData | PlainMessage | undefined, b: FungibleTokenPacketData | PlainMessage | undefined): boolean { - return proto3.util.equals(FungibleTokenPacketData, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/query_cosmes.ts deleted file mode 100644 index c21e98d4a..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/query_cosmes.ts +++ /dev/null @@ -1,81 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/query.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryDenomHashRequest, QueryDenomHashResponse, QueryDenomRequest, QueryDenomResponse, QueryDenomsRequest, QueryDenomsResponse, QueryEscrowAddressRequest, QueryEscrowAddressResponse, QueryParamsRequest, QueryParamsResponse, QueryTotalEscrowForDenomRequest, QueryTotalEscrowForDenomResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.applications.transfer.v1.Query"; - -/** - * Params queries all parameters of the ibc-transfer module. - * - * @generated from rpc ibc.applications.transfer.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * Denoms queries all denominations - * - * @generated from rpc ibc.applications.transfer.v1.Query.Denoms - */ -export const QueryDenomsService = { - typeName: TYPE_NAME, - method: "Denoms", - Request: QueryDenomsRequest, - Response: QueryDenomsResponse, -} as const; - -/** - * Denom queries a denomination - * - * @generated from rpc ibc.applications.transfer.v1.Query.Denom - */ -export const QueryDenomService = { - typeName: TYPE_NAME, - method: "Denom", - Request: QueryDenomRequest, - Response: QueryDenomResponse, -} as const; - -/** - * DenomHash queries a denomination hash information. - * - * @generated from rpc ibc.applications.transfer.v1.Query.DenomHash - */ -export const QueryDenomHashService = { - typeName: TYPE_NAME, - method: "DenomHash", - Request: QueryDenomHashRequest, - Response: QueryDenomHashResponse, -} as const; - -/** - * EscrowAddress returns the escrow address for a particular port and channel id. - * - * @generated from rpc ibc.applications.transfer.v1.Query.EscrowAddress - */ -export const QueryEscrowAddressService = { - typeName: TYPE_NAME, - method: "EscrowAddress", - Request: QueryEscrowAddressRequest, - Response: QueryEscrowAddressResponse, -} as const; - -/** - * TotalEscrowForDenom returns the total amount of tokens in escrow based on the denom. - * - * @generated from rpc ibc.applications.transfer.v1.Query.TotalEscrowForDenom - */ -export const QueryTotalEscrowForDenomService = { - typeName: TYPE_NAME, - method: "TotalEscrowForDenom", - Request: QueryTotalEscrowForDenomRequest, - Response: QueryTotalEscrowForDenomResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/query_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/query_pb.ts deleted file mode 100644 index 848df5193..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/query_pb.ts +++ /dev/null @@ -1,514 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/query.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./transfer_pb.js"; -import { Denom } from "./token_pb.js"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: ibc.applications.transfer.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryDenomRequest is the request type for the Query/Denom RPC - * method - * - * @generated from message ibc.applications.transfer.v1.QueryDenomRequest - */ -export class QueryDenomRequest extends Message { - /** - * hash (in hex format) or denom (full denom with ibc prefix) of the on chain denomination. - * - * @generated from field: string hash = 1; - */ - hash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomRequest { - return new QueryDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomRequest { - return new QueryDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomRequest { - return new QueryDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomRequest | PlainMessage | undefined, b: QueryDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomRequest, a, b); - } -} - -/** - * QueryDenomResponse is the response type for the Query/Denom RPC - * method. - * - * @generated from message ibc.applications.transfer.v1.QueryDenomResponse - */ -export class QueryDenomResponse extends Message { - /** - * denom returns the requested denomination. - * - * @generated from field: ibc.applications.transfer.v1.Denom denom = 1; - */ - denom?: Denom; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "message", T: Denom }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomResponse { - return new QueryDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomResponse { - return new QueryDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomResponse { - return new QueryDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomResponse | PlainMessage | undefined, b: QueryDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomResponse, a, b); - } -} - -/** - * QueryDenomsRequest is the request type for the Query/Denoms RPC - * method - * - * @generated from message ibc.applications.transfer.v1.QueryDenomsRequest - */ -export class QueryDenomsRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomsRequest { - return new QueryDenomsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomsRequest { - return new QueryDenomsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomsRequest { - return new QueryDenomsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomsRequest | PlainMessage | undefined, b: QueryDenomsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomsRequest, a, b); - } -} - -/** - * QueryDenomsResponse is the response type for the Query/Denoms RPC - * method. - * - * @generated from message ibc.applications.transfer.v1.QueryDenomsResponse - */ -export class QueryDenomsResponse extends Message { - /** - * denoms returns all denominations. - * - * @generated from field: repeated ibc.applications.transfer.v1.Denom denoms = 1; - */ - denoms: Denom[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denoms", kind: "message", T: Denom, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomsResponse { - return new QueryDenomsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomsResponse { - return new QueryDenomsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomsResponse { - return new QueryDenomsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomsResponse | PlainMessage | undefined, b: QueryDenomsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomsResponse, a, b); - } -} - -/** - * QueryDenomHashRequest is the request type for the Query/DenomHash RPC - * method - * - * @generated from message ibc.applications.transfer.v1.QueryDenomHashRequest - */ -export class QueryDenomHashRequest extends Message { - /** - * The denomination trace ([port_id]/[channel_id])+/[denom] - * - * @generated from field: string trace = 1; - */ - trace = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomHashRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "trace", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomHashRequest { - return new QueryDenomHashRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomHashRequest { - return new QueryDenomHashRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomHashRequest { - return new QueryDenomHashRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomHashRequest | PlainMessage | undefined, b: QueryDenomHashRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomHashRequest, a, b); - } -} - -/** - * QueryDenomHashResponse is the response type for the Query/DenomHash RPC - * method. - * - * @generated from message ibc.applications.transfer.v1.QueryDenomHashResponse - */ -export class QueryDenomHashResponse extends Message { - /** - * hash (in hex format) of the denomination trace information. - * - * @generated from field: string hash = 1; - */ - hash = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryDenomHashResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomHashResponse { - return new QueryDenomHashResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomHashResponse { - return new QueryDenomHashResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomHashResponse { - return new QueryDenomHashResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomHashResponse | PlainMessage | undefined, b: QueryDenomHashResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomHashResponse, a, b); - } -} - -/** - * QueryEscrowAddressRequest is the request type for the EscrowAddress RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryEscrowAddressRequest - */ -export class QueryEscrowAddressRequest extends Message { - /** - * unique port identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * unique channel identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryEscrowAddressRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEscrowAddressRequest { - return new QueryEscrowAddressRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEscrowAddressRequest { - return new QueryEscrowAddressRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEscrowAddressRequest { - return new QueryEscrowAddressRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEscrowAddressRequest | PlainMessage | undefined, b: QueryEscrowAddressRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEscrowAddressRequest, a, b); - } -} - -/** - * QueryEscrowAddressResponse is the response type of the EscrowAddress RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryEscrowAddressResponse - */ -export class QueryEscrowAddressResponse extends Message { - /** - * the escrow account address - * - * @generated from field: string escrow_address = 1; - */ - escrowAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryEscrowAddressResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "escrow_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEscrowAddressResponse { - return new QueryEscrowAddressResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEscrowAddressResponse { - return new QueryEscrowAddressResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEscrowAddressResponse { - return new QueryEscrowAddressResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEscrowAddressResponse | PlainMessage | undefined, b: QueryEscrowAddressResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEscrowAddressResponse, a, b); - } -} - -/** - * QueryTotalEscrowForDenomRequest is the request type for TotalEscrowForDenom RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryTotalEscrowForDenomRequest - */ -export class QueryTotalEscrowForDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryTotalEscrowForDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalEscrowForDenomRequest { - return new QueryTotalEscrowForDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalEscrowForDenomRequest { - return new QueryTotalEscrowForDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalEscrowForDenomRequest { - return new QueryTotalEscrowForDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalEscrowForDenomRequest | PlainMessage | undefined, b: QueryTotalEscrowForDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalEscrowForDenomRequest, a, b); - } -} - -/** - * QueryTotalEscrowForDenomResponse is the response type for TotalEscrowForDenom RPC method. - * - * @generated from message ibc.applications.transfer.v1.QueryTotalEscrowForDenomResponse - */ -export class QueryTotalEscrowForDenomResponse extends Message { - /** - * @generated from field: cosmos.base.v1beta1.Coin amount = 1; - */ - amount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.QueryTotalEscrowForDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalEscrowForDenomResponse { - return new QueryTotalEscrowForDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalEscrowForDenomResponse { - return new QueryTotalEscrowForDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalEscrowForDenomResponse { - return new QueryTotalEscrowForDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalEscrowForDenomResponse | PlainMessage | undefined, b: QueryTotalEscrowForDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalEscrowForDenomResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/token_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/token_pb.ts deleted file mode 100644 index 438908fd3..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/token_pb.ts +++ /dev/null @@ -1,151 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/token.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Token defines a struct which represents a token to be transferred. - * - * @generated from message ibc.applications.transfer.v1.Token - */ -export class Token extends Message { - /** - * the token denomination - * - * @generated from field: ibc.applications.transfer.v1.Denom denom = 1; - */ - denom?: Denom; - - /** - * the token amount to be transferred - * - * @generated from field: string amount = 2; - */ - amount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.Token"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "message", T: Denom }, - { no: 2, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Token { - return new Token().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Token { - return new Token().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Token { - return new Token().fromJsonString(jsonString, options); - } - - static equals(a: Token | PlainMessage | undefined, b: Token | PlainMessage | undefined): boolean { - return proto3.util.equals(Token, a, b); - } -} - -/** - * Denom holds the base denom of a Token and a trace of the chains it was sent through. - * - * @generated from message ibc.applications.transfer.v1.Denom - */ -export class Denom extends Message { - /** - * the base token denomination - * - * @generated from field: string base = 1; - */ - base = ""; - - /** - * the trace of the token - * - * @generated from field: repeated ibc.applications.transfer.v1.Hop trace = 3; - */ - trace: Hop[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.Denom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "trace", kind: "message", T: Hop, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Denom { - return new Denom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Denom { - return new Denom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Denom { - return new Denom().fromJsonString(jsonString, options); - } - - static equals(a: Denom | PlainMessage | undefined, b: Denom | PlainMessage | undefined): boolean { - return proto3.util.equals(Denom, a, b); - } -} - -/** - * Hop defines a port ID, channel ID pair specifying a unique "hop" in a trace - * - * @generated from message ibc.applications.transfer.v1.Hop - */ -export class Hop extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.Hop"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Hop { - return new Hop().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Hop { - return new Hop().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Hop { - return new Hop().fromJsonString(jsonString, options); - } - - static equals(a: Hop | PlainMessage | undefined, b: Hop | PlainMessage | undefined): boolean { - return proto3.util.equals(Hop, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/transfer_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/transfer_pb.ts deleted file mode 100644 index 77bef6922..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/transfer_pb.ts +++ /dev/null @@ -1,62 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/transfer.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params defines the set of IBC transfer parameters. - * NOTE: To prevent a single token from being transferred, set the - * TransfersEnabled parameter to true and then set the bank module's SendEnabled - * parameter for the denomination to false. - * - * @generated from message ibc.applications.transfer.v1.Params - */ -export class Params extends Message { - /** - * send_enabled enables or disables all cross-chain token transfers from this - * chain. - * - * @generated from field: bool send_enabled = 1; - */ - sendEnabled = false; - - /** - * receive_enabled enables or disables all cross-chain token transfers to this - * chain. - * - * @generated from field: bool receive_enabled = 2; - */ - receiveEnabled = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "send_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "receive_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_cosmes.ts deleted file mode 100644 index d24c07660..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/tx.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgTransfer, MsgTransferResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.applications.transfer.v1.Msg"; - -/** - * Transfer defines a rpc handler method for MsgTransfer. - * - * @generated from rpc ibc.applications.transfer.v1.Msg.Transfer - */ -export const MsgTransferService = { - typeName: TYPE_NAME, - method: "Transfer", - Request: MsgTransfer, - Response: MsgTransferResponse, -} as const; - -/** - * UpdateParams defines a rpc handler for MsgUpdateParams. - * - * @generated from rpc ibc.applications.transfer.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_pb.ts deleted file mode 100644 index 5cd2a930c..000000000 --- a/packages/es/src/protobufs/ibc/applications/transfer/v1/tx_pb.ts +++ /dev/null @@ -1,261 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/applications/transfer/v1/tx.proto (package ibc.applications.transfer.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; -import { Height } from "../../../core/client/v1/client_pb.js"; -import { Params } from "./transfer_pb.js"; - -/** - * MsgTransfer defines a msg to transfer fungible tokens (i.e Coins) between - * ICS20 enabled chains. See ICS Spec here: - * https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures - * - * @generated from message ibc.applications.transfer.v1.MsgTransfer - */ -export class MsgTransfer extends Message { - /** - * the port on which the packet will be sent - * - * @generated from field: string source_port = 1; - */ - sourcePort = ""; - - /** - * the channel by which the packet will be sent - * - * @generated from field: string source_channel = 2; - */ - sourceChannel = ""; - - /** - * token to be transferred - * - * @generated from field: cosmos.base.v1beta1.Coin token = 3; - */ - token?: Coin; - - /** - * the sender address - * - * @generated from field: string sender = 4; - */ - sender = ""; - - /** - * the recipient address on the destination chain - * - * @generated from field: string receiver = 5; - */ - receiver = ""; - - /** - * Timeout height relative to the current block height. - * If you are sending with IBC v1 protocol, either timeout_height or timeout_timestamp must be set. - * If you are sending with IBC v2 protocol, timeout_timestamp must be set, and timeout_height must be omitted. - * - * @generated from field: ibc.core.client.v1.Height timeout_height = 6; - */ - timeoutHeight?: Height; - - /** - * Timeout timestamp in absolute nanoseconds since unix epoch. - * If you are sending with IBC v1 protocol, either timeout_height or timeout_timestamp must be set. - * If you are sending with IBC v2 protocol, timeout_timestamp must be set. - * - * @generated from field: uint64 timeout_timestamp = 7; - */ - timeoutTimestamp = protoInt64.zero; - - /** - * optional memo - * - * @generated from field: string memo = 8; - */ - memo = ""; - - /** - * optional encoding - * - * @generated from field: string encoding = 9; - */ - encoding = ""; - - /** - * boolean flag to indicate if the transfer message - * is sent with the IBC v2 protocol but uses v1 channel identifiers. - * In this case, the v1 channel identifiers function as aliases to the - * underlying client ids. - * This only needs to be set if the channel IDs - * are V1 channel identifiers. - * - * @generated from field: bool use_aliasing = 10; - */ - useAliasing = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.MsgTransfer"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "source_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "source_channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token", kind: "message", T: Coin }, - { no: 4, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "receiver", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "timeout_height", kind: "message", T: Height }, - { no: 7, name: "timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 8, name: "memo", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "encoding", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "use_aliasing", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTransfer { - return new MsgTransfer().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTransfer { - return new MsgTransfer().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTransfer { - return new MsgTransfer().fromJsonString(jsonString, options); - } - - static equals(a: MsgTransfer | PlainMessage | undefined, b: MsgTransfer | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTransfer, a, b); - } -} - -/** - * MsgTransferResponse defines the Msg/Transfer response type. - * - * @generated from message ibc.applications.transfer.v1.MsgTransferResponse - */ -export class MsgTransferResponse extends Message { - /** - * sequence number of the transfer packet sent - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.MsgTransferResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTransferResponse { - return new MsgTransferResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTransferResponse { - return new MsgTransferResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTransferResponse { - return new MsgTransferResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgTransferResponse | PlainMessage | undefined, b: MsgTransferResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTransferResponse, a, b); - } -} - -/** - * MsgUpdateParams is the Msg/UpdateParams request type. - * - * @generated from message ibc.applications.transfer.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * params defines the transfer parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: ibc.applications.transfer.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * @generated from message ibc.applications.transfer.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.applications.transfer.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/channel_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v1/channel_pb.ts deleted file mode 100644 index c8e1622dd..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/channel_pb.ts +++ /dev/null @@ -1,650 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/channel.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Height } from "../../client/v1/client_pb.js"; - -/** - * State defines if a channel is in one of the following states: - * CLOSED, INIT, TRYOPEN, OPEN, or UNINITIALIZED. - * - * @generated from enum ibc.core.channel.v1.State - */ -export enum State { - /** - * Default State - * - * @generated from enum value: STATE_UNINITIALIZED_UNSPECIFIED = 0; - */ - UNINITIALIZED_UNSPECIFIED = 0, - - /** - * A channel has just started the opening handshake. - * - * @generated from enum value: STATE_INIT = 1; - */ - INIT = 1, - - /** - * A channel has acknowledged the handshake step on the counterparty chain. - * - * @generated from enum value: STATE_TRYOPEN = 2; - */ - TRYOPEN = 2, - - /** - * A channel has completed the handshake. Open channels are - * ready to send and receive packets. - * - * @generated from enum value: STATE_OPEN = 3; - */ - OPEN = 3, - - /** - * A channel has been closed and can no longer be used to send or receive - * packets. - * - * @generated from enum value: STATE_CLOSED = 4; - */ - CLOSED = 4, -} -// Retrieve enum metadata with: proto3.getEnumType(State) -proto3.util.setEnumType(State, "ibc.core.channel.v1.State", [ - { no: 0, name: "STATE_UNINITIALIZED_UNSPECIFIED" }, - { no: 1, name: "STATE_INIT" }, - { no: 2, name: "STATE_TRYOPEN" }, - { no: 3, name: "STATE_OPEN" }, - { no: 4, name: "STATE_CLOSED" }, -]); - -/** - * Order defines if a channel is ORDERED or UNORDERED - * - * @generated from enum ibc.core.channel.v1.Order - */ -export enum Order { - /** - * zero-value for channel ordering - * - * @generated from enum value: ORDER_NONE_UNSPECIFIED = 0; - */ - NONE_UNSPECIFIED = 0, - - /** - * packets can be delivered in any order, which may differ from the order in - * which they were sent. - * - * @generated from enum value: ORDER_UNORDERED = 1; - */ - UNORDERED = 1, - - /** - * packets are delivered exactly in the order which they were sent - * - * @generated from enum value: ORDER_ORDERED = 2; - */ - ORDERED = 2, -} -// Retrieve enum metadata with: proto3.getEnumType(Order) -proto3.util.setEnumType(Order, "ibc.core.channel.v1.Order", [ - { no: 0, name: "ORDER_NONE_UNSPECIFIED" }, - { no: 1, name: "ORDER_UNORDERED" }, - { no: 2, name: "ORDER_ORDERED" }, -]); - -/** - * Channel defines pipeline for exactly-once packet delivery between specific - * modules on separate blockchains, which has at least one end capable of - * sending packets and one end capable of receiving packets. - * - * @generated from message ibc.core.channel.v1.Channel - */ -export class Channel extends Message { - /** - * current state of the channel end - * - * @generated from field: ibc.core.channel.v1.State state = 1; - */ - state = State.UNINITIALIZED_UNSPECIFIED; - - /** - * whether the channel is ordered or unordered - * - * @generated from field: ibc.core.channel.v1.Order ordering = 2; - */ - ordering = Order.NONE_UNSPECIFIED; - - /** - * counterparty channel end - * - * @generated from field: ibc.core.channel.v1.Counterparty counterparty = 3; - */ - counterparty?: Counterparty; - - /** - * list of connection identifiers, in order, along which packets sent on - * this channel will travel - * - * @generated from field: repeated string connection_hops = 4; - */ - connectionHops: string[] = []; - - /** - * opaque channel version, which is agreed upon during the handshake - * - * @generated from field: string version = 5; - */ - version = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.Channel"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "state", kind: "enum", T: proto3.getEnumType(State) }, - { no: 2, name: "ordering", kind: "enum", T: proto3.getEnumType(Order) }, - { no: 3, name: "counterparty", kind: "message", T: Counterparty }, - { no: 4, name: "connection_hops", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Channel { - return new Channel().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Channel { - return new Channel().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Channel { - return new Channel().fromJsonString(jsonString, options); - } - - static equals(a: Channel | PlainMessage | undefined, b: Channel | PlainMessage | undefined): boolean { - return proto3.util.equals(Channel, a, b); - } -} - -/** - * IdentifiedChannel defines a channel with additional port and channel - * identifier fields. - * - * @generated from message ibc.core.channel.v1.IdentifiedChannel - */ -export class IdentifiedChannel extends Message { - /** - * current state of the channel end - * - * @generated from field: ibc.core.channel.v1.State state = 1; - */ - state = State.UNINITIALIZED_UNSPECIFIED; - - /** - * whether the channel is ordered or unordered - * - * @generated from field: ibc.core.channel.v1.Order ordering = 2; - */ - ordering = Order.NONE_UNSPECIFIED; - - /** - * counterparty channel end - * - * @generated from field: ibc.core.channel.v1.Counterparty counterparty = 3; - */ - counterparty?: Counterparty; - - /** - * list of connection identifiers, in order, along which packets sent on - * this channel will travel - * - * @generated from field: repeated string connection_hops = 4; - */ - connectionHops: string[] = []; - - /** - * opaque channel version, which is agreed upon during the handshake - * - * @generated from field: string version = 5; - */ - version = ""; - - /** - * port identifier - * - * @generated from field: string port_id = 6; - */ - portId = ""; - - /** - * channel identifier - * - * @generated from field: string channel_id = 7; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.IdentifiedChannel"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "state", kind: "enum", T: proto3.getEnumType(State) }, - { no: 2, name: "ordering", kind: "enum", T: proto3.getEnumType(Order) }, - { no: 3, name: "counterparty", kind: "message", T: Counterparty }, - { no: 4, name: "connection_hops", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IdentifiedChannel { - return new IdentifiedChannel().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IdentifiedChannel { - return new IdentifiedChannel().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IdentifiedChannel { - return new IdentifiedChannel().fromJsonString(jsonString, options); - } - - static equals(a: IdentifiedChannel | PlainMessage | undefined, b: IdentifiedChannel | PlainMessage | undefined): boolean { - return proto3.util.equals(IdentifiedChannel, a, b); - } -} - -/** - * Counterparty defines a channel end counterparty - * - * @generated from message ibc.core.channel.v1.Counterparty - */ -export class Counterparty extends Message { - /** - * port on the counterparty chain which owns the other end of the channel. - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel end on the counterparty chain - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.Counterparty"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Counterparty { - return new Counterparty().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Counterparty { - return new Counterparty().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Counterparty { - return new Counterparty().fromJsonString(jsonString, options); - } - - static equals(a: Counterparty | PlainMessage | undefined, b: Counterparty | PlainMessage | undefined): boolean { - return proto3.util.equals(Counterparty, a, b); - } -} - -/** - * Packet defines a type that carries data across different chains through IBC - * - * @generated from message ibc.core.channel.v1.Packet - */ -export class Packet extends Message { - /** - * number corresponds to the order of sends and receives, where a Packet - * with an earlier sequence number must be sent and received before a Packet - * with a later sequence number. - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * identifies the port on the sending chain. - * - * @generated from field: string source_port = 2; - */ - sourcePort = ""; - - /** - * identifies the channel end on the sending chain. - * - * @generated from field: string source_channel = 3; - */ - sourceChannel = ""; - - /** - * identifies the port on the receiving chain. - * - * @generated from field: string destination_port = 4; - */ - destinationPort = ""; - - /** - * identifies the channel end on the receiving chain. - * - * @generated from field: string destination_channel = 5; - */ - destinationChannel = ""; - - /** - * actual opaque bytes transferred directly to the application module - * - * @generated from field: bytes data = 6; - */ - data = new Uint8Array(0); - - /** - * block height after which the packet times out - * - * @generated from field: ibc.core.client.v1.Height timeout_height = 7; - */ - timeoutHeight?: Height; - - /** - * block timestamp (in nanoseconds) after which the packet times out - * - * @generated from field: uint64 timeout_timestamp = 8; - */ - timeoutTimestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.Packet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "source_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "source_channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "destination_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "destination_channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "timeout_height", kind: "message", T: Height }, - { no: 8, name: "timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Packet { - return new Packet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Packet { - return new Packet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Packet { - return new Packet().fromJsonString(jsonString, options); - } - - static equals(a: Packet | PlainMessage | undefined, b: Packet | PlainMessage | undefined): boolean { - return proto3.util.equals(Packet, a, b); - } -} - -/** - * PacketState defines the generic type necessary to retrieve and store - * packet commitments, acknowledgements, and receipts. - * Caller is responsible for knowing the context necessary to interpret this - * state as a commitment, acknowledgement, or a receipt. - * - * @generated from message ibc.core.channel.v1.PacketState - */ -export class PacketState extends Message { - /** - * channel port identifier. - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier. - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * packet sequence. - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - /** - * embedded data that represents packet state. - * - * @generated from field: bytes data = 4; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.PacketState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketState { - return new PacketState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketState { - return new PacketState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketState { - return new PacketState().fromJsonString(jsonString, options); - } - - static equals(a: PacketState | PlainMessage | undefined, b: PacketState | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketState, a, b); - } -} - -/** - * PacketId is an identifier for a unique Packet - * Source chains refer to packets by source port/channel - * Destination chains refer to packets by destination port/channel - * - * @generated from message ibc.core.channel.v1.PacketId - */ -export class PacketId extends Message { - /** - * channel port identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.PacketId"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketId { - return new PacketId().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketId { - return new PacketId().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketId { - return new PacketId().fromJsonString(jsonString, options); - } - - static equals(a: PacketId | PlainMessage | undefined, b: PacketId | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketId, a, b); - } -} - -/** - * Acknowledgement is the recommended acknowledgement format to be used by - * app-specific protocols. - * NOTE: The field numbers 21 and 22 were explicitly chosen to avoid accidental - * conflicts with other protobuf message formats used for acknowledgements. - * The first byte of any message with this format will be the non-ASCII values - * `0xaa` (result) or `0xb2` (error). Implemented as defined by ICS: - * https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#acknowledgement-envelope - * - * @generated from message ibc.core.channel.v1.Acknowledgement - */ -export class Acknowledgement extends Message { - /** - * response contains either a result or an error and must be non-empty - * - * @generated from oneof ibc.core.channel.v1.Acknowledgement.response - */ - response: { - /** - * @generated from field: bytes result = 21; - */ - value: Uint8Array; - case: "result"; - } | { - /** - * @generated from field: string error = 22; - */ - value: string; - case: "error"; - } | { case: undefined; value?: undefined } = { case: undefined }; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.Acknowledgement"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 21, name: "result", kind: "scalar", T: 12 /* ScalarType.BYTES */, oneof: "response" }, - { no: 22, name: "error", kind: "scalar", T: 9 /* ScalarType.STRING */, oneof: "response" }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Acknowledgement { - return new Acknowledgement().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Acknowledgement { - return new Acknowledgement().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Acknowledgement { - return new Acknowledgement().fromJsonString(jsonString, options); - } - - static equals(a: Acknowledgement | PlainMessage | undefined, b: Acknowledgement | PlainMessage | undefined): boolean { - return proto3.util.equals(Acknowledgement, a, b); - } -} - -/** - * Timeout defines an execution deadline structure for 04-channel handlers. - * This includes packet lifecycle handlers. - * A valid Timeout contains either one or both of a timestamp and block height (sequence). - * - * @generated from message ibc.core.channel.v1.Timeout - */ -export class Timeout extends Message { - /** - * block height after which the packet times out - * - * @generated from field: ibc.core.client.v1.Height height = 1; - */ - height?: Height; - - /** - * block timestamp (in nanoseconds) after which the packet times out - * - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.Timeout"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "height", kind: "message", T: Height }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Timeout { - return new Timeout().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Timeout { - return new Timeout().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Timeout { - return new Timeout().fromJsonString(jsonString, options); - } - - static equals(a: Timeout | PlainMessage | undefined, b: Timeout | PlainMessage | undefined): boolean { - return proto3.util.equals(Timeout, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v1/genesis_pb.ts deleted file mode 100644 index f92262d41..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/genesis_pb.ts +++ /dev/null @@ -1,144 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/genesis.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { IdentifiedChannel, PacketState } from "./channel_pb.js"; - -/** - * GenesisState defines the ibc channel submodule's genesis state. - * - * @generated from message ibc.core.channel.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated ibc.core.channel.v1.IdentifiedChannel channels = 1; - */ - channels: IdentifiedChannel[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketState acknowledgements = 2; - */ - acknowledgements: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketState commitments = 3; - */ - commitments: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketState receipts = 4; - */ - receipts: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketSequence send_sequences = 5; - */ - sendSequences: PacketSequence[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketSequence recv_sequences = 6; - */ - recvSequences: PacketSequence[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v1.PacketSequence ack_sequences = 7; - */ - ackSequences: PacketSequence[] = []; - - /** - * the sequence for the next generated channel identifier - * - * @generated from field: uint64 next_channel_sequence = 8; - */ - nextChannelSequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channels", kind: "message", T: IdentifiedChannel, repeated: true }, - { no: 2, name: "acknowledgements", kind: "message", T: PacketState, repeated: true }, - { no: 3, name: "commitments", kind: "message", T: PacketState, repeated: true }, - { no: 4, name: "receipts", kind: "message", T: PacketState, repeated: true }, - { no: 5, name: "send_sequences", kind: "message", T: PacketSequence, repeated: true }, - { no: 6, name: "recv_sequences", kind: "message", T: PacketSequence, repeated: true }, - { no: 7, name: "ack_sequences", kind: "message", T: PacketSequence, repeated: true }, - { no: 8, name: "next_channel_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * PacketSequence defines the genesis type necessary to retrieve and store - * next send and receive sequences. - * - * @generated from message ibc.core.channel.v1.PacketSequence - */ -export class PacketSequence extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.PacketSequence"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketSequence { - return new PacketSequence().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketSequence { - return new PacketSequence().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketSequence { - return new PacketSequence().fromJsonString(jsonString, options); - } - - static equals(a: PacketSequence | PlainMessage | undefined, b: PacketSequence | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketSequence, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/core/channel/v1/query_cosmes.ts deleted file mode 100644 index e3b5f6752..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/query_cosmes.ts +++ /dev/null @@ -1,185 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/query.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryChannelClientStateRequest, QueryChannelClientStateResponse, QueryChannelConsensusStateRequest, QueryChannelConsensusStateResponse, QueryChannelRequest, QueryChannelResponse, QueryChannelsRequest, QueryChannelsResponse, QueryConnectionChannelsRequest, QueryConnectionChannelsResponse, QueryNextSequenceReceiveRequest, QueryNextSequenceReceiveResponse, QueryNextSequenceSendRequest, QueryNextSequenceSendResponse, QueryPacketAcknowledgementRequest, QueryPacketAcknowledgementResponse, QueryPacketAcknowledgementsRequest, QueryPacketAcknowledgementsResponse, QueryPacketCommitmentRequest, QueryPacketCommitmentResponse, QueryPacketCommitmentsRequest, QueryPacketCommitmentsResponse, QueryPacketReceiptRequest, QueryPacketReceiptResponse, QueryUnreceivedAcksRequest, QueryUnreceivedAcksResponse, QueryUnreceivedPacketsRequest, QueryUnreceivedPacketsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.core.channel.v1.Query"; - -/** - * Channel queries an IBC Channel. - * - * @generated from rpc ibc.core.channel.v1.Query.Channel - */ -export const QueryChannelService = { - typeName: TYPE_NAME, - method: "Channel", - Request: QueryChannelRequest, - Response: QueryChannelResponse, -} as const; - -/** - * Channels queries all the IBC channels of a chain. - * - * @generated from rpc ibc.core.channel.v1.Query.Channels - */ -export const QueryChannelsService = { - typeName: TYPE_NAME, - method: "Channels", - Request: QueryChannelsRequest, - Response: QueryChannelsResponse, -} as const; - -/** - * ConnectionChannels queries all the channels associated with a connection - * end. - * - * @generated from rpc ibc.core.channel.v1.Query.ConnectionChannels - */ -export const QueryConnectionChannelsService = { - typeName: TYPE_NAME, - method: "ConnectionChannels", - Request: QueryConnectionChannelsRequest, - Response: QueryConnectionChannelsResponse, -} as const; - -/** - * ChannelClientState queries for the client state for the channel associated - * with the provided channel identifiers. - * - * @generated from rpc ibc.core.channel.v1.Query.ChannelClientState - */ -export const QueryChannelClientStateService = { - typeName: TYPE_NAME, - method: "ChannelClientState", - Request: QueryChannelClientStateRequest, - Response: QueryChannelClientStateResponse, -} as const; - -/** - * ChannelConsensusState queries for the consensus state for the channel - * associated with the provided channel identifiers. - * - * @generated from rpc ibc.core.channel.v1.Query.ChannelConsensusState - */ -export const QueryChannelConsensusStateService = { - typeName: TYPE_NAME, - method: "ChannelConsensusState", - Request: QueryChannelConsensusStateRequest, - Response: QueryChannelConsensusStateResponse, -} as const; - -/** - * PacketCommitment queries a stored packet commitment hash. - * - * @generated from rpc ibc.core.channel.v1.Query.PacketCommitment - */ -export const QueryPacketCommitmentService = { - typeName: TYPE_NAME, - method: "PacketCommitment", - Request: QueryPacketCommitmentRequest, - Response: QueryPacketCommitmentResponse, -} as const; - -/** - * PacketCommitments returns all the packet commitments hashes associated - * with a channel. - * - * @generated from rpc ibc.core.channel.v1.Query.PacketCommitments - */ -export const QueryPacketCommitmentsService = { - typeName: TYPE_NAME, - method: "PacketCommitments", - Request: QueryPacketCommitmentsRequest, - Response: QueryPacketCommitmentsResponse, -} as const; - -/** - * PacketReceipt queries if a given packet sequence has been received on the - * queried chain - * - * @generated from rpc ibc.core.channel.v1.Query.PacketReceipt - */ -export const QueryPacketReceiptService = { - typeName: TYPE_NAME, - method: "PacketReceipt", - Request: QueryPacketReceiptRequest, - Response: QueryPacketReceiptResponse, -} as const; - -/** - * PacketAcknowledgement queries a stored packet acknowledgement hash. - * - * @generated from rpc ibc.core.channel.v1.Query.PacketAcknowledgement - */ -export const QueryPacketAcknowledgementService = { - typeName: TYPE_NAME, - method: "PacketAcknowledgement", - Request: QueryPacketAcknowledgementRequest, - Response: QueryPacketAcknowledgementResponse, -} as const; - -/** - * PacketAcknowledgements returns all the packet acknowledgements associated - * with a channel. - * - * @generated from rpc ibc.core.channel.v1.Query.PacketAcknowledgements - */ -export const QueryPacketAcknowledgementsService = { - typeName: TYPE_NAME, - method: "PacketAcknowledgements", - Request: QueryPacketAcknowledgementsRequest, - Response: QueryPacketAcknowledgementsResponse, -} as const; - -/** - * UnreceivedPackets returns all the unreceived IBC packets associated with a - * channel and sequences. - * - * @generated from rpc ibc.core.channel.v1.Query.UnreceivedPackets - */ -export const QueryUnreceivedPacketsService = { - typeName: TYPE_NAME, - method: "UnreceivedPackets", - Request: QueryUnreceivedPacketsRequest, - Response: QueryUnreceivedPacketsResponse, -} as const; - -/** - * UnreceivedAcks returns all the unreceived IBC acknowledgements associated - * with a channel and sequences. - * - * @generated from rpc ibc.core.channel.v1.Query.UnreceivedAcks - */ -export const QueryUnreceivedAcksService = { - typeName: TYPE_NAME, - method: "UnreceivedAcks", - Request: QueryUnreceivedAcksRequest, - Response: QueryUnreceivedAcksResponse, -} as const; - -/** - * NextSequenceReceive returns the next receive sequence for a given channel. - * - * @generated from rpc ibc.core.channel.v1.Query.NextSequenceReceive - */ -export const QueryNextSequenceReceiveService = { - typeName: TYPE_NAME, - method: "NextSequenceReceive", - Request: QueryNextSequenceReceiveRequest, - Response: QueryNextSequenceReceiveResponse, -} as const; - -/** - * NextSequenceSend returns the next send sequence for a given channel. - * - * @generated from rpc ibc.core.channel.v1.Query.NextSequenceSend - */ -export const QueryNextSequenceSendService = { - typeName: TYPE_NAME, - method: "NextSequenceSend", - Request: QueryNextSequenceSendRequest, - Response: QueryNextSequenceSendResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/query_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v1/query_pb.ts deleted file mode 100644 index 322dcdc6f..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/query_pb.ts +++ /dev/null @@ -1,1584 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/query.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Channel, IdentifiedChannel, PacketState } from "./channel_pb.js"; -import { Height, IdentifiedClientState } from "../../client/v1/client_pb.js"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; - -/** - * QueryChannelRequest is the request type for the Query/Channel RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelRequest - */ -export class QueryChannelRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelRequest { - return new QueryChannelRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelRequest { - return new QueryChannelRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelRequest { - return new QueryChannelRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelRequest | PlainMessage | undefined, b: QueryChannelRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelRequest, a, b); - } -} - -/** - * QueryChannelResponse is the response type for the Query/Channel RPC method. - * Besides the Channel end, it includes a proof and the height from which the - * proof was retrieved. - * - * @generated from message ibc.core.channel.v1.QueryChannelResponse - */ -export class QueryChannelResponse extends Message { - /** - * channel associated with the request identifiers - * - * @generated from field: ibc.core.channel.v1.Channel channel = 1; - */ - channel?: Channel; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channel", kind: "message", T: Channel }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelResponse { - return new QueryChannelResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelResponse { - return new QueryChannelResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelResponse { - return new QueryChannelResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelResponse | PlainMessage | undefined, b: QueryChannelResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelResponse, a, b); - } -} - -/** - * QueryChannelsRequest is the request type for the Query/Channels RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelsRequest - */ -export class QueryChannelsRequest extends Message { - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelsRequest { - return new QueryChannelsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelsRequest { - return new QueryChannelsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelsRequest { - return new QueryChannelsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelsRequest | PlainMessage | undefined, b: QueryChannelsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelsRequest, a, b); - } -} - -/** - * QueryChannelsResponse is the response type for the Query/Channels RPC method. - * - * @generated from message ibc.core.channel.v1.QueryChannelsResponse - */ -export class QueryChannelsResponse extends Message { - /** - * list of stored channels of the chain. - * - * @generated from field: repeated ibc.core.channel.v1.IdentifiedChannel channels = 1; - */ - channels: IdentifiedChannel[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channels", kind: "message", T: IdentifiedChannel, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelsResponse { - return new QueryChannelsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelsResponse { - return new QueryChannelsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelsResponse { - return new QueryChannelsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelsResponse | PlainMessage | undefined, b: QueryChannelsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelsResponse, a, b); - } -} - -/** - * QueryConnectionChannelsRequest is the request type for the - * Query/QueryConnectionChannels RPC method - * - * @generated from message ibc.core.channel.v1.QueryConnectionChannelsRequest - */ -export class QueryConnectionChannelsRequest extends Message { - /** - * connection unique identifier - * - * @generated from field: string connection = 1; - */ - connection = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryConnectionChannelsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionChannelsRequest { - return new QueryConnectionChannelsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionChannelsRequest { - return new QueryConnectionChannelsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionChannelsRequest { - return new QueryConnectionChannelsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionChannelsRequest | PlainMessage | undefined, b: QueryConnectionChannelsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionChannelsRequest, a, b); - } -} - -/** - * QueryConnectionChannelsResponse is the Response type for the - * Query/QueryConnectionChannels RPC method - * - * @generated from message ibc.core.channel.v1.QueryConnectionChannelsResponse - */ -export class QueryConnectionChannelsResponse extends Message { - /** - * list of channels associated with a connection. - * - * @generated from field: repeated ibc.core.channel.v1.IdentifiedChannel channels = 1; - */ - channels: IdentifiedChannel[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryConnectionChannelsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channels", kind: "message", T: IdentifiedChannel, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionChannelsResponse { - return new QueryConnectionChannelsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionChannelsResponse { - return new QueryConnectionChannelsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionChannelsResponse { - return new QueryConnectionChannelsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionChannelsResponse | PlainMessage | undefined, b: QueryConnectionChannelsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionChannelsResponse, a, b); - } -} - -/** - * QueryChannelClientStateRequest is the request type for the Query/ClientState - * RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelClientStateRequest - */ -export class QueryChannelClientStateRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelClientStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelClientStateRequest { - return new QueryChannelClientStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelClientStateRequest { - return new QueryChannelClientStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelClientStateRequest { - return new QueryChannelClientStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelClientStateRequest | PlainMessage | undefined, b: QueryChannelClientStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelClientStateRequest, a, b); - } -} - -/** - * QueryChannelClientStateResponse is the Response type for the - * Query/QueryChannelClientState RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelClientStateResponse - */ -export class QueryChannelClientStateResponse extends Message { - /** - * client state associated with the channel - * - * @generated from field: ibc.core.client.v1.IdentifiedClientState identified_client_state = 1; - */ - identifiedClientState?: IdentifiedClientState; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelClientStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "identified_client_state", kind: "message", T: IdentifiedClientState }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelClientStateResponse { - return new QueryChannelClientStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelClientStateResponse { - return new QueryChannelClientStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelClientStateResponse { - return new QueryChannelClientStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelClientStateResponse | PlainMessage | undefined, b: QueryChannelClientStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelClientStateResponse, a, b); - } -} - -/** - * QueryChannelConsensusStateRequest is the request type for the - * Query/ConsensusState RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelConsensusStateRequest - */ -export class QueryChannelConsensusStateRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * revision number of the consensus state - * - * @generated from field: uint64 revision_number = 3; - */ - revisionNumber = protoInt64.zero; - - /** - * revision height of the consensus state - * - * @generated from field: uint64 revision_height = 4; - */ - revisionHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelConsensusStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "revision_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "revision_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelConsensusStateRequest { - return new QueryChannelConsensusStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelConsensusStateRequest { - return new QueryChannelConsensusStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelConsensusStateRequest { - return new QueryChannelConsensusStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelConsensusStateRequest | PlainMessage | undefined, b: QueryChannelConsensusStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelConsensusStateRequest, a, b); - } -} - -/** - * QueryChannelClientStateResponse is the Response type for the - * Query/QueryChannelClientState RPC method - * - * @generated from message ibc.core.channel.v1.QueryChannelConsensusStateResponse - */ -export class QueryChannelConsensusStateResponse extends Message { - /** - * consensus state associated with the channel - * - * @generated from field: google.protobuf.Any consensus_state = 1; - */ - consensusState?: Any; - - /** - * client ID associated with the consensus state - * - * @generated from field: string client_id = 2; - */ - clientId = ""; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 3; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryChannelConsensusStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "consensus_state", kind: "message", T: Any }, - { no: 2, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChannelConsensusStateResponse { - return new QueryChannelConsensusStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChannelConsensusStateResponse { - return new QueryChannelConsensusStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChannelConsensusStateResponse { - return new QueryChannelConsensusStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryChannelConsensusStateResponse | PlainMessage | undefined, b: QueryChannelConsensusStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChannelConsensusStateResponse, a, b); - } -} - -/** - * QueryPacketCommitmentRequest is the request type for the - * Query/PacketCommitment RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketCommitmentRequest - */ -export class QueryPacketCommitmentRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketCommitmentRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentRequest | PlainMessage | undefined, b: QueryPacketCommitmentRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentRequest, a, b); - } -} - -/** - * QueryPacketCommitmentResponse defines the client query response for a packet - * which also includes a proof and the height from which the proof was - * retrieved - * - * @generated from message ibc.core.channel.v1.QueryPacketCommitmentResponse - */ -export class QueryPacketCommitmentResponse extends Message { - /** - * packet associated with the request fields - * - * @generated from field: bytes commitment = 1; - */ - commitment = new Uint8Array(0); - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketCommitmentResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "commitment", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentResponse | PlainMessage | undefined, b: QueryPacketCommitmentResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentResponse, a, b); - } -} - -/** - * QueryPacketCommitmentsRequest is the request type for the - * Query/QueryPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketCommitmentsRequest - */ -export class QueryPacketCommitmentsRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketCommitmentsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentsRequest | PlainMessage | undefined, b: QueryPacketCommitmentsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentsRequest, a, b); - } -} - -/** - * QueryPacketCommitmentsResponse is the request type for the - * Query/QueryPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketCommitmentsResponse - */ -export class QueryPacketCommitmentsResponse extends Message { - /** - * @generated from field: repeated ibc.core.channel.v1.PacketState commitments = 1; - */ - commitments: PacketState[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketCommitmentsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "commitments", kind: "message", T: PacketState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentsResponse | PlainMessage | undefined, b: QueryPacketCommitmentsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentsResponse, a, b); - } -} - -/** - * QueryPacketReceiptRequest is the request type for the - * Query/PacketReceipt RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketReceiptRequest - */ -export class QueryPacketReceiptRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketReceiptRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketReceiptRequest | PlainMessage | undefined, b: QueryPacketReceiptRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketReceiptRequest, a, b); - } -} - -/** - * QueryPacketReceiptResponse defines the client query response for a packet - * receipt which also includes a proof, and the height from which the proof was - * retrieved - * - * @generated from message ibc.core.channel.v1.QueryPacketReceiptResponse - */ -export class QueryPacketReceiptResponse extends Message { - /** - * success flag for if receipt exists - * - * @generated from field: bool received = 2; - */ - received = false; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 3; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketReceiptResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "received", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketReceiptResponse | PlainMessage | undefined, b: QueryPacketReceiptResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketReceiptResponse, a, b); - } -} - -/** - * QueryPacketAcknowledgementRequest is the request type for the - * Query/PacketAcknowledgement RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketAcknowledgementRequest - */ -export class QueryPacketAcknowledgementRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 3; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketAcknowledgementRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementRequest | PlainMessage | undefined, b: QueryPacketAcknowledgementRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementRequest, a, b); - } -} - -/** - * QueryPacketAcknowledgementResponse defines the client query response for a - * packet which also includes a proof and the height from which the - * proof was retrieved - * - * @generated from message ibc.core.channel.v1.QueryPacketAcknowledgementResponse - */ -export class QueryPacketAcknowledgementResponse extends Message { - /** - * packet associated with the request fields - * - * @generated from field: bytes acknowledgement = 1; - */ - acknowledgement = new Uint8Array(0); - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketAcknowledgementResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "acknowledgement", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementResponse | PlainMessage | undefined, b: QueryPacketAcknowledgementResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementResponse, a, b); - } -} - -/** - * QueryPacketAcknowledgementsRequest is the request type for the - * Query/QueryPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketAcknowledgementsRequest - */ -export class QueryPacketAcknowledgementsRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - /** - * list of packet sequences - * - * @generated from field: repeated uint64 packet_commitment_sequences = 4; - */ - packetCommitmentSequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketAcknowledgementsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - { no: 4, name: "packet_commitment_sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementsRequest | PlainMessage | undefined, b: QueryPacketAcknowledgementsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementsRequest, a, b); - } -} - -/** - * QueryPacketAcknowledgemetsResponse is the request type for the - * Query/QueryPacketAcknowledgements RPC method - * - * @generated from message ibc.core.channel.v1.QueryPacketAcknowledgementsResponse - */ -export class QueryPacketAcknowledgementsResponse extends Message { - /** - * @generated from field: repeated ibc.core.channel.v1.PacketState acknowledgements = 1; - */ - acknowledgements: PacketState[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryPacketAcknowledgementsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "acknowledgements", kind: "message", T: PacketState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementsResponse | PlainMessage | undefined, b: QueryPacketAcknowledgementsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementsResponse, a, b); - } -} - -/** - * QueryUnreceivedPacketsRequest is the request type for the - * Query/UnreceivedPackets RPC method - * - * @generated from message ibc.core.channel.v1.QueryUnreceivedPacketsRequest - */ -export class QueryUnreceivedPacketsRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * list of packet sequences - * - * @generated from field: repeated uint64 packet_commitment_sequences = 3; - */ - packetCommitmentSequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryUnreceivedPacketsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "packet_commitment_sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedPacketsRequest | PlainMessage | undefined, b: QueryUnreceivedPacketsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedPacketsRequest, a, b); - } -} - -/** - * QueryUnreceivedPacketsResponse is the response type for the - * Query/UnreceivedPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v1.QueryUnreceivedPacketsResponse - */ -export class QueryUnreceivedPacketsResponse extends Message { - /** - * list of unreceived packet sequences - * - * @generated from field: repeated uint64 sequences = 1; - */ - sequences: bigint[] = []; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 2; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryUnreceivedPacketsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedPacketsResponse | PlainMessage | undefined, b: QueryUnreceivedPacketsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedPacketsResponse, a, b); - } -} - -/** - * QueryUnreceivedAcks is the request type for the - * Query/UnreceivedAcks RPC method - * - * @generated from message ibc.core.channel.v1.QueryUnreceivedAcksRequest - */ -export class QueryUnreceivedAcksRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * list of acknowledgement sequences - * - * @generated from field: repeated uint64 packet_ack_sequences = 3; - */ - packetAckSequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryUnreceivedAcksRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "packet_ack_sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedAcksRequest | PlainMessage | undefined, b: QueryUnreceivedAcksRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedAcksRequest, a, b); - } -} - -/** - * QueryUnreceivedAcksResponse is the response type for the - * Query/UnreceivedAcks RPC method - * - * @generated from message ibc.core.channel.v1.QueryUnreceivedAcksResponse - */ -export class QueryUnreceivedAcksResponse extends Message { - /** - * list of unreceived acknowledgement sequences - * - * @generated from field: repeated uint64 sequences = 1; - */ - sequences: bigint[] = []; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 2; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryUnreceivedAcksResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedAcksResponse | PlainMessage | undefined, b: QueryUnreceivedAcksResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedAcksResponse, a, b); - } -} - -/** - * QueryNextSequenceReceiveRequest is the request type for the - * Query/QueryNextSequenceReceiveRequest RPC method - * - * @generated from message ibc.core.channel.v1.QueryNextSequenceReceiveRequest - */ -export class QueryNextSequenceReceiveRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryNextSequenceReceiveRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceReceiveRequest { - return new QueryNextSequenceReceiveRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceReceiveRequest { - return new QueryNextSequenceReceiveRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceReceiveRequest { - return new QueryNextSequenceReceiveRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceReceiveRequest | PlainMessage | undefined, b: QueryNextSequenceReceiveRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceReceiveRequest, a, b); - } -} - -/** - * QuerySequenceResponse is the response type for the - * Query/QueryNextSequenceReceiveResponse RPC method - * - * @generated from message ibc.core.channel.v1.QueryNextSequenceReceiveResponse - */ -export class QueryNextSequenceReceiveResponse extends Message { - /** - * next sequence receive number - * - * @generated from field: uint64 next_sequence_receive = 1; - */ - nextSequenceReceive = protoInt64.zero; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryNextSequenceReceiveResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "next_sequence_receive", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceReceiveResponse { - return new QueryNextSequenceReceiveResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceReceiveResponse { - return new QueryNextSequenceReceiveResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceReceiveResponse { - return new QueryNextSequenceReceiveResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceReceiveResponse | PlainMessage | undefined, b: QueryNextSequenceReceiveResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceReceiveResponse, a, b); - } -} - -/** - * QueryNextSequenceSendRequest is the request type for the - * Query/QueryNextSequenceSend RPC method - * - * @generated from message ibc.core.channel.v1.QueryNextSequenceSendRequest - */ -export class QueryNextSequenceSendRequest extends Message { - /** - * port unique identifier - * - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * channel unique identifier - * - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryNextSequenceSendRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceSendRequest | PlainMessage | undefined, b: QueryNextSequenceSendRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceSendRequest, a, b); - } -} - -/** - * QueryNextSequenceSendResponse is the request type for the - * Query/QueryNextSequenceSend RPC method - * - * @generated from message ibc.core.channel.v1.QueryNextSequenceSendResponse - */ -export class QueryNextSequenceSendResponse extends Message { - /** - * next sequence send number - * - * @generated from field: uint64 next_sequence_send = 1; - */ - nextSequenceSend = protoInt64.zero; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.QueryNextSequenceSendResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "next_sequence_send", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceSendResponse | PlainMessage | undefined, b: QueryNextSequenceSendResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceSendResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/core/channel/v1/tx_cosmes.ts deleted file mode 100644 index ab1ebf9c8..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/tx_cosmes.ts +++ /dev/null @@ -1,130 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/tx.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAcknowledgement, MsgAcknowledgementResponse, MsgChannelCloseConfirm, MsgChannelCloseConfirmResponse, MsgChannelCloseInit, MsgChannelCloseInitResponse, MsgChannelOpenAck, MsgChannelOpenAckResponse, MsgChannelOpenConfirm, MsgChannelOpenConfirmResponse, MsgChannelOpenInit, MsgChannelOpenInitResponse, MsgChannelOpenTry, MsgChannelOpenTryResponse, MsgRecvPacket, MsgRecvPacketResponse, MsgTimeout, MsgTimeoutOnClose, MsgTimeoutOnCloseResponse, MsgTimeoutResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.core.channel.v1.Msg"; - -/** - * ChannelOpenInit defines a rpc handler method for MsgChannelOpenInit. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelOpenInit - */ -export const MsgChannelOpenInitService = { - typeName: TYPE_NAME, - method: "ChannelOpenInit", - Request: MsgChannelOpenInit, - Response: MsgChannelOpenInitResponse, -} as const; - -/** - * ChannelOpenTry defines a rpc handler method for MsgChannelOpenTry. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelOpenTry - */ -export const MsgChannelOpenTryService = { - typeName: TYPE_NAME, - method: "ChannelOpenTry", - Request: MsgChannelOpenTry, - Response: MsgChannelOpenTryResponse, -} as const; - -/** - * ChannelOpenAck defines a rpc handler method for MsgChannelOpenAck. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelOpenAck - */ -export const MsgChannelOpenAckService = { - typeName: TYPE_NAME, - method: "ChannelOpenAck", - Request: MsgChannelOpenAck, - Response: MsgChannelOpenAckResponse, -} as const; - -/** - * ChannelOpenConfirm defines a rpc handler method for MsgChannelOpenConfirm. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelOpenConfirm - */ -export const MsgChannelOpenConfirmService = { - typeName: TYPE_NAME, - method: "ChannelOpenConfirm", - Request: MsgChannelOpenConfirm, - Response: MsgChannelOpenConfirmResponse, -} as const; - -/** - * ChannelCloseInit defines a rpc handler method for MsgChannelCloseInit. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelCloseInit - */ -export const MsgChannelCloseInitService = { - typeName: TYPE_NAME, - method: "ChannelCloseInit", - Request: MsgChannelCloseInit, - Response: MsgChannelCloseInitResponse, -} as const; - -/** - * ChannelCloseConfirm defines a rpc handler method for - * MsgChannelCloseConfirm. - * - * @generated from rpc ibc.core.channel.v1.Msg.ChannelCloseConfirm - */ -export const MsgChannelCloseConfirmService = { - typeName: TYPE_NAME, - method: "ChannelCloseConfirm", - Request: MsgChannelCloseConfirm, - Response: MsgChannelCloseConfirmResponse, -} as const; - -/** - * RecvPacket defines a rpc handler method for MsgRecvPacket. - * - * @generated from rpc ibc.core.channel.v1.Msg.RecvPacket - */ -export const MsgRecvPacketService = { - typeName: TYPE_NAME, - method: "RecvPacket", - Request: MsgRecvPacket, - Response: MsgRecvPacketResponse, -} as const; - -/** - * Timeout defines a rpc handler method for MsgTimeout. - * - * @generated from rpc ibc.core.channel.v1.Msg.Timeout - */ -export const MsgTimeoutService = { - typeName: TYPE_NAME, - method: "Timeout", - Request: MsgTimeout, - Response: MsgTimeoutResponse, -} as const; - -/** - * TimeoutOnClose defines a rpc handler method for MsgTimeoutOnClose. - * - * @generated from rpc ibc.core.channel.v1.Msg.TimeoutOnClose - */ -export const MsgTimeoutOnCloseService = { - typeName: TYPE_NAME, - method: "TimeoutOnClose", - Request: MsgTimeoutOnClose, - Response: MsgTimeoutOnCloseResponse, -} as const; - -/** - * Acknowledgement defines a rpc handler method for MsgAcknowledgement. - * - * @generated from rpc ibc.core.channel.v1.Msg.Acknowledgement - */ -export const MsgAcknowledgementService = { - typeName: TYPE_NAME, - method: "Acknowledgement", - Request: MsgAcknowledgement, - Response: MsgAcknowledgementResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/channel/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v1/tx_pb.ts deleted file mode 100644 index e4402a861..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v1/tx_pb.ts +++ /dev/null @@ -1,1074 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v1/tx.proto (package ibc.core.channel.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Channel, Packet } from "./channel_pb.js"; -import { Height } from "../../client/v1/client_pb.js"; - -/** - * ResponseResultType defines the possible outcomes of the execution of a message - * - * @generated from enum ibc.core.channel.v1.ResponseResultType - */ -export enum ResponseResultType { - /** - * Default zero value enumeration - * - * @generated from enum value: RESPONSE_RESULT_TYPE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * The message did not call the IBC application callbacks (because, for example, the packet had already been relayed) - * - * @generated from enum value: RESPONSE_RESULT_TYPE_NOOP = 1; - */ - NOOP = 1, - - /** - * The message was executed successfully - * - * @generated from enum value: RESPONSE_RESULT_TYPE_SUCCESS = 2; - */ - SUCCESS = 2, - - /** - * The message was executed unsuccessfully - * - * @generated from enum value: RESPONSE_RESULT_TYPE_FAILURE = 3; - */ - FAILURE = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(ResponseResultType) -proto3.util.setEnumType(ResponseResultType, "ibc.core.channel.v1.ResponseResultType", [ - { no: 0, name: "RESPONSE_RESULT_TYPE_UNSPECIFIED" }, - { no: 1, name: "RESPONSE_RESULT_TYPE_NOOP" }, - { no: 2, name: "RESPONSE_RESULT_TYPE_SUCCESS" }, - { no: 3, name: "RESPONSE_RESULT_TYPE_FAILURE" }, -]); - -/** - * MsgChannelOpenInit defines an sdk.Msg to initialize a channel handshake. It - * is called by a relayer on Chain A. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenInit - */ -export class MsgChannelOpenInit extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: ibc.core.channel.v1.Channel channel = 2; - */ - channel?: Channel; - - /** - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenInit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel", kind: "message", T: Channel }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenInit { - return new MsgChannelOpenInit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenInit { - return new MsgChannelOpenInit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenInit { - return new MsgChannelOpenInit().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenInit | PlainMessage | undefined, b: MsgChannelOpenInit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenInit, a, b); - } -} - -/** - * MsgChannelOpenInitResponse defines the Msg/ChannelOpenInit response type. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenInitResponse - */ -export class MsgChannelOpenInitResponse extends Message { - /** - * @generated from field: string channel_id = 1; - */ - channelId = ""; - - /** - * @generated from field: string version = 2; - */ - version = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenInitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenInitResponse { - return new MsgChannelOpenInitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenInitResponse { - return new MsgChannelOpenInitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenInitResponse { - return new MsgChannelOpenInitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenInitResponse | PlainMessage | undefined, b: MsgChannelOpenInitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenInitResponse, a, b); - } -} - -/** - * MsgChannelOpenInit defines a msg sent by a Relayer to try to open a channel - * on Chain B. The version field within the Channel field has been deprecated. Its - * value will be ignored by core IBC. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenTry - */ -export class MsgChannelOpenTry extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * Deprecated: this field is unused. Crossing hello's are no longer supported in core IBC. - * - * @generated from field: string previous_channel_id = 2 [deprecated = true]; - * @deprecated - */ - previousChannelId = ""; - - /** - * NOTE: the version field within the channel has been deprecated. Its value will be ignored by core IBC. - * - * @generated from field: ibc.core.channel.v1.Channel channel = 3; - */ - channel?: Channel; - - /** - * @generated from field: string counterparty_version = 4; - */ - counterpartyVersion = ""; - - /** - * @generated from field: bytes proof_init = 5; - */ - proofInit = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 6; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 7; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenTry"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "previous_channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "channel", kind: "message", T: Channel }, - { no: 4, name: "counterparty_version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "proof_init", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "proof_height", kind: "message", T: Height }, - { no: 7, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenTry { - return new MsgChannelOpenTry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenTry { - return new MsgChannelOpenTry().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenTry { - return new MsgChannelOpenTry().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenTry | PlainMessage | undefined, b: MsgChannelOpenTry | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenTry, a, b); - } -} - -/** - * MsgChannelOpenTryResponse defines the Msg/ChannelOpenTry response type. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenTryResponse - */ -export class MsgChannelOpenTryResponse extends Message { - /** - * @generated from field: string version = 1; - */ - version = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenTryResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenTryResponse { - return new MsgChannelOpenTryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenTryResponse { - return new MsgChannelOpenTryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenTryResponse { - return new MsgChannelOpenTryResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenTryResponse | PlainMessage | undefined, b: MsgChannelOpenTryResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenTryResponse, a, b); - } -} - -/** - * MsgChannelOpenAck defines a msg sent by a Relayer to Chain A to acknowledge - * the change of channel state to TRYOPEN on Chain B. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenAck - */ -export class MsgChannelOpenAck extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * @generated from field: string counterparty_channel_id = 3; - */ - counterpartyChannelId = ""; - - /** - * @generated from field: string counterparty_version = 4; - */ - counterpartyVersion = ""; - - /** - * @generated from field: bytes proof_try = 5; - */ - proofTry = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 6; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 7; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenAck"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "counterparty_channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "counterparty_version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "proof_try", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "proof_height", kind: "message", T: Height }, - { no: 7, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenAck { - return new MsgChannelOpenAck().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenAck { - return new MsgChannelOpenAck().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenAck { - return new MsgChannelOpenAck().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenAck | PlainMessage | undefined, b: MsgChannelOpenAck | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenAck, a, b); - } -} - -/** - * MsgChannelOpenAckResponse defines the Msg/ChannelOpenAck response type. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenAckResponse - */ -export class MsgChannelOpenAckResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenAckResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenAckResponse { - return new MsgChannelOpenAckResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenAckResponse { - return new MsgChannelOpenAckResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenAckResponse { - return new MsgChannelOpenAckResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenAckResponse | PlainMessage | undefined, b: MsgChannelOpenAckResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenAckResponse, a, b); - } -} - -/** - * MsgChannelOpenConfirm defines a msg sent by a Relayer to Chain B to - * acknowledge the change of channel state to OPEN on Chain A. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenConfirm - */ -export class MsgChannelOpenConfirm extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * @generated from field: bytes proof_ack = 3; - */ - proofAck = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenConfirm"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "proof_ack", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenConfirm { - return new MsgChannelOpenConfirm().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenConfirm { - return new MsgChannelOpenConfirm().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenConfirm { - return new MsgChannelOpenConfirm().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenConfirm | PlainMessage | undefined, b: MsgChannelOpenConfirm | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenConfirm, a, b); - } -} - -/** - * MsgChannelOpenConfirmResponse defines the Msg/ChannelOpenConfirm response - * type. - * - * @generated from message ibc.core.channel.v1.MsgChannelOpenConfirmResponse - */ -export class MsgChannelOpenConfirmResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelOpenConfirmResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelOpenConfirmResponse { - return new MsgChannelOpenConfirmResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelOpenConfirmResponse { - return new MsgChannelOpenConfirmResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelOpenConfirmResponse { - return new MsgChannelOpenConfirmResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelOpenConfirmResponse | PlainMessage | undefined, b: MsgChannelOpenConfirmResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelOpenConfirmResponse, a, b); - } -} - -/** - * MsgChannelCloseInit defines a msg sent by a Relayer to Chain A - * to close a channel with Chain B. - * - * @generated from message ibc.core.channel.v1.MsgChannelCloseInit - */ -export class MsgChannelCloseInit extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelCloseInit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelCloseInit { - return new MsgChannelCloseInit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelCloseInit { - return new MsgChannelCloseInit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelCloseInit { - return new MsgChannelCloseInit().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelCloseInit | PlainMessage | undefined, b: MsgChannelCloseInit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelCloseInit, a, b); - } -} - -/** - * MsgChannelCloseInitResponse defines the Msg/ChannelCloseInit response type. - * - * @generated from message ibc.core.channel.v1.MsgChannelCloseInitResponse - */ -export class MsgChannelCloseInitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelCloseInitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelCloseInitResponse { - return new MsgChannelCloseInitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelCloseInitResponse { - return new MsgChannelCloseInitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelCloseInitResponse { - return new MsgChannelCloseInitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelCloseInitResponse | PlainMessage | undefined, b: MsgChannelCloseInitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelCloseInitResponse, a, b); - } -} - -/** - * MsgChannelCloseConfirm defines a msg sent by a Relayer to Chain B - * to acknowledge the change of channel state to CLOSED on Chain A. - * - * @generated from message ibc.core.channel.v1.MsgChannelCloseConfirm - */ -export class MsgChannelCloseConfirm extends Message { - /** - * @generated from field: string port_id = 1; - */ - portId = ""; - - /** - * @generated from field: string channel_id = 2; - */ - channelId = ""; - - /** - * @generated from field: bytes proof_init = 3; - */ - proofInit = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelCloseConfirm"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "port_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "channel_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "proof_init", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelCloseConfirm { - return new MsgChannelCloseConfirm().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelCloseConfirm { - return new MsgChannelCloseConfirm().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelCloseConfirm { - return new MsgChannelCloseConfirm().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelCloseConfirm | PlainMessage | undefined, b: MsgChannelCloseConfirm | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelCloseConfirm, a, b); - } -} - -/** - * MsgChannelCloseConfirmResponse defines the Msg/ChannelCloseConfirm response - * type. - * - * @generated from message ibc.core.channel.v1.MsgChannelCloseConfirmResponse - */ -export class MsgChannelCloseConfirmResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgChannelCloseConfirmResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChannelCloseConfirmResponse { - return new MsgChannelCloseConfirmResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChannelCloseConfirmResponse { - return new MsgChannelCloseConfirmResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChannelCloseConfirmResponse { - return new MsgChannelCloseConfirmResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChannelCloseConfirmResponse | PlainMessage | undefined, b: MsgChannelCloseConfirmResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChannelCloseConfirmResponse, a, b); - } -} - -/** - * MsgRecvPacket receives incoming IBC packet - * - * @generated from message ibc.core.channel.v1.MsgRecvPacket - */ -export class MsgRecvPacket extends Message { - /** - * @generated from field: ibc.core.channel.v1.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes proof_commitment = 2; - */ - proofCommitment = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 4; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgRecvPacket"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "proof_commitment", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 4, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecvPacket | PlainMessage | undefined, b: MsgRecvPacket | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecvPacket, a, b); - } -} - -/** - * MsgRecvPacketResponse defines the Msg/RecvPacket response type. - * - * @generated from message ibc.core.channel.v1.MsgRecvPacketResponse - */ -export class MsgRecvPacketResponse extends Message { - /** - * @generated from field: ibc.core.channel.v1.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgRecvPacketResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecvPacketResponse | PlainMessage | undefined, b: MsgRecvPacketResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecvPacketResponse, a, b); - } -} - -/** - * MsgTimeout receives timed-out packet - * - * @generated from message ibc.core.channel.v1.MsgTimeout - */ -export class MsgTimeout extends Message { - /** - * @generated from field: ibc.core.channel.v1.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes proof_unreceived = 2; - */ - proofUnreceived = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * @generated from field: uint64 next_sequence_recv = 4; - */ - nextSequenceRecv = protoInt64.zero; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgTimeout"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "proof_unreceived", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 4, name: "next_sequence_recv", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeout { - return new MsgTimeout().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeout { - return new MsgTimeout().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeout { - return new MsgTimeout().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeout | PlainMessage | undefined, b: MsgTimeout | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeout, a, b); - } -} - -/** - * MsgTimeoutResponse defines the Msg/Timeout response type. - * - * @generated from message ibc.core.channel.v1.MsgTimeoutResponse - */ -export class MsgTimeoutResponse extends Message { - /** - * @generated from field: ibc.core.channel.v1.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgTimeoutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeoutResponse | PlainMessage | undefined, b: MsgTimeoutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeoutResponse, a, b); - } -} - -/** - * MsgTimeoutOnClose timed-out packet upon counterparty channel closure. - * - * @generated from message ibc.core.channel.v1.MsgTimeoutOnClose - */ -export class MsgTimeoutOnClose extends Message { - /** - * @generated from field: ibc.core.channel.v1.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes proof_unreceived = 2; - */ - proofUnreceived = new Uint8Array(0); - - /** - * @generated from field: bytes proof_close = 3; - */ - proofClose = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - /** - * @generated from field: uint64 next_sequence_recv = 5; - */ - nextSequenceRecv = protoInt64.zero; - - /** - * @generated from field: string signer = 6; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgTimeoutOnClose"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "proof_unreceived", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_close", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "next_sequence_recv", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeoutOnClose { - return new MsgTimeoutOnClose().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeoutOnClose { - return new MsgTimeoutOnClose().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeoutOnClose { - return new MsgTimeoutOnClose().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeoutOnClose | PlainMessage | undefined, b: MsgTimeoutOnClose | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeoutOnClose, a, b); - } -} - -/** - * MsgTimeoutOnCloseResponse defines the Msg/TimeoutOnClose response type. - * - * @generated from message ibc.core.channel.v1.MsgTimeoutOnCloseResponse - */ -export class MsgTimeoutOnCloseResponse extends Message { - /** - * @generated from field: ibc.core.channel.v1.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgTimeoutOnCloseResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeoutOnCloseResponse { - return new MsgTimeoutOnCloseResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeoutOnCloseResponse { - return new MsgTimeoutOnCloseResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeoutOnCloseResponse { - return new MsgTimeoutOnCloseResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeoutOnCloseResponse | PlainMessage | undefined, b: MsgTimeoutOnCloseResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeoutOnCloseResponse, a, b); - } -} - -/** - * MsgAcknowledgement receives incoming IBC acknowledgement - * - * @generated from message ibc.core.channel.v1.MsgAcknowledgement - */ -export class MsgAcknowledgement extends Message { - /** - * @generated from field: ibc.core.channel.v1.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes acknowledgement = 2; - */ - acknowledgement = new Uint8Array(0); - - /** - * @generated from field: bytes proof_acked = 3; - */ - proofAcked = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgAcknowledgement"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "acknowledgement", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_acked", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromJsonString(jsonString, options); - } - - static equals(a: MsgAcknowledgement | PlainMessage | undefined, b: MsgAcknowledgement | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAcknowledgement, a, b); - } -} - -/** - * MsgAcknowledgementResponse defines the Msg/Acknowledgement response type. - * - * @generated from message ibc.core.channel.v1.MsgAcknowledgementResponse - */ -export class MsgAcknowledgementResponse extends Message { - /** - * @generated from field: ibc.core.channel.v1.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v1.MsgAcknowledgementResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAcknowledgementResponse | PlainMessage | undefined, b: MsgAcknowledgementResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAcknowledgementResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v2/genesis_pb.ts deleted file mode 100644 index ff7557bbd..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/genesis_pb.ts +++ /dev/null @@ -1,180 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/genesis.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * GenesisState defines the ibc channel/v2 submodule's genesis state. - * - * @generated from message ibc.core.channel.v2.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated ibc.core.channel.v2.PacketState acknowledgements = 2; - */ - acknowledgements: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v2.PacketState commitments = 3; - */ - commitments: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v2.PacketState receipts = 4; - */ - receipts: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v2.PacketState async_packets = 5; - */ - asyncPackets: PacketState[] = []; - - /** - * @generated from field: repeated ibc.core.channel.v2.PacketSequence send_sequences = 6; - */ - sendSequences: PacketSequence[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "acknowledgements", kind: "message", T: PacketState, repeated: true }, - { no: 3, name: "commitments", kind: "message", T: PacketState, repeated: true }, - { no: 4, name: "receipts", kind: "message", T: PacketState, repeated: true }, - { no: 5, name: "async_packets", kind: "message", T: PacketState, repeated: true }, - { no: 6, name: "send_sequences", kind: "message", T: PacketSequence, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * PacketState defines the generic type necessary to retrieve and store - * packet commitments, acknowledgements, and receipts. - * Caller is responsible for knowing the context necessary to interpret this - * state as a commitment, acknowledgement, or a receipt. - * - * @generated from message ibc.core.channel.v2.PacketState - */ -export class PacketState extends Message { - /** - * client unique identifier. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * packet sequence. - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - /** - * embedded data that represents packet state. - * - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.PacketState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketState { - return new PacketState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketState { - return new PacketState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketState { - return new PacketState().fromJsonString(jsonString, options); - } - - static equals(a: PacketState | PlainMessage | undefined, b: PacketState | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketState, a, b); - } -} - -/** - * PacketSequence defines the genesis type necessary to retrieve and store next send sequences. - * - * @generated from message ibc.core.channel.v2.PacketSequence - */ -export class PacketSequence extends Message { - /** - * client unique identifier. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.PacketSequence"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketSequence { - return new PacketSequence().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketSequence { - return new PacketSequence().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketSequence { - return new PacketSequence().fromJsonString(jsonString, options); - } - - static equals(a: PacketSequence | PlainMessage | undefined, b: PacketSequence | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketSequence, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/packet_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v2/packet_pb.ts deleted file mode 100644 index bd701e4f9..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/packet_pb.ts +++ /dev/null @@ -1,291 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/packet.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * PacketStatus specifies the status of a RecvPacketResult. - * - * @generated from enum ibc.core.channel.v2.PacketStatus - */ -export enum PacketStatus { - /** - * PACKET_STATUS_UNSPECIFIED indicates an unknown packet status. - * - * @generated from enum value: PACKET_STATUS_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * PACKET_STATUS_SUCCESS indicates a successful packet receipt. - * - * @generated from enum value: PACKET_STATUS_SUCCESS = 1; - */ - SUCCESS = 1, - - /** - * PACKET_STATUS_FAILURE indicates a failed packet receipt. - * - * @generated from enum value: PACKET_STATUS_FAILURE = 2; - */ - FAILURE = 2, - - /** - * PACKET_STATUS_ASYNC indicates an async packet receipt. - * - * @generated from enum value: PACKET_STATUS_ASYNC = 3; - */ - ASYNC = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(PacketStatus) -proto3.util.setEnumType(PacketStatus, "ibc.core.channel.v2.PacketStatus", [ - { no: 0, name: "PACKET_STATUS_UNSPECIFIED" }, - { no: 1, name: "PACKET_STATUS_SUCCESS" }, - { no: 2, name: "PACKET_STATUS_FAILURE" }, - { no: 3, name: "PACKET_STATUS_ASYNC" }, -]); - -/** - * Packet defines a type that carries data across different chains through IBC - * - * @generated from message ibc.core.channel.v2.Packet - */ -export class Packet extends Message { - /** - * number corresponds to the order of sends and receives, where a Packet - * with an earlier sequence number must be sent and received before a Packet - * with a later sequence number. - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * identifies the sending client on the sending chain. - * - * @generated from field: string source_client = 2; - */ - sourceClient = ""; - - /** - * identifies the receiving client on the receiving chain. - * - * @generated from field: string destination_client = 3; - */ - destinationClient = ""; - - /** - * timeout timestamp in seconds after which the packet times out. - * - * @generated from field: uint64 timeout_timestamp = 4; - */ - timeoutTimestamp = protoInt64.zero; - - /** - * a list of payloads, each one for a specific application. - * - * @generated from field: repeated ibc.core.channel.v2.Payload payloads = 5; - */ - payloads: Payload[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.Packet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "source_client", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "destination_client", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "payloads", kind: "message", T: Payload, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Packet { - return new Packet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Packet { - return new Packet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Packet { - return new Packet().fromJsonString(jsonString, options); - } - - static equals(a: Packet | PlainMessage | undefined, b: Packet | PlainMessage | undefined): boolean { - return proto3.util.equals(Packet, a, b); - } -} - -/** - * Payload contains the source and destination ports and payload for the application (version, encoding, raw bytes) - * - * @generated from message ibc.core.channel.v2.Payload - */ -export class Payload extends Message { - /** - * specifies the source port of the packet. - * - * @generated from field: string source_port = 1; - */ - sourcePort = ""; - - /** - * specifies the destination port of the packet. - * - * @generated from field: string destination_port = 2; - */ - destinationPort = ""; - - /** - * version of the specified application. - * - * @generated from field: string version = 3; - */ - version = ""; - - /** - * the encoding used for the provided value. - * - * @generated from field: string encoding = 4; - */ - encoding = ""; - - /** - * the raw bytes for the payload. - * - * @generated from field: bytes value = 5; - */ - value = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.Payload"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "source_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "destination_port", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "version", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "encoding", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Payload { - return new Payload().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Payload { - return new Payload().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Payload { - return new Payload().fromJsonString(jsonString, options); - } - - static equals(a: Payload | PlainMessage | undefined, b: Payload | PlainMessage | undefined): boolean { - return proto3.util.equals(Payload, a, b); - } -} - -/** - * Acknowledgement contains a list of all ack results associated with a single packet. - * In the case of a successful receive, the acknowledgement will contain an app acknowledgement - * for each application that received a payload in the same order that the payloads were sent - * in the packet. - * If the receive is not successful, the acknowledgement will contain a single app acknowledgment - * which will be a constant error acknowledgment as defined by the IBC v2 protocol. - * - * @generated from message ibc.core.channel.v2.Acknowledgement - */ -export class Acknowledgement extends Message { - /** - * @generated from field: repeated bytes app_acknowledgements = 1; - */ - appAcknowledgements: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.Acknowledgement"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "app_acknowledgements", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Acknowledgement { - return new Acknowledgement().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Acknowledgement { - return new Acknowledgement().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Acknowledgement { - return new Acknowledgement().fromJsonString(jsonString, options); - } - - static equals(a: Acknowledgement | PlainMessage | undefined, b: Acknowledgement | PlainMessage | undefined): boolean { - return proto3.util.equals(Acknowledgement, a, b); - } -} - -/** - * RecvPacketResult speecifies the status of a packet as well as the acknowledgement bytes. - * - * @generated from message ibc.core.channel.v2.RecvPacketResult - */ -export class RecvPacketResult extends Message { - /** - * status of the packet - * - * @generated from field: ibc.core.channel.v2.PacketStatus status = 1; - */ - status = PacketStatus.UNSPECIFIED; - - /** - * acknowledgement of the packet - * - * @generated from field: bytes acknowledgement = 2; - */ - acknowledgement = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.RecvPacketResult"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "status", kind: "enum", T: proto3.getEnumType(PacketStatus) }, - { no: 2, name: "acknowledgement", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RecvPacketResult { - return new RecvPacketResult().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RecvPacketResult { - return new RecvPacketResult().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RecvPacketResult { - return new RecvPacketResult().fromJsonString(jsonString, options); - } - - static equals(a: RecvPacketResult | PlainMessage | undefined, b: RecvPacketResult | PlainMessage | undefined): boolean { - return proto3.util.equals(RecvPacketResult, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/query_cosmes.ts b/packages/es/src/protobufs/ibc/core/channel/v2/query_cosmes.ts deleted file mode 100644 index 7b2dd448a..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/query_cosmes.ts +++ /dev/null @@ -1,105 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/query.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryNextSequenceSendRequest, QueryNextSequenceSendResponse, QueryPacketAcknowledgementRequest, QueryPacketAcknowledgementResponse, QueryPacketAcknowledgementsRequest, QueryPacketAcknowledgementsResponse, QueryPacketCommitmentRequest, QueryPacketCommitmentResponse, QueryPacketCommitmentsRequest, QueryPacketCommitmentsResponse, QueryPacketReceiptRequest, QueryPacketReceiptResponse, QueryUnreceivedAcksRequest, QueryUnreceivedAcksResponse, QueryUnreceivedPacketsRequest, QueryUnreceivedPacketsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.core.channel.v2.Query"; - -/** - * NextSequenceSend returns the next send sequence for a given channel. - * - * @generated from rpc ibc.core.channel.v2.Query.NextSequenceSend - */ -export const QueryNextSequenceSendService = { - typeName: TYPE_NAME, - method: "NextSequenceSend", - Request: QueryNextSequenceSendRequest, - Response: QueryNextSequenceSendResponse, -} as const; - -/** - * PacketCommitment queries a stored packet commitment hash. - * - * @generated from rpc ibc.core.channel.v2.Query.PacketCommitment - */ -export const QueryPacketCommitmentService = { - typeName: TYPE_NAME, - method: "PacketCommitment", - Request: QueryPacketCommitmentRequest, - Response: QueryPacketCommitmentResponse, -} as const; - -/** - * PacketCommitments queries a stored packet commitment hash. - * - * @generated from rpc ibc.core.channel.v2.Query.PacketCommitments - */ -export const QueryPacketCommitmentsService = { - typeName: TYPE_NAME, - method: "PacketCommitments", - Request: QueryPacketCommitmentsRequest, - Response: QueryPacketCommitmentsResponse, -} as const; - -/** - * PacketAcknowledgement queries a stored acknowledgement commitment hash. - * - * @generated from rpc ibc.core.channel.v2.Query.PacketAcknowledgement - */ -export const QueryPacketAcknowledgementService = { - typeName: TYPE_NAME, - method: "PacketAcknowledgement", - Request: QueryPacketAcknowledgementRequest, - Response: QueryPacketAcknowledgementResponse, -} as const; - -/** - * PacketAcknowledgements returns all packet acknowledgements associated with a channel. - * - * @generated from rpc ibc.core.channel.v2.Query.PacketAcknowledgements - */ -export const QueryPacketAcknowledgementsService = { - typeName: TYPE_NAME, - method: "PacketAcknowledgements", - Request: QueryPacketAcknowledgementsRequest, - Response: QueryPacketAcknowledgementsResponse, -} as const; - -/** - * PacketReceipt queries a stored packet receipt. - * - * @generated from rpc ibc.core.channel.v2.Query.PacketReceipt - */ -export const QueryPacketReceiptService = { - typeName: TYPE_NAME, - method: "PacketReceipt", - Request: QueryPacketReceiptRequest, - Response: QueryPacketReceiptResponse, -} as const; - -/** - * UnreceivedPackets returns all the unreceived IBC packets associated with a channel and sequences. - * - * @generated from rpc ibc.core.channel.v2.Query.UnreceivedPackets - */ -export const QueryUnreceivedPacketsService = { - typeName: TYPE_NAME, - method: "UnreceivedPackets", - Request: QueryUnreceivedPacketsRequest, - Response: QueryUnreceivedPacketsResponse, -} as const; - -/** - * UnreceivedAcks returns all the unreceived IBC acknowledgements associated with a channel and sequences. - * - * @generated from rpc ibc.core.channel.v2.Query.UnreceivedAcks - */ -export const QueryUnreceivedAcksService = { - typeName: TYPE_NAME, - method: "UnreceivedAcks", - Request: QueryUnreceivedAcksRequest, - Response: QueryUnreceivedAcksResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/query_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v2/query_pb.ts deleted file mode 100644 index e67b034de..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/query_pb.ts +++ /dev/null @@ -1,845 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/query.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Height } from "../../client/v1/client_pb.js"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { PacketState } from "./genesis_pb.js"; - -/** - * QueryNextSequenceSendRequest is the request type for the Query/QueryNextSequenceSend RPC method - * - * @generated from message ibc.core.channel.v2.QueryNextSequenceSendRequest - */ -export class QueryNextSequenceSendRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryNextSequenceSendRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceSendRequest { - return new QueryNextSequenceSendRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceSendRequest | PlainMessage | undefined, b: QueryNextSequenceSendRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceSendRequest, a, b); - } -} - -/** - * QueryNextSequenceSendResponse is the response type for the Query/QueryNextSequenceSend RPC method - * - * @generated from message ibc.core.channel.v2.QueryNextSequenceSendResponse - */ -export class QueryNextSequenceSendResponse extends Message { - /** - * next sequence send number - * - * @generated from field: uint64 next_sequence_send = 1; - */ - nextSequenceSend = protoInt64.zero; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryNextSequenceSendResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "next_sequence_send", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNextSequenceSendResponse { - return new QueryNextSequenceSendResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryNextSequenceSendResponse | PlainMessage | undefined, b: QueryNextSequenceSendResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNextSequenceSendResponse, a, b); - } -} - -/** - * QueryPacketCommitmentRequest is the request type for the Query/PacketCommitment RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketCommitmentRequest - */ -export class QueryPacketCommitmentRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketCommitmentRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentRequest { - return new QueryPacketCommitmentRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentRequest | PlainMessage | undefined, b: QueryPacketCommitmentRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentRequest, a, b); - } -} - -/** - * QueryPacketCommitmentResponse is the response type for the Query/PacketCommitment RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketCommitmentResponse - */ -export class QueryPacketCommitmentResponse extends Message { - /** - * packet associated with the request fields - * - * @generated from field: bytes commitment = 1; - */ - commitment = new Uint8Array(0); - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketCommitmentResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "commitment", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentResponse { - return new QueryPacketCommitmentResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentResponse | PlainMessage | undefined, b: QueryPacketCommitmentResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentResponse, a, b); - } -} - -/** - * QueryPacketCommitmentsRequest is the request type for the Query/PacketCommitments RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketCommitmentsRequest - */ -export class QueryPacketCommitmentsRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketCommitmentsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentsRequest { - return new QueryPacketCommitmentsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentsRequest | PlainMessage | undefined, b: QueryPacketCommitmentsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentsRequest, a, b); - } -} - -/** - * QueryPacketCommitmentResponse is the response type for the Query/PacketCommitment RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketCommitmentsResponse - */ -export class QueryPacketCommitmentsResponse extends Message { - /** - * collection of packet commitments for the requested channel identifier. - * - * @generated from field: repeated ibc.core.channel.v2.PacketState commitments = 1; - */ - commitments: PacketState[] = []; - - /** - * pagination response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height. - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketCommitmentsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "commitments", kind: "message", T: PacketState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketCommitmentsResponse { - return new QueryPacketCommitmentsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketCommitmentsResponse | PlainMessage | undefined, b: QueryPacketCommitmentsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketCommitmentsResponse, a, b); - } -} - -/** - * QueryPacketAcknowledgementRequest is the request type for the Query/PacketAcknowledgement RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketAcknowledgementRequest - */ -export class QueryPacketAcknowledgementRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketAcknowledgementRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementRequest { - return new QueryPacketAcknowledgementRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementRequest | PlainMessage | undefined, b: QueryPacketAcknowledgementRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementRequest, a, b); - } -} - -/** - * QueryPacketAcknowledgementResponse is the response type for the Query/PacketAcknowledgement RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketAcknowledgementResponse - */ -export class QueryPacketAcknowledgementResponse extends Message { - /** - * acknowledgement associated with the request fields - * - * @generated from field: bytes acknowledgement = 1; - */ - acknowledgement = new Uint8Array(0); - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketAcknowledgementResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "acknowledgement", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementResponse { - return new QueryPacketAcknowledgementResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementResponse | PlainMessage | undefined, b: QueryPacketAcknowledgementResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementResponse, a, b); - } -} - -/** - * QueryPacketAcknowledgementsRequest is the request type for the - * Query/QueryPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v2.QueryPacketAcknowledgementsRequest - */ -export class QueryPacketAcknowledgementsRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - /** - * list of packet sequences - * - * @generated from field: repeated uint64 packet_commitment_sequences = 3; - */ - packetCommitmentSequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketAcknowledgementsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - { no: 3, name: "packet_commitment_sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementsRequest { - return new QueryPacketAcknowledgementsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementsRequest | PlainMessage | undefined, b: QueryPacketAcknowledgementsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementsRequest, a, b); - } -} - -/** - * QueryPacketAcknowledgemetsResponse is the request type for the - * Query/QueryPacketAcknowledgements RPC method - * - * @generated from message ibc.core.channel.v2.QueryPacketAcknowledgementsResponse - */ -export class QueryPacketAcknowledgementsResponse extends Message { - /** - * @generated from field: repeated ibc.core.channel.v2.PacketState acknowledgements = 1; - */ - acknowledgements: PacketState[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketAcknowledgementsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "acknowledgements", kind: "message", T: PacketState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketAcknowledgementsResponse { - return new QueryPacketAcknowledgementsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketAcknowledgementsResponse | PlainMessage | undefined, b: QueryPacketAcknowledgementsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketAcknowledgementsResponse, a, b); - } -} - -/** - * QueryPacketReceiptRequest is the request type for the Query/PacketReceipt RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketReceiptRequest - */ -export class QueryPacketReceiptRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * packet sequence - * - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketReceiptRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketReceiptRequest { - return new QueryPacketReceiptRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketReceiptRequest | PlainMessage | undefined, b: QueryPacketReceiptRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketReceiptRequest, a, b); - } -} - -/** - * QueryPacketReceiptResponse is the response type for the Query/PacketReceipt RPC method. - * - * @generated from message ibc.core.channel.v2.QueryPacketReceiptResponse - */ -export class QueryPacketReceiptResponse extends Message { - /** - * success flag for if receipt exists - * - * @generated from field: bool received = 2; - */ - received = false; - - /** - * merkle proof of existence or absence - * - * @generated from field: bytes proof = 3; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryPacketReceiptResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "received", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPacketReceiptResponse { - return new QueryPacketReceiptResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPacketReceiptResponse | PlainMessage | undefined, b: QueryPacketReceiptResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPacketReceiptResponse, a, b); - } -} - -/** - * QueryUnreceivedPacketsRequest is the request type for the Query/UnreceivedPackets RPC method - * - * @generated from message ibc.core.channel.v2.QueryUnreceivedPacketsRequest - */ -export class QueryUnreceivedPacketsRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * list of packet sequences - * - * @generated from field: repeated uint64 sequences = 2; - */ - sequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryUnreceivedPacketsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedPacketsRequest { - return new QueryUnreceivedPacketsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedPacketsRequest | PlainMessage | undefined, b: QueryUnreceivedPacketsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedPacketsRequest, a, b); - } -} - -/** - * QueryUnreceivedPacketsResponse is the response type for the Query/UnreceivedPacketCommitments RPC method - * - * @generated from message ibc.core.channel.v2.QueryUnreceivedPacketsResponse - */ -export class QueryUnreceivedPacketsResponse extends Message { - /** - * list of unreceived packet sequences - * - * @generated from field: repeated uint64 sequences = 1; - */ - sequences: bigint[] = []; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 2; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryUnreceivedPacketsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedPacketsResponse { - return new QueryUnreceivedPacketsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedPacketsResponse | PlainMessage | undefined, b: QueryUnreceivedPacketsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedPacketsResponse, a, b); - } -} - -/** - * QueryUnreceivedAcks is the request type for the - * Query/UnreceivedAcks RPC method - * - * @generated from message ibc.core.channel.v2.QueryUnreceivedAcksRequest - */ -export class QueryUnreceivedAcksRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * list of acknowledgement sequences - * - * @generated from field: repeated uint64 packet_ack_sequences = 2; - */ - packetAckSequences: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryUnreceivedAcksRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "packet_ack_sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedAcksRequest { - return new QueryUnreceivedAcksRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedAcksRequest | PlainMessage | undefined, b: QueryUnreceivedAcksRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedAcksRequest, a, b); - } -} - -/** - * QueryUnreceivedAcksResponse is the response type for the - * Query/UnreceivedAcks RPC method - * - * @generated from message ibc.core.channel.v2.QueryUnreceivedAcksResponse - */ -export class QueryUnreceivedAcksResponse extends Message { - /** - * list of unreceived acknowledgement sequences - * - * @generated from field: repeated uint64 sequences = 1; - */ - sequences: bigint[] = []; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 2; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.QueryUnreceivedAcksResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequences", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnreceivedAcksResponse { - return new QueryUnreceivedAcksResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnreceivedAcksResponse | PlainMessage | undefined, b: QueryUnreceivedAcksResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnreceivedAcksResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/tx_cosmes.ts b/packages/es/src/protobufs/ibc/core/channel/v2/tx_cosmes.ts deleted file mode 100644 index 59690696b..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/tx_cosmes.ts +++ /dev/null @@ -1,57 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/tx.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAcknowledgement, MsgAcknowledgementResponse, MsgRecvPacket, MsgRecvPacketResponse, MsgSendPacket, MsgSendPacketResponse, MsgTimeout, MsgTimeoutResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.core.channel.v2.Msg"; - -/** - * SendPacket defines a rpc handler method for MsgSendPacket. - * - * @generated from rpc ibc.core.channel.v2.Msg.SendPacket - */ -export const MsgSendPacketService = { - typeName: TYPE_NAME, - method: "SendPacket", - Request: MsgSendPacket, - Response: MsgSendPacketResponse, -} as const; - -/** - * RecvPacket defines a rpc handler method for MsgRecvPacket. - * - * @generated from rpc ibc.core.channel.v2.Msg.RecvPacket - */ -export const MsgRecvPacketService = { - typeName: TYPE_NAME, - method: "RecvPacket", - Request: MsgRecvPacket, - Response: MsgRecvPacketResponse, -} as const; - -/** - * Timeout defines a rpc handler method for MsgTimeout. - * - * @generated from rpc ibc.core.channel.v2.Msg.Timeout - */ -export const MsgTimeoutService = { - typeName: TYPE_NAME, - method: "Timeout", - Request: MsgTimeout, - Response: MsgTimeoutResponse, -} as const; - -/** - * Acknowledgement defines a rpc handler method for MsgAcknowledgement. - * - * @generated from rpc ibc.core.channel.v2.Msg.Acknowledgement - */ -export const MsgAcknowledgementService = { - typeName: TYPE_NAME, - method: "Acknowledgement", - Request: MsgAcknowledgement, - Response: MsgAcknowledgementResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/channel/v2/tx_pb.ts b/packages/es/src/protobufs/ibc/core/channel/v2/tx_pb.ts deleted file mode 100644 index c39042e07..000000000 --- a/packages/es/src/protobufs/ibc/core/channel/v2/tx_pb.ts +++ /dev/null @@ -1,442 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/channel/v2/tx.proto (package ibc.core.channel.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Acknowledgement, Packet, Payload } from "./packet_pb.js"; -import { Height } from "../../client/v1/client_pb.js"; - -/** - * ResponseResultType defines the possible outcomes of the execution of a message - * - * @generated from enum ibc.core.channel.v2.ResponseResultType - */ -export enum ResponseResultType { - /** - * Default zero value enumeration - * - * @generated from enum value: RESPONSE_RESULT_TYPE_UNSPECIFIED = 0; - */ - UNSPECIFIED = 0, - - /** - * The message did not call the IBC application callbacks (because, for example, the packet had already been relayed) - * - * @generated from enum value: RESPONSE_RESULT_TYPE_NOOP = 1; - */ - NOOP = 1, - - /** - * The message was executed successfully - * - * @generated from enum value: RESPONSE_RESULT_TYPE_SUCCESS = 2; - */ - SUCCESS = 2, - - /** - * The message was executed unsuccessfully - * - * @generated from enum value: RESPONSE_RESULT_TYPE_FAILURE = 3; - */ - FAILURE = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(ResponseResultType) -proto3.util.setEnumType(ResponseResultType, "ibc.core.channel.v2.ResponseResultType", [ - { no: 0, name: "RESPONSE_RESULT_TYPE_UNSPECIFIED" }, - { no: 1, name: "RESPONSE_RESULT_TYPE_NOOP" }, - { no: 2, name: "RESPONSE_RESULT_TYPE_SUCCESS" }, - { no: 3, name: "RESPONSE_RESULT_TYPE_FAILURE" }, -]); - -/** - * MsgSendPacket sends an outgoing IBC packet. - * - * @generated from message ibc.core.channel.v2.MsgSendPacket - */ -export class MsgSendPacket extends Message { - /** - * @generated from field: string source_client = 1; - */ - sourceClient = ""; - - /** - * @generated from field: uint64 timeout_timestamp = 2; - */ - timeoutTimestamp = protoInt64.zero; - - /** - * @generated from field: repeated ibc.core.channel.v2.Payload payloads = 3; - */ - payloads: Payload[] = []; - - /** - * @generated from field: string signer = 4; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgSendPacket"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "source_client", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timeout_timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "payloads", kind: "message", T: Payload, repeated: true }, - { no: 4, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSendPacket { - return new MsgSendPacket().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSendPacket { - return new MsgSendPacket().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSendPacket { - return new MsgSendPacket().fromJsonString(jsonString, options); - } - - static equals(a: MsgSendPacket | PlainMessage | undefined, b: MsgSendPacket | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSendPacket, a, b); - } -} - -/** - * MsgSendPacketResponse defines the Msg/SendPacket response type. - * - * @generated from message ibc.core.channel.v2.MsgSendPacketResponse - */ -export class MsgSendPacketResponse extends Message { - /** - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgSendPacketResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSendPacketResponse { - return new MsgSendPacketResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSendPacketResponse { - return new MsgSendPacketResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSendPacketResponse { - return new MsgSendPacketResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSendPacketResponse | PlainMessage | undefined, b: MsgSendPacketResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSendPacketResponse, a, b); - } -} - -/** - * MsgRecvPacket receives an incoming IBC packet. - * - * @generated from message ibc.core.channel.v2.MsgRecvPacket - */ -export class MsgRecvPacket extends Message { - /** - * @generated from field: ibc.core.channel.v2.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes proof_commitment = 2; - */ - proofCommitment = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 4; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgRecvPacket"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "proof_commitment", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 4, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecvPacket { - return new MsgRecvPacket().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecvPacket | PlainMessage | undefined, b: MsgRecvPacket | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecvPacket, a, b); - } -} - -/** - * MsgRecvPacketResponse defines the Msg/RecvPacket response type. - * - * @generated from message ibc.core.channel.v2.MsgRecvPacketResponse - */ -export class MsgRecvPacketResponse extends Message { - /** - * @generated from field: ibc.core.channel.v2.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgRecvPacketResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecvPacketResponse { - return new MsgRecvPacketResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecvPacketResponse | PlainMessage | undefined, b: MsgRecvPacketResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecvPacketResponse, a, b); - } -} - -/** - * MsgTimeout receives timed-out packet - * - * @generated from message ibc.core.channel.v2.MsgTimeout - */ -export class MsgTimeout extends Message { - /** - * @generated from field: ibc.core.channel.v2.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: bytes proof_unreceived = 2; - */ - proofUnreceived = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgTimeout"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "proof_unreceived", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeout { - return new MsgTimeout().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeout { - return new MsgTimeout().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeout { - return new MsgTimeout().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeout | PlainMessage | undefined, b: MsgTimeout | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeout, a, b); - } -} - -/** - * MsgTimeoutResponse defines the Msg/Timeout response type. - * - * @generated from message ibc.core.channel.v2.MsgTimeoutResponse - */ -export class MsgTimeoutResponse extends Message { - /** - * @generated from field: ibc.core.channel.v2.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgTimeoutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTimeoutResponse { - return new MsgTimeoutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgTimeoutResponse | PlainMessage | undefined, b: MsgTimeoutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTimeoutResponse, a, b); - } -} - -/** - * MsgAcknowledgement receives incoming IBC acknowledgement. - * - * @generated from message ibc.core.channel.v2.MsgAcknowledgement - */ -export class MsgAcknowledgement extends Message { - /** - * @generated from field: ibc.core.channel.v2.Packet packet = 1; - */ - packet?: Packet; - - /** - * @generated from field: ibc.core.channel.v2.Acknowledgement acknowledgement = 2; - */ - acknowledgement?: Acknowledgement; - - /** - * @generated from field: bytes proof_acked = 3; - */ - proofAcked = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgAcknowledgement"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "packet", kind: "message", T: Packet }, - { no: 2, name: "acknowledgement", kind: "message", T: Acknowledgement }, - { no: 3, name: "proof_acked", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAcknowledgement { - return new MsgAcknowledgement().fromJsonString(jsonString, options); - } - - static equals(a: MsgAcknowledgement | PlainMessage | undefined, b: MsgAcknowledgement | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAcknowledgement, a, b); - } -} - -/** - * MsgAcknowledgementResponse defines the Msg/Acknowledgement response type. - * - * @generated from message ibc.core.channel.v2.MsgAcknowledgementResponse - */ -export class MsgAcknowledgementResponse extends Message { - /** - * @generated from field: ibc.core.channel.v2.ResponseResultType result = 1; - */ - result = ResponseResultType.UNSPECIFIED; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.channel.v2.MsgAcknowledgementResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "result", kind: "enum", T: proto3.getEnumType(ResponseResultType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAcknowledgementResponse { - return new MsgAcknowledgementResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAcknowledgementResponse | PlainMessage | undefined, b: MsgAcknowledgementResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAcknowledgementResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/client_pb.ts b/packages/es/src/protobufs/ibc/core/client/v1/client_pb.ts deleted file mode 100644 index fa3930976..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/client_pb.ts +++ /dev/null @@ -1,262 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v1/client.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * IdentifiedClientState defines a client state with an additional client - * identifier field. - * - * @generated from message ibc.core.client.v1.IdentifiedClientState - */ -export class IdentifiedClientState extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * client state - * - * @generated from field: google.protobuf.Any client_state = 2; - */ - clientState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.IdentifiedClientState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IdentifiedClientState { - return new IdentifiedClientState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IdentifiedClientState { - return new IdentifiedClientState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IdentifiedClientState { - return new IdentifiedClientState().fromJsonString(jsonString, options); - } - - static equals(a: IdentifiedClientState | PlainMessage | undefined, b: IdentifiedClientState | PlainMessage | undefined): boolean { - return proto3.util.equals(IdentifiedClientState, a, b); - } -} - -/** - * ConsensusStateWithHeight defines a consensus state with an additional height - * field. - * - * @generated from message ibc.core.client.v1.ConsensusStateWithHeight - */ -export class ConsensusStateWithHeight extends Message { - /** - * consensus state height - * - * @generated from field: ibc.core.client.v1.Height height = 1; - */ - height?: Height; - - /** - * consensus state - * - * @generated from field: google.protobuf.Any consensus_state = 2; - */ - consensusState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.ConsensusStateWithHeight"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "height", kind: "message", T: Height }, - { no: 2, name: "consensus_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusStateWithHeight { - return new ConsensusStateWithHeight().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusStateWithHeight { - return new ConsensusStateWithHeight().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusStateWithHeight { - return new ConsensusStateWithHeight().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusStateWithHeight | PlainMessage | undefined, b: ConsensusStateWithHeight | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusStateWithHeight, a, b); - } -} - -/** - * ClientConsensusStates defines all the stored consensus states for a given - * client. - * - * @generated from message ibc.core.client.v1.ClientConsensusStates - */ -export class ClientConsensusStates extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * consensus states and their heights associated with the client - * - * @generated from field: repeated ibc.core.client.v1.ConsensusStateWithHeight consensus_states = 2; - */ - consensusStates: ConsensusStateWithHeight[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.ClientConsensusStates"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "consensus_states", kind: "message", T: ConsensusStateWithHeight, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientConsensusStates { - return new ClientConsensusStates().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientConsensusStates { - return new ClientConsensusStates().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientConsensusStates { - return new ClientConsensusStates().fromJsonString(jsonString, options); - } - - static equals(a: ClientConsensusStates | PlainMessage | undefined, b: ClientConsensusStates | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientConsensusStates, a, b); - } -} - -/** - * Height is a monotonically increasing data type - * that can be compared against another Height for the purposes of updating and - * freezing clients - * - * Normally the RevisionHeight is incremented at each height while keeping - * RevisionNumber the same. However some consensus algorithms may choose to - * reset the height in certain conditions e.g. hard forks, state-machine - * breaking changes In these cases, the RevisionNumber is incremented so that - * height continues to be monitonically increasing even as the RevisionHeight - * gets reset - * - * Please note that json tags for generated Go code are overridden to explicitly exclude the omitempty jsontag. - * This enforces the Go json marshaller to always emit zero values for both revision_number and revision_height. - * - * @generated from message ibc.core.client.v1.Height - */ -export class Height extends Message { - /** - * the revision that the client is currently on - * - * @generated from field: uint64 revision_number = 1; - */ - revisionNumber = protoInt64.zero; - - /** - * the height within the given revision - * - * @generated from field: uint64 revision_height = 2; - */ - revisionHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.Height"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "revision_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "revision_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Height { - return new Height().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Height { - return new Height().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Height { - return new Height().fromJsonString(jsonString, options); - } - - static equals(a: Height | PlainMessage | undefined, b: Height | PlainMessage | undefined): boolean { - return proto3.util.equals(Height, a, b); - } -} - -/** - * Params defines the set of IBC light client parameters. - * - * @generated from message ibc.core.client.v1.Params - */ -export class Params extends Message { - /** - * allowed_clients defines the list of allowed client state types which can be created - * and interacted with. If a client type is removed from the allowed clients list, usage - * of this client will be disabled until it is added again to the list. - * - * @generated from field: repeated string allowed_clients = 1; - */ - allowedClients: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "allowed_clients", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/client/v1/genesis_pb.ts deleted file mode 100644 index 90b738e6c..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/genesis_pb.ts +++ /dev/null @@ -1,186 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v1/genesis.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ClientConsensusStates, IdentifiedClientState, Params } from "./client_pb.js"; - -/** - * GenesisState defines the ibc client submodule's genesis state. - * - * @generated from message ibc.core.client.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * client states with their corresponding identifiers - * - * @generated from field: repeated ibc.core.client.v1.IdentifiedClientState clients = 1; - */ - clients: IdentifiedClientState[] = []; - - /** - * consensus states from each client - * - * @generated from field: repeated ibc.core.client.v1.ClientConsensusStates clients_consensus = 2; - */ - clientsConsensus: ClientConsensusStates[] = []; - - /** - * metadata from each client - * - * @generated from field: repeated ibc.core.client.v1.IdentifiedGenesisMetadata clients_metadata = 3; - */ - clientsMetadata: IdentifiedGenesisMetadata[] = []; - - /** - * @generated from field: ibc.core.client.v1.Params params = 4; - */ - params?: Params; - - /** - * Deprecated: create_localhost has been deprecated. - * The localhost client is automatically created at genesis. - * - * @generated from field: bool create_localhost = 5 [deprecated = true]; - * @deprecated - */ - createLocalhost = false; - - /** - * the sequence for the next generated client identifier - * - * @generated from field: uint64 next_client_sequence = 6; - */ - nextClientSequence = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "clients", kind: "message", T: IdentifiedClientState, repeated: true }, - { no: 2, name: "clients_consensus", kind: "message", T: ClientConsensusStates, repeated: true }, - { no: 3, name: "clients_metadata", kind: "message", T: IdentifiedGenesisMetadata, repeated: true }, - { no: 4, name: "params", kind: "message", T: Params }, - { no: 5, name: "create_localhost", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 6, name: "next_client_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * GenesisMetadata defines the genesis type for metadata that will be used - * to export all client store keys that are not client or consensus states. - * - * @generated from message ibc.core.client.v1.GenesisMetadata - */ -export class GenesisMetadata extends Message { - /** - * store key of metadata without clientID-prefix - * - * @generated from field: bytes key = 1; - */ - key = new Uint8Array(0); - - /** - * metadata value - * - * @generated from field: bytes value = 2; - */ - value = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.GenesisMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisMetadata { - return new GenesisMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisMetadata { - return new GenesisMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisMetadata { - return new GenesisMetadata().fromJsonString(jsonString, options); - } - - static equals(a: GenesisMetadata | PlainMessage | undefined, b: GenesisMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisMetadata, a, b); - } -} - -/** - * IdentifiedGenesisMetadata has the client metadata with the corresponding - * client id. - * - * @generated from message ibc.core.client.v1.IdentifiedGenesisMetadata - */ -export class IdentifiedGenesisMetadata extends Message { - /** - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * @generated from field: repeated ibc.core.client.v1.GenesisMetadata client_metadata = 2; - */ - clientMetadata: GenesisMetadata[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.IdentifiedGenesisMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_metadata", kind: "message", T: GenesisMetadata, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IdentifiedGenesisMetadata { - return new IdentifiedGenesisMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IdentifiedGenesisMetadata { - return new IdentifiedGenesisMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IdentifiedGenesisMetadata { - return new IdentifiedGenesisMetadata().fromJsonString(jsonString, options); - } - - static equals(a: IdentifiedGenesisMetadata | PlainMessage | undefined, b: IdentifiedGenesisMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(IdentifiedGenesisMetadata, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/core/client/v1/query_cosmes.ts deleted file mode 100644 index 4bae5d6fb..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/query_cosmes.ts +++ /dev/null @@ -1,143 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/client/v1/query.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryClientCreatorRequest, QueryClientCreatorResponse, QueryClientParamsRequest, QueryClientParamsResponse, QueryClientStateRequest, QueryClientStateResponse, QueryClientStatesRequest, QueryClientStatesResponse, QueryClientStatusRequest, QueryClientStatusResponse, QueryConsensusStateHeightsRequest, QueryConsensusStateHeightsResponse, QueryConsensusStateRequest, QueryConsensusStateResponse, QueryConsensusStatesRequest, QueryConsensusStatesResponse, QueryUpgradedClientStateRequest, QueryUpgradedClientStateResponse, QueryUpgradedConsensusStateRequest, QueryUpgradedConsensusStateResponse, QueryVerifyMembershipRequest, QueryVerifyMembershipResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.core.client.v1.Query"; - -/** - * ClientState queries an IBC light client. - * - * @generated from rpc ibc.core.client.v1.Query.ClientState - */ -export const QueryClientStateService = { - typeName: TYPE_NAME, - method: "ClientState", - Request: QueryClientStateRequest, - Response: QueryClientStateResponse, -} as const; - -/** - * ClientStates queries all the IBC light clients of a chain. - * - * @generated from rpc ibc.core.client.v1.Query.ClientStates - */ -export const QueryClientStatesService = { - typeName: TYPE_NAME, - method: "ClientStates", - Request: QueryClientStatesRequest, - Response: QueryClientStatesResponse, -} as const; - -/** - * ConsensusState queries a consensus state associated with a client state at - * a given height. - * - * @generated from rpc ibc.core.client.v1.Query.ConsensusState - */ -export const QueryConsensusStateService = { - typeName: TYPE_NAME, - method: "ConsensusState", - Request: QueryConsensusStateRequest, - Response: QueryConsensusStateResponse, -} as const; - -/** - * ConsensusStates queries all the consensus state associated with a given - * client. - * - * @generated from rpc ibc.core.client.v1.Query.ConsensusStates - */ -export const QueryConsensusStatesService = { - typeName: TYPE_NAME, - method: "ConsensusStates", - Request: QueryConsensusStatesRequest, - Response: QueryConsensusStatesResponse, -} as const; - -/** - * ConsensusStateHeights queries the height of every consensus states associated with a given client. - * - * @generated from rpc ibc.core.client.v1.Query.ConsensusStateHeights - */ -export const QueryConsensusStateHeightsService = { - typeName: TYPE_NAME, - method: "ConsensusStateHeights", - Request: QueryConsensusStateHeightsRequest, - Response: QueryConsensusStateHeightsResponse, -} as const; - -/** - * Status queries the status of an IBC client. - * - * @generated from rpc ibc.core.client.v1.Query.ClientStatus - */ -export const QueryClientStatusService = { - typeName: TYPE_NAME, - method: "ClientStatus", - Request: QueryClientStatusRequest, - Response: QueryClientStatusResponse, -} as const; - -/** - * ClientParams queries all parameters of the ibc client submodule. - * - * @generated from rpc ibc.core.client.v1.Query.ClientParams - */ -export const QueryClientParamsService = { - typeName: TYPE_NAME, - method: "ClientParams", - Request: QueryClientParamsRequest, - Response: QueryClientParamsResponse, -} as const; - -/** - * ClientCreator queries the creator of a given client. - * - * @generated from rpc ibc.core.client.v1.Query.ClientCreator - */ -export const QueryClientCreatorService = { - typeName: TYPE_NAME, - method: "ClientCreator", - Request: QueryClientCreatorRequest, - Response: QueryClientCreatorResponse, -} as const; - -/** - * UpgradedClientState queries an Upgraded IBC light client. - * - * @generated from rpc ibc.core.client.v1.Query.UpgradedClientState - */ -export const QueryUpgradedClientStateService = { - typeName: TYPE_NAME, - method: "UpgradedClientState", - Request: QueryUpgradedClientStateRequest, - Response: QueryUpgradedClientStateResponse, -} as const; - -/** - * UpgradedConsensusState queries an Upgraded IBC consensus state. - * - * @generated from rpc ibc.core.client.v1.Query.UpgradedConsensusState - */ -export const QueryUpgradedConsensusStateService = { - typeName: TYPE_NAME, - method: "UpgradedConsensusState", - Request: QueryUpgradedConsensusStateRequest, - Response: QueryUpgradedConsensusStateResponse, -} as const; - -/** - * VerifyMembership queries an IBC light client for proof verification of a value at a given key path. - * - * @generated from rpc ibc.core.client.v1.Query.VerifyMembership - */ -export const QueryVerifyMembershipService = { - typeName: TYPE_NAME, - method: "VerifyMembership", - Request: QueryVerifyMembershipRequest, - Response: QueryVerifyMembershipResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/query_pb.ts b/packages/es/src/protobufs/ibc/core/client/v1/query_pb.ts deleted file mode 100644 index ddd7bdde0..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/query_pb.ts +++ /dev/null @@ -1,1054 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v1/query.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ConsensusStateWithHeight, Height, IdentifiedClientState, Params } from "./client_pb.js"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { MerklePath } from "../../commitment/v2/commitment_pb.js"; - -/** - * QueryClientStateRequest is the request type for the Query/ClientState RPC - * method - * - * @generated from message ibc.core.client.v1.QueryClientStateRequest - */ -export class QueryClientStateRequest extends Message { - /** - * client state unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStateRequest { - return new QueryClientStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStateRequest { - return new QueryClientStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStateRequest { - return new QueryClientStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStateRequest | PlainMessage | undefined, b: QueryClientStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStateRequest, a, b); - } -} - -/** - * QueryClientStateResponse is the response type for the Query/ClientState RPC - * method. Besides the client state, it includes a proof and the height from - * which the proof was retrieved. - * - * @generated from message ibc.core.client.v1.QueryClientStateResponse - */ -export class QueryClientStateResponse extends Message { - /** - * client state associated with the request identifier - * - * @generated from field: google.protobuf.Any client_state = 1; - */ - clientState?: Any; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_state", kind: "message", T: Any }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStateResponse { - return new QueryClientStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStateResponse { - return new QueryClientStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStateResponse { - return new QueryClientStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStateResponse | PlainMessage | undefined, b: QueryClientStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStateResponse, a, b); - } -} - -/** - * QueryClientStatesRequest is the request type for the Query/ClientStates RPC - * method - * - * @generated from message ibc.core.client.v1.QueryClientStatesRequest - */ -export class QueryClientStatesRequest extends Message { - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStatesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStatesRequest { - return new QueryClientStatesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStatesRequest { - return new QueryClientStatesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStatesRequest { - return new QueryClientStatesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStatesRequest | PlainMessage | undefined, b: QueryClientStatesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStatesRequest, a, b); - } -} - -/** - * QueryClientStatesResponse is the response type for the Query/ClientStates RPC - * method. - * - * @generated from message ibc.core.client.v1.QueryClientStatesResponse - */ -export class QueryClientStatesResponse extends Message { - /** - * list of stored ClientStates of the chain. - * - * @generated from field: repeated ibc.core.client.v1.IdentifiedClientState client_states = 1; - */ - clientStates: IdentifiedClientState[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStatesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_states", kind: "message", T: IdentifiedClientState, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStatesResponse { - return new QueryClientStatesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStatesResponse { - return new QueryClientStatesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStatesResponse { - return new QueryClientStatesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStatesResponse | PlainMessage | undefined, b: QueryClientStatesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStatesResponse, a, b); - } -} - -/** - * QueryConsensusStateRequest is the request type for the Query/ConsensusState - * RPC method. Besides the consensus state, it includes a proof and the height - * from which the proof was retrieved. - * - * @generated from message ibc.core.client.v1.QueryConsensusStateRequest - */ -export class QueryConsensusStateRequest extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * consensus state revision number - * - * @generated from field: uint64 revision_number = 2; - */ - revisionNumber = protoInt64.zero; - - /** - * consensus state revision height - * - * @generated from field: uint64 revision_height = 3; - */ - revisionHeight = protoInt64.zero; - - /** - * latest_height overrides the height field and queries the latest stored - * ConsensusState - * - * @generated from field: bool latest_height = 4; - */ - latestHeight = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "revision_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "revision_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "latest_height", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStateRequest { - return new QueryConsensusStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStateRequest { - return new QueryConsensusStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStateRequest { - return new QueryConsensusStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStateRequest | PlainMessage | undefined, b: QueryConsensusStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStateRequest, a, b); - } -} - -/** - * QueryConsensusStateResponse is the response type for the Query/ConsensusState - * RPC method - * - * @generated from message ibc.core.client.v1.QueryConsensusStateResponse - */ -export class QueryConsensusStateResponse extends Message { - /** - * consensus state associated with the client identifier at the given height - * - * @generated from field: google.protobuf.Any consensus_state = 1; - */ - consensusState?: Any; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "consensus_state", kind: "message", T: Any }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStateResponse { - return new QueryConsensusStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStateResponse { - return new QueryConsensusStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStateResponse { - return new QueryConsensusStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStateResponse | PlainMessage | undefined, b: QueryConsensusStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStateResponse, a, b); - } -} - -/** - * QueryConsensusStatesRequest is the request type for the Query/ConsensusStates - * RPC method. - * - * @generated from message ibc.core.client.v1.QueryConsensusStatesRequest - */ -export class QueryConsensusStatesRequest extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStatesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStatesRequest { - return new QueryConsensusStatesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStatesRequest { - return new QueryConsensusStatesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStatesRequest { - return new QueryConsensusStatesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStatesRequest | PlainMessage | undefined, b: QueryConsensusStatesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStatesRequest, a, b); - } -} - -/** - * QueryConsensusStatesResponse is the response type for the - * Query/ConsensusStates RPC method - * - * @generated from message ibc.core.client.v1.QueryConsensusStatesResponse - */ -export class QueryConsensusStatesResponse extends Message { - /** - * consensus states associated with the identifier - * - * @generated from field: repeated ibc.core.client.v1.ConsensusStateWithHeight consensus_states = 1; - */ - consensusStates: ConsensusStateWithHeight[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStatesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "consensus_states", kind: "message", T: ConsensusStateWithHeight, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStatesResponse { - return new QueryConsensusStatesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStatesResponse { - return new QueryConsensusStatesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStatesResponse { - return new QueryConsensusStatesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStatesResponse | PlainMessage | undefined, b: QueryConsensusStatesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStatesResponse, a, b); - } -} - -/** - * QueryConsensusStateHeightsRequest is the request type for Query/ConsensusStateHeights - * RPC method. - * - * @generated from message ibc.core.client.v1.QueryConsensusStateHeightsRequest - */ -export class QueryConsensusStateHeightsRequest extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * pagination request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStateHeightsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStateHeightsRequest { - return new QueryConsensusStateHeightsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStateHeightsRequest { - return new QueryConsensusStateHeightsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStateHeightsRequest { - return new QueryConsensusStateHeightsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStateHeightsRequest | PlainMessage | undefined, b: QueryConsensusStateHeightsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStateHeightsRequest, a, b); - } -} - -/** - * QueryConsensusStateHeightsResponse is the response type for the - * Query/ConsensusStateHeights RPC method - * - * @generated from message ibc.core.client.v1.QueryConsensusStateHeightsResponse - */ -export class QueryConsensusStateHeightsResponse extends Message { - /** - * consensus state heights - * - * @generated from field: repeated ibc.core.client.v1.Height consensus_state_heights = 1; - */ - consensusStateHeights: Height[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryConsensusStateHeightsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "consensus_state_heights", kind: "message", T: Height, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConsensusStateHeightsResponse { - return new QueryConsensusStateHeightsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConsensusStateHeightsResponse { - return new QueryConsensusStateHeightsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConsensusStateHeightsResponse { - return new QueryConsensusStateHeightsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConsensusStateHeightsResponse | PlainMessage | undefined, b: QueryConsensusStateHeightsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConsensusStateHeightsResponse, a, b); - } -} - -/** - * QueryClientStatusRequest is the request type for the Query/ClientStatus RPC - * method - * - * @generated from message ibc.core.client.v1.QueryClientStatusRequest - */ -export class QueryClientStatusRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStatusRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStatusRequest { - return new QueryClientStatusRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStatusRequest { - return new QueryClientStatusRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStatusRequest { - return new QueryClientStatusRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStatusRequest | PlainMessage | undefined, b: QueryClientStatusRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStatusRequest, a, b); - } -} - -/** - * QueryClientStatusResponse is the response type for the Query/ClientStatus RPC - * method. It returns the current status of the IBC client. - * - * @generated from message ibc.core.client.v1.QueryClientStatusResponse - */ -export class QueryClientStatusResponse extends Message { - /** - * @generated from field: string status = 1; - */ - status = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientStatusResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "status", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientStatusResponse { - return new QueryClientStatusResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientStatusResponse { - return new QueryClientStatusResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientStatusResponse { - return new QueryClientStatusResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientStatusResponse | PlainMessage | undefined, b: QueryClientStatusResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientStatusResponse, a, b); - } -} - -/** - * QueryClientParamsRequest is the request type for the Query/ClientParams RPC - * method. - * - * @generated from message ibc.core.client.v1.QueryClientParamsRequest - */ -export class QueryClientParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientParamsRequest { - return new QueryClientParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientParamsRequest { - return new QueryClientParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientParamsRequest { - return new QueryClientParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientParamsRequest | PlainMessage | undefined, b: QueryClientParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientParamsRequest, a, b); - } -} - -/** - * QueryClientParamsResponse is the response type for the Query/ClientParams RPC - * method. - * - * @generated from message ibc.core.client.v1.QueryClientParamsResponse - */ -export class QueryClientParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: ibc.core.client.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientParamsResponse { - return new QueryClientParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientParamsResponse { - return new QueryClientParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientParamsResponse { - return new QueryClientParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientParamsResponse | PlainMessage | undefined, b: QueryClientParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientParamsResponse, a, b); - } -} - -/** - * QueryClientCreatorRequest is the request type for the Query/ClientCreator RPC - * method. - * - * @generated from message ibc.core.client.v1.QueryClientCreatorRequest - */ -export class QueryClientCreatorRequest extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientCreatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientCreatorRequest { - return new QueryClientCreatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientCreatorRequest { - return new QueryClientCreatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientCreatorRequest { - return new QueryClientCreatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientCreatorRequest | PlainMessage | undefined, b: QueryClientCreatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientCreatorRequest, a, b); - } -} - -/** - * QueryClientCreatorResponse is the response type for the Query/ClientCreator RPC - * method. - * - * @generated from message ibc.core.client.v1.QueryClientCreatorResponse - */ -export class QueryClientCreatorResponse extends Message { - /** - * creator of the client - * - * @generated from field: string creator = 1; - */ - creator = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryClientCreatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientCreatorResponse { - return new QueryClientCreatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientCreatorResponse { - return new QueryClientCreatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientCreatorResponse { - return new QueryClientCreatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientCreatorResponse | PlainMessage | undefined, b: QueryClientCreatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientCreatorResponse, a, b); - } -} - -/** - * QueryUpgradedClientStateRequest is the request type for the - * Query/UpgradedClientState RPC method - * - * @generated from message ibc.core.client.v1.QueryUpgradedClientStateRequest - */ -export class QueryUpgradedClientStateRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryUpgradedClientStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUpgradedClientStateRequest { - return new QueryUpgradedClientStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUpgradedClientStateRequest { - return new QueryUpgradedClientStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUpgradedClientStateRequest { - return new QueryUpgradedClientStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUpgradedClientStateRequest | PlainMessage | undefined, b: QueryUpgradedClientStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUpgradedClientStateRequest, a, b); - } -} - -/** - * QueryUpgradedClientStateResponse is the response type for the - * Query/UpgradedClientState RPC method. - * - * @generated from message ibc.core.client.v1.QueryUpgradedClientStateResponse - */ -export class QueryUpgradedClientStateResponse extends Message { - /** - * client state associated with the request identifier - * - * @generated from field: google.protobuf.Any upgraded_client_state = 1; - */ - upgradedClientState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryUpgradedClientStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "upgraded_client_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUpgradedClientStateResponse { - return new QueryUpgradedClientStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUpgradedClientStateResponse { - return new QueryUpgradedClientStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUpgradedClientStateResponse { - return new QueryUpgradedClientStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUpgradedClientStateResponse | PlainMessage | undefined, b: QueryUpgradedClientStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUpgradedClientStateResponse, a, b); - } -} - -/** - * QueryUpgradedConsensusStateRequest is the request type for the - * Query/UpgradedConsensusState RPC method - * - * @generated from message ibc.core.client.v1.QueryUpgradedConsensusStateRequest - */ -export class QueryUpgradedConsensusStateRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryUpgradedConsensusStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUpgradedConsensusStateRequest { - return new QueryUpgradedConsensusStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUpgradedConsensusStateRequest { - return new QueryUpgradedConsensusStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUpgradedConsensusStateRequest { - return new QueryUpgradedConsensusStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUpgradedConsensusStateRequest | PlainMessage | undefined, b: QueryUpgradedConsensusStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUpgradedConsensusStateRequest, a, b); - } -} - -/** - * QueryUpgradedConsensusStateResponse is the response type for the - * Query/UpgradedConsensusState RPC method. - * - * @generated from message ibc.core.client.v1.QueryUpgradedConsensusStateResponse - */ -export class QueryUpgradedConsensusStateResponse extends Message { - /** - * Consensus state associated with the request identifier - * - * @generated from field: google.protobuf.Any upgraded_consensus_state = 1; - */ - upgradedConsensusState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryUpgradedConsensusStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "upgraded_consensus_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUpgradedConsensusStateResponse { - return new QueryUpgradedConsensusStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUpgradedConsensusStateResponse { - return new QueryUpgradedConsensusStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUpgradedConsensusStateResponse { - return new QueryUpgradedConsensusStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUpgradedConsensusStateResponse | PlainMessage | undefined, b: QueryUpgradedConsensusStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUpgradedConsensusStateResponse, a, b); - } -} - -/** - * QueryVerifyMembershipRequest is the request type for the Query/VerifyMembership RPC method - * - * @generated from message ibc.core.client.v1.QueryVerifyMembershipRequest - */ -export class QueryVerifyMembershipRequest extends Message { - /** - * client unique identifier. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * the proof to be verified by the client. - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * the height of the commitment root at which the proof is verified. - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * the value which is proven. - * - * @generated from field: bytes value = 5; - */ - value = new Uint8Array(0); - - /** - * optional time delay - * - * @generated from field: uint64 time_delay = 6; - */ - timeDelay = protoInt64.zero; - - /** - * optional block delay - * - * @generated from field: uint64 block_delay = 7; - */ - blockDelay = protoInt64.zero; - - /** - * the commitment key path. - * - * @generated from field: ibc.core.commitment.v2.MerklePath merkle_path = 8; - */ - merklePath?: MerklePath; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryVerifyMembershipRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 5, name: "value", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "time_delay", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "block_delay", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 8, name: "merkle_path", kind: "message", T: MerklePath }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVerifyMembershipRequest { - return new QueryVerifyMembershipRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVerifyMembershipRequest { - return new QueryVerifyMembershipRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVerifyMembershipRequest { - return new QueryVerifyMembershipRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryVerifyMembershipRequest | PlainMessage | undefined, b: QueryVerifyMembershipRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVerifyMembershipRequest, a, b); - } -} - -/** - * QueryVerifyMembershipResponse is the response type for the Query/VerifyMembership RPC method - * - * @generated from message ibc.core.client.v1.QueryVerifyMembershipResponse - */ -export class QueryVerifyMembershipResponse extends Message { - /** - * boolean indicating success or failure of proof verification. - * - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.QueryVerifyMembershipResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryVerifyMembershipResponse { - return new QueryVerifyMembershipResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryVerifyMembershipResponse { - return new QueryVerifyMembershipResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryVerifyMembershipResponse { - return new QueryVerifyMembershipResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryVerifyMembershipResponse | PlainMessage | undefined, b: QueryVerifyMembershipResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryVerifyMembershipResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/core/client/v1/tx_cosmes.ts deleted file mode 100644 index c8f2d8864..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/tx_cosmes.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/client/v1/tx.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCreateClient, MsgCreateClientResponse, MsgDeleteClientCreator, MsgDeleteClientCreatorResponse, MsgIBCSoftwareUpgrade, MsgIBCSoftwareUpgradeResponse, MsgRecoverClient, MsgRecoverClientResponse, MsgUpdateClient, MsgUpdateClientResponse, MsgUpdateParams, MsgUpdateParamsResponse, MsgUpgradeClient, MsgUpgradeClientResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.core.client.v1.Msg"; - -/** - * CreateClient defines a rpc handler method for MsgCreateClient. - * - * @generated from rpc ibc.core.client.v1.Msg.CreateClient - */ -export const MsgCreateClientService = { - typeName: TYPE_NAME, - method: "CreateClient", - Request: MsgCreateClient, - Response: MsgCreateClientResponse, -} as const; - -/** - * UpdateClient defines a rpc handler method for MsgUpdateClient. - * - * @generated from rpc ibc.core.client.v1.Msg.UpdateClient - */ -export const MsgUpdateClientService = { - typeName: TYPE_NAME, - method: "UpdateClient", - Request: MsgUpdateClient, - Response: MsgUpdateClientResponse, -} as const; - -/** - * UpgradeClient defines a rpc handler method for MsgUpgradeClient. - * - * @generated from rpc ibc.core.client.v1.Msg.UpgradeClient - */ -export const MsgUpgradeClientService = { - typeName: TYPE_NAME, - method: "UpgradeClient", - Request: MsgUpgradeClient, - Response: MsgUpgradeClientResponse, -} as const; - -/** - * RecoverClient defines a rpc handler method for MsgRecoverClient. - * - * @generated from rpc ibc.core.client.v1.Msg.RecoverClient - */ -export const MsgRecoverClientService = { - typeName: TYPE_NAME, - method: "RecoverClient", - Request: MsgRecoverClient, - Response: MsgRecoverClientResponse, -} as const; - -/** - * IBCSoftwareUpgrade defines a rpc handler method for MsgIBCSoftwareUpgrade. - * - * @generated from rpc ibc.core.client.v1.Msg.IBCSoftwareUpgrade - */ -export const MsgIBCSoftwareUpgradeService = { - typeName: TYPE_NAME, - method: "IBCSoftwareUpgrade", - Request: MsgIBCSoftwareUpgrade, - Response: MsgIBCSoftwareUpgradeResponse, -} as const; - -/** - * UpdateClientParams defines a rpc handler method for MsgUpdateParams. - * - * @generated from rpc ibc.core.client.v1.Msg.UpdateClientParams - */ -export const MsgUpdateClientParamsService = { - typeName: TYPE_NAME, - method: "UpdateClientParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * DeleteClientCreator defines a rpc handler method for MsgDeleteClientCreator. - * - * @generated from rpc ibc.core.client.v1.Msg.DeleteClientCreator - */ -export const MsgDeleteClientCreatorService = { - typeName: TYPE_NAME, - method: "DeleteClientCreator", - Request: MsgDeleteClientCreator, - Response: MsgDeleteClientCreatorResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/client/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/core/client/v1/tx_pb.ts deleted file mode 100644 index ec51b44c3..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v1/tx_pb.ts +++ /dev/null @@ -1,666 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v1/tx.proto (package ibc.core.client.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3 } from "@bufbuild/protobuf"; -import { Plan } from "../../../../cosmos/upgrade/v1beta1/upgrade_pb.js"; -import { Params } from "./client_pb.js"; - -/** - * MsgCreateClient defines a message to create an IBC client - * - * @generated from message ibc.core.client.v1.MsgCreateClient - */ -export class MsgCreateClient extends Message { - /** - * light client state - * - * @generated from field: google.protobuf.Any client_state = 1; - */ - clientState?: Any; - - /** - * consensus state associated with the client that corresponds to a given - * height. - * - * @generated from field: google.protobuf.Any consensus_state = 2; - */ - consensusState?: Any; - - /** - * signer address - * - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgCreateClient"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_state", kind: "message", T: Any }, - { no: 2, name: "consensus_state", kind: "message", T: Any }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateClient { - return new MsgCreateClient().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateClient { - return new MsgCreateClient().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateClient { - return new MsgCreateClient().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateClient | PlainMessage | undefined, b: MsgCreateClient | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateClient, a, b); - } -} - -/** - * MsgCreateClientResponse defines the Msg/CreateClient response type. - * - * @generated from message ibc.core.client.v1.MsgCreateClientResponse - */ -export class MsgCreateClientResponse extends Message { - /** - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgCreateClientResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateClientResponse { - return new MsgCreateClientResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateClientResponse { - return new MsgCreateClientResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateClientResponse { - return new MsgCreateClientResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateClientResponse | PlainMessage | undefined, b: MsgCreateClientResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateClientResponse, a, b); - } -} - -/** - * MsgUpdateClient defines an sdk.Msg to update a IBC client state using - * the given client message. - * - * @generated from message ibc.core.client.v1.MsgUpdateClient - */ -export class MsgUpdateClient extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * client message to update the light client - * - * @generated from field: google.protobuf.Any client_message = 2; - */ - clientMessage?: Any; - - /** - * signer address - * - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpdateClient"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_message", kind: "message", T: Any }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateClient { - return new MsgUpdateClient().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateClient { - return new MsgUpdateClient().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateClient { - return new MsgUpdateClient().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateClient | PlainMessage | undefined, b: MsgUpdateClient | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateClient, a, b); - } -} - -/** - * MsgUpdateClientResponse defines the Msg/UpdateClient response type. - * - * @generated from message ibc.core.client.v1.MsgUpdateClientResponse - */ -export class MsgUpdateClientResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpdateClientResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateClientResponse { - return new MsgUpdateClientResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateClientResponse { - return new MsgUpdateClientResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateClientResponse { - return new MsgUpdateClientResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateClientResponse | PlainMessage | undefined, b: MsgUpdateClientResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateClientResponse, a, b); - } -} - -/** - * MsgUpgradeClient defines an sdk.Msg to upgrade an IBC client to a new client - * state - * - * @generated from message ibc.core.client.v1.MsgUpgradeClient - */ -export class MsgUpgradeClient extends Message { - /** - * client unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * upgraded client state - * - * @generated from field: google.protobuf.Any client_state = 2; - */ - clientState?: Any; - - /** - * upgraded consensus state, only contains enough information to serve as a - * basis of trust in update logic - * - * @generated from field: google.protobuf.Any consensus_state = 3; - */ - consensusState?: Any; - - /** - * proof that old chain committed to new client - * - * @generated from field: bytes proof_upgrade_client = 4; - */ - proofUpgradeClient = new Uint8Array(0); - - /** - * proof that old chain committed to new consensus state - * - * @generated from field: bytes proof_upgrade_consensus_state = 5; - */ - proofUpgradeConsensusState = new Uint8Array(0); - - /** - * signer address - * - * @generated from field: string signer = 6; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpgradeClient"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_state", kind: "message", T: Any }, - { no: 3, name: "consensus_state", kind: "message", T: Any }, - { no: 4, name: "proof_upgrade_client", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "proof_upgrade_consensus_state", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpgradeClient { - return new MsgUpgradeClient().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpgradeClient { - return new MsgUpgradeClient().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpgradeClient { - return new MsgUpgradeClient().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpgradeClient | PlainMessage | undefined, b: MsgUpgradeClient | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpgradeClient, a, b); - } -} - -/** - * MsgUpgradeClientResponse defines the Msg/UpgradeClient response type. - * - * @generated from message ibc.core.client.v1.MsgUpgradeClientResponse - */ -export class MsgUpgradeClientResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpgradeClientResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpgradeClientResponse { - return new MsgUpgradeClientResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpgradeClientResponse { - return new MsgUpgradeClientResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpgradeClientResponse { - return new MsgUpgradeClientResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpgradeClientResponse | PlainMessage | undefined, b: MsgUpgradeClientResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpgradeClientResponse, a, b); - } -} - -/** - * MsgRecoverClient defines the message used to recover a frozen or expired client. - * - * @generated from message ibc.core.client.v1.MsgRecoverClient - */ -export class MsgRecoverClient extends Message { - /** - * the client identifier for the client to be updated if the proposal passes - * - * @generated from field: string subject_client_id = 1; - */ - subjectClientId = ""; - - /** - * the substitute client identifier for the client which will replace the subject - * client - * - * @generated from field: string substitute_client_id = 2; - */ - substituteClientId = ""; - - /** - * signer address - * - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgRecoverClient"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "subject_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "substitute_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecoverClient { - return new MsgRecoverClient().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecoverClient { - return new MsgRecoverClient().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecoverClient { - return new MsgRecoverClient().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecoverClient | PlainMessage | undefined, b: MsgRecoverClient | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecoverClient, a, b); - } -} - -/** - * MsgRecoverClientResponse defines the Msg/RecoverClient response type. - * - * @generated from message ibc.core.client.v1.MsgRecoverClientResponse - */ -export class MsgRecoverClientResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgRecoverClientResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRecoverClientResponse { - return new MsgRecoverClientResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRecoverClientResponse { - return new MsgRecoverClientResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRecoverClientResponse { - return new MsgRecoverClientResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRecoverClientResponse | PlainMessage | undefined, b: MsgRecoverClientResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRecoverClientResponse, a, b); - } -} - -/** - * MsgIBCSoftwareUpgrade defines the message used to schedule an upgrade of an IBC client using a v1 governance proposal - * - * @generated from message ibc.core.client.v1.MsgIBCSoftwareUpgrade - */ -export class MsgIBCSoftwareUpgrade extends Message { - /** - * @generated from field: cosmos.upgrade.v1beta1.Plan plan = 1; - */ - plan?: Plan; - - /** - * An UpgradedClientState must be provided to perform an IBC breaking upgrade. - * This will make the chain commit to the correct upgraded (self) client state - * before the upgrade occurs, so that connecting chains can verify that the - * new upgraded client is valid by verifying a proof on the previous version - * of the chain. This will allow IBC connections to persist smoothly across - * planned chain upgrades. Correspondingly, the UpgradedClientState field has been - * deprecated in the Cosmos SDK to allow for this logic to exist solely in - * the 02-client module. - * - * @generated from field: google.protobuf.Any upgraded_client_state = 2; - */ - upgradedClientState?: Any; - - /** - * signer address - * - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgIBCSoftwareUpgrade"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "plan", kind: "message", T: Plan }, - { no: 2, name: "upgraded_client_state", kind: "message", T: Any }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCSoftwareUpgrade { - return new MsgIBCSoftwareUpgrade().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCSoftwareUpgrade { - return new MsgIBCSoftwareUpgrade().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCSoftwareUpgrade { - return new MsgIBCSoftwareUpgrade().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCSoftwareUpgrade | PlainMessage | undefined, b: MsgIBCSoftwareUpgrade | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCSoftwareUpgrade, a, b); - } -} - -/** - * MsgIBCSoftwareUpgradeResponse defines the Msg/IBCSoftwareUpgrade response type. - * - * @generated from message ibc.core.client.v1.MsgIBCSoftwareUpgradeResponse - */ -export class MsgIBCSoftwareUpgradeResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgIBCSoftwareUpgradeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgIBCSoftwareUpgradeResponse { - return new MsgIBCSoftwareUpgradeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgIBCSoftwareUpgradeResponse { - return new MsgIBCSoftwareUpgradeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgIBCSoftwareUpgradeResponse { - return new MsgIBCSoftwareUpgradeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgIBCSoftwareUpgradeResponse | PlainMessage | undefined, b: MsgIBCSoftwareUpgradeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgIBCSoftwareUpgradeResponse, a, b); - } -} - -/** - * MsgUpdateParams defines the sdk.Msg type to update the client parameters. - * - * @generated from message ibc.core.client.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * params defines the client parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: ibc.core.client.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the MsgUpdateParams response type. - * - * @generated from message ibc.core.client.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgDeleteClientCreator defines a message to delete the client creator of a client - * - * @generated from message ibc.core.client.v1.MsgDeleteClientCreator - */ -export class MsgDeleteClientCreator extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * signer address - * - * @generated from field: string signer = 2; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgDeleteClientCreator"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDeleteClientCreator { - return new MsgDeleteClientCreator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDeleteClientCreator { - return new MsgDeleteClientCreator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDeleteClientCreator { - return new MsgDeleteClientCreator().fromJsonString(jsonString, options); - } - - static equals(a: MsgDeleteClientCreator | PlainMessage | undefined, b: MsgDeleteClientCreator | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDeleteClientCreator, a, b); - } -} - -/** - * MsgDeleteClientCreatorResponse defines the Msg/DeleteClientCreator response type. - * - * @generated from message ibc.core.client.v1.MsgDeleteClientCreatorResponse - */ -export class MsgDeleteClientCreatorResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v1.MsgDeleteClientCreatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDeleteClientCreatorResponse { - return new MsgDeleteClientCreatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDeleteClientCreatorResponse { - return new MsgDeleteClientCreatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDeleteClientCreatorResponse { - return new MsgDeleteClientCreatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgDeleteClientCreatorResponse | PlainMessage | undefined, b: MsgDeleteClientCreatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDeleteClientCreatorResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/config_pb.ts b/packages/es/src/protobufs/ibc/core/client/v2/config_pb.ts deleted file mode 100644 index 2da502405..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/config_pb.ts +++ /dev/null @@ -1,52 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v2/config.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Config is a **per-client** configuration struct that sets which relayers are allowed to relay v2 IBC messages - * for a given client. - * If it is set, then only relayers in the allow list can send v2 messages - * If it is not set, then the client allows permissionless relaying of v2 messages - * - * @generated from message ibc.core.client.v2.Config - */ -export class Config extends Message { - /** - * allowed_relayers defines the set of allowed relayers for IBC V2 protocol for the given client - * - * @generated from field: repeated string allowed_relayers = 1; - */ - allowedRelayers: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.Config"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "allowed_relayers", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Config { - return new Config().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Config { - return new Config().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Config { - return new Config().fromJsonString(jsonString, options); - } - - static equals(a: Config | PlainMessage | undefined, b: Config | PlainMessage | undefined): boolean { - return proto3.util.equals(Config, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/counterparty_pb.ts b/packages/es/src/protobufs/ibc/core/client/v2/counterparty_pb.ts deleted file mode 100644 index e9dca296e..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/counterparty_pb.ts +++ /dev/null @@ -1,57 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v2/counterparty.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * CounterpartyInfo defines the key that the counterparty will use to message our client - * - * @generated from message ibc.core.client.v2.CounterpartyInfo - */ -export class CounterpartyInfo extends Message { - /** - * merkle prefix key is the prefix that ics provable keys are stored under - * - * @generated from field: repeated bytes merkle_prefix = 1; - */ - merklePrefix: Uint8Array[] = []; - - /** - * client identifier is the identifier used to send packet messages to our client - * - * @generated from field: string client_id = 2; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.CounterpartyInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "merkle_prefix", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - { no: 2, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CounterpartyInfo { - return new CounterpartyInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CounterpartyInfo { - return new CounterpartyInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CounterpartyInfo { - return new CounterpartyInfo().fromJsonString(jsonString, options); - } - - static equals(a: CounterpartyInfo | PlainMessage | undefined, b: CounterpartyInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(CounterpartyInfo, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/client/v2/genesis_pb.ts deleted file mode 100644 index 60826e72f..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/genesis_pb.ts +++ /dev/null @@ -1,99 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v2/genesis.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { CounterpartyInfo } from "./counterparty_pb.js"; - -/** - * GenesisCounterpartyInfo defines the state associating a client with a counterparty. - * - * @generated from message ibc.core.client.v2.GenesisCounterpartyInfo - */ -export class GenesisCounterpartyInfo extends Message { - /** - * ClientId is the ID of the given client. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * CounterpartyInfo is the counterparty info of the given client. - * - * @generated from field: ibc.core.client.v2.CounterpartyInfo counterparty_info = 2; - */ - counterpartyInfo?: CounterpartyInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.GenesisCounterpartyInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "counterparty_info", kind: "message", T: CounterpartyInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisCounterpartyInfo { - return new GenesisCounterpartyInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisCounterpartyInfo { - return new GenesisCounterpartyInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisCounterpartyInfo { - return new GenesisCounterpartyInfo().fromJsonString(jsonString, options); - } - - static equals(a: GenesisCounterpartyInfo | PlainMessage | undefined, b: GenesisCounterpartyInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisCounterpartyInfo, a, b); - } -} - -/** - * GenesisState defines the ibc client v2 submodule's genesis state. - * - * @generated from message ibc.core.client.v2.GenesisState - */ -export class GenesisState extends Message { - /** - * counterparty info for each client - * - * @generated from field: repeated ibc.core.client.v2.GenesisCounterpartyInfo counterparty_infos = 1; - */ - counterpartyInfos: GenesisCounterpartyInfo[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "counterparty_infos", kind: "message", T: GenesisCounterpartyInfo, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/query_cosmes.ts b/packages/es/src/protobufs/ibc/core/client/v2/query_cosmes.ts deleted file mode 100644 index 9a3a67d4b..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/query_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/client/v2/query.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryConfigRequest, QueryConfigResponse, QueryCounterpartyInfoRequest, QueryCounterpartyInfoResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.core.client.v2.Query"; - -/** - * CounterpartyInfo queries an IBC light counter party info. - * - * @generated from rpc ibc.core.client.v2.Query.CounterpartyInfo - */ -export const QueryCounterpartyInfoService = { - typeName: TYPE_NAME, - method: "CounterpartyInfo", - Request: QueryCounterpartyInfoRequest, - Response: QueryCounterpartyInfoResponse, -} as const; - -/** - * Config queries the IBC client v2 configuration for a given client. - * - * @generated from rpc ibc.core.client.v2.Query.Config - */ -export const QueryConfigService = { - typeName: TYPE_NAME, - method: "Config", - Request: QueryConfigRequest, - Response: QueryConfigResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/query_pb.ts b/packages/es/src/protobufs/ibc/core/client/v2/query_pb.ts deleted file mode 100644 index 059b0c39d..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/query_pb.ts +++ /dev/null @@ -1,172 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v2/query.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { CounterpartyInfo } from "./counterparty_pb.js"; -import { Config } from "./config_pb.js"; - -/** - * QueryCounterpartyInfoRequest is the request type for the Query/CounterpartyInfo RPC - * method - * - * @generated from message ibc.core.client.v2.QueryCounterpartyInfoRequest - */ -export class QueryCounterpartyInfoRequest extends Message { - /** - * client state unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.QueryCounterpartyInfoRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCounterpartyInfoRequest { - return new QueryCounterpartyInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCounterpartyInfoRequest { - return new QueryCounterpartyInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCounterpartyInfoRequest { - return new QueryCounterpartyInfoRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCounterpartyInfoRequest | PlainMessage | undefined, b: QueryCounterpartyInfoRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCounterpartyInfoRequest, a, b); - } -} - -/** - * QueryCounterpartyInfoResponse is the response type for the - * Query/CounterpartyInfo RPC method. - * - * @generated from message ibc.core.client.v2.QueryCounterpartyInfoResponse - */ -export class QueryCounterpartyInfoResponse extends Message { - /** - * @generated from field: ibc.core.client.v2.CounterpartyInfo counterparty_info = 1; - */ - counterpartyInfo?: CounterpartyInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.QueryCounterpartyInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "counterparty_info", kind: "message", T: CounterpartyInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCounterpartyInfoResponse { - return new QueryCounterpartyInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCounterpartyInfoResponse { - return new QueryCounterpartyInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCounterpartyInfoResponse { - return new QueryCounterpartyInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCounterpartyInfoResponse | PlainMessage | undefined, b: QueryCounterpartyInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCounterpartyInfoResponse, a, b); - } -} - -/** - * QueryConfigRequest is the request type for the Query/Config RPC method - * - * @generated from message ibc.core.client.v2.QueryConfigRequest - */ -export class QueryConfigRequest extends Message { - /** - * client state unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.QueryConfigRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConfigRequest { - return new QueryConfigRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConfigRequest { - return new QueryConfigRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConfigRequest { - return new QueryConfigRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConfigRequest | PlainMessage | undefined, b: QueryConfigRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConfigRequest, a, b); - } -} - -/** - * QueryConfigResponse is the response type for the Query/Config RPC method - * - * @generated from message ibc.core.client.v2.QueryConfigResponse - */ -export class QueryConfigResponse extends Message { - /** - * @generated from field: ibc.core.client.v2.Config config = 1; - */ - config?: Config; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.QueryConfigResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "config", kind: "message", T: Config }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConfigResponse { - return new QueryConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConfigResponse { - return new QueryConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConfigResponse { - return new QueryConfigResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConfigResponse | PlainMessage | undefined, b: QueryConfigResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConfigResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/tx_cosmes.ts b/packages/es/src/protobufs/ibc/core/client/v2/tx_cosmes.ts deleted file mode 100644 index 78ea56d8a..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/tx_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/client/v2/tx.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgRegisterCounterparty, MsgRegisterCounterpartyResponse, MsgUpdateClientConfig, MsgUpdateClientConfigResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.core.client.v2.Msg"; - -/** - * RegisterCounterparty defines a rpc handler method for MsgRegisterCounterparty. - * - * @generated from rpc ibc.core.client.v2.Msg.RegisterCounterparty - */ -export const MsgRegisterCounterpartyService = { - typeName: TYPE_NAME, - method: "RegisterCounterparty", - Request: MsgRegisterCounterparty, - Response: MsgRegisterCounterpartyResponse, -} as const; - -/** - * UpdateClientConfig defines a rpc handler method for MsgUpdateClientConfig. - * - * @generated from rpc ibc.core.client.v2.Msg.UpdateClientConfig - */ -export const MsgUpdateClientConfigService = { - typeName: TYPE_NAME, - method: "UpdateClientConfig", - Request: MsgUpdateClientConfig, - Response: MsgUpdateClientConfigResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/client/v2/tx_pb.ts b/packages/es/src/protobufs/ibc/core/client/v2/tx_pb.ts deleted file mode 100644 index cfa02a633..000000000 --- a/packages/es/src/protobufs/ibc/core/client/v2/tx_pb.ts +++ /dev/null @@ -1,199 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/client/v2/tx.proto (package ibc.core.client.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Config } from "./config_pb.js"; - -/** - * MsgRegisterCounterparty defines a message to register a counterparty on a client - * - * @generated from message ibc.core.client.v2.MsgRegisterCounterparty - */ -export class MsgRegisterCounterparty extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * counterparty merkle prefix - * - * @generated from field: repeated bytes counterparty_merkle_prefix = 2; - */ - counterpartyMerklePrefix: Uint8Array[] = []; - - /** - * counterparty client identifier - * - * @generated from field: string counterparty_client_id = 3; - */ - counterpartyClientId = ""; - - /** - * signer address - * - * @generated from field: string signer = 4; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.MsgRegisterCounterparty"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "counterparty_merkle_prefix", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - { no: 3, name: "counterparty_client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterCounterparty { - return new MsgRegisterCounterparty().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterCounterparty { - return new MsgRegisterCounterparty().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterCounterparty { - return new MsgRegisterCounterparty().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterCounterparty | PlainMessage | undefined, b: MsgRegisterCounterparty | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterCounterparty, a, b); - } -} - -/** - * MsgRegisterCounterpartyResponse defines the Msg/RegisterCounterparty response type. - * - * @generated from message ibc.core.client.v2.MsgRegisterCounterpartyResponse - */ -export class MsgRegisterCounterpartyResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.MsgRegisterCounterpartyResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterCounterpartyResponse { - return new MsgRegisterCounterpartyResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterCounterpartyResponse { - return new MsgRegisterCounterpartyResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterCounterpartyResponse { - return new MsgRegisterCounterpartyResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterCounterpartyResponse | PlainMessage | undefined, b: MsgRegisterCounterpartyResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterCounterpartyResponse, a, b); - } -} - -/** - * MsgUpdateClientConfig defines the sdk.Msg type to update the configuration for a given client - * - * @generated from message ibc.core.client.v2.MsgUpdateClientConfig - */ -export class MsgUpdateClientConfig extends Message { - /** - * client identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * allowed relayers - * - * NOTE: All fields in the config must be supplied. - * - * @generated from field: ibc.core.client.v2.Config config = 2; - */ - config?: Config; - - /** - * signer address - * - * @generated from field: string signer = 3; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.MsgUpdateClientConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "config", kind: "message", T: Config }, - { no: 3, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateClientConfig { - return new MsgUpdateClientConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateClientConfig { - return new MsgUpdateClientConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateClientConfig { - return new MsgUpdateClientConfig().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateClientConfig | PlainMessage | undefined, b: MsgUpdateClientConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateClientConfig, a, b); - } -} - -/** - * MsgUpdateClientConfigResponse defines the MsgUpdateClientConfig response type. - * - * @generated from message ibc.core.client.v2.MsgUpdateClientConfigResponse - */ -export class MsgUpdateClientConfigResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.client.v2.MsgUpdateClientConfigResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateClientConfigResponse { - return new MsgUpdateClientConfigResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateClientConfigResponse { - return new MsgUpdateClientConfigResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateClientConfigResponse { - return new MsgUpdateClientConfigResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateClientConfigResponse | PlainMessage | undefined, b: MsgUpdateClientConfigResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateClientConfigResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/commitment/v1/commitment_pb.ts b/packages/es/src/protobufs/ibc/core/commitment/v1/commitment_pb.ts deleted file mode 100644 index 7261f96be..000000000 --- a/packages/es/src/protobufs/ibc/core/commitment/v1/commitment_pb.ts +++ /dev/null @@ -1,133 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/commitment/v1/commitment.proto (package ibc.core.commitment.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { CommitmentProof } from "../../../../cosmos/ics23/v1/proofs_pb.js"; - -/** - * MerkleRoot defines a merkle root hash. - * In the Cosmos SDK, the AppHash of a block header becomes the root. - * - * @generated from message ibc.core.commitment.v1.MerkleRoot - */ -export class MerkleRoot extends Message { - /** - * @generated from field: bytes hash = 1; - */ - hash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.commitment.v1.MerkleRoot"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MerkleRoot { - return new MerkleRoot().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MerkleRoot { - return new MerkleRoot().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MerkleRoot { - return new MerkleRoot().fromJsonString(jsonString, options); - } - - static equals(a: MerkleRoot | PlainMessage | undefined, b: MerkleRoot | PlainMessage | undefined): boolean { - return proto3.util.equals(MerkleRoot, a, b); - } -} - -/** - * MerklePrefix is merkle path prefixed to the key. - * The constructed key from the Path and the key will be append(Path.KeyPath, - * append(Path.KeyPrefix, key...)) - * - * @generated from message ibc.core.commitment.v1.MerklePrefix - */ -export class MerklePrefix extends Message { - /** - * @generated from field: bytes key_prefix = 1; - */ - keyPrefix = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.commitment.v1.MerklePrefix"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key_prefix", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MerklePrefix { - return new MerklePrefix().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MerklePrefix { - return new MerklePrefix().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MerklePrefix { - return new MerklePrefix().fromJsonString(jsonString, options); - } - - static equals(a: MerklePrefix | PlainMessage | undefined, b: MerklePrefix | PlainMessage | undefined): boolean { - return proto3.util.equals(MerklePrefix, a, b); - } -} - -/** - * MerkleProof is a wrapper type over a chain of CommitmentProofs. - * It demonstrates membership or non-membership for an element or set of - * elements, verifiable in conjunction with a known commitment root. Proofs - * should be succinct. - * MerkleProofs are ordered from leaf-to-root - * - * @generated from message ibc.core.commitment.v1.MerkleProof - */ -export class MerkleProof extends Message { - /** - * @generated from field: repeated cosmos.ics23.v1.CommitmentProof proofs = 1; - */ - proofs: CommitmentProof[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.commitment.v1.MerkleProof"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "proofs", kind: "message", T: CommitmentProof, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MerkleProof { - return new MerkleProof().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MerkleProof { - return new MerkleProof().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MerkleProof { - return new MerkleProof().fromJsonString(jsonString, options); - } - - static equals(a: MerkleProof | PlainMessage | undefined, b: MerkleProof | PlainMessage | undefined): boolean { - return proto3.util.equals(MerkleProof, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/commitment/v2/commitment_pb.ts b/packages/es/src/protobufs/ibc/core/commitment/v2/commitment_pb.ts deleted file mode 100644 index 4b04871c8..000000000 --- a/packages/es/src/protobufs/ibc/core/commitment/v2/commitment_pb.ts +++ /dev/null @@ -1,77 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/commitment/v2/commitment.proto (package ibc.core.commitment.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * MerklePath is the path used to verify commitment proofs, which can be an - * arbitrary structured object (defined by a commitment type). - * ICS-23 verification supports membership proofs for nested merkle trees. - * The ICS-24 standard provable keys MUST be stored in the lowest level tree with an optional prefix. - * The IC24 provable tree may then be stored in a higher level tree(s) that hash up to the root hash - * stored in the consensus state of the client. - * Each element of the path represents the key of a merkle tree from the root to the leaf. - * The elements of the path before the final element must be the path to the tree that contains - * the ICS24 provable store. Thus, it should remain constant for all ICS24 proofs. - * The final element of the path is the key of the leaf in the ICS24 provable store, - * Thus IBC core will append the ICS24 path to the final element of the MerklePath - * stored in the counterparty to create the full path to the leaf for proof verification. - * Examples: - * Cosmos SDK: - * The Cosmos SDK commits to a multi-tree where each store is an IAVL tree and all store hashes - * are hashed in a simple merkle tree to get the final root hash. Thus, the MerklePath in the counterparty - * MerklePrefix has the following structure: ["ibc", ""] - * The core IBC handler will append the ICS24 path to the final element of the MerklePath - * like so: ["ibc", "{packetCommitmentPath}"] which will then be used for final verification. - * Ethereum: - * The Ethereum client commits to a single Patricia merkle trie. The ICS24 provable store is managed - * by the smart contract state. Each smart contract has a specific prefix reserved within the global trie. - * Thus the MerklePath in the counterparty is the prefix to the smart contract state in the global trie. - * Since there is only one tree in the commitment structure of ethereum the MerklePath in the counterparty - * MerklePrefix has the following structure: ["IBCCoreContractAddressStoragePrefix"] - * The core IBC handler will append the ICS24 path to the final element of the MerklePath - * like so: ["IBCCoreContractAddressStoragePrefix{packetCommitmentPath}"] which will then be used for final - * verification. Thus the MerklePath in the counterparty MerklePrefix is the nested key path from the root hash of the - * consensus state down to the ICS24 provable store. The IBC handler retrieves the counterparty key path to the ICS24 - * provable store from the MerklePath and appends the ICS24 path to get the final key path to the value being verified - * by the client against the root hash in the client's consensus state. - * - * @generated from message ibc.core.commitment.v2.MerklePath - */ -export class MerklePath extends Message { - /** - * @generated from field: repeated bytes key_path = 1; - */ - keyPath: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.commitment.v2.MerklePath"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "key_path", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MerklePath { - return new MerklePath().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MerklePath { - return new MerklePath().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MerklePath { - return new MerklePath().fromJsonString(jsonString, options); - } - - static equals(a: MerklePath | PlainMessage | undefined, b: MerklePath | PlainMessage | undefined): boolean { - return proto3.util.equals(MerklePath, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/connection_pb.ts b/packages/es/src/protobufs/ibc/core/connection/v1/connection_pb.ts deleted file mode 100644 index dd19dd665..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/connection_pb.ts +++ /dev/null @@ -1,457 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/connection.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { MerklePrefix } from "../../commitment/v1/commitment_pb.js"; - -/** - * State defines if a connection is in one of the following states: - * INIT, TRYOPEN, OPEN or UNINITIALIZED. - * - * @generated from enum ibc.core.connection.v1.State - */ -export enum State { - /** - * Default State - * - * @generated from enum value: STATE_UNINITIALIZED_UNSPECIFIED = 0; - */ - UNINITIALIZED_UNSPECIFIED = 0, - - /** - * A connection end has just started the opening handshake. - * - * @generated from enum value: STATE_INIT = 1; - */ - INIT = 1, - - /** - * A connection end has acknowledged the handshake step on the counterparty - * chain. - * - * @generated from enum value: STATE_TRYOPEN = 2; - */ - TRYOPEN = 2, - - /** - * A connection end has completed the handshake. - * - * @generated from enum value: STATE_OPEN = 3; - */ - OPEN = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(State) -proto3.util.setEnumType(State, "ibc.core.connection.v1.State", [ - { no: 0, name: "STATE_UNINITIALIZED_UNSPECIFIED" }, - { no: 1, name: "STATE_INIT" }, - { no: 2, name: "STATE_TRYOPEN" }, - { no: 3, name: "STATE_OPEN" }, -]); - -/** - * ConnectionEnd defines a stateful object on a chain connected to another - * separate one. - * NOTE: there must only be 2 defined ConnectionEnds to establish - * a connection between two chains. - * - * @generated from message ibc.core.connection.v1.ConnectionEnd - */ -export class ConnectionEnd extends Message { - /** - * client associated with this connection. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * IBC version which can be utilised to determine encodings or protocols for - * channels or packets utilising this connection. - * - * @generated from field: repeated ibc.core.connection.v1.Version versions = 2; - */ - versions: Version[] = []; - - /** - * current state of the connection end. - * - * @generated from field: ibc.core.connection.v1.State state = 3; - */ - state = State.UNINITIALIZED_UNSPECIFIED; - - /** - * counterparty chain associated with this connection. - * - * @generated from field: ibc.core.connection.v1.Counterparty counterparty = 4; - */ - counterparty?: Counterparty; - - /** - * delay period that must pass before a consensus state can be used for - * packet-verification NOTE: delay period logic is only implemented by some - * clients. - * - * @generated from field: uint64 delay_period = 5; - */ - delayPeriod = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.ConnectionEnd"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "versions", kind: "message", T: Version, repeated: true }, - { no: 3, name: "state", kind: "enum", T: proto3.getEnumType(State) }, - { no: 4, name: "counterparty", kind: "message", T: Counterparty }, - { no: 5, name: "delay_period", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConnectionEnd { - return new ConnectionEnd().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConnectionEnd { - return new ConnectionEnd().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConnectionEnd { - return new ConnectionEnd().fromJsonString(jsonString, options); - } - - static equals(a: ConnectionEnd | PlainMessage | undefined, b: ConnectionEnd | PlainMessage | undefined): boolean { - return proto3.util.equals(ConnectionEnd, a, b); - } -} - -/** - * IdentifiedConnection defines a connection with additional connection - * identifier field. - * - * @generated from message ibc.core.connection.v1.IdentifiedConnection - */ -export class IdentifiedConnection extends Message { - /** - * connection identifier. - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * client associated with this connection. - * - * @generated from field: string client_id = 2; - */ - clientId = ""; - - /** - * IBC version which can be utilised to determine encodings or protocols for - * channels or packets utilising this connection - * - * @generated from field: repeated ibc.core.connection.v1.Version versions = 3; - */ - versions: Version[] = []; - - /** - * current state of the connection end. - * - * @generated from field: ibc.core.connection.v1.State state = 4; - */ - state = State.UNINITIALIZED_UNSPECIFIED; - - /** - * counterparty chain associated with this connection. - * - * @generated from field: ibc.core.connection.v1.Counterparty counterparty = 5; - */ - counterparty?: Counterparty; - - /** - * delay period associated with this connection. - * - * @generated from field: uint64 delay_period = 6; - */ - delayPeriod = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.IdentifiedConnection"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "versions", kind: "message", T: Version, repeated: true }, - { no: 4, name: "state", kind: "enum", T: proto3.getEnumType(State) }, - { no: 5, name: "counterparty", kind: "message", T: Counterparty }, - { no: 6, name: "delay_period", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IdentifiedConnection { - return new IdentifiedConnection().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IdentifiedConnection { - return new IdentifiedConnection().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IdentifiedConnection { - return new IdentifiedConnection().fromJsonString(jsonString, options); - } - - static equals(a: IdentifiedConnection | PlainMessage | undefined, b: IdentifiedConnection | PlainMessage | undefined): boolean { - return proto3.util.equals(IdentifiedConnection, a, b); - } -} - -/** - * Counterparty defines the counterparty chain associated with a connection end. - * - * @generated from message ibc.core.connection.v1.Counterparty - */ -export class Counterparty extends Message { - /** - * identifies the client on the counterparty chain associated with a given - * connection. - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * identifies the connection end on the counterparty chain associated with a - * given connection. - * - * @generated from field: string connection_id = 2; - */ - connectionId = ""; - - /** - * commitment merkle prefix of the counterparty chain. - * - * @generated from field: ibc.core.commitment.v1.MerklePrefix prefix = 3; - */ - prefix?: MerklePrefix; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.Counterparty"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "prefix", kind: "message", T: MerklePrefix }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Counterparty { - return new Counterparty().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Counterparty { - return new Counterparty().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Counterparty { - return new Counterparty().fromJsonString(jsonString, options); - } - - static equals(a: Counterparty | PlainMessage | undefined, b: Counterparty | PlainMessage | undefined): boolean { - return proto3.util.equals(Counterparty, a, b); - } -} - -/** - * ClientPaths define all the connection paths for a client state. - * - * @generated from message ibc.core.connection.v1.ClientPaths - */ -export class ClientPaths extends Message { - /** - * list of connection paths - * - * @generated from field: repeated string paths = 1; - */ - paths: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.ClientPaths"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "paths", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientPaths { - return new ClientPaths().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientPaths { - return new ClientPaths().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientPaths { - return new ClientPaths().fromJsonString(jsonString, options); - } - - static equals(a: ClientPaths | PlainMessage | undefined, b: ClientPaths | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientPaths, a, b); - } -} - -/** - * ConnectionPaths define all the connection paths for a given client state. - * - * @generated from message ibc.core.connection.v1.ConnectionPaths - */ -export class ConnectionPaths extends Message { - /** - * client state unique identifier - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * list of connection paths - * - * @generated from field: repeated string paths = 2; - */ - paths: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.ConnectionPaths"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "paths", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConnectionPaths { - return new ConnectionPaths().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConnectionPaths { - return new ConnectionPaths().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConnectionPaths { - return new ConnectionPaths().fromJsonString(jsonString, options); - } - - static equals(a: ConnectionPaths | PlainMessage | undefined, b: ConnectionPaths | PlainMessage | undefined): boolean { - return proto3.util.equals(ConnectionPaths, a, b); - } -} - -/** - * Version defines the versioning scheme used to negotiate the IBC version in - * the connection handshake. - * - * @generated from message ibc.core.connection.v1.Version - */ -export class Version extends Message { - /** - * unique version identifier - * - * @generated from field: string identifier = 1; - */ - identifier = ""; - - /** - * list of features compatible with the specified identifier - * - * @generated from field: repeated string features = 2; - */ - features: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.Version"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "features", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Version { - return new Version().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Version { - return new Version().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Version { - return new Version().fromJsonString(jsonString, options); - } - - static equals(a: Version | PlainMessage | undefined, b: Version | PlainMessage | undefined): boolean { - return proto3.util.equals(Version, a, b); - } -} - -/** - * Params defines the set of Connection parameters. - * - * @generated from message ibc.core.connection.v1.Params - */ -export class Params extends Message { - /** - * maximum expected time per block (in nanoseconds), used to enforce block delay. This parameter should reflect the - * largest amount of time that the chain might reasonably take to produce the next block under normal operating - * conditions. A safe choice is 3-5x the expected time per block. - * - * @generated from field: uint64 max_expected_time_per_block = 1; - */ - maxExpectedTimePerBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_expected_time_per_block", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/connection/v1/genesis_pb.ts deleted file mode 100644 index 8a479889a..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/genesis_pb.ts +++ /dev/null @@ -1,68 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/genesis.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ConnectionPaths, IdentifiedConnection, Params } from "./connection_pb.js"; - -/** - * GenesisState defines the ibc connection submodule's genesis state. - * - * @generated from message ibc.core.connection.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated ibc.core.connection.v1.IdentifiedConnection connections = 1; - */ - connections: IdentifiedConnection[] = []; - - /** - * @generated from field: repeated ibc.core.connection.v1.ConnectionPaths client_connection_paths = 2; - */ - clientConnectionPaths: ConnectionPaths[] = []; - - /** - * the sequence for the next generated connection identifier - * - * @generated from field: uint64 next_connection_sequence = 3; - */ - nextConnectionSequence = protoInt64.zero; - - /** - * @generated from field: ibc.core.connection.v1.Params params = 4; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connections", kind: "message", T: IdentifiedConnection, repeated: true }, - { no: 2, name: "client_connection_paths", kind: "message", T: ConnectionPaths, repeated: true }, - { no: 3, name: "next_connection_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/core/connection/v1/query_cosmes.ts deleted file mode 100644 index 0a65f866a..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/query_cosmes.ts +++ /dev/null @@ -1,84 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/query.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryClientConnectionsRequest, QueryClientConnectionsResponse, QueryConnectionClientStateRequest, QueryConnectionClientStateResponse, QueryConnectionConsensusStateRequest, QueryConnectionConsensusStateResponse, QueryConnectionParamsRequest, QueryConnectionParamsResponse, QueryConnectionRequest, QueryConnectionResponse, QueryConnectionsRequest, QueryConnectionsResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.core.connection.v1.Query"; - -/** - * Connection queries an IBC connection end. - * - * @generated from rpc ibc.core.connection.v1.Query.Connection - */ -export const QueryConnectionService = { - typeName: TYPE_NAME, - method: "Connection", - Request: QueryConnectionRequest, - Response: QueryConnectionResponse, -} as const; - -/** - * Connections queries all the IBC connections of a chain. - * - * @generated from rpc ibc.core.connection.v1.Query.Connections - */ -export const QueryConnectionsService = { - typeName: TYPE_NAME, - method: "Connections", - Request: QueryConnectionsRequest, - Response: QueryConnectionsResponse, -} as const; - -/** - * ClientConnections queries the connection paths associated with a client - * state. - * - * @generated from rpc ibc.core.connection.v1.Query.ClientConnections - */ -export const QueryClientConnectionsService = { - typeName: TYPE_NAME, - method: "ClientConnections", - Request: QueryClientConnectionsRequest, - Response: QueryClientConnectionsResponse, -} as const; - -/** - * ConnectionClientState queries the client state associated with the - * connection. - * - * @generated from rpc ibc.core.connection.v1.Query.ConnectionClientState - */ -export const QueryConnectionClientStateService = { - typeName: TYPE_NAME, - method: "ConnectionClientState", - Request: QueryConnectionClientStateRequest, - Response: QueryConnectionClientStateResponse, -} as const; - -/** - * ConnectionConsensusState queries the consensus state associated with the - * connection. - * - * @generated from rpc ibc.core.connection.v1.Query.ConnectionConsensusState - */ -export const QueryConnectionConsensusStateService = { - typeName: TYPE_NAME, - method: "ConnectionConsensusState", - Request: QueryConnectionConsensusStateRequest, - Response: QueryConnectionConsensusStateResponse, -} as const; - -/** - * ConnectionParams queries all parameters of the ibc connection submodule. - * - * @generated from rpc ibc.core.connection.v1.Query.ConnectionParams - */ -export const QueryConnectionParamsService = { - typeName: TYPE_NAME, - method: "ConnectionParams", - Request: QueryConnectionParamsRequest, - Response: QueryConnectionParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/query_pb.ts b/packages/es/src/protobufs/ibc/core/connection/v1/query_pb.ts deleted file mode 100644 index 82330dc94..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/query_pb.ts +++ /dev/null @@ -1,604 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/query.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ConnectionEnd, IdentifiedConnection, Params } from "./connection_pb.js"; -import { Height, IdentifiedClientState } from "../../client/v1/client_pb.js"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; - -/** - * QueryConnectionRequest is the request type for the Query/Connection RPC - * method - * - * @generated from message ibc.core.connection.v1.QueryConnectionRequest - */ -export class QueryConnectionRequest extends Message { - /** - * connection unique identifier - * - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionRequest { - return new QueryConnectionRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionRequest { - return new QueryConnectionRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionRequest { - return new QueryConnectionRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionRequest | PlainMessage | undefined, b: QueryConnectionRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionRequest, a, b); - } -} - -/** - * QueryConnectionResponse is the response type for the Query/Connection RPC - * method. Besides the connection end, it includes a proof and the height from - * which the proof was retrieved. - * - * @generated from message ibc.core.connection.v1.QueryConnectionResponse - */ -export class QueryConnectionResponse extends Message { - /** - * connection associated with the request identifier - * - * @generated from field: ibc.core.connection.v1.ConnectionEnd connection = 1; - */ - connection?: ConnectionEnd; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection", kind: "message", T: ConnectionEnd }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionResponse { - return new QueryConnectionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionResponse { - return new QueryConnectionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionResponse { - return new QueryConnectionResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionResponse | PlainMessage | undefined, b: QueryConnectionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionResponse, a, b); - } -} - -/** - * QueryConnectionsRequest is the request type for the Query/Connections RPC - * method - * - * @generated from message ibc.core.connection.v1.QueryConnectionsRequest - */ -export class QueryConnectionsRequest extends Message { - /** - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionsRequest { - return new QueryConnectionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionsRequest { - return new QueryConnectionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionsRequest { - return new QueryConnectionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionsRequest | PlainMessage | undefined, b: QueryConnectionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionsRequest, a, b); - } -} - -/** - * QueryConnectionsResponse is the response type for the Query/Connections RPC - * method. - * - * @generated from message ibc.core.connection.v1.QueryConnectionsResponse - */ -export class QueryConnectionsResponse extends Message { - /** - * list of stored connections of the chain. - * - * @generated from field: repeated ibc.core.connection.v1.IdentifiedConnection connections = 1; - */ - connections: IdentifiedConnection[] = []; - - /** - * pagination response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - /** - * query block height - * - * @generated from field: ibc.core.client.v1.Height height = 3; - */ - height?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connections", kind: "message", T: IdentifiedConnection, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - { no: 3, name: "height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionsResponse { - return new QueryConnectionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionsResponse { - return new QueryConnectionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionsResponse { - return new QueryConnectionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionsResponse | PlainMessage | undefined, b: QueryConnectionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionsResponse, a, b); - } -} - -/** - * QueryClientConnectionsRequest is the request type for the - * Query/ClientConnections RPC method - * - * @generated from message ibc.core.connection.v1.QueryClientConnectionsRequest - */ -export class QueryClientConnectionsRequest extends Message { - /** - * client identifier associated with a connection - * - * @generated from field: string client_id = 1; - */ - clientId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryClientConnectionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientConnectionsRequest { - return new QueryClientConnectionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientConnectionsRequest { - return new QueryClientConnectionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientConnectionsRequest { - return new QueryClientConnectionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientConnectionsRequest | PlainMessage | undefined, b: QueryClientConnectionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientConnectionsRequest, a, b); - } -} - -/** - * QueryClientConnectionsResponse is the response type for the - * Query/ClientConnections RPC method - * - * @generated from message ibc.core.connection.v1.QueryClientConnectionsResponse - */ -export class QueryClientConnectionsResponse extends Message { - /** - * slice of all the connection paths associated with a client. - * - * @generated from field: repeated string connection_paths = 1; - */ - connectionPaths: string[] = []; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was generated - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryClientConnectionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_paths", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryClientConnectionsResponse { - return new QueryClientConnectionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryClientConnectionsResponse { - return new QueryClientConnectionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryClientConnectionsResponse { - return new QueryClientConnectionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryClientConnectionsResponse | PlainMessage | undefined, b: QueryClientConnectionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryClientConnectionsResponse, a, b); - } -} - -/** - * QueryConnectionClientStateRequest is the request type for the - * Query/ConnectionClientState RPC method - * - * @generated from message ibc.core.connection.v1.QueryConnectionClientStateRequest - */ -export class QueryConnectionClientStateRequest extends Message { - /** - * connection identifier - * - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionClientStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionClientStateRequest { - return new QueryConnectionClientStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionClientStateRequest { - return new QueryConnectionClientStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionClientStateRequest { - return new QueryConnectionClientStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionClientStateRequest | PlainMessage | undefined, b: QueryConnectionClientStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionClientStateRequest, a, b); - } -} - -/** - * QueryConnectionClientStateResponse is the response type for the - * Query/ConnectionClientState RPC method - * - * @generated from message ibc.core.connection.v1.QueryConnectionClientStateResponse - */ -export class QueryConnectionClientStateResponse extends Message { - /** - * client state associated with the channel - * - * @generated from field: ibc.core.client.v1.IdentifiedClientState identified_client_state = 1; - */ - identifiedClientState?: IdentifiedClientState; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 2; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionClientStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "identified_client_state", kind: "message", T: IdentifiedClientState }, - { no: 2, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionClientStateResponse { - return new QueryConnectionClientStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionClientStateResponse { - return new QueryConnectionClientStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionClientStateResponse { - return new QueryConnectionClientStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionClientStateResponse | PlainMessage | undefined, b: QueryConnectionClientStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionClientStateResponse, a, b); - } -} - -/** - * QueryConnectionConsensusStateRequest is the request type for the - * Query/ConnectionConsensusState RPC method - * - * @generated from message ibc.core.connection.v1.QueryConnectionConsensusStateRequest - */ -export class QueryConnectionConsensusStateRequest extends Message { - /** - * connection identifier - * - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * @generated from field: uint64 revision_number = 2; - */ - revisionNumber = protoInt64.zero; - - /** - * @generated from field: uint64 revision_height = 3; - */ - revisionHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionConsensusStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "revision_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "revision_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionConsensusStateRequest { - return new QueryConnectionConsensusStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionConsensusStateRequest { - return new QueryConnectionConsensusStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionConsensusStateRequest { - return new QueryConnectionConsensusStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionConsensusStateRequest | PlainMessage | undefined, b: QueryConnectionConsensusStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionConsensusStateRequest, a, b); - } -} - -/** - * QueryConnectionConsensusStateResponse is the response type for the - * Query/ConnectionConsensusState RPC method - * - * @generated from message ibc.core.connection.v1.QueryConnectionConsensusStateResponse - */ -export class QueryConnectionConsensusStateResponse extends Message { - /** - * consensus state associated with the channel - * - * @generated from field: google.protobuf.Any consensus_state = 1; - */ - consensusState?: Any; - - /** - * client ID associated with the consensus state - * - * @generated from field: string client_id = 2; - */ - clientId = ""; - - /** - * merkle proof of existence - * - * @generated from field: bytes proof = 3; - */ - proof = new Uint8Array(0); - - /** - * height at which the proof was retrieved - * - * @generated from field: ibc.core.client.v1.Height proof_height = 4; - */ - proofHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionConsensusStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "consensus_state", kind: "message", T: Any }, - { no: 2, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "proof_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionConsensusStateResponse { - return new QueryConnectionConsensusStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionConsensusStateResponse { - return new QueryConnectionConsensusStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionConsensusStateResponse { - return new QueryConnectionConsensusStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionConsensusStateResponse | PlainMessage | undefined, b: QueryConnectionConsensusStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionConsensusStateResponse, a, b); - } -} - -/** - * QueryConnectionParamsRequest is the request type for the Query/ConnectionParams RPC method. - * - * @generated from message ibc.core.connection.v1.QueryConnectionParamsRequest - */ -export class QueryConnectionParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionParamsRequest { - return new QueryConnectionParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionParamsRequest { - return new QueryConnectionParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionParamsRequest { - return new QueryConnectionParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionParamsRequest | PlainMessage | undefined, b: QueryConnectionParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionParamsRequest, a, b); - } -} - -/** - * QueryConnectionParamsResponse is the response type for the Query/ConnectionParams RPC method. - * - * @generated from message ibc.core.connection.v1.QueryConnectionParamsResponse - */ -export class QueryConnectionParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: ibc.core.connection.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.QueryConnectionParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConnectionParamsResponse { - return new QueryConnectionParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConnectionParamsResponse { - return new QueryConnectionParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConnectionParamsResponse { - return new QueryConnectionParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConnectionParamsResponse | PlainMessage | undefined, b: QueryConnectionParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConnectionParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/core/connection/v1/tx_cosmes.ts deleted file mode 100644 index a68bae284..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/tx_cosmes.ts +++ /dev/null @@ -1,71 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/tx.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgConnectionOpenAck, MsgConnectionOpenAckResponse, MsgConnectionOpenConfirm, MsgConnectionOpenConfirmResponse, MsgConnectionOpenInit, MsgConnectionOpenInitResponse, MsgConnectionOpenTry, MsgConnectionOpenTryResponse, MsgUpdateParams, MsgUpdateParamsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.core.connection.v1.Msg"; - -/** - * ConnectionOpenInit defines a rpc handler method for MsgConnectionOpenInit. - * - * @generated from rpc ibc.core.connection.v1.Msg.ConnectionOpenInit - */ -export const MsgConnectionOpenInitService = { - typeName: TYPE_NAME, - method: "ConnectionOpenInit", - Request: MsgConnectionOpenInit, - Response: MsgConnectionOpenInitResponse, -} as const; - -/** - * ConnectionOpenTry defines a rpc handler method for MsgConnectionOpenTry. - * - * @generated from rpc ibc.core.connection.v1.Msg.ConnectionOpenTry - */ -export const MsgConnectionOpenTryService = { - typeName: TYPE_NAME, - method: "ConnectionOpenTry", - Request: MsgConnectionOpenTry, - Response: MsgConnectionOpenTryResponse, -} as const; - -/** - * ConnectionOpenAck defines a rpc handler method for MsgConnectionOpenAck. - * - * @generated from rpc ibc.core.connection.v1.Msg.ConnectionOpenAck - */ -export const MsgConnectionOpenAckService = { - typeName: TYPE_NAME, - method: "ConnectionOpenAck", - Request: MsgConnectionOpenAck, - Response: MsgConnectionOpenAckResponse, -} as const; - -/** - * ConnectionOpenConfirm defines a rpc handler method for - * MsgConnectionOpenConfirm. - * - * @generated from rpc ibc.core.connection.v1.Msg.ConnectionOpenConfirm - */ -export const MsgConnectionOpenConfirmService = { - typeName: TYPE_NAME, - method: "ConnectionOpenConfirm", - Request: MsgConnectionOpenConfirm, - Response: MsgConnectionOpenConfirmResponse, -} as const; - -/** - * UpdateConnectionParams defines a rpc handler method for - * MsgUpdateParams. - * - * @generated from rpc ibc.core.connection.v1.Msg.UpdateConnectionParams - */ -export const MsgUpdateConnectionParamsService = { - typeName: TYPE_NAME, - method: "UpdateConnectionParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/core/connection/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/core/connection/v1/tx_pb.ts deleted file mode 100644 index c6085e52c..000000000 --- a/packages/es/src/protobufs/ibc/core/connection/v1/tx_pb.ts +++ /dev/null @@ -1,603 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/connection/v1/tx.proto (package ibc.core.connection.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Counterparty, Params, Version } from "./connection_pb.js"; -import { Height } from "../../client/v1/client_pb.js"; - -/** - * MsgConnectionOpenInit defines the msg sent by an account on Chain A to - * initialize a connection with Chain B. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenInit - */ -export class MsgConnectionOpenInit extends Message { - /** - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * @generated from field: ibc.core.connection.v1.Counterparty counterparty = 2; - */ - counterparty?: Counterparty; - - /** - * @generated from field: ibc.core.connection.v1.Version version = 3; - */ - version?: Version; - - /** - * @generated from field: uint64 delay_period = 4; - */ - delayPeriod = protoInt64.zero; - - /** - * @generated from field: string signer = 5; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenInit"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "counterparty", kind: "message", T: Counterparty }, - { no: 3, name: "version", kind: "message", T: Version }, - { no: 4, name: "delay_period", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenInit { - return new MsgConnectionOpenInit().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenInit { - return new MsgConnectionOpenInit().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenInit { - return new MsgConnectionOpenInit().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenInit | PlainMessage | undefined, b: MsgConnectionOpenInit | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenInit, a, b); - } -} - -/** - * MsgConnectionOpenInitResponse defines the Msg/ConnectionOpenInit response - * type. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenInitResponse - */ -export class MsgConnectionOpenInitResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenInitResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenInitResponse { - return new MsgConnectionOpenInitResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenInitResponse { - return new MsgConnectionOpenInitResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenInitResponse { - return new MsgConnectionOpenInitResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenInitResponse | PlainMessage | undefined, b: MsgConnectionOpenInitResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenInitResponse, a, b); - } -} - -/** - * MsgConnectionOpenTry defines a msg sent by a Relayer to try to open a - * connection on Chain B. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenTry - */ -export class MsgConnectionOpenTry extends Message { - /** - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * Deprecated: this field is unused. Crossing hellos are no longer supported in core IBC. - * - * @generated from field: string previous_connection_id = 2 [deprecated = true]; - * @deprecated - */ - previousConnectionId = ""; - - /** - * Deprecated: this field is unused. - * - * @generated from field: google.protobuf.Any client_state = 3 [deprecated = true]; - * @deprecated - */ - clientState?: Any; - - /** - * @generated from field: ibc.core.connection.v1.Counterparty counterparty = 4; - */ - counterparty?: Counterparty; - - /** - * @generated from field: uint64 delay_period = 5; - */ - delayPeriod = protoInt64.zero; - - /** - * @generated from field: repeated ibc.core.connection.v1.Version counterparty_versions = 6; - */ - counterpartyVersions: Version[] = []; - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 7; - */ - proofHeight?: Height; - - /** - * proof of the initialization the connection on Chain A: `UNINITIALIZED -> - * INIT` - * - * @generated from field: bytes proof_init = 8; - */ - proofInit = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes proof_client = 9 [deprecated = true]; - * @deprecated - */ - proofClient = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes proof_consensus = 10 [deprecated = true]; - * @deprecated - */ - proofConsensus = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: ibc.core.client.v1.Height consensus_height = 11 [deprecated = true]; - * @deprecated - */ - consensusHeight?: Height; - - /** - * @generated from field: string signer = 12; - */ - signer = ""; - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes host_consensus_state_proof = 13 [deprecated = true]; - * @deprecated - */ - hostConsensusStateProof = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenTry"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "previous_connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "client_state", kind: "message", T: Any }, - { no: 4, name: "counterparty", kind: "message", T: Counterparty }, - { no: 5, name: "delay_period", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "counterparty_versions", kind: "message", T: Version, repeated: true }, - { no: 7, name: "proof_height", kind: "message", T: Height }, - { no: 8, name: "proof_init", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "proof_client", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 10, name: "proof_consensus", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 11, name: "consensus_height", kind: "message", T: Height }, - { no: 12, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "host_consensus_state_proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenTry { - return new MsgConnectionOpenTry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenTry { - return new MsgConnectionOpenTry().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenTry { - return new MsgConnectionOpenTry().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenTry | PlainMessage | undefined, b: MsgConnectionOpenTry | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenTry, a, b); - } -} - -/** - * MsgConnectionOpenTryResponse defines the Msg/ConnectionOpenTry response type. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenTryResponse - */ -export class MsgConnectionOpenTryResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenTryResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenTryResponse { - return new MsgConnectionOpenTryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenTryResponse { - return new MsgConnectionOpenTryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenTryResponse { - return new MsgConnectionOpenTryResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenTryResponse | PlainMessage | undefined, b: MsgConnectionOpenTryResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenTryResponse, a, b); - } -} - -/** - * MsgConnectionOpenAck defines a msg sent by a Relayer to Chain A to - * acknowledge the change of connection state to TRYOPEN on Chain B. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenAck - */ -export class MsgConnectionOpenAck extends Message { - /** - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * @generated from field: string counterparty_connection_id = 2; - */ - counterpartyConnectionId = ""; - - /** - * @generated from field: ibc.core.connection.v1.Version version = 3; - */ - version?: Version; - - /** - * Deprecated: this field is unused. - * - * @generated from field: google.protobuf.Any client_state = 4 [deprecated = true]; - * @deprecated - */ - clientState?: Any; - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 5; - */ - proofHeight?: Height; - - /** - * proof of the initialization the connection on Chain B: `UNINITIALIZED -> - * TRYOPEN` - * - * @generated from field: bytes proof_try = 6; - */ - proofTry = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes proof_client = 7 [deprecated = true]; - * @deprecated - */ - proofClient = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes proof_consensus = 8 [deprecated = true]; - * @deprecated - */ - proofConsensus = new Uint8Array(0); - - /** - * Deprecated: this field is unused. - * - * @generated from field: ibc.core.client.v1.Height consensus_height = 9 [deprecated = true]; - * @deprecated - */ - consensusHeight?: Height; - - /** - * @generated from field: string signer = 10; - */ - signer = ""; - - /** - * Deprecated: this field is unused. - * - * @generated from field: bytes host_consensus_state_proof = 11 [deprecated = true]; - * @deprecated - */ - hostConsensusStateProof = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenAck"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "counterparty_connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "version", kind: "message", T: Version }, - { no: 4, name: "client_state", kind: "message", T: Any }, - { no: 5, name: "proof_height", kind: "message", T: Height }, - { no: 6, name: "proof_try", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 7, name: "proof_client", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 8, name: "proof_consensus", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 9, name: "consensus_height", kind: "message", T: Height }, - { no: 10, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "host_consensus_state_proof", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenAck { - return new MsgConnectionOpenAck().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenAck { - return new MsgConnectionOpenAck().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenAck { - return new MsgConnectionOpenAck().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenAck | PlainMessage | undefined, b: MsgConnectionOpenAck | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenAck, a, b); - } -} - -/** - * MsgConnectionOpenAckResponse defines the Msg/ConnectionOpenAck response type. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenAckResponse - */ -export class MsgConnectionOpenAckResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenAckResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenAckResponse { - return new MsgConnectionOpenAckResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenAckResponse { - return new MsgConnectionOpenAckResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenAckResponse { - return new MsgConnectionOpenAckResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenAckResponse | PlainMessage | undefined, b: MsgConnectionOpenAckResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenAckResponse, a, b); - } -} - -/** - * MsgConnectionOpenConfirm defines a msg sent by a Relayer to Chain B to - * acknowledge the change of connection state to OPEN on Chain A. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenConfirm - */ -export class MsgConnectionOpenConfirm extends Message { - /** - * @generated from field: string connection_id = 1; - */ - connectionId = ""; - - /** - * proof for the change of the connection state on Chain A: `INIT -> OPEN` - * - * @generated from field: bytes proof_ack = 2; - */ - proofAck = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height proof_height = 3; - */ - proofHeight?: Height; - - /** - * @generated from field: string signer = 4; - */ - signer = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenConfirm"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "connection_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "proof_ack", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "proof_height", kind: "message", T: Height }, - { no: 4, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenConfirm { - return new MsgConnectionOpenConfirm().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenConfirm { - return new MsgConnectionOpenConfirm().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenConfirm { - return new MsgConnectionOpenConfirm().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenConfirm | PlainMessage | undefined, b: MsgConnectionOpenConfirm | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenConfirm, a, b); - } -} - -/** - * MsgConnectionOpenConfirmResponse defines the Msg/ConnectionOpenConfirm - * response type. - * - * @generated from message ibc.core.connection.v1.MsgConnectionOpenConfirmResponse - */ -export class MsgConnectionOpenConfirmResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgConnectionOpenConfirmResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgConnectionOpenConfirmResponse { - return new MsgConnectionOpenConfirmResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgConnectionOpenConfirmResponse { - return new MsgConnectionOpenConfirmResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgConnectionOpenConfirmResponse { - return new MsgConnectionOpenConfirmResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgConnectionOpenConfirmResponse | PlainMessage | undefined, b: MsgConnectionOpenConfirmResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgConnectionOpenConfirmResponse, a, b); - } -} - -/** - * MsgUpdateParams defines the sdk.Msg type to update the connection parameters. - * - * @generated from message ibc.core.connection.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * params defines the connection parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: ibc.core.connection.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the MsgUpdateParams response type. - * - * @generated from message ibc.core.connection.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.connection.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/core/types/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/core/types/v1/genesis_pb.ts deleted file mode 100644 index fbc3f8c08..000000000 --- a/packages/es/src/protobufs/ibc/core/types/v1/genesis_pb.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/core/types/v1/genesis.proto (package ibc.core.types.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { GenesisState as GenesisState$1 } from "../../client/v1/genesis_pb.js"; -import { GenesisState as GenesisState$2 } from "../../connection/v1/genesis_pb.js"; -import { GenesisState as GenesisState$3 } from "../../channel/v1/genesis_pb.js"; -import { GenesisState as GenesisState$4 } from "../../client/v2/genesis_pb.js"; -import { GenesisState as GenesisState$5 } from "../../channel/v2/genesis_pb.js"; - -/** - * GenesisState defines the ibc module's genesis state. - * - * @generated from message ibc.core.types.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * ICS002 - Clients genesis state - * - * @generated from field: ibc.core.client.v1.GenesisState client_genesis = 1; - */ - clientGenesis?: GenesisState$1; - - /** - * ICS003 - Connections genesis state - * - * @generated from field: ibc.core.connection.v1.GenesisState connection_genesis = 2; - */ - connectionGenesis?: GenesisState$2; - - /** - * ICS004 - Channel genesis state - * - * @generated from field: ibc.core.channel.v1.GenesisState channel_genesis = 3; - */ - channelGenesis?: GenesisState$3; - - /** - * ICS002 - Clients/v2 genesis state - * - * @generated from field: ibc.core.client.v2.GenesisState client_v2_genesis = 4; - */ - clientV2Genesis?: GenesisState$4; - - /** - * ICS004 - Channel/v2 genesis state - * - * @generated from field: ibc.core.channel.v2.GenesisState channel_v2_genesis = 5; - */ - channelV2Genesis?: GenesisState$5; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.core.types.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_genesis", kind: "message", T: GenesisState$1 }, - { no: 2, name: "connection_genesis", kind: "message", T: GenesisState$2 }, - { no: 3, name: "channel_genesis", kind: "message", T: GenesisState$3 }, - { no: 4, name: "client_v2_genesis", kind: "message", T: GenesisState$4 }, - { no: 5, name: "channel_v2_genesis", kind: "message", T: GenesisState$5 }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/solomachine/v2/solomachine_pb.ts b/packages/es/src/protobufs/ibc/lightclients/solomachine/v2/solomachine_pb.ts deleted file mode 100644 index 22373fc8d..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/solomachine/v2/solomachine_pb.ts +++ /dev/null @@ -1,929 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/solomachine/v2/solomachine.proto (package ibc.lightclients.solomachine.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ConnectionEnd } from "../../../core/connection/v1/connection_pb.js"; -import { Channel } from "../../../core/channel/v1/channel_pb.js"; - -/** - * DataType defines the type of solo machine proof being created. This is done - * to preserve uniqueness of different data sign byte encodings. - * - * @generated from enum ibc.lightclients.solomachine.v2.DataType - */ -export enum DataType { - /** - * Default State - * - * @generated from enum value: DATA_TYPE_UNINITIALIZED_UNSPECIFIED = 0; - */ - UNINITIALIZED_UNSPECIFIED = 0, - - /** - * Data type for client state verification - * - * @generated from enum value: DATA_TYPE_CLIENT_STATE = 1; - */ - CLIENT_STATE = 1, - - /** - * Data type for consensus state verification - * - * @generated from enum value: DATA_TYPE_CONSENSUS_STATE = 2; - */ - CONSENSUS_STATE = 2, - - /** - * Data type for connection state verification - * - * @generated from enum value: DATA_TYPE_CONNECTION_STATE = 3; - */ - CONNECTION_STATE = 3, - - /** - * Data type for channel state verification - * - * @generated from enum value: DATA_TYPE_CHANNEL_STATE = 4; - */ - CHANNEL_STATE = 4, - - /** - * Data type for packet commitment verification - * - * @generated from enum value: DATA_TYPE_PACKET_COMMITMENT = 5; - */ - PACKET_COMMITMENT = 5, - - /** - * Data type for packet acknowledgement verification - * - * @generated from enum value: DATA_TYPE_PACKET_ACKNOWLEDGEMENT = 6; - */ - PACKET_ACKNOWLEDGEMENT = 6, - - /** - * Data type for packet receipt absence verification - * - * @generated from enum value: DATA_TYPE_PACKET_RECEIPT_ABSENCE = 7; - */ - PACKET_RECEIPT_ABSENCE = 7, - - /** - * Data type for next sequence recv verification - * - * @generated from enum value: DATA_TYPE_NEXT_SEQUENCE_RECV = 8; - */ - NEXT_SEQUENCE_RECV = 8, - - /** - * Data type for header verification - * - * @generated from enum value: DATA_TYPE_HEADER = 9; - */ - HEADER = 9, -} -// Retrieve enum metadata with: proto3.getEnumType(DataType) -proto3.util.setEnumType(DataType, "ibc.lightclients.solomachine.v2.DataType", [ - { no: 0, name: "DATA_TYPE_UNINITIALIZED_UNSPECIFIED" }, - { no: 1, name: "DATA_TYPE_CLIENT_STATE" }, - { no: 2, name: "DATA_TYPE_CONSENSUS_STATE" }, - { no: 3, name: "DATA_TYPE_CONNECTION_STATE" }, - { no: 4, name: "DATA_TYPE_CHANNEL_STATE" }, - { no: 5, name: "DATA_TYPE_PACKET_COMMITMENT" }, - { no: 6, name: "DATA_TYPE_PACKET_ACKNOWLEDGEMENT" }, - { no: 7, name: "DATA_TYPE_PACKET_RECEIPT_ABSENCE" }, - { no: 8, name: "DATA_TYPE_NEXT_SEQUENCE_RECV" }, - { no: 9, name: "DATA_TYPE_HEADER" }, -]); - -/** - * ClientState defines a solo machine client that tracks the current consensus - * state and if the client is frozen. - * - * @generated from message ibc.lightclients.solomachine.v2.ClientState - */ -export class ClientState extends Message { - /** - * latest sequence of the client state - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * frozen sequence of the solo machine - * - * @generated from field: bool is_frozen = 2; - */ - isFrozen = false; - - /** - * @generated from field: ibc.lightclients.solomachine.v2.ConsensusState consensus_state = 3; - */ - consensusState?: ConsensusState; - - /** - * when set to true, will allow governance to update a solo machine client. - * The client will be unfrozen if it is frozen. - * - * @generated from field: bool allow_update_after_proposal = 4; - */ - allowUpdateAfterProposal = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ClientState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "is_frozen", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "consensus_state", kind: "message", T: ConsensusState }, - { no: 4, name: "allow_update_after_proposal", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientState { - return new ClientState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientState { - return new ClientState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientState { - return new ClientState().fromJsonString(jsonString, options); - } - - static equals(a: ClientState | PlainMessage | undefined, b: ClientState | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientState, a, b); - } -} - -/** - * ConsensusState defines a solo machine consensus state. The sequence of a - * consensus state is contained in the "height" key used in storing the - * consensus state. - * - * @generated from message ibc.lightclients.solomachine.v2.ConsensusState - */ -export class ConsensusState extends Message { - /** - * public key of the solo machine - * - * @generated from field: google.protobuf.Any public_key = 1; - */ - publicKey?: Any; - - /** - * diversifier allows the same public key to be reused across different solo - * machine clients (potentially on different chains) without being considered - * misbehaviour. - * - * @generated from field: string diversifier = 2; - */ - diversifier = ""; - - /** - * @generated from field: uint64 timestamp = 3; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ConsensusState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "public_key", kind: "message", T: Any }, - { no: 2, name: "diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusState { - return new ConsensusState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusState { - return new ConsensusState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusState { - return new ConsensusState().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusState | PlainMessage | undefined, b: ConsensusState | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusState, a, b); - } -} - -/** - * Header defines a solo machine consensus header - * - * @generated from message ibc.lightclients.solomachine.v2.Header - */ -export class Header extends Message
{ - /** - * sequence to update solo machine public key at - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - /** - * @generated from field: bytes signature = 3; - */ - signature = new Uint8Array(0); - - /** - * @generated from field: google.protobuf.Any new_public_key = 4; - */ - newPublicKey?: Any; - - /** - * @generated from field: string new_diversifier = 5; - */ - newDiversifier = ""; - - constructor(data?: PartialMessage
) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.Header"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "signature", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "new_public_key", kind: "message", T: Any }, - { no: 5, name: "new_diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Header { - return new Header().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Header { - return new Header().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Header { - return new Header().fromJsonString(jsonString, options); - } - - static equals(a: Header | PlainMessage
| undefined, b: Header | PlainMessage
| undefined): boolean { - return proto3.util.equals(Header, a, b); - } -} - -/** - * Misbehaviour defines misbehaviour for a solo machine which consists - * of a sequence and two signatures over different messages at that sequence. - * - * @generated from message ibc.lightclients.solomachine.v2.Misbehaviour - */ -export class Misbehaviour extends Message { - /** - * @generated from field: string client_id = 1; - */ - clientId = ""; - - /** - * @generated from field: uint64 sequence = 2; - */ - sequence = protoInt64.zero; - - /** - * @generated from field: ibc.lightclients.solomachine.v2.SignatureAndData signature_one = 3; - */ - signatureOne?: SignatureAndData; - - /** - * @generated from field: ibc.lightclients.solomachine.v2.SignatureAndData signature_two = 4; - */ - signatureTwo?: SignatureAndData; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.Misbehaviour"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "signature_one", kind: "message", T: SignatureAndData }, - { no: 4, name: "signature_two", kind: "message", T: SignatureAndData }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Misbehaviour { - return new Misbehaviour().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJsonString(jsonString, options); - } - - static equals(a: Misbehaviour | PlainMessage | undefined, b: Misbehaviour | PlainMessage | undefined): boolean { - return proto3.util.equals(Misbehaviour, a, b); - } -} - -/** - * SignatureAndData contains a signature and the data signed over to create that - * signature. - * - * @generated from message ibc.lightclients.solomachine.v2.SignatureAndData - */ -export class SignatureAndData extends Message { - /** - * @generated from field: bytes signature = 1; - */ - signature = new Uint8Array(0); - - /** - * @generated from field: ibc.lightclients.solomachine.v2.DataType data_type = 2; - */ - dataType = DataType.UNINITIALIZED_UNSPECIFIED; - - /** - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - /** - * @generated from field: uint64 timestamp = 4; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.SignatureAndData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signature", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "data_type", kind: "enum", T: proto3.getEnumType(DataType) }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignatureAndData { - return new SignatureAndData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignatureAndData { - return new SignatureAndData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignatureAndData { - return new SignatureAndData().fromJsonString(jsonString, options); - } - - static equals(a: SignatureAndData | PlainMessage | undefined, b: SignatureAndData | PlainMessage | undefined): boolean { - return proto3.util.equals(SignatureAndData, a, b); - } -} - -/** - * TimestampedSignatureData contains the signature data and the timestamp of the - * signature. - * - * @generated from message ibc.lightclients.solomachine.v2.TimestampedSignatureData - */ -export class TimestampedSignatureData extends Message { - /** - * @generated from field: bytes signature_data = 1; - */ - signatureData = new Uint8Array(0); - - /** - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.TimestampedSignatureData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signature_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromJsonString(jsonString, options); - } - - static equals(a: TimestampedSignatureData | PlainMessage | undefined, b: TimestampedSignatureData | PlainMessage | undefined): boolean { - return proto3.util.equals(TimestampedSignatureData, a, b); - } -} - -/** - * SignBytes defines the signed bytes used for signature verification. - * - * @generated from message ibc.lightclients.solomachine.v2.SignBytes - */ -export class SignBytes extends Message { - /** - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - /** - * @generated from field: string diversifier = 3; - */ - diversifier = ""; - - /** - * type of the data used - * - * @generated from field: ibc.lightclients.solomachine.v2.DataType data_type = 4; - */ - dataType = DataType.UNINITIALIZED_UNSPECIFIED; - - /** - * marshaled data - * - * @generated from field: bytes data = 5; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.SignBytes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "data_type", kind: "enum", T: proto3.getEnumType(DataType) }, - { no: 5, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignBytes { - return new SignBytes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignBytes { - return new SignBytes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignBytes { - return new SignBytes().fromJsonString(jsonString, options); - } - - static equals(a: SignBytes | PlainMessage | undefined, b: SignBytes | PlainMessage | undefined): boolean { - return proto3.util.equals(SignBytes, a, b); - } -} - -/** - * HeaderData returns the SignBytes data for update verification. - * - * @generated from message ibc.lightclients.solomachine.v2.HeaderData - */ -export class HeaderData extends Message { - /** - * header public key - * - * @generated from field: google.protobuf.Any new_pub_key = 1; - */ - newPubKey?: Any; - - /** - * header diversifier - * - * @generated from field: string new_diversifier = 2; - */ - newDiversifier = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.HeaderData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "new_pub_key", kind: "message", T: Any }, - { no: 2, name: "new_diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): HeaderData { - return new HeaderData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): HeaderData { - return new HeaderData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): HeaderData { - return new HeaderData().fromJsonString(jsonString, options); - } - - static equals(a: HeaderData | PlainMessage | undefined, b: HeaderData | PlainMessage | undefined): boolean { - return proto3.util.equals(HeaderData, a, b); - } -} - -/** - * ClientStateData returns the SignBytes data for client state verification. - * - * @generated from message ibc.lightclients.solomachine.v2.ClientStateData - */ -export class ClientStateData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: google.protobuf.Any client_state = 2; - */ - clientState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ClientStateData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "client_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientStateData { - return new ClientStateData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientStateData { - return new ClientStateData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientStateData { - return new ClientStateData().fromJsonString(jsonString, options); - } - - static equals(a: ClientStateData | PlainMessage | undefined, b: ClientStateData | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientStateData, a, b); - } -} - -/** - * ConsensusStateData returns the SignBytes data for consensus state - * verification. - * - * @generated from message ibc.lightclients.solomachine.v2.ConsensusStateData - */ -export class ConsensusStateData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: google.protobuf.Any consensus_state = 2; - */ - consensusState?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ConsensusStateData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "consensus_state", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusStateData { - return new ConsensusStateData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusStateData { - return new ConsensusStateData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusStateData { - return new ConsensusStateData().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusStateData | PlainMessage | undefined, b: ConsensusStateData | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusStateData, a, b); - } -} - -/** - * ConnectionStateData returns the SignBytes data for connection state - * verification. - * - * @generated from message ibc.lightclients.solomachine.v2.ConnectionStateData - */ -export class ConnectionStateData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: ibc.core.connection.v1.ConnectionEnd connection = 2; - */ - connection?: ConnectionEnd; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ConnectionStateData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "connection", kind: "message", T: ConnectionEnd }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConnectionStateData { - return new ConnectionStateData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConnectionStateData { - return new ConnectionStateData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConnectionStateData { - return new ConnectionStateData().fromJsonString(jsonString, options); - } - - static equals(a: ConnectionStateData | PlainMessage | undefined, b: ConnectionStateData | PlainMessage | undefined): boolean { - return proto3.util.equals(ConnectionStateData, a, b); - } -} - -/** - * ChannelStateData returns the SignBytes data for channel state - * verification. - * - * @generated from message ibc.lightclients.solomachine.v2.ChannelStateData - */ -export class ChannelStateData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: ibc.core.channel.v1.Channel channel = 2; - */ - channel?: Channel; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.ChannelStateData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "channel", kind: "message", T: Channel }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ChannelStateData { - return new ChannelStateData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ChannelStateData { - return new ChannelStateData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ChannelStateData { - return new ChannelStateData().fromJsonString(jsonString, options); - } - - static equals(a: ChannelStateData | PlainMessage | undefined, b: ChannelStateData | PlainMessage | undefined): boolean { - return proto3.util.equals(ChannelStateData, a, b); - } -} - -/** - * PacketCommitmentData returns the SignBytes data for packet commitment - * verification. - * - * @generated from message ibc.lightclients.solomachine.v2.PacketCommitmentData - */ -export class PacketCommitmentData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: bytes commitment = 2; - */ - commitment = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.PacketCommitmentData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "commitment", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketCommitmentData { - return new PacketCommitmentData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketCommitmentData { - return new PacketCommitmentData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketCommitmentData { - return new PacketCommitmentData().fromJsonString(jsonString, options); - } - - static equals(a: PacketCommitmentData | PlainMessage | undefined, b: PacketCommitmentData | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketCommitmentData, a, b); - } -} - -/** - * PacketAcknowledgementData returns the SignBytes data for acknowledgement - * verification. - * - * @generated from message ibc.lightclients.solomachine.v2.PacketAcknowledgementData - */ -export class PacketAcknowledgementData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: bytes acknowledgement = 2; - */ - acknowledgement = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.PacketAcknowledgementData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "acknowledgement", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketAcknowledgementData { - return new PacketAcknowledgementData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketAcknowledgementData { - return new PacketAcknowledgementData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketAcknowledgementData { - return new PacketAcknowledgementData().fromJsonString(jsonString, options); - } - - static equals(a: PacketAcknowledgementData | PlainMessage | undefined, b: PacketAcknowledgementData | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketAcknowledgementData, a, b); - } -} - -/** - * PacketReceiptAbsenceData returns the SignBytes data for - * packet receipt absence verification. - * - * @generated from message ibc.lightclients.solomachine.v2.PacketReceiptAbsenceData - */ -export class PacketReceiptAbsenceData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.PacketReceiptAbsenceData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PacketReceiptAbsenceData { - return new PacketReceiptAbsenceData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PacketReceiptAbsenceData { - return new PacketReceiptAbsenceData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PacketReceiptAbsenceData { - return new PacketReceiptAbsenceData().fromJsonString(jsonString, options); - } - - static equals(a: PacketReceiptAbsenceData | PlainMessage | undefined, b: PacketReceiptAbsenceData | PlainMessage | undefined): boolean { - return proto3.util.equals(PacketReceiptAbsenceData, a, b); - } -} - -/** - * NextSequenceRecvData returns the SignBytes data for verification of the next - * sequence to be received. - * - * @generated from message ibc.lightclients.solomachine.v2.NextSequenceRecvData - */ -export class NextSequenceRecvData extends Message { - /** - * @generated from field: bytes path = 1; - */ - path = new Uint8Array(0); - - /** - * @generated from field: uint64 next_seq_recv = 2; - */ - nextSeqRecv = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v2.NextSequenceRecvData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "next_seq_recv", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NextSequenceRecvData { - return new NextSequenceRecvData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NextSequenceRecvData { - return new NextSequenceRecvData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NextSequenceRecvData { - return new NextSequenceRecvData().fromJsonString(jsonString, options); - } - - static equals(a: NextSequenceRecvData | PlainMessage | undefined, b: NextSequenceRecvData | PlainMessage | undefined): boolean { - return proto3.util.equals(NextSequenceRecvData, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/solomachine/v3/solomachine_pb.ts b/packages/es/src/protobufs/ibc/lightclients/solomachine/v3/solomachine_pb.ts deleted file mode 100644 index 8e160dfd7..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/solomachine/v3/solomachine_pb.ts +++ /dev/null @@ -1,458 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/solomachine/v3/solomachine.proto (package ibc.lightclients.solomachine.v3, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * ClientState defines a solo machine client that tracks the current consensus - * state and if the client is frozen. - * - * @generated from message ibc.lightclients.solomachine.v3.ClientState - */ -export class ClientState extends Message { - /** - * latest sequence of the client state - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * frozen sequence of the solo machine - * - * @generated from field: bool is_frozen = 2; - */ - isFrozen = false; - - /** - * @generated from field: ibc.lightclients.solomachine.v3.ConsensusState consensus_state = 3; - */ - consensusState?: ConsensusState; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.ClientState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "is_frozen", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "consensus_state", kind: "message", T: ConsensusState }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientState { - return new ClientState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientState { - return new ClientState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientState { - return new ClientState().fromJsonString(jsonString, options); - } - - static equals(a: ClientState | PlainMessage | undefined, b: ClientState | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientState, a, b); - } -} - -/** - * ConsensusState defines a solo machine consensus state. The sequence of a - * consensus state is contained in the "height" key used in storing the - * consensus state. - * - * @generated from message ibc.lightclients.solomachine.v3.ConsensusState - */ -export class ConsensusState extends Message { - /** - * public key of the solo machine - * - * @generated from field: google.protobuf.Any public_key = 1; - */ - publicKey?: Any; - - /** - * diversifier allows the same public key to be reused across different solo - * machine clients (potentially on different chains) without being considered - * misbehaviour. - * - * @generated from field: string diversifier = 2; - */ - diversifier = ""; - - /** - * @generated from field: uint64 timestamp = 3; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.ConsensusState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "public_key", kind: "message", T: Any }, - { no: 2, name: "diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusState { - return new ConsensusState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusState { - return new ConsensusState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusState { - return new ConsensusState().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusState | PlainMessage | undefined, b: ConsensusState | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusState, a, b); - } -} - -/** - * Header defines a solo machine consensus header - * - * @generated from message ibc.lightclients.solomachine.v3.Header - */ -export class Header extends Message
{ - /** - * @generated from field: uint64 timestamp = 1; - */ - timestamp = protoInt64.zero; - - /** - * @generated from field: bytes signature = 2; - */ - signature = new Uint8Array(0); - - /** - * @generated from field: google.protobuf.Any new_public_key = 3; - */ - newPublicKey?: Any; - - /** - * @generated from field: string new_diversifier = 4; - */ - newDiversifier = ""; - - constructor(data?: PartialMessage
) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.Header"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "signature", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "new_public_key", kind: "message", T: Any }, - { no: 4, name: "new_diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Header { - return new Header().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Header { - return new Header().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Header { - return new Header().fromJsonString(jsonString, options); - } - - static equals(a: Header | PlainMessage
| undefined, b: Header | PlainMessage
| undefined): boolean { - return proto3.util.equals(Header, a, b); - } -} - -/** - * Misbehaviour defines misbehaviour for a solo machine which consists - * of a sequence and two signatures over different messages at that sequence. - * - * @generated from message ibc.lightclients.solomachine.v3.Misbehaviour - */ -export class Misbehaviour extends Message { - /** - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * @generated from field: ibc.lightclients.solomachine.v3.SignatureAndData signature_one = 2; - */ - signatureOne?: SignatureAndData; - - /** - * @generated from field: ibc.lightclients.solomachine.v3.SignatureAndData signature_two = 3; - */ - signatureTwo?: SignatureAndData; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.Misbehaviour"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "signature_one", kind: "message", T: SignatureAndData }, - { no: 3, name: "signature_two", kind: "message", T: SignatureAndData }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Misbehaviour { - return new Misbehaviour().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJsonString(jsonString, options); - } - - static equals(a: Misbehaviour | PlainMessage | undefined, b: Misbehaviour | PlainMessage | undefined): boolean { - return proto3.util.equals(Misbehaviour, a, b); - } -} - -/** - * SignatureAndData contains a signature and the data signed over to create that - * signature. - * - * @generated from message ibc.lightclients.solomachine.v3.SignatureAndData - */ -export class SignatureAndData extends Message { - /** - * @generated from field: bytes signature = 1; - */ - signature = new Uint8Array(0); - - /** - * @generated from field: bytes path = 2; - */ - path = new Uint8Array(0); - - /** - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - /** - * @generated from field: uint64 timestamp = 4; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.SignatureAndData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signature", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignatureAndData { - return new SignatureAndData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignatureAndData { - return new SignatureAndData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignatureAndData { - return new SignatureAndData().fromJsonString(jsonString, options); - } - - static equals(a: SignatureAndData | PlainMessage | undefined, b: SignatureAndData | PlainMessage | undefined): boolean { - return proto3.util.equals(SignatureAndData, a, b); - } -} - -/** - * TimestampedSignatureData contains the signature data and the timestamp of the - * signature. - * - * @generated from message ibc.lightclients.solomachine.v3.TimestampedSignatureData - */ -export class TimestampedSignatureData extends Message { - /** - * @generated from field: bytes signature_data = 1; - */ - signatureData = new Uint8Array(0); - - /** - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.TimestampedSignatureData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signature_data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TimestampedSignatureData { - return new TimestampedSignatureData().fromJsonString(jsonString, options); - } - - static equals(a: TimestampedSignatureData | PlainMessage | undefined, b: TimestampedSignatureData | PlainMessage | undefined): boolean { - return proto3.util.equals(TimestampedSignatureData, a, b); - } -} - -/** - * SignBytes defines the signed bytes used for signature verification. - * - * @generated from message ibc.lightclients.solomachine.v3.SignBytes - */ -export class SignBytes extends Message { - /** - * the sequence number - * - * @generated from field: uint64 sequence = 1; - */ - sequence = protoInt64.zero; - - /** - * the proof timestamp - * - * @generated from field: uint64 timestamp = 2; - */ - timestamp = protoInt64.zero; - - /** - * the public key diversifier - * - * @generated from field: string diversifier = 3; - */ - diversifier = ""; - - /** - * the standardised path bytes - * - * @generated from field: bytes path = 4; - */ - path = new Uint8Array(0); - - /** - * the marshaled data bytes - * - * @generated from field: bytes data = 5; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.SignBytes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "timestamp", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "path", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 5, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SignBytes { - return new SignBytes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SignBytes { - return new SignBytes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SignBytes { - return new SignBytes().fromJsonString(jsonString, options); - } - - static equals(a: SignBytes | PlainMessage | undefined, b: SignBytes | PlainMessage | undefined): boolean { - return proto3.util.equals(SignBytes, a, b); - } -} - -/** - * HeaderData returns the SignBytes data for update verification. - * - * @generated from message ibc.lightclients.solomachine.v3.HeaderData - */ -export class HeaderData extends Message { - /** - * header public key - * - * @generated from field: google.protobuf.Any new_pub_key = 1; - */ - newPubKey?: Any; - - /** - * header diversifier - * - * @generated from field: string new_diversifier = 2; - */ - newDiversifier = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.solomachine.v3.HeaderData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "new_pub_key", kind: "message", T: Any }, - { no: 2, name: "new_diversifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): HeaderData { - return new HeaderData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): HeaderData { - return new HeaderData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): HeaderData { - return new HeaderData().fromJsonString(jsonString, options); - } - - static equals(a: HeaderData | PlainMessage | undefined, b: HeaderData | PlainMessage | undefined): boolean { - return proto3.util.equals(HeaderData, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/tendermint/v1/tendermint_pb.ts b/packages/es/src/protobufs/ibc/lightclients/tendermint/v1/tendermint_pb.ts deleted file mode 100644 index daf2cebc8..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/tendermint/v1/tendermint_pb.ts +++ /dev/null @@ -1,365 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/tendermint/v1/tendermint.proto (package ibc.lightclients.tendermint.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Height } from "../../../core/client/v1/client_pb.js"; -import { ProofSpec } from "../../../../cosmos/ics23/v1/proofs_pb.js"; -import { MerkleRoot } from "../../../core/commitment/v1/commitment_pb.js"; -import { SignedHeader } from "../../../../tendermint/types/types_pb.js"; -import { ValidatorSet } from "../../../../tendermint/types/validator_pb.js"; - -/** - * ClientState from Tendermint tracks the current validator set, latest height, - * and a possible frozen height. - * - * @generated from message ibc.lightclients.tendermint.v1.ClientState - */ -export class ClientState extends Message { - /** - * @generated from field: string chain_id = 1; - */ - chainId = ""; - - /** - * @generated from field: ibc.lightclients.tendermint.v1.Fraction trust_level = 2; - */ - trustLevel?: Fraction; - - /** - * duration of the period since the LatestTimestamp during which the - * submitted headers are valid for upgrade - * - * @generated from field: google.protobuf.Duration trusting_period = 3; - */ - trustingPeriod?: Duration; - - /** - * duration of the staking unbonding period - * - * @generated from field: google.protobuf.Duration unbonding_period = 4; - */ - unbondingPeriod?: Duration; - - /** - * defines how much new (untrusted) header's Time can drift into the future. - * - * @generated from field: google.protobuf.Duration max_clock_drift = 5; - */ - maxClockDrift?: Duration; - - /** - * Block height when the client was frozen due to a misbehaviour - * - * @generated from field: ibc.core.client.v1.Height frozen_height = 6; - */ - frozenHeight?: Height; - - /** - * Latest height the client was updated to - * - * @generated from field: ibc.core.client.v1.Height latest_height = 7; - */ - latestHeight?: Height; - - /** - * Proof specifications used in verifying counterparty state - * - * @generated from field: repeated cosmos.ics23.v1.ProofSpec proof_specs = 8; - */ - proofSpecs: ProofSpec[] = []; - - /** - * Path at which next upgraded client will be committed. - * Each element corresponds to the key for a single CommitmentProof in the - * chained proof. NOTE: ClientState must stored under - * `{upgradePath}/{upgradeHeight}/clientState` ConsensusState must be stored - * under `{upgradepath}/{upgradeHeight}/consensusState` For SDK chains using - * the default upgrade module, upgrade_path should be []string{"upgrade", - * "upgradedIBCState"}` - * - * @generated from field: repeated string upgrade_path = 9; - */ - upgradePath: string[] = []; - - /** - * allow_update_after_expiry is deprecated - * - * @generated from field: bool allow_update_after_expiry = 10 [deprecated = true]; - * @deprecated - */ - allowUpdateAfterExpiry = false; - - /** - * allow_update_after_misbehaviour is deprecated - * - * @generated from field: bool allow_update_after_misbehaviour = 11 [deprecated = true]; - * @deprecated - */ - allowUpdateAfterMisbehaviour = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.tendermint.v1.ClientState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "chain_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "trust_level", kind: "message", T: Fraction }, - { no: 3, name: "trusting_period", kind: "message", T: Duration }, - { no: 4, name: "unbonding_period", kind: "message", T: Duration }, - { no: 5, name: "max_clock_drift", kind: "message", T: Duration }, - { no: 6, name: "frozen_height", kind: "message", T: Height }, - { no: 7, name: "latest_height", kind: "message", T: Height }, - { no: 8, name: "proof_specs", kind: "message", T: ProofSpec, repeated: true }, - { no: 9, name: "upgrade_path", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "allow_update_after_expiry", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 11, name: "allow_update_after_misbehaviour", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientState { - return new ClientState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientState { - return new ClientState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientState { - return new ClientState().fromJsonString(jsonString, options); - } - - static equals(a: ClientState | PlainMessage | undefined, b: ClientState | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientState, a, b); - } -} - -/** - * ConsensusState defines the consensus state from Tendermint. - * - * @generated from message ibc.lightclients.tendermint.v1.ConsensusState - */ -export class ConsensusState extends Message { - /** - * timestamp that corresponds to the block height in which the ConsensusState - * was stored. - * - * @generated from field: google.protobuf.Timestamp timestamp = 1; - */ - timestamp?: Timestamp; - - /** - * commitment root (i.e app hash) - * - * @generated from field: ibc.core.commitment.v1.MerkleRoot root = 2; - */ - root?: MerkleRoot; - - /** - * @generated from field: bytes next_validators_hash = 3; - */ - nextValidatorsHash = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.tendermint.v1.ConsensusState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "timestamp", kind: "message", T: Timestamp }, - { no: 2, name: "root", kind: "message", T: MerkleRoot }, - { no: 3, name: "next_validators_hash", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusState { - return new ConsensusState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusState { - return new ConsensusState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusState { - return new ConsensusState().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusState | PlainMessage | undefined, b: ConsensusState | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusState, a, b); - } -} - -/** - * Misbehaviour is a wrapper over two conflicting Headers - * that implements Misbehaviour interface expected by ICS-02 - * - * @generated from message ibc.lightclients.tendermint.v1.Misbehaviour - */ -export class Misbehaviour extends Message { - /** - * ClientID is deprecated - * - * @generated from field: string client_id = 1 [deprecated = true]; - * @deprecated - */ - clientId = ""; - - /** - * @generated from field: ibc.lightclients.tendermint.v1.Header header_1 = 2; - */ - header1?: Header; - - /** - * @generated from field: ibc.lightclients.tendermint.v1.Header header_2 = 3; - */ - header2?: Header; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.tendermint.v1.Misbehaviour"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "header_1", kind: "message", T: Header }, - { no: 3, name: "header_2", kind: "message", T: Header }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Misbehaviour { - return new Misbehaviour().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Misbehaviour { - return new Misbehaviour().fromJsonString(jsonString, options); - } - - static equals(a: Misbehaviour | PlainMessage | undefined, b: Misbehaviour | PlainMessage | undefined): boolean { - return proto3.util.equals(Misbehaviour, a, b); - } -} - -/** - * Header defines the Tendermint client consensus Header. - * It encapsulates all the information necessary to update from a trusted - * Tendermint ConsensusState. The inclusion of TrustedHeight and - * TrustedValidators allows this update to process correctly, so long as the - * ConsensusState for the TrustedHeight exists, this removes race conditions - * among relayers The SignedHeader and ValidatorSet are the new untrusted update - * fields for the client. The TrustedHeight is the height of a stored - * ConsensusState on the client that will be used to verify the new untrusted - * header. The Trusted ConsensusState must be within the unbonding period of - * current time in order to correctly verify, and the TrustedValidators must - * hash to TrustedConsensusState.NextValidatorsHash since that is the last - * trusted validator set at the TrustedHeight. - * - * @generated from message ibc.lightclients.tendermint.v1.Header - */ -export class Header extends Message
{ - /** - * @generated from field: tendermint.types.SignedHeader signed_header = 1; - */ - signedHeader?: SignedHeader; - - /** - * @generated from field: tendermint.types.ValidatorSet validator_set = 2; - */ - validatorSet?: ValidatorSet; - - /** - * @generated from field: ibc.core.client.v1.Height trusted_height = 3; - */ - trustedHeight?: Height; - - /** - * @generated from field: tendermint.types.ValidatorSet trusted_validators = 4; - */ - trustedValidators?: ValidatorSet; - - constructor(data?: PartialMessage
) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.tendermint.v1.Header"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signed_header", kind: "message", T: SignedHeader }, - { no: 2, name: "validator_set", kind: "message", T: ValidatorSet }, - { no: 3, name: "trusted_height", kind: "message", T: Height }, - { no: 4, name: "trusted_validators", kind: "message", T: ValidatorSet }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Header { - return new Header().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Header { - return new Header().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Header { - return new Header().fromJsonString(jsonString, options); - } - - static equals(a: Header | PlainMessage
| undefined, b: Header | PlainMessage
| undefined): boolean { - return proto3.util.equals(Header, a, b); - } -} - -/** - * Fraction defines the protobuf message type for tmmath.Fraction that only - * supports positive values. - * - * @generated from message ibc.lightclients.tendermint.v1.Fraction - */ -export class Fraction extends Message { - /** - * @generated from field: uint64 numerator = 1; - */ - numerator = protoInt64.zero; - - /** - * @generated from field: uint64 denominator = 2; - */ - denominator = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.tendermint.v1.Fraction"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "numerator", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "denominator", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Fraction { - return new Fraction().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Fraction { - return new Fraction().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Fraction { - return new Fraction().fromJsonString(jsonString, options); - } - - static equals(a: Fraction | PlainMessage | undefined, b: Fraction | PlainMessage | undefined): boolean { - return proto3.util.equals(Fraction, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/genesis_pb.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/genesis_pb.ts deleted file mode 100644 index 28664cbd4..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/genesis_pb.ts +++ /dev/null @@ -1,90 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/genesis.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * GenesisState defines 08-wasm's keeper genesis state - * - * @generated from message ibc.lightclients.wasm.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * uploaded light client wasm contracts - * - * @generated from field: repeated ibc.lightclients.wasm.v1.Contract contracts = 1; - */ - contracts: Contract[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contracts", kind: "message", T: Contract, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Contract stores contract code - * - * @generated from message ibc.lightclients.wasm.v1.Contract - */ -export class Contract extends Message { - /** - * contract byte code - * - * @generated from field: bytes code_bytes = 1; - */ - codeBytes = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.Contract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_bytes", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Contract { - return new Contract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Contract { - return new Contract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Contract { - return new Contract().fromJsonString(jsonString, options); - } - - static equals(a: Contract | PlainMessage | undefined, b: Contract | PlainMessage | undefined): boolean { - return proto3.util.equals(Contract, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_cosmes.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_cosmes.ts deleted file mode 100644 index b706abf75..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/query.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryChecksumsRequest, QueryChecksumsResponse, QueryCodeRequest, QueryCodeResponse } from "./query_pb.js"; - -const TYPE_NAME = "ibc.lightclients.wasm.v1.Query"; - -/** - * Get all Wasm checksums - * - * @generated from rpc ibc.lightclients.wasm.v1.Query.Checksums - */ -export const QueryChecksumsService = { - typeName: TYPE_NAME, - method: "Checksums", - Request: QueryChecksumsRequest, - Response: QueryChecksumsResponse, -} as const; - -/** - * Get Wasm code for given checksum - * - * @generated from rpc ibc.lightclients.wasm.v1.Query.Code - */ -export const QueryCodeService = { - typeName: TYPE_NAME, - method: "Code", - Request: QueryCodeRequest, - Response: QueryCodeResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_pb.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_pb.ts deleted file mode 100644 index e4ddae6b7..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/query_pb.ts +++ /dev/null @@ -1,179 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/query.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { PageRequest, PageResponse } from "../../../../cosmos/base/query/v1beta1/pagination_pb.js"; - -/** - * QueryChecksumsRequest is the request type for the Query/Checksums RPC method. - * - * @generated from message ibc.lightclients.wasm.v1.QueryChecksumsRequest - */ -export class QueryChecksumsRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.QueryChecksumsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChecksumsRequest { - return new QueryChecksumsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChecksumsRequest { - return new QueryChecksumsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChecksumsRequest { - return new QueryChecksumsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryChecksumsRequest | PlainMessage | undefined, b: QueryChecksumsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChecksumsRequest, a, b); - } -} - -/** - * QueryChecksumsResponse is the response type for the Query/Checksums RPC method. - * - * @generated from message ibc.lightclients.wasm.v1.QueryChecksumsResponse - */ -export class QueryChecksumsResponse extends Message { - /** - * checksums is a list of the hex encoded checksums of all wasm codes stored. - * - * @generated from field: repeated string checksums = 1; - */ - checksums: string[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.QueryChecksumsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "checksums", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryChecksumsResponse { - return new QueryChecksumsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryChecksumsResponse { - return new QueryChecksumsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryChecksumsResponse { - return new QueryChecksumsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryChecksumsResponse | PlainMessage | undefined, b: QueryChecksumsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryChecksumsResponse, a, b); - } -} - -/** - * QueryCodeRequest is the request type for the Query/Code RPC method. - * - * @generated from message ibc.lightclients.wasm.v1.QueryCodeRequest - */ -export class QueryCodeRequest extends Message { - /** - * checksum is a hex encoded string of the code stored. - * - * @generated from field: string checksum = 1; - */ - checksum = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.QueryCodeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "checksum", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeRequest { - return new QueryCodeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeRequest | PlainMessage | undefined, b: QueryCodeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeRequest, a, b); - } -} - -/** - * QueryCodeResponse is the response type for the Query/Code RPC method. - * - * @generated from message ibc.lightclients.wasm.v1.QueryCodeResponse - */ -export class QueryCodeResponse extends Message { - /** - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.QueryCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCodeResponse { - return new QueryCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCodeResponse | PlainMessage | undefined, b: QueryCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCodeResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_cosmes.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_cosmes.ts deleted file mode 100644 index 8b6e2f910..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_cosmes.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/tx.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgMigrateContract, MsgMigrateContractResponse, MsgRemoveChecksum, MsgRemoveChecksumResponse, MsgStoreCode, MsgStoreCodeResponse } from "./tx_pb.js"; - -const TYPE_NAME = "ibc.lightclients.wasm.v1.Msg"; - -/** - * StoreCode defines a rpc handler method for MsgStoreCode. - * - * @generated from rpc ibc.lightclients.wasm.v1.Msg.StoreCode - */ -export const MsgStoreCodeService = { - typeName: TYPE_NAME, - method: "StoreCode", - Request: MsgStoreCode, - Response: MsgStoreCodeResponse, -} as const; - -/** - * RemoveChecksum defines a rpc handler method for MsgRemoveChecksum. - * - * @generated from rpc ibc.lightclients.wasm.v1.Msg.RemoveChecksum - */ -export const MsgRemoveChecksumService = { - typeName: TYPE_NAME, - method: "RemoveChecksum", - Request: MsgRemoveChecksum, - Response: MsgRemoveChecksumResponse, -} as const; - -/** - * MigrateContract defines a rpc handler method for MsgMigrateContract. - * - * @generated from rpc ibc.lightclients.wasm.v1.Msg.MigrateContract - */ -export const MsgMigrateContractService = { - typeName: TYPE_NAME, - method: "MigrateContract", - Request: MsgMigrateContract, - Response: MsgMigrateContractResponse, -} as const; - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_pb.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_pb.ts deleted file mode 100644 index 50a5cffa8..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/tx_pb.ts +++ /dev/null @@ -1,278 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/tx.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * MsgStoreCode defines the request type for the StoreCode rpc. - * - * @generated from message ibc.lightclients.wasm.v1.MsgStoreCode - */ -export class MsgStoreCode extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * wasm byte code of light client contract. It can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 2; - */ - wasmByteCode = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgStoreCode"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreCode { - return new MsgStoreCode().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreCode | PlainMessage | undefined, b: MsgStoreCode | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreCode, a, b); - } -} - -/** - * MsgStoreCodeResponse defines the response type for the StoreCode rpc - * - * @generated from message ibc.lightclients.wasm.v1.MsgStoreCodeResponse - */ -export class MsgStoreCodeResponse extends Message { - /** - * checksum is the sha256 hash of the stored code - * - * @generated from field: bytes checksum = 1; - */ - checksum = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgStoreCodeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStoreCodeResponse { - return new MsgStoreCodeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgStoreCodeResponse | PlainMessage | undefined, b: MsgStoreCodeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStoreCodeResponse, a, b); - } -} - -/** - * MsgRemoveChecksum defines the request type for the MsgRemoveChecksum rpc. - * - * @generated from message ibc.lightclients.wasm.v1.MsgRemoveChecksum - */ -export class MsgRemoveChecksum extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * checksum is the sha256 hash to be removed from the store - * - * @generated from field: bytes checksum = 2; - */ - checksum = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgRemoveChecksum"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveChecksum { - return new MsgRemoveChecksum().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveChecksum { - return new MsgRemoveChecksum().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveChecksum { - return new MsgRemoveChecksum().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveChecksum | PlainMessage | undefined, b: MsgRemoveChecksum | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveChecksum, a, b); - } -} - -/** - * MsgStoreChecksumResponse defines the response type for the StoreCode rpc - * - * @generated from message ibc.lightclients.wasm.v1.MsgRemoveChecksumResponse - */ -export class MsgRemoveChecksumResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgRemoveChecksumResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveChecksumResponse { - return new MsgRemoveChecksumResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveChecksumResponse { - return new MsgRemoveChecksumResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveChecksumResponse { - return new MsgRemoveChecksumResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveChecksumResponse | PlainMessage | undefined, b: MsgRemoveChecksumResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveChecksumResponse, a, b); - } -} - -/** - * MsgMigrateContract defines the request type for the MigrateContract rpc. - * - * @generated from message ibc.lightclients.wasm.v1.MsgMigrateContract - */ -export class MsgMigrateContract extends Message { - /** - * signer address - * - * @generated from field: string signer = 1; - */ - signer = ""; - - /** - * the client id of the contract - * - * @generated from field: string client_id = 2; - */ - clientId = ""; - - /** - * checksum is the sha256 hash of the new wasm byte code for the contract - * - * @generated from field: bytes checksum = 3; - */ - checksum = new Uint8Array(0); - - /** - * the json encoded message to be passed to the contract on migration - * - * @generated from field: bytes msg = 4; - */ - msg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgMigrateContract"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "signer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "client_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMigrateContract { - return new MsgMigrateContract().fromJsonString(jsonString, options); - } - - static equals(a: MsgMigrateContract | PlainMessage | undefined, b: MsgMigrateContract | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMigrateContract, a, b); - } -} - -/** - * MsgMigrateContractResponse defines the response type for the MigrateContract rpc - * - * @generated from message ibc.lightclients.wasm.v1.MsgMigrateContractResponse - */ -export class MsgMigrateContractResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.MsgMigrateContractResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMigrateContractResponse { - return new MsgMigrateContractResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgMigrateContractResponse | PlainMessage | undefined, b: MsgMigrateContractResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMigrateContractResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/wasm_pb.ts b/packages/es/src/protobufs/ibc/lightclients/wasm/v1/wasm_pb.ts deleted file mode 100644 index 8219c45d3..000000000 --- a/packages/es/src/protobufs/ibc/lightclients/wasm/v1/wasm_pb.ts +++ /dev/null @@ -1,144 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file ibc/lightclients/wasm/v1/wasm.proto (package ibc.lightclients.wasm.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Height } from "../../../core/client/v1/client_pb.js"; - -/** - * Wasm light client's Client state - * - * @generated from message ibc.lightclients.wasm.v1.ClientState - */ -export class ClientState extends Message { - /** - * bytes encoding the client state of the underlying light client - * implemented as a Wasm contract. - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - /** - * @generated from field: bytes checksum = 2; - */ - checksum = new Uint8Array(0); - - /** - * @generated from field: ibc.core.client.v1.Height latest_height = 3; - */ - latestHeight?: Height; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.ClientState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "checksum", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "latest_height", kind: "message", T: Height }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientState { - return new ClientState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientState { - return new ClientState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientState { - return new ClientState().fromJsonString(jsonString, options); - } - - static equals(a: ClientState | PlainMessage | undefined, b: ClientState | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientState, a, b); - } -} - -/** - * Wasm light client's ConsensusState - * - * @generated from message ibc.lightclients.wasm.v1.ConsensusState - */ -export class ConsensusState extends Message { - /** - * bytes encoding the consensus state of the underlying light client - * implemented as a Wasm contract. - * - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.ConsensusState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConsensusState { - return new ConsensusState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConsensusState { - return new ConsensusState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConsensusState { - return new ConsensusState().fromJsonString(jsonString, options); - } - - static equals(a: ConsensusState | PlainMessage | undefined, b: ConsensusState | PlainMessage | undefined): boolean { - return proto3.util.equals(ConsensusState, a, b); - } -} - -/** - * Wasm light client message (either header(s) or misbehaviour) - * - * @generated from message ibc.lightclients.wasm.v1.ClientMessage - */ -export class ClientMessage extends Message { - /** - * @generated from field: bytes data = 1; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "ibc.lightclients.wasm.v1.ClientMessage"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClientMessage { - return new ClientMessage().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClientMessage { - return new ClientMessage().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClientMessage { - return new ClientMessage().fromJsonString(jsonString, options); - } - - static equals(a: ClientMessage | PlainMessage | undefined, b: ClientMessage | PlainMessage | undefined): boolean { - return proto3.util.equals(ClientMessage, a, b); - } -} - diff --git a/packages/es/src/protobufs/index.ts b/packages/es/src/protobufs/index.ts deleted file mode 100644 index 12cb90d76..000000000 --- a/packages/es/src/protobufs/index.ts +++ /dev/null @@ -1,2711 +0,0 @@ -/** This file is generated by gen-protobufs.mjs. Do not edit. */ - -export { -} from "./index.js"; -export { - MsgUpdateParams as SvcV1MsgUpdateParams, - MsgUpdateParamsResponse as SvcV1MsgUpdateParamsResponse, - MsgInitiateDomainVerification as SvcV1MsgInitiateDomainVerification, - MsgInitiateDomainVerificationResponse as SvcV1MsgInitiateDomainVerificationResponse, - MsgVerifyDomain as SvcV1MsgVerifyDomain, - MsgVerifyDomainResponse as SvcV1MsgVerifyDomainResponse, - MsgRegisterService as SvcV1MsgRegisterService, - MsgRegisterServiceResponse as SvcV1MsgRegisterServiceResponse, -} from "./svc/v1/tx_pb.js"; -export { - MsgUpdateParamsService as SvcV1MsgUpdateParamsService, - MsgInitiateDomainVerificationService as SvcV1MsgInitiateDomainVerificationService, - MsgVerifyDomainService as SvcV1MsgVerifyDomainService, - MsgRegisterServiceService as SvcV1MsgRegisterServiceService, -} from "./svc/v1/tx_cosmes.js"; -export { - DomainVerificationStatus as SvcV1DomainVerificationStatus, - ServiceStatus as SvcV1ServiceStatus, - Service as SvcV1Service, - DomainVerification as SvcV1DomainVerification, - ServiceCapability as SvcV1ServiceCapability, - ServiceResource as SvcV1ServiceResource, - ServiceOIDCConfig as SvcV1ServiceOIDCConfig, - JWK as SvcV1JWK, - ServiceJWKS as SvcV1ServiceJWKS, -} from "./svc/v1/state_pb.js"; -export { - QueryParamsRequest as SvcV1QueryParamsRequest, - QueryParamsResponse as SvcV1QueryParamsResponse, - QueryDomainVerificationRequest as SvcV1QueryDomainVerificationRequest, - QueryDomainVerificationResponse as SvcV1QueryDomainVerificationResponse, - QueryServiceRequest as SvcV1QueryServiceRequest, - QueryServiceResponse as SvcV1QueryServiceResponse, - QueryServicesByOwnerRequest as SvcV1QueryServicesByOwnerRequest, - QueryServicesByOwnerResponse as SvcV1QueryServicesByOwnerResponse, - QueryServicesByDomainRequest as SvcV1QueryServicesByDomainRequest, - QueryServicesByDomainResponse as SvcV1QueryServicesByDomainResponse, - QueryServiceOIDCDiscoveryRequest as SvcV1QueryServiceOIDCDiscoveryRequest, - QueryServiceOIDCDiscoveryResponse as SvcV1QueryServiceOIDCDiscoveryResponse, - QueryServiceOIDCJWKSRequest as SvcV1QueryServiceOIDCJWKSRequest, - QueryServiceOIDCJWKSResponse as SvcV1QueryServiceOIDCJWKSResponse, - QueryServiceOIDCMetadataRequest as SvcV1QueryServiceOIDCMetadataRequest, - QueryServiceOIDCMetadataResponse as SvcV1QueryServiceOIDCMetadataResponse, -} from "./svc/v1/query_pb.js"; -export { - QueryParamsService as SvcV1QueryParamsService, - QueryDomainVerificationService as SvcV1QueryDomainVerificationService, - QueryServiceService as SvcV1QueryServiceService, - QueryServicesByOwnerService as SvcV1QueryServicesByOwnerService, - QueryServicesByDomainService as SvcV1QueryServicesByDomainService, - QueryServiceOIDCDiscoveryService as SvcV1QueryServiceOIDCDiscoveryService, - QueryServiceOIDCJWKSService as SvcV1QueryServiceOIDCJWKSService, - QueryServiceOIDCMetadataService as SvcV1QueryServiceOIDCMetadataService, -} from "./svc/v1/query_cosmes.js"; -export { - GenesisState as SvcV1GenesisState, - Params as SvcV1Params, -} from "./svc/v1/genesis_pb.js"; -export { - EventDomainVerificationInitiated as SvcV1EventDomainVerificationInitiated, - EventDomainVerified as SvcV1EventDomainVerified, - EventServiceRegistered as SvcV1EventServiceRegistered, -} from "./svc/v1/events_pb.js"; -export { - Module as SvcModuleV1Module, -} from "./svc/module/v1/module_pb.js"; -export { - MsgSetValidatorSetPreference as OsmosisValsetprefV1beta1MsgSetValidatorSetPreference, - MsgSetValidatorSetPreferenceResponse as OsmosisValsetprefV1beta1MsgSetValidatorSetPreferenceResponse, - MsgDelegateToValidatorSet as OsmosisValsetprefV1beta1MsgDelegateToValidatorSet, - MsgDelegateToValidatorSetResponse as OsmosisValsetprefV1beta1MsgDelegateToValidatorSetResponse, - MsgUndelegateFromValidatorSet as OsmosisValsetprefV1beta1MsgUndelegateFromValidatorSet, - MsgUndelegateFromValidatorSetResponse as OsmosisValsetprefV1beta1MsgUndelegateFromValidatorSetResponse, - MsgUndelegateFromRebalancedValidatorSet as OsmosisValsetprefV1beta1MsgUndelegateFromRebalancedValidatorSet, - MsgUndelegateFromRebalancedValidatorSetResponse as OsmosisValsetprefV1beta1MsgUndelegateFromRebalancedValidatorSetResponse, - MsgRedelegateValidatorSet as OsmosisValsetprefV1beta1MsgRedelegateValidatorSet, - MsgRedelegateValidatorSetResponse as OsmosisValsetprefV1beta1MsgRedelegateValidatorSetResponse, - MsgWithdrawDelegationRewards as OsmosisValsetprefV1beta1MsgWithdrawDelegationRewards, - MsgWithdrawDelegationRewardsResponse as OsmosisValsetprefV1beta1MsgWithdrawDelegationRewardsResponse, - MsgDelegateBondedTokens as OsmosisValsetprefV1beta1MsgDelegateBondedTokens, - MsgDelegateBondedTokensResponse as OsmosisValsetprefV1beta1MsgDelegateBondedTokensResponse, -} from "./osmosis/valsetpref/v1beta1/tx_pb.js"; -export { - MsgSetValidatorSetPreferenceService as OsmosisValsetprefV1beta1MsgSetValidatorSetPreferenceService, - MsgDelegateToValidatorSetService as OsmosisValsetprefV1beta1MsgDelegateToValidatorSetService, - MsgUndelegateFromValidatorSetService as OsmosisValsetprefV1beta1MsgUndelegateFromValidatorSetService, - MsgUndelegateFromRebalancedValidatorSetService as OsmosisValsetprefV1beta1MsgUndelegateFromRebalancedValidatorSetService, - MsgRedelegateValidatorSetService as OsmosisValsetprefV1beta1MsgRedelegateValidatorSetService, - MsgWithdrawDelegationRewardsService as OsmosisValsetprefV1beta1MsgWithdrawDelegationRewardsService, - MsgDelegateBondedTokensService as OsmosisValsetprefV1beta1MsgDelegateBondedTokensService, -} from "./osmosis/valsetpref/v1beta1/tx_cosmes.js"; -export { - ValidatorPreference as OsmosisValsetprefV1beta1ValidatorPreference, - ValidatorSetPreferences as OsmosisValsetprefV1beta1ValidatorSetPreferences, -} from "./osmosis/valsetpref/v1beta1/state_pb.js"; -export { - UserValidatorPreferencesRequest as OsmosisValsetprefV1beta1UserValidatorPreferencesRequest, - UserValidatorPreferencesResponse as OsmosisValsetprefV1beta1UserValidatorPreferencesResponse, -} from "./osmosis/valsetpref/v1beta1/query_pb.js"; -export { - QueryUserValidatorPreferencesService as OsmosisValsetprefV1beta1QueryUserValidatorPreferencesService, -} from "./osmosis/valsetpref/v1beta1/query_cosmes.js"; -export { - MsgSetFeeTokens as OsmosisTxfeesV1beta1MsgSetFeeTokens, - MsgSetFeeTokensResponse as OsmosisTxfeesV1beta1MsgSetFeeTokensResponse, -} from "./osmosis/txfees/v1beta1/tx_pb.js"; -export { - MsgSetFeeTokensService as OsmosisTxfeesV1beta1MsgSetFeeTokensService, -} from "./osmosis/txfees/v1beta1/tx_cosmes.js"; -export { - QueryFeeTokensRequest as OsmosisTxfeesV1beta1QueryFeeTokensRequest, - QueryFeeTokensResponse as OsmosisTxfeesV1beta1QueryFeeTokensResponse, - QueryDenomSpotPriceRequest as OsmosisTxfeesV1beta1QueryDenomSpotPriceRequest, - QueryDenomSpotPriceResponse as OsmosisTxfeesV1beta1QueryDenomSpotPriceResponse, - QueryDenomPoolIdRequest as OsmosisTxfeesV1beta1QueryDenomPoolIdRequest, - QueryDenomPoolIdResponse as OsmosisTxfeesV1beta1QueryDenomPoolIdResponse, - QueryBaseDenomRequest as OsmosisTxfeesV1beta1QueryBaseDenomRequest, - QueryBaseDenomResponse as OsmosisTxfeesV1beta1QueryBaseDenomResponse, - QueryEipBaseFeeRequest as OsmosisTxfeesV1beta1QueryEipBaseFeeRequest, - QueryEipBaseFeeResponse as OsmosisTxfeesV1beta1QueryEipBaseFeeResponse, -} from "./osmosis/txfees/v1beta1/query_pb.js"; -export { - QueryFeeTokensService as OsmosisTxfeesV1beta1QueryFeeTokensService, - QueryDenomSpotPriceService as OsmosisTxfeesV1beta1QueryDenomSpotPriceService, - QueryDenomPoolIdService as OsmosisTxfeesV1beta1QueryDenomPoolIdService, - QueryBaseDenomService as OsmosisTxfeesV1beta1QueryBaseDenomService, - QueryGetEipBaseFeeService as OsmosisTxfeesV1beta1QueryGetEipBaseFeeService, -} from "./osmosis/txfees/v1beta1/query_cosmes.js"; -export { - Params as OsmosisTxfeesV1beta1Params, -} from "./osmosis/txfees/v1beta1/params_pb.js"; -export { - UpdateFeeTokenProposal as OsmosisTxfeesV1beta1UpdateFeeTokenProposal, -} from "./osmosis/txfees/v1beta1/gov_pb.js"; -export { - GenesisState as OsmosisTxfeesV1beta1GenesisState, - TxFeesTracker as OsmosisTxfeesV1beta1TxFeesTracker, -} from "./osmosis/txfees/v1beta1/genesis_pb.js"; -export { - FeeToken as OsmosisTxfeesV1beta1FeeToken, -} from "./osmosis/txfees/v1beta1/feetoken_pb.js"; -export { - TwapRecord as OsmosisTwapV1beta1TwapRecord, - PruningState as OsmosisTwapV1beta1PruningState, -} from "./osmosis/twap/v1beta1/twap_record_pb.js"; -export { - ArithmeticTwapRequest as OsmosisTwapV1beta1ArithmeticTwapRequest, - ArithmeticTwapResponse as OsmosisTwapV1beta1ArithmeticTwapResponse, - ArithmeticTwapToNowRequest as OsmosisTwapV1beta1ArithmeticTwapToNowRequest, - ArithmeticTwapToNowResponse as OsmosisTwapV1beta1ArithmeticTwapToNowResponse, - GeometricTwapRequest as OsmosisTwapV1beta1GeometricTwapRequest, - GeometricTwapResponse as OsmosisTwapV1beta1GeometricTwapResponse, - GeometricTwapToNowRequest as OsmosisTwapV1beta1GeometricTwapToNowRequest, - GeometricTwapToNowResponse as OsmosisTwapV1beta1GeometricTwapToNowResponse, - ParamsRequest as OsmosisTwapV1beta1ParamsRequest, - ParamsResponse as OsmosisTwapV1beta1ParamsResponse, -} from "./osmosis/twap/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisTwapV1beta1QueryParamsService, - QueryArithmeticTwapService as OsmosisTwapV1beta1QueryArithmeticTwapService, - QueryArithmeticTwapToNowService as OsmosisTwapV1beta1QueryArithmeticTwapToNowService, - QueryGeometricTwapService as OsmosisTwapV1beta1QueryGeometricTwapService, - QueryGeometricTwapToNowService as OsmosisTwapV1beta1QueryGeometricTwapToNowService, -} from "./osmosis/twap/v1beta1/query_cosmes.js"; -export { - Params as OsmosisTwapV1beta1Params, - GenesisState as OsmosisTwapV1beta1GenesisState, -} from "./osmosis/twap/v1beta1/genesis_pb.js"; -export { - MsgCreateDenom as OsmosisTokenfactoryV1beta1MsgCreateDenom, - MsgCreateDenomResponse as OsmosisTokenfactoryV1beta1MsgCreateDenomResponse, - MsgMint as OsmosisTokenfactoryV1beta1MsgMint, - MsgMintResponse as OsmosisTokenfactoryV1beta1MsgMintResponse, - MsgBurn as OsmosisTokenfactoryV1beta1MsgBurn, - MsgBurnResponse as OsmosisTokenfactoryV1beta1MsgBurnResponse, - MsgChangeAdmin as OsmosisTokenfactoryV1beta1MsgChangeAdmin, - MsgChangeAdminResponse as OsmosisTokenfactoryV1beta1MsgChangeAdminResponse, - MsgSetBeforeSendHook as OsmosisTokenfactoryV1beta1MsgSetBeforeSendHook, - MsgSetBeforeSendHookResponse as OsmosisTokenfactoryV1beta1MsgSetBeforeSendHookResponse, - MsgSetDenomMetadata as OsmosisTokenfactoryV1beta1MsgSetDenomMetadata, - MsgSetDenomMetadataResponse as OsmosisTokenfactoryV1beta1MsgSetDenomMetadataResponse, - MsgForceTransfer as OsmosisTokenfactoryV1beta1MsgForceTransfer, - MsgForceTransferResponse as OsmosisTokenfactoryV1beta1MsgForceTransferResponse, -} from "./osmosis/tokenfactory/v1beta1/tx_pb.js"; -export { - MsgCreateDenomService as OsmosisTokenfactoryV1beta1MsgCreateDenomService, - MsgMintService as OsmosisTokenfactoryV1beta1MsgMintService, - MsgBurnService as OsmosisTokenfactoryV1beta1MsgBurnService, - MsgChangeAdminService as OsmosisTokenfactoryV1beta1MsgChangeAdminService, - MsgSetDenomMetadataService as OsmosisTokenfactoryV1beta1MsgSetDenomMetadataService, - MsgSetBeforeSendHookService as OsmosisTokenfactoryV1beta1MsgSetBeforeSendHookService, - MsgForceTransferService as OsmosisTokenfactoryV1beta1MsgForceTransferService, -} from "./osmosis/tokenfactory/v1beta1/tx_cosmes.js"; -export { - QueryParamsRequest as OsmosisTokenfactoryV1beta1QueryParamsRequest, - QueryParamsResponse as OsmosisTokenfactoryV1beta1QueryParamsResponse, - QueryDenomAuthorityMetadataRequest as OsmosisTokenfactoryV1beta1QueryDenomAuthorityMetadataRequest, - QueryDenomAuthorityMetadataResponse as OsmosisTokenfactoryV1beta1QueryDenomAuthorityMetadataResponse, - QueryDenomsFromCreatorRequest as OsmosisTokenfactoryV1beta1QueryDenomsFromCreatorRequest, - QueryDenomsFromCreatorResponse as OsmosisTokenfactoryV1beta1QueryDenomsFromCreatorResponse, - QueryBeforeSendHookAddressRequest as OsmosisTokenfactoryV1beta1QueryBeforeSendHookAddressRequest, - QueryBeforeSendHookAddressResponse as OsmosisTokenfactoryV1beta1QueryBeforeSendHookAddressResponse, - QueryAllBeforeSendHooksAddressesRequest as OsmosisTokenfactoryV1beta1QueryAllBeforeSendHooksAddressesRequest, - QueryAllBeforeSendHooksAddressesResponse as OsmosisTokenfactoryV1beta1QueryAllBeforeSendHooksAddressesResponse, -} from "./osmosis/tokenfactory/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisTokenfactoryV1beta1QueryParamsService, - QueryDenomAuthorityMetadataService as OsmosisTokenfactoryV1beta1QueryDenomAuthorityMetadataService, - QueryDenomsFromCreatorService as OsmosisTokenfactoryV1beta1QueryDenomsFromCreatorService, - QueryBeforeSendHookAddressService as OsmosisTokenfactoryV1beta1QueryBeforeSendHookAddressService, - QueryAllBeforeSendHooksAddressesService as OsmosisTokenfactoryV1beta1QueryAllBeforeSendHooksAddressesService, -} from "./osmosis/tokenfactory/v1beta1/query_cosmes.js"; -export { - Params as OsmosisTokenfactoryV1beta1Params, -} from "./osmosis/tokenfactory/v1beta1/params_pb.js"; -export { - GenesisState as OsmosisTokenfactoryV1beta1GenesisState, - GenesisDenom as OsmosisTokenfactoryV1beta1GenesisDenom, -} from "./osmosis/tokenfactory/v1beta1/genesis_pb.js"; -export { - DenomAuthorityMetadata as OsmosisTokenfactoryV1beta1DenomAuthorityMetadata, -} from "./osmosis/tokenfactory/v1beta1/authorityMetadata_pb.js"; -export { - MsgSuperfluidDelegate as OsmosisSuperfluidMsgSuperfluidDelegate, - MsgSuperfluidDelegateResponse as OsmosisSuperfluidMsgSuperfluidDelegateResponse, - MsgSuperfluidUndelegate as OsmosisSuperfluidMsgSuperfluidUndelegate, - MsgSuperfluidUndelegateResponse as OsmosisSuperfluidMsgSuperfluidUndelegateResponse, - MsgSuperfluidUnbondLock as OsmosisSuperfluidMsgSuperfluidUnbondLock, - MsgSuperfluidUnbondLockResponse as OsmosisSuperfluidMsgSuperfluidUnbondLockResponse, - MsgSuperfluidUndelegateAndUnbondLock as OsmosisSuperfluidMsgSuperfluidUndelegateAndUnbondLock, - MsgSuperfluidUndelegateAndUnbondLockResponse as OsmosisSuperfluidMsgSuperfluidUndelegateAndUnbondLockResponse, - MsgLockAndSuperfluidDelegate as OsmosisSuperfluidMsgLockAndSuperfluidDelegate, - MsgLockAndSuperfluidDelegateResponse as OsmosisSuperfluidMsgLockAndSuperfluidDelegateResponse, - MsgCreateFullRangePositionAndSuperfluidDelegate as OsmosisSuperfluidMsgCreateFullRangePositionAndSuperfluidDelegate, - MsgCreateFullRangePositionAndSuperfluidDelegateResponse as OsmosisSuperfluidMsgCreateFullRangePositionAndSuperfluidDelegateResponse, - MsgUnPoolWhitelistedPool as OsmosisSuperfluidMsgUnPoolWhitelistedPool, - MsgUnPoolWhitelistedPoolResponse as OsmosisSuperfluidMsgUnPoolWhitelistedPoolResponse, - MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition as OsmosisSuperfluidMsgUnlockAndMigrateSharesToFullRangeConcentratedPosition, - MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse as OsmosisSuperfluidMsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse, - MsgAddToConcentratedLiquiditySuperfluidPosition as OsmosisSuperfluidMsgAddToConcentratedLiquiditySuperfluidPosition, - MsgAddToConcentratedLiquiditySuperfluidPositionResponse as OsmosisSuperfluidMsgAddToConcentratedLiquiditySuperfluidPositionResponse, - MsgUnbondConvertAndStake as OsmosisSuperfluidMsgUnbondConvertAndStake, - MsgUnbondConvertAndStakeResponse as OsmosisSuperfluidMsgUnbondConvertAndStakeResponse, -} from "./osmosis/superfluid/tx_pb.js"; -export { - MsgSuperfluidDelegateService as OsmosisSuperfluidMsgSuperfluidDelegateService, - MsgSuperfluidUndelegateService as OsmosisSuperfluidMsgSuperfluidUndelegateService, - MsgSuperfluidUnbondLockService as OsmosisSuperfluidMsgSuperfluidUnbondLockService, - MsgSuperfluidUndelegateAndUnbondLockService as OsmosisSuperfluidMsgSuperfluidUndelegateAndUnbondLockService, - MsgLockAndSuperfluidDelegateService as OsmosisSuperfluidMsgLockAndSuperfluidDelegateService, - MsgCreateFullRangePositionAndSuperfluidDelegateService as OsmosisSuperfluidMsgCreateFullRangePositionAndSuperfluidDelegateService, - MsgUnPoolWhitelistedPoolService as OsmosisSuperfluidMsgUnPoolWhitelistedPoolService, - MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionService as OsmosisSuperfluidMsgUnlockAndMigrateSharesToFullRangeConcentratedPositionService, - MsgAddToConcentratedLiquiditySuperfluidPositionService as OsmosisSuperfluidMsgAddToConcentratedLiquiditySuperfluidPositionService, - MsgUnbondConvertAndStakeService as OsmosisSuperfluidMsgUnbondConvertAndStakeService, -} from "./osmosis/superfluid/tx_cosmes.js"; -export { - SuperfluidAssetType as OsmosisSuperfluidSuperfluidAssetType, - SuperfluidAsset as OsmosisSuperfluidSuperfluidAsset, - SuperfluidIntermediaryAccount as OsmosisSuperfluidSuperfluidIntermediaryAccount, - OsmoEquivalentMultiplierRecord as OsmosisSuperfluidOsmoEquivalentMultiplierRecord, - SuperfluidDelegationRecord as OsmosisSuperfluidSuperfluidDelegationRecord, - LockIdIntermediaryAccountConnection as OsmosisSuperfluidLockIdIntermediaryAccountConnection, - UnpoolWhitelistedPools as OsmosisSuperfluidUnpoolWhitelistedPools, - ConcentratedPoolUserPositionRecord as OsmosisSuperfluidConcentratedPoolUserPositionRecord, -} from "./osmosis/superfluid/superfluid_pb.js"; -export { - QueryParamsRequest as OsmosisSuperfluidQueryParamsRequest, - QueryParamsResponse as OsmosisSuperfluidQueryParamsResponse, - AssetTypeRequest as OsmosisSuperfluidAssetTypeRequest, - AssetTypeResponse as OsmosisSuperfluidAssetTypeResponse, - AllAssetsRequest as OsmosisSuperfluidAllAssetsRequest, - AllAssetsResponse as OsmosisSuperfluidAllAssetsResponse, - AssetMultiplierRequest as OsmosisSuperfluidAssetMultiplierRequest, - AssetMultiplierResponse as OsmosisSuperfluidAssetMultiplierResponse, - SuperfluidIntermediaryAccountInfo as OsmosisSuperfluidSuperfluidIntermediaryAccountInfo, - AllIntermediaryAccountsRequest as OsmosisSuperfluidAllIntermediaryAccountsRequest, - AllIntermediaryAccountsResponse as OsmosisSuperfluidAllIntermediaryAccountsResponse, - ConnectedIntermediaryAccountRequest as OsmosisSuperfluidConnectedIntermediaryAccountRequest, - ConnectedIntermediaryAccountResponse as OsmosisSuperfluidConnectedIntermediaryAccountResponse, - QueryTotalDelegationByValidatorForDenomRequest as OsmosisSuperfluidQueryTotalDelegationByValidatorForDenomRequest, - QueryTotalDelegationByValidatorForDenomResponse as OsmosisSuperfluidQueryTotalDelegationByValidatorForDenomResponse, - Delegations as OsmosisSuperfluidDelegations, - TotalSuperfluidDelegationsRequest as OsmosisSuperfluidTotalSuperfluidDelegationsRequest, - TotalSuperfluidDelegationsResponse as OsmosisSuperfluidTotalSuperfluidDelegationsResponse, - SuperfluidDelegationAmountRequest as OsmosisSuperfluidSuperfluidDelegationAmountRequest, - SuperfluidDelegationAmountResponse as OsmosisSuperfluidSuperfluidDelegationAmountResponse, - SuperfluidDelegationsByDelegatorRequest as OsmosisSuperfluidSuperfluidDelegationsByDelegatorRequest, - SuperfluidDelegationsByDelegatorResponse as OsmosisSuperfluidSuperfluidDelegationsByDelegatorResponse, - SuperfluidUndelegationsByDelegatorRequest as OsmosisSuperfluidSuperfluidUndelegationsByDelegatorRequest, - SuperfluidUndelegationsByDelegatorResponse as OsmosisSuperfluidSuperfluidUndelegationsByDelegatorResponse, - SuperfluidDelegationsByValidatorDenomRequest as OsmosisSuperfluidSuperfluidDelegationsByValidatorDenomRequest, - SuperfluidDelegationsByValidatorDenomResponse as OsmosisSuperfluidSuperfluidDelegationsByValidatorDenomResponse, - EstimateSuperfluidDelegatedAmountByValidatorDenomRequest as OsmosisSuperfluidEstimateSuperfluidDelegatedAmountByValidatorDenomRequest, - EstimateSuperfluidDelegatedAmountByValidatorDenomResponse as OsmosisSuperfluidEstimateSuperfluidDelegatedAmountByValidatorDenomResponse, - QueryTotalDelegationByDelegatorRequest as OsmosisSuperfluidQueryTotalDelegationByDelegatorRequest, - QueryTotalDelegationByDelegatorResponse as OsmosisSuperfluidQueryTotalDelegationByDelegatorResponse, - QueryUnpoolWhitelistRequest as OsmosisSuperfluidQueryUnpoolWhitelistRequest, - QueryUnpoolWhitelistResponse as OsmosisSuperfluidQueryUnpoolWhitelistResponse, - UserConcentratedSuperfluidPositionsDelegatedRequest as OsmosisSuperfluidUserConcentratedSuperfluidPositionsDelegatedRequest, - UserConcentratedSuperfluidPositionsDelegatedResponse as OsmosisSuperfluidUserConcentratedSuperfluidPositionsDelegatedResponse, - UserConcentratedSuperfluidPositionsUndelegatingRequest as OsmosisSuperfluidUserConcentratedSuperfluidPositionsUndelegatingRequest, - UserConcentratedSuperfluidPositionsUndelegatingResponse as OsmosisSuperfluidUserConcentratedSuperfluidPositionsUndelegatingResponse, - QueryRestSupplyRequest as OsmosisSuperfluidQueryRestSupplyRequest, - QueryRestSupplyResponse as OsmosisSuperfluidQueryRestSupplyResponse, -} from "./osmosis/superfluid/query_pb.js"; -export { - QueryParamsService as OsmosisSuperfluidQueryParamsService, - QueryAssetTypeService as OsmosisSuperfluidQueryAssetTypeService, - QueryAllAssetsService as OsmosisSuperfluidQueryAllAssetsService, - QueryAssetMultiplierService as OsmosisSuperfluidQueryAssetMultiplierService, - QueryAllIntermediaryAccountsService as OsmosisSuperfluidQueryAllIntermediaryAccountsService, - QueryConnectedIntermediaryAccountService as OsmosisSuperfluidQueryConnectedIntermediaryAccountService, - QueryTotalDelegationByValidatorForDenomService as OsmosisSuperfluidQueryTotalDelegationByValidatorForDenomService, - QueryTotalSuperfluidDelegationsService as OsmosisSuperfluidQueryTotalSuperfluidDelegationsService, - QuerySuperfluidDelegationAmountService as OsmosisSuperfluidQuerySuperfluidDelegationAmountService, - QuerySuperfluidDelegationsByDelegatorService as OsmosisSuperfluidQuerySuperfluidDelegationsByDelegatorService, - QuerySuperfluidUndelegationsByDelegatorService as OsmosisSuperfluidQuerySuperfluidUndelegationsByDelegatorService, - QuerySuperfluidDelegationsByValidatorDenomService as OsmosisSuperfluidQuerySuperfluidDelegationsByValidatorDenomService, - QueryEstimateSuperfluidDelegatedAmountByValidatorDenomService as OsmosisSuperfluidQueryEstimateSuperfluidDelegatedAmountByValidatorDenomService, - QueryTotalDelegationByDelegatorService as OsmosisSuperfluidQueryTotalDelegationByDelegatorService, - QueryUnpoolWhitelistService as OsmosisSuperfluidQueryUnpoolWhitelistService, - QueryUserConcentratedSuperfluidPositionsDelegatedService as OsmosisSuperfluidQueryUserConcentratedSuperfluidPositionsDelegatedService, - QueryUserConcentratedSuperfluidPositionsUndelegatingService as OsmosisSuperfluidQueryUserConcentratedSuperfluidPositionsUndelegatingService, - QueryRestSupplyService as OsmosisSuperfluidQueryRestSupplyService, -} from "./osmosis/superfluid/query_cosmes.js"; -export { - Params as OsmosisSuperfluidParams, -} from "./osmosis/superfluid/params_pb.js"; -export { - GenesisState as OsmosisSuperfluidGenesisState, -} from "./osmosis/superfluid/genesis_pb.js"; -export { - SetSuperfluidAssetsProposal as OsmosisSuperfluidV1beta1SetSuperfluidAssetsProposal, - RemoveSuperfluidAssetsProposal as OsmosisSuperfluidV1beta1RemoveSuperfluidAssetsProposal, - UpdateUnpoolWhiteListProposal as OsmosisSuperfluidV1beta1UpdateUnpoolWhiteListProposal, -} from "./osmosis/superfluid/v1beta1/gov_pb.js"; -export { - Node as OsmosisStoreV1beta1Node, - Child as OsmosisStoreV1beta1Child, - Leaf as OsmosisStoreV1beta1Leaf, -} from "./osmosis/store/v1beta1/tree_pb.js"; -export { - MsgAddAuthenticator as OsmosisSmartaccountV1beta1MsgAddAuthenticator, - MsgAddAuthenticatorResponse as OsmosisSmartaccountV1beta1MsgAddAuthenticatorResponse, - MsgRemoveAuthenticator as OsmosisSmartaccountV1beta1MsgRemoveAuthenticator, - MsgRemoveAuthenticatorResponse as OsmosisSmartaccountV1beta1MsgRemoveAuthenticatorResponse, - MsgSetActiveState as OsmosisSmartaccountV1beta1MsgSetActiveState, - MsgSetActiveStateResponse as OsmosisSmartaccountV1beta1MsgSetActiveStateResponse, - TxExtension as OsmosisSmartaccountV1beta1TxExtension, -} from "./osmosis/smartaccount/v1beta1/tx_pb.js"; -export { - MsgAddAuthenticatorService as OsmosisSmartaccountV1beta1MsgAddAuthenticatorService, - MsgRemoveAuthenticatorService as OsmosisSmartaccountV1beta1MsgRemoveAuthenticatorService, - MsgSetActiveStateService as OsmosisSmartaccountV1beta1MsgSetActiveStateService, -} from "./osmosis/smartaccount/v1beta1/tx_cosmes.js"; -export { - QueryParamsRequest as OsmosisSmartaccountV1beta1QueryParamsRequest, - QueryParamsResponse as OsmosisSmartaccountV1beta1QueryParamsResponse, - GetAuthenticatorsRequest as OsmosisSmartaccountV1beta1GetAuthenticatorsRequest, - GetAuthenticatorsResponse as OsmosisSmartaccountV1beta1GetAuthenticatorsResponse, - GetAuthenticatorRequest as OsmosisSmartaccountV1beta1GetAuthenticatorRequest, - GetAuthenticatorResponse as OsmosisSmartaccountV1beta1GetAuthenticatorResponse, -} from "./osmosis/smartaccount/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisSmartaccountV1beta1QueryParamsService, - QueryGetAuthenticatorService as OsmosisSmartaccountV1beta1QueryGetAuthenticatorService, - QueryGetAuthenticatorsService as OsmosisSmartaccountV1beta1QueryGetAuthenticatorsService, -} from "./osmosis/smartaccount/v1beta1/query_cosmes.js"; -export { - Params as OsmosisSmartaccountV1beta1Params, -} from "./osmosis/smartaccount/v1beta1/params_pb.js"; -export { - AccountAuthenticator as OsmosisSmartaccountV1beta1AccountAuthenticator, -} from "./osmosis/smartaccount/v1beta1/models_pb.js"; -export { - AuthenticatorData as OsmosisSmartaccountV1beta1AuthenticatorData, - GenesisState as OsmosisSmartaccountV1beta1GenesisState, -} from "./osmosis/smartaccount/v1beta1/genesis_pb.js"; -export { - MsgSetHotRoutes as OsmosisProtorevV1beta1MsgSetHotRoutes, - MsgSetHotRoutesResponse as OsmosisProtorevV1beta1MsgSetHotRoutesResponse, - MsgSetDeveloperAccount as OsmosisProtorevV1beta1MsgSetDeveloperAccount, - MsgSetDeveloperAccountResponse as OsmosisProtorevV1beta1MsgSetDeveloperAccountResponse, - MsgSetInfoByPoolType as OsmosisProtorevV1beta1MsgSetInfoByPoolType, - MsgSetInfoByPoolTypeResponse as OsmosisProtorevV1beta1MsgSetInfoByPoolTypeResponse, - MsgSetMaxPoolPointsPerTx as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerTx, - MsgSetMaxPoolPointsPerTxResponse as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerTxResponse, - MsgSetMaxPoolPointsPerBlock as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerBlock, - MsgSetMaxPoolPointsPerBlockResponse as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerBlockResponse, - MsgSetBaseDenoms as OsmosisProtorevV1beta1MsgSetBaseDenoms, - MsgSetBaseDenomsResponse as OsmosisProtorevV1beta1MsgSetBaseDenomsResponse, - MsgSetPoolWeights as OsmosisProtorevV1beta1MsgSetPoolWeights, -} from "./osmosis/protorev/v1beta1/tx_pb.js"; -export { - MsgSetHotRoutesService as OsmosisProtorevV1beta1MsgSetHotRoutesService, - MsgSetDeveloperAccountService as OsmosisProtorevV1beta1MsgSetDeveloperAccountService, - MsgSetMaxPoolPointsPerTxService as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerTxService, - MsgSetMaxPoolPointsPerBlockService as OsmosisProtorevV1beta1MsgSetMaxPoolPointsPerBlockService, - MsgSetInfoByPoolTypeService as OsmosisProtorevV1beta1MsgSetInfoByPoolTypeService, - MsgSetBaseDenomsService as OsmosisProtorevV1beta1MsgSetBaseDenomsService, -} from "./osmosis/protorev/v1beta1/tx_cosmes.js"; -export { - QueryParamsRequest as OsmosisProtorevV1beta1QueryParamsRequest, - QueryParamsResponse as OsmosisProtorevV1beta1QueryParamsResponse, - QueryGetProtoRevNumberOfTradesRequest as OsmosisProtorevV1beta1QueryGetProtoRevNumberOfTradesRequest, - QueryGetProtoRevNumberOfTradesResponse as OsmosisProtorevV1beta1QueryGetProtoRevNumberOfTradesResponse, - QueryGetProtoRevProfitsByDenomRequest as OsmosisProtorevV1beta1QueryGetProtoRevProfitsByDenomRequest, - QueryGetProtoRevProfitsByDenomResponse as OsmosisProtorevV1beta1QueryGetProtoRevProfitsByDenomResponse, - QueryGetProtoRevAllProfitsRequest as OsmosisProtorevV1beta1QueryGetProtoRevAllProfitsRequest, - QueryGetProtoRevAllProfitsResponse as OsmosisProtorevV1beta1QueryGetProtoRevAllProfitsResponse, - QueryGetProtoRevStatisticsByRouteRequest as OsmosisProtorevV1beta1QueryGetProtoRevStatisticsByRouteRequest, - QueryGetProtoRevStatisticsByRouteResponse as OsmosisProtorevV1beta1QueryGetProtoRevStatisticsByRouteResponse, - QueryGetProtoRevAllRouteStatisticsRequest as OsmosisProtorevV1beta1QueryGetProtoRevAllRouteStatisticsRequest, - QueryGetProtoRevAllRouteStatisticsResponse as OsmosisProtorevV1beta1QueryGetProtoRevAllRouteStatisticsResponse, - QueryGetProtoRevTokenPairArbRoutesRequest as OsmosisProtorevV1beta1QueryGetProtoRevTokenPairArbRoutesRequest, - QueryGetProtoRevTokenPairArbRoutesResponse as OsmosisProtorevV1beta1QueryGetProtoRevTokenPairArbRoutesResponse, - QueryGetProtoRevAdminAccountRequest as OsmosisProtorevV1beta1QueryGetProtoRevAdminAccountRequest, - QueryGetProtoRevAdminAccountResponse as OsmosisProtorevV1beta1QueryGetProtoRevAdminAccountResponse, - QueryGetProtoRevDeveloperAccountRequest as OsmosisProtorevV1beta1QueryGetProtoRevDeveloperAccountRequest, - QueryGetProtoRevDeveloperAccountResponse as OsmosisProtorevV1beta1QueryGetProtoRevDeveloperAccountResponse, - QueryGetProtoRevInfoByPoolTypeRequest as OsmosisProtorevV1beta1QueryGetProtoRevInfoByPoolTypeRequest, - QueryGetProtoRevInfoByPoolTypeResponse as OsmosisProtorevV1beta1QueryGetProtoRevInfoByPoolTypeResponse, - QueryGetProtoRevMaxPoolPointsPerBlockRequest as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerBlockRequest, - QueryGetProtoRevMaxPoolPointsPerBlockResponse as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerBlockResponse, - QueryGetProtoRevMaxPoolPointsPerTxRequest as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerTxRequest, - QueryGetProtoRevMaxPoolPointsPerTxResponse as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerTxResponse, - QueryGetProtoRevBaseDenomsRequest as OsmosisProtorevV1beta1QueryGetProtoRevBaseDenomsRequest, - QueryGetProtoRevBaseDenomsResponse as OsmosisProtorevV1beta1QueryGetProtoRevBaseDenomsResponse, - QueryGetProtoRevEnabledRequest as OsmosisProtorevV1beta1QueryGetProtoRevEnabledRequest, - QueryGetProtoRevEnabledResponse as OsmosisProtorevV1beta1QueryGetProtoRevEnabledResponse, - QueryGetProtoRevPoolRequest as OsmosisProtorevV1beta1QueryGetProtoRevPoolRequest, - QueryGetProtoRevPoolResponse as OsmosisProtorevV1beta1QueryGetProtoRevPoolResponse, - QueryGetAllProtocolRevenueRequest as OsmosisProtorevV1beta1QueryGetAllProtocolRevenueRequest, - QueryGetAllProtocolRevenueResponse as OsmosisProtorevV1beta1QueryGetAllProtocolRevenueResponse, -} from "./osmosis/protorev/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisProtorevV1beta1QueryParamsService, - QueryGetProtoRevNumberOfTradesService as OsmosisProtorevV1beta1QueryGetProtoRevNumberOfTradesService, - QueryGetProtoRevProfitsByDenomService as OsmosisProtorevV1beta1QueryGetProtoRevProfitsByDenomService, - QueryGetProtoRevAllProfitsService as OsmosisProtorevV1beta1QueryGetProtoRevAllProfitsService, - QueryGetProtoRevStatisticsByRouteService as OsmosisProtorevV1beta1QueryGetProtoRevStatisticsByRouteService, - QueryGetProtoRevAllRouteStatisticsService as OsmosisProtorevV1beta1QueryGetProtoRevAllRouteStatisticsService, - QueryGetProtoRevTokenPairArbRoutesService as OsmosisProtorevV1beta1QueryGetProtoRevTokenPairArbRoutesService, - QueryGetProtoRevAdminAccountService as OsmosisProtorevV1beta1QueryGetProtoRevAdminAccountService, - QueryGetProtoRevDeveloperAccountService as OsmosisProtorevV1beta1QueryGetProtoRevDeveloperAccountService, - QueryGetProtoRevInfoByPoolTypeService as OsmosisProtorevV1beta1QueryGetProtoRevInfoByPoolTypeService, - QueryGetProtoRevMaxPoolPointsPerTxService as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerTxService, - QueryGetProtoRevMaxPoolPointsPerBlockService as OsmosisProtorevV1beta1QueryGetProtoRevMaxPoolPointsPerBlockService, - QueryGetProtoRevBaseDenomsService as OsmosisProtorevV1beta1QueryGetProtoRevBaseDenomsService, - QueryGetProtoRevEnabledService as OsmosisProtorevV1beta1QueryGetProtoRevEnabledService, - QueryGetProtoRevPoolService as OsmosisProtorevV1beta1QueryGetProtoRevPoolService, - QueryGetAllProtocolRevenueService as OsmosisProtorevV1beta1QueryGetAllProtocolRevenueService, -} from "./osmosis/protorev/v1beta1/query_cosmes.js"; -export { - TokenPairArbRoutes as OsmosisProtorevV1beta1TokenPairArbRoutes, - Route as OsmosisProtorevV1beta1Route, - Trade as OsmosisProtorevV1beta1Trade, - RouteStatistics as OsmosisProtorevV1beta1RouteStatistics, - PoolWeights as OsmosisProtorevV1beta1PoolWeights, - InfoByPoolType as OsmosisProtorevV1beta1InfoByPoolType, - StablePoolInfo as OsmosisProtorevV1beta1StablePoolInfo, - BalancerPoolInfo as OsmosisProtorevV1beta1BalancerPoolInfo, - ConcentratedPoolInfo as OsmosisProtorevV1beta1ConcentratedPoolInfo, - CosmwasmPoolInfo as OsmosisProtorevV1beta1CosmwasmPoolInfo, - WeightMap as OsmosisProtorevV1beta1WeightMap, - BaseDenom as OsmosisProtorevV1beta1BaseDenom, - BaseDenoms as OsmosisProtorevV1beta1BaseDenoms, - AllProtocolRevenue as OsmosisProtorevV1beta1AllProtocolRevenue, - CyclicArbTracker as OsmosisProtorevV1beta1CyclicArbTracker, -} from "./osmosis/protorev/v1beta1/protorev_pb.js"; -export { - Params as OsmosisProtorevV1beta1Params, -} from "./osmosis/protorev/v1beta1/params_pb.js"; -export { - SetProtoRevEnabledProposal as OsmosisProtorevV1beta1SetProtoRevEnabledProposal, - SetProtoRevAdminAccountProposal as OsmosisProtorevV1beta1SetProtoRevAdminAccountProposal, -} from "./osmosis/protorev/v1beta1/gov_pb.js"; -export { - GenesisState as OsmosisProtorevV1beta1GenesisState, -} from "./osmosis/protorev/v1beta1/genesis_pb.js"; -export { - SpotPriceRequest as OsmosisPoolmanagerV2SpotPriceRequest, - SpotPriceResponse as OsmosisPoolmanagerV2SpotPriceResponse, -} from "./osmosis/poolmanager/v2/query_pb.js"; -export { - QuerySpotPriceV2Service as OsmosisPoolmanagerV2QuerySpotPriceV2Service, -} from "./osmosis/poolmanager/v2/query_cosmes.js"; -export { - MsgSwapExactAmountIn as OsmosisPoolmanagerV1beta1MsgSwapExactAmountIn, - MsgSwapExactAmountInResponse as OsmosisPoolmanagerV1beta1MsgSwapExactAmountInResponse, - MsgSplitRouteSwapExactAmountIn as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountIn, - MsgSplitRouteSwapExactAmountInResponse as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountInResponse, - MsgSwapExactAmountOut as OsmosisPoolmanagerV1beta1MsgSwapExactAmountOut, - MsgSwapExactAmountOutResponse as OsmosisPoolmanagerV1beta1MsgSwapExactAmountOutResponse, - MsgSplitRouteSwapExactAmountOut as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountOut, - MsgSplitRouteSwapExactAmountOutResponse as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountOutResponse, - MsgSetDenomPairTakerFee as OsmosisPoolmanagerV1beta1MsgSetDenomPairTakerFee, - MsgSetDenomPairTakerFeeResponse as OsmosisPoolmanagerV1beta1MsgSetDenomPairTakerFeeResponse, - MsgSetTakerFeeShareAgreementForDenom as OsmosisPoolmanagerV1beta1MsgSetTakerFeeShareAgreementForDenom, - MsgSetTakerFeeShareAgreementForDenomResponse as OsmosisPoolmanagerV1beta1MsgSetTakerFeeShareAgreementForDenomResponse, - MsgSetRegisteredAlloyedPool as OsmosisPoolmanagerV1beta1MsgSetRegisteredAlloyedPool, - MsgSetRegisteredAlloyedPoolResponse as OsmosisPoolmanagerV1beta1MsgSetRegisteredAlloyedPoolResponse, - DenomPairTakerFee as OsmosisPoolmanagerV1beta1DenomPairTakerFee, -} from "./osmosis/poolmanager/v1beta1/tx_pb.js"; -export { - MsgSwapExactAmountInService as OsmosisPoolmanagerV1beta1MsgSwapExactAmountInService, - MsgSwapExactAmountOutService as OsmosisPoolmanagerV1beta1MsgSwapExactAmountOutService, - MsgSplitRouteSwapExactAmountInService as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountInService, - MsgSplitRouteSwapExactAmountOutService as OsmosisPoolmanagerV1beta1MsgSplitRouteSwapExactAmountOutService, - MsgSetDenomPairTakerFeeService as OsmosisPoolmanagerV1beta1MsgSetDenomPairTakerFeeService, - MsgSetTakerFeeShareAgreementForDenomService as OsmosisPoolmanagerV1beta1MsgSetTakerFeeShareAgreementForDenomService, - MsgSetRegisteredAlloyedPoolService as OsmosisPoolmanagerV1beta1MsgSetRegisteredAlloyedPoolService, -} from "./osmosis/poolmanager/v1beta1/tx_cosmes.js"; -export { - TrackedVolume as OsmosisPoolmanagerV1beta1TrackedVolume, -} from "./osmosis/poolmanager/v1beta1/tracked_volume_pb.js"; -export { - TakerFeeShareAgreement as OsmosisPoolmanagerV1beta1TakerFeeShareAgreement, - TakerFeeSkimAccumulator as OsmosisPoolmanagerV1beta1TakerFeeSkimAccumulator, - AlloyContractTakerFeeShareState as OsmosisPoolmanagerV1beta1AlloyContractTakerFeeShareState, -} from "./osmosis/poolmanager/v1beta1/taker_fee_share_pb.js"; -export { - SwapAmountInRoute as OsmosisPoolmanagerV1beta1SwapAmountInRoute, - SwapAmountOutRoute as OsmosisPoolmanagerV1beta1SwapAmountOutRoute, - SwapAmountInSplitRoute as OsmosisPoolmanagerV1beta1SwapAmountInSplitRoute, - SwapAmountOutSplitRoute as OsmosisPoolmanagerV1beta1SwapAmountOutSplitRoute, -} from "./osmosis/poolmanager/v1beta1/swap_route_pb.js"; -export { - ParamsRequest as OsmosisPoolmanagerV1beta1ParamsRequest, - ParamsResponse as OsmosisPoolmanagerV1beta1ParamsResponse, - EstimateSwapExactAmountInRequest as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountInRequest, - EstimateSwapExactAmountInWithPrimitiveTypesRequest as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountInWithPrimitiveTypesRequest, - EstimateSinglePoolSwapExactAmountInRequest as OsmosisPoolmanagerV1beta1EstimateSinglePoolSwapExactAmountInRequest, - EstimateSwapExactAmountInResponse as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountInResponse, - EstimateSwapExactAmountOutRequest as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountOutRequest, - EstimateSwapExactAmountOutWithPrimitiveTypesRequest as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountOutWithPrimitiveTypesRequest, - EstimateSinglePoolSwapExactAmountOutRequest as OsmosisPoolmanagerV1beta1EstimateSinglePoolSwapExactAmountOutRequest, - EstimateSwapExactAmountOutResponse as OsmosisPoolmanagerV1beta1EstimateSwapExactAmountOutResponse, - NumPoolsRequest as OsmosisPoolmanagerV1beta1NumPoolsRequest, - NumPoolsResponse as OsmosisPoolmanagerV1beta1NumPoolsResponse, - PoolRequest as OsmosisPoolmanagerV1beta1PoolRequest, - PoolResponse as OsmosisPoolmanagerV1beta1PoolResponse, - AllPoolsRequest as OsmosisPoolmanagerV1beta1AllPoolsRequest, - AllPoolsResponse as OsmosisPoolmanagerV1beta1AllPoolsResponse, - ListPoolsByDenomRequest as OsmosisPoolmanagerV1beta1ListPoolsByDenomRequest, - ListPoolsByDenomResponse as OsmosisPoolmanagerV1beta1ListPoolsByDenomResponse, - SpotPriceRequest as OsmosisPoolmanagerV1beta1SpotPriceRequest, - SpotPriceResponse as OsmosisPoolmanagerV1beta1SpotPriceResponse, - TotalPoolLiquidityRequest as OsmosisPoolmanagerV1beta1TotalPoolLiquidityRequest, - TotalPoolLiquidityResponse as OsmosisPoolmanagerV1beta1TotalPoolLiquidityResponse, - TotalLiquidityRequest as OsmosisPoolmanagerV1beta1TotalLiquidityRequest, - TotalLiquidityResponse as OsmosisPoolmanagerV1beta1TotalLiquidityResponse, - TotalVolumeForPoolRequest as OsmosisPoolmanagerV1beta1TotalVolumeForPoolRequest, - TotalVolumeForPoolResponse as OsmosisPoolmanagerV1beta1TotalVolumeForPoolResponse, - TradingPairTakerFeeRequest as OsmosisPoolmanagerV1beta1TradingPairTakerFeeRequest, - TradingPairTakerFeeResponse as OsmosisPoolmanagerV1beta1TradingPairTakerFeeResponse, - EstimateTradeBasedOnPriceImpactRequest as OsmosisPoolmanagerV1beta1EstimateTradeBasedOnPriceImpactRequest, - EstimateTradeBasedOnPriceImpactResponse as OsmosisPoolmanagerV1beta1EstimateTradeBasedOnPriceImpactResponse, - AllTakerFeeShareAgreementsRequest as OsmosisPoolmanagerV1beta1AllTakerFeeShareAgreementsRequest, - AllTakerFeeShareAgreementsResponse as OsmosisPoolmanagerV1beta1AllTakerFeeShareAgreementsResponse, - TakerFeeShareAgreementFromDenomRequest as OsmosisPoolmanagerV1beta1TakerFeeShareAgreementFromDenomRequest, - TakerFeeShareAgreementFromDenomResponse as OsmosisPoolmanagerV1beta1TakerFeeShareAgreementFromDenomResponse, - TakerFeeShareDenomsToAccruedValueRequest as OsmosisPoolmanagerV1beta1TakerFeeShareDenomsToAccruedValueRequest, - TakerFeeShareDenomsToAccruedValueResponse as OsmosisPoolmanagerV1beta1TakerFeeShareDenomsToAccruedValueResponse, - AllTakerFeeShareAccumulatorsRequest as OsmosisPoolmanagerV1beta1AllTakerFeeShareAccumulatorsRequest, - AllTakerFeeShareAccumulatorsResponse as OsmosisPoolmanagerV1beta1AllTakerFeeShareAccumulatorsResponse, - RegisteredAlloyedPoolFromDenomRequest as OsmosisPoolmanagerV1beta1RegisteredAlloyedPoolFromDenomRequest, - RegisteredAlloyedPoolFromDenomResponse as OsmosisPoolmanagerV1beta1RegisteredAlloyedPoolFromDenomResponse, - RegisteredAlloyedPoolFromPoolIdRequest as OsmosisPoolmanagerV1beta1RegisteredAlloyedPoolFromPoolIdRequest, - RegisteredAlloyedPoolFromPoolIdResponse as OsmosisPoolmanagerV1beta1RegisteredAlloyedPoolFromPoolIdResponse, - AllRegisteredAlloyedPoolsRequest as OsmosisPoolmanagerV1beta1AllRegisteredAlloyedPoolsRequest, - AllRegisteredAlloyedPoolsResponse as OsmosisPoolmanagerV1beta1AllRegisteredAlloyedPoolsResponse, -} from "./osmosis/poolmanager/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisPoolmanagerV1beta1QueryParamsService, - QueryEstimateSwapExactAmountInService as OsmosisPoolmanagerV1beta1QueryEstimateSwapExactAmountInService, - QueryEstimateSwapExactAmountInWithPrimitiveTypesService as OsmosisPoolmanagerV1beta1QueryEstimateSwapExactAmountInWithPrimitiveTypesService, - QueryEstimateSinglePoolSwapExactAmountInService as OsmosisPoolmanagerV1beta1QueryEstimateSinglePoolSwapExactAmountInService, - QueryEstimateSwapExactAmountOutService as OsmosisPoolmanagerV1beta1QueryEstimateSwapExactAmountOutService, - QueryEstimateSwapExactAmountOutWithPrimitiveTypesService as OsmosisPoolmanagerV1beta1QueryEstimateSwapExactAmountOutWithPrimitiveTypesService, - QueryEstimateSinglePoolSwapExactAmountOutService as OsmosisPoolmanagerV1beta1QueryEstimateSinglePoolSwapExactAmountOutService, - QueryNumPoolsService as OsmosisPoolmanagerV1beta1QueryNumPoolsService, - QueryPoolService as OsmosisPoolmanagerV1beta1QueryPoolService, - QueryAllPoolsService as OsmosisPoolmanagerV1beta1QueryAllPoolsService, - QueryListPoolsByDenomService as OsmosisPoolmanagerV1beta1QueryListPoolsByDenomService, - QuerySpotPriceService as OsmosisPoolmanagerV1beta1QuerySpotPriceService, - QueryTotalPoolLiquidityService as OsmosisPoolmanagerV1beta1QueryTotalPoolLiquidityService, - QueryTotalLiquidityService as OsmosisPoolmanagerV1beta1QueryTotalLiquidityService, - QueryTotalVolumeForPoolService as OsmosisPoolmanagerV1beta1QueryTotalVolumeForPoolService, - QueryTradingPairTakerFeeService as OsmosisPoolmanagerV1beta1QueryTradingPairTakerFeeService, - QueryEstimateTradeBasedOnPriceImpactService as OsmosisPoolmanagerV1beta1QueryEstimateTradeBasedOnPriceImpactService, - QueryAllTakerFeeShareAgreementsService as OsmosisPoolmanagerV1beta1QueryAllTakerFeeShareAgreementsService, - QueryTakerFeeShareAgreementFromDenomService as OsmosisPoolmanagerV1beta1QueryTakerFeeShareAgreementFromDenomService, - QueryTakerFeeShareDenomsToAccruedValueService as OsmosisPoolmanagerV1beta1QueryTakerFeeShareDenomsToAccruedValueService, - QueryAllTakerFeeShareAccumulatorsService as OsmosisPoolmanagerV1beta1QueryAllTakerFeeShareAccumulatorsService, - QueryRegisteredAlloyedPoolFromDenomService as OsmosisPoolmanagerV1beta1QueryRegisteredAlloyedPoolFromDenomService, - QueryRegisteredAlloyedPoolFromPoolIdService as OsmosisPoolmanagerV1beta1QueryRegisteredAlloyedPoolFromPoolIdService, - QueryAllRegisteredAlloyedPoolsService as OsmosisPoolmanagerV1beta1QueryAllRegisteredAlloyedPoolsService, -} from "./osmosis/poolmanager/v1beta1/query_cosmes.js"; -export { - PoolType as OsmosisPoolmanagerV1beta1PoolType, - ModuleRoute as OsmosisPoolmanagerV1beta1ModuleRoute, -} from "./osmosis/poolmanager/v1beta1/module_route_pb.js"; -export { - DenomPairTakerFeeProposal as OsmosisPoolmanagerV1beta1DenomPairTakerFeeProposal, -} from "./osmosis/poolmanager/v1beta1/gov_pb.js"; -export { - Params as OsmosisPoolmanagerV1beta1Params, - GenesisState as OsmosisPoolmanagerV1beta1GenesisState, - TakerFeeParams as OsmosisPoolmanagerV1beta1TakerFeeParams, - TakerFeeDistributionPercentage as OsmosisPoolmanagerV1beta1TakerFeeDistributionPercentage, - TakerFeesTracker as OsmosisPoolmanagerV1beta1TakerFeesTracker, - PoolVolume as OsmosisPoolmanagerV1beta1PoolVolume, -} from "./osmosis/poolmanager/v1beta1/genesis_pb.js"; -export { - MigrationRecords as OsmosisPoolincentivesV1beta1MigrationRecords, - BalancerToConcentratedPoolLink as OsmosisPoolincentivesV1beta1BalancerToConcentratedPoolLink, -} from "./osmosis/poolincentives/v1beta1/shared_pb.js"; -export { - QueryGaugeIdsRequest as OsmosisPoolincentivesV1beta1QueryGaugeIdsRequest, - QueryGaugeIdsResponse as OsmosisPoolincentivesV1beta1QueryGaugeIdsResponse, - QueryGaugeIdsResponse_GaugeIdWithDuration as OsmosisPoolincentivesV1beta1QueryGaugeIdsResponse_GaugeIdWithDuration, - QueryDistrInfoRequest as OsmosisPoolincentivesV1beta1QueryDistrInfoRequest, - QueryDistrInfoResponse as OsmosisPoolincentivesV1beta1QueryDistrInfoResponse, - QueryParamsRequest as OsmosisPoolincentivesV1beta1QueryParamsRequest, - QueryParamsResponse as OsmosisPoolincentivesV1beta1QueryParamsResponse, - QueryLockableDurationsRequest as OsmosisPoolincentivesV1beta1QueryLockableDurationsRequest, - QueryLockableDurationsResponse as OsmosisPoolincentivesV1beta1QueryLockableDurationsResponse, - QueryIncentivizedPoolsRequest as OsmosisPoolincentivesV1beta1QueryIncentivizedPoolsRequest, - IncentivizedPool as OsmosisPoolincentivesV1beta1IncentivizedPool, - QueryIncentivizedPoolsResponse as OsmosisPoolincentivesV1beta1QueryIncentivizedPoolsResponse, - QueryExternalIncentiveGaugesRequest as OsmosisPoolincentivesV1beta1QueryExternalIncentiveGaugesRequest, - QueryExternalIncentiveGaugesResponse as OsmosisPoolincentivesV1beta1QueryExternalIncentiveGaugesResponse, -} from "./osmosis/poolincentives/v1beta1/query_pb.js"; -export { - QueryGaugeIdsService as OsmosisPoolincentivesV1beta1QueryGaugeIdsService, - QueryDistrInfoService as OsmosisPoolincentivesV1beta1QueryDistrInfoService, - QueryParamsService as OsmosisPoolincentivesV1beta1QueryParamsService, - QueryLockableDurationsService as OsmosisPoolincentivesV1beta1QueryLockableDurationsService, - QueryIncentivizedPoolsService as OsmosisPoolincentivesV1beta1QueryIncentivizedPoolsService, - QueryExternalIncentiveGaugesService as OsmosisPoolincentivesV1beta1QueryExternalIncentiveGaugesService, -} from "./osmosis/poolincentives/v1beta1/query_cosmes.js"; -export { - Params as OsmosisPoolincentivesV1beta1Params, - LockableDurationsInfo as OsmosisPoolincentivesV1beta1LockableDurationsInfo, - DistrInfo as OsmosisPoolincentivesV1beta1DistrInfo, - DistrRecord as OsmosisPoolincentivesV1beta1DistrRecord, - PoolToGauge as OsmosisPoolincentivesV1beta1PoolToGauge, - AnyPoolToInternalGauges as OsmosisPoolincentivesV1beta1AnyPoolToInternalGauges, - ConcentratedPoolToNoLockGauges as OsmosisPoolincentivesV1beta1ConcentratedPoolToNoLockGauges, -} from "./osmosis/poolincentives/v1beta1/incentives_pb.js"; -export { - ReplacePoolIncentivesProposal as OsmosisPoolincentivesV1beta1ReplacePoolIncentivesProposal, - UpdatePoolIncentivesProposal as OsmosisPoolincentivesV1beta1UpdatePoolIncentivesProposal, -} from "./osmosis/poolincentives/v1beta1/gov_pb.js"; -export { - GenesisState as OsmosisPoolincentivesV1beta1GenesisState, -} from "./osmosis/poolincentives/v1beta1/genesis_pb.js"; -export { - QueryParamsRequest as OsmosisMintV1beta1QueryParamsRequest, - QueryParamsResponse as OsmosisMintV1beta1QueryParamsResponse, - QueryEpochProvisionsRequest as OsmosisMintV1beta1QueryEpochProvisionsRequest, - QueryEpochProvisionsResponse as OsmosisMintV1beta1QueryEpochProvisionsResponse, - QueryInflationRequest as OsmosisMintV1beta1QueryInflationRequest, - QueryInflationResponse as OsmosisMintV1beta1QueryInflationResponse, -} from "./osmosis/mint/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisMintV1beta1QueryParamsService, - QueryEpochProvisionsService as OsmosisMintV1beta1QueryEpochProvisionsService, - QueryInflationService as OsmosisMintV1beta1QueryInflationService, -} from "./osmosis/mint/v1beta1/query_cosmes.js"; -export { - Minter as OsmosisMintV1beta1Minter, - WeightedAddress as OsmosisMintV1beta1WeightedAddress, - DistributionProportions as OsmosisMintV1beta1DistributionProportions, - Params as OsmosisMintV1beta1Params, -} from "./osmosis/mint/v1beta1/mint_pb.js"; -export { - GenesisState as OsmosisMintV1beta1GenesisState, -} from "./osmosis/mint/v1beta1/genesis_pb.js"; -export { - MsgLockTokens as OsmosisLockupMsgLockTokens, - MsgLockTokensResponse as OsmosisLockupMsgLockTokensResponse, - MsgBeginUnlockingAll as OsmosisLockupMsgBeginUnlockingAll, - MsgBeginUnlockingAllResponse as OsmosisLockupMsgBeginUnlockingAllResponse, - MsgBeginUnlocking as OsmosisLockupMsgBeginUnlocking, - MsgBeginUnlockingResponse as OsmosisLockupMsgBeginUnlockingResponse, - MsgExtendLockup as OsmosisLockupMsgExtendLockup, - MsgExtendLockupResponse as OsmosisLockupMsgExtendLockupResponse, - MsgForceUnlock as OsmosisLockupMsgForceUnlock, - MsgForceUnlockResponse as OsmosisLockupMsgForceUnlockResponse, - MsgSetRewardReceiverAddress as OsmosisLockupMsgSetRewardReceiverAddress, - MsgSetRewardReceiverAddressResponse as OsmosisLockupMsgSetRewardReceiverAddressResponse, - MsgUnlockPeriodLock as OsmosisLockupMsgUnlockPeriodLock, - MsgUnlockTokens as OsmosisLockupMsgUnlockTokens, -} from "./osmosis/lockup/tx_pb.js"; -export { - MsgLockTokensService as OsmosisLockupMsgLockTokensService, - MsgBeginUnlockingAllService as OsmosisLockupMsgBeginUnlockingAllService, - MsgBeginUnlockingService as OsmosisLockupMsgBeginUnlockingService, - MsgExtendLockupService as OsmosisLockupMsgExtendLockupService, - MsgForceUnlockService as OsmosisLockupMsgForceUnlockService, - MsgSetRewardReceiverAddressService as OsmosisLockupMsgSetRewardReceiverAddressService, -} from "./osmosis/lockup/tx_cosmes.js"; -export { - ModuleBalanceRequest as OsmosisLockupModuleBalanceRequest, - ModuleBalanceResponse as OsmosisLockupModuleBalanceResponse, - ModuleLockedAmountRequest as OsmosisLockupModuleLockedAmountRequest, - ModuleLockedAmountResponse as OsmosisLockupModuleLockedAmountResponse, - AccountUnlockableCoinsRequest as OsmosisLockupAccountUnlockableCoinsRequest, - AccountUnlockableCoinsResponse as OsmosisLockupAccountUnlockableCoinsResponse, - AccountUnlockingCoinsRequest as OsmosisLockupAccountUnlockingCoinsRequest, - AccountUnlockingCoinsResponse as OsmosisLockupAccountUnlockingCoinsResponse, - AccountLockedCoinsRequest as OsmosisLockupAccountLockedCoinsRequest, - AccountLockedCoinsResponse as OsmosisLockupAccountLockedCoinsResponse, - AccountLockedPastTimeRequest as OsmosisLockupAccountLockedPastTimeRequest, - AccountLockedPastTimeResponse as OsmosisLockupAccountLockedPastTimeResponse, - AccountLockedPastTimeNotUnlockingOnlyRequest as OsmosisLockupAccountLockedPastTimeNotUnlockingOnlyRequest, - AccountLockedPastTimeNotUnlockingOnlyResponse as OsmosisLockupAccountLockedPastTimeNotUnlockingOnlyResponse, - AccountUnlockedBeforeTimeRequest as OsmosisLockupAccountUnlockedBeforeTimeRequest, - AccountUnlockedBeforeTimeResponse as OsmosisLockupAccountUnlockedBeforeTimeResponse, - AccountLockedPastTimeDenomRequest as OsmosisLockupAccountLockedPastTimeDenomRequest, - AccountLockedPastTimeDenomResponse as OsmosisLockupAccountLockedPastTimeDenomResponse, - LockedDenomRequest as OsmosisLockupLockedDenomRequest, - LockedDenomResponse as OsmosisLockupLockedDenomResponse, - LockedRequest as OsmosisLockupLockedRequest, - LockedResponse as OsmosisLockupLockedResponse, - LockRewardReceiverRequest as OsmosisLockupLockRewardReceiverRequest, - LockRewardReceiverResponse as OsmosisLockupLockRewardReceiverResponse, - NextLockIDRequest as OsmosisLockupNextLockIDRequest, - NextLockIDResponse as OsmosisLockupNextLockIDResponse, - SyntheticLockupsByLockupIDRequest as OsmosisLockupSyntheticLockupsByLockupIDRequest, - SyntheticLockupsByLockupIDResponse as OsmosisLockupSyntheticLockupsByLockupIDResponse, - SyntheticLockupByLockupIDRequest as OsmosisLockupSyntheticLockupByLockupIDRequest, - SyntheticLockupByLockupIDResponse as OsmosisLockupSyntheticLockupByLockupIDResponse, - AccountLockedLongerDurationRequest as OsmosisLockupAccountLockedLongerDurationRequest, - AccountLockedLongerDurationResponse as OsmosisLockupAccountLockedLongerDurationResponse, - AccountLockedDurationRequest as OsmosisLockupAccountLockedDurationRequest, - AccountLockedDurationResponse as OsmosisLockupAccountLockedDurationResponse, - AccountLockedLongerDurationNotUnlockingOnlyRequest as OsmosisLockupAccountLockedLongerDurationNotUnlockingOnlyRequest, - AccountLockedLongerDurationNotUnlockingOnlyResponse as OsmosisLockupAccountLockedLongerDurationNotUnlockingOnlyResponse, - AccountLockedLongerDurationDenomRequest as OsmosisLockupAccountLockedLongerDurationDenomRequest, - AccountLockedLongerDurationDenomResponse as OsmosisLockupAccountLockedLongerDurationDenomResponse, - QueryParamsRequest as OsmosisLockupQueryParamsRequest, - QueryParamsResponse as OsmosisLockupQueryParamsResponse, -} from "./osmosis/lockup/query_pb.js"; -export { - QueryModuleBalanceService as OsmosisLockupQueryModuleBalanceService, - QueryModuleLockedAmountService as OsmosisLockupQueryModuleLockedAmountService, - QueryAccountUnlockableCoinsService as OsmosisLockupQueryAccountUnlockableCoinsService, - QueryAccountUnlockingCoinsService as OsmosisLockupQueryAccountUnlockingCoinsService, - QueryAccountLockedCoinsService as OsmosisLockupQueryAccountLockedCoinsService, - QueryAccountLockedPastTimeService as OsmosisLockupQueryAccountLockedPastTimeService, - QueryAccountLockedPastTimeNotUnlockingOnlyService as OsmosisLockupQueryAccountLockedPastTimeNotUnlockingOnlyService, - QueryAccountUnlockedBeforeTimeService as OsmosisLockupQueryAccountUnlockedBeforeTimeService, - QueryAccountLockedPastTimeDenomService as OsmosisLockupQueryAccountLockedPastTimeDenomService, - QueryLockedDenomService as OsmosisLockupQueryLockedDenomService, - QueryLockedByIDService as OsmosisLockupQueryLockedByIDService, - QueryLockRewardReceiverService as OsmosisLockupQueryLockRewardReceiverService, - QueryNextLockIDService as OsmosisLockupQueryNextLockIDService, - QuerySyntheticLockupsByLockupIDService as OsmosisLockupQuerySyntheticLockupsByLockupIDService, - QuerySyntheticLockupByLockupIDService as OsmosisLockupQuerySyntheticLockupByLockupIDService, - QueryAccountLockedLongerDurationService as OsmosisLockupQueryAccountLockedLongerDurationService, - QueryAccountLockedDurationService as OsmosisLockupQueryAccountLockedDurationService, - QueryAccountLockedLongerDurationNotUnlockingOnlyService as OsmosisLockupQueryAccountLockedLongerDurationNotUnlockingOnlyService, - QueryAccountLockedLongerDurationDenomService as OsmosisLockupQueryAccountLockedLongerDurationDenomService, - QueryParamsService as OsmosisLockupQueryParamsService, -} from "./osmosis/lockup/query_cosmes.js"; -export { - Params as OsmosisLockupParams, -} from "./osmosis/lockup/params_pb.js"; -export { - LockQueryType as OsmosisLockupLockQueryType, - PeriodLock as OsmosisLockupPeriodLock, - QueryCondition as OsmosisLockupQueryCondition, - SyntheticLock as OsmosisLockupSyntheticLock, -} from "./osmosis/lockup/lock_pb.js"; -export { - GenesisState as OsmosisLockupGenesisState, -} from "./osmosis/lockup/genesis_pb.js"; -export { - PoolData as OsmosisIngestV1beta1PoolData, - ProcessBlockRequest as OsmosisIngestV1beta1ProcessBlockRequest, - ProcessBlockReply as OsmosisIngestV1beta1ProcessBlockReply, -} from "./osmosis/ingest/v1beta1/ingest_pb.js"; -export { - SQSIngesterProcessBlockService as OsmosisIngestV1beta1SQSIngesterProcessBlockService, -} from "./osmosis/ingest/v1beta1/ingest_cosmes.js"; -export { - MsgCreateGauge as OsmosisIncentivesMsgCreateGauge, - MsgCreateGaugeResponse as OsmosisIncentivesMsgCreateGaugeResponse, - MsgAddToGauge as OsmosisIncentivesMsgAddToGauge, - MsgAddToGaugeResponse as OsmosisIncentivesMsgAddToGaugeResponse, - MsgCreateGroup as OsmosisIncentivesMsgCreateGroup, - MsgCreateGroupResponse as OsmosisIncentivesMsgCreateGroupResponse, -} from "./osmosis/incentives/tx_pb.js"; -export { - MsgCreateGaugeService as OsmosisIncentivesMsgCreateGaugeService, - MsgAddToGaugeService as OsmosisIncentivesMsgAddToGaugeService, - MsgCreateGroupService as OsmosisIncentivesMsgCreateGroupService, -} from "./osmosis/incentives/tx_cosmes.js"; -export { - ModuleToDistributeCoinsRequest as OsmosisIncentivesModuleToDistributeCoinsRequest, - ModuleToDistributeCoinsResponse as OsmosisIncentivesModuleToDistributeCoinsResponse, - GaugeByIDRequest as OsmosisIncentivesGaugeByIDRequest, - GaugeByIDResponse as OsmosisIncentivesGaugeByIDResponse, - GaugesRequest as OsmosisIncentivesGaugesRequest, - GaugesResponse as OsmosisIncentivesGaugesResponse, - ActiveGaugesRequest as OsmosisIncentivesActiveGaugesRequest, - ActiveGaugesResponse as OsmosisIncentivesActiveGaugesResponse, - ActiveGaugesPerDenomRequest as OsmosisIncentivesActiveGaugesPerDenomRequest, - ActiveGaugesPerDenomResponse as OsmosisIncentivesActiveGaugesPerDenomResponse, - UpcomingGaugesRequest as OsmosisIncentivesUpcomingGaugesRequest, - UpcomingGaugesResponse as OsmosisIncentivesUpcomingGaugesResponse, - UpcomingGaugesPerDenomRequest as OsmosisIncentivesUpcomingGaugesPerDenomRequest, - UpcomingGaugesPerDenomResponse as OsmosisIncentivesUpcomingGaugesPerDenomResponse, - RewardsEstRequest as OsmosisIncentivesRewardsEstRequest, - RewardsEstResponse as OsmosisIncentivesRewardsEstResponse, - QueryLockableDurationsRequest as OsmosisIncentivesQueryLockableDurationsRequest, - QueryLockableDurationsResponse as OsmosisIncentivesQueryLockableDurationsResponse, - QueryAllGroupsRequest as OsmosisIncentivesQueryAllGroupsRequest, - QueryAllGroupsResponse as OsmosisIncentivesQueryAllGroupsResponse, - QueryAllGroupsGaugesRequest as OsmosisIncentivesQueryAllGroupsGaugesRequest, - QueryAllGroupsGaugesResponse as OsmosisIncentivesQueryAllGroupsGaugesResponse, - QueryAllGroupsWithGaugeRequest as OsmosisIncentivesQueryAllGroupsWithGaugeRequest, - QueryAllGroupsWithGaugeResponse as OsmosisIncentivesQueryAllGroupsWithGaugeResponse, - QueryGroupByGroupGaugeIDRequest as OsmosisIncentivesQueryGroupByGroupGaugeIDRequest, - QueryGroupByGroupGaugeIDResponse as OsmosisIncentivesQueryGroupByGroupGaugeIDResponse, - QueryCurrentWeightByGroupGaugeIDRequest as OsmosisIncentivesQueryCurrentWeightByGroupGaugeIDRequest, - QueryCurrentWeightByGroupGaugeIDResponse as OsmosisIncentivesQueryCurrentWeightByGroupGaugeIDResponse, - GaugeWeight as OsmosisIncentivesGaugeWeight, - QueryInternalGaugesRequest as OsmosisIncentivesQueryInternalGaugesRequest, - QueryInternalGaugesResponse as OsmosisIncentivesQueryInternalGaugesResponse, - QueryExternalGaugesRequest as OsmosisIncentivesQueryExternalGaugesRequest, - QueryExternalGaugesResponse as OsmosisIncentivesQueryExternalGaugesResponse, - QueryGaugesByPoolIDRequest as OsmosisIncentivesQueryGaugesByPoolIDRequest, - QueryGaugesByPoolIDResponse as OsmosisIncentivesQueryGaugesByPoolIDResponse, - ParamsRequest as OsmosisIncentivesParamsRequest, - ParamsResponse as OsmosisIncentivesParamsResponse, -} from "./osmosis/incentives/query_pb.js"; -export { - QueryModuleToDistributeCoinsService as OsmosisIncentivesQueryModuleToDistributeCoinsService, - QueryGaugeByIDService as OsmosisIncentivesQueryGaugeByIDService, - QueryGaugesService as OsmosisIncentivesQueryGaugesService, - QueryActiveGaugesService as OsmosisIncentivesQueryActiveGaugesService, - QueryActiveGaugesPerDenomService as OsmosisIncentivesQueryActiveGaugesPerDenomService, - QueryUpcomingGaugesService as OsmosisIncentivesQueryUpcomingGaugesService, - QueryUpcomingGaugesPerDenomService as OsmosisIncentivesQueryUpcomingGaugesPerDenomService, - QueryRewardsEstService as OsmosisIncentivesQueryRewardsEstService, - QueryLockableDurationsService as OsmosisIncentivesQueryLockableDurationsService, - QueryAllGroupsService as OsmosisIncentivesQueryAllGroupsService, - QueryAllGroupsGaugesService as OsmosisIncentivesQueryAllGroupsGaugesService, - QueryAllGroupsWithGaugeService as OsmosisIncentivesQueryAllGroupsWithGaugeService, - QueryGroupByGroupGaugeIDService as OsmosisIncentivesQueryGroupByGroupGaugeIDService, - QueryCurrentWeightByGroupGaugeIDService as OsmosisIncentivesQueryCurrentWeightByGroupGaugeIDService, - QueryInternalGaugesService as OsmosisIncentivesQueryInternalGaugesService, - QueryExternalGaugesService as OsmosisIncentivesQueryExternalGaugesService, - QueryGaugesByPoolIDService as OsmosisIncentivesQueryGaugesByPoolIDService, - QueryParamsService as OsmosisIncentivesQueryParamsService, -} from "./osmosis/incentives/query_cosmes.js"; -export { - Params as OsmosisIncentivesParams, -} from "./osmosis/incentives/params_pb.js"; -export { - SplittingPolicy as OsmosisIncentivesSplittingPolicy, - InternalGaugeInfo as OsmosisIncentivesInternalGaugeInfo, - InternalGaugeRecord as OsmosisIncentivesInternalGaugeRecord, - Group as OsmosisIncentivesGroup, - CreateGroup as OsmosisIncentivesCreateGroup, - GroupsWithGauge as OsmosisIncentivesGroupsWithGauge, -} from "./osmosis/incentives/group_pb.js"; -export { - CreateGroupsProposal as OsmosisIncentivesCreateGroupsProposal, -} from "./osmosis/incentives/gov_pb.js"; -export { - GenesisState as OsmosisIncentivesGenesisState, -} from "./osmosis/incentives/genesis_pb.js"; -export { - Gauge as OsmosisIncentivesGauge, - LockableDurationsInfo as OsmosisIncentivesLockableDurationsInfo, -} from "./osmosis/incentives/gauge_pb.js"; -export { - ParamsRequest as OsmosisIbcratelimitV1beta1ParamsRequest, - ParamsResponse as OsmosisIbcratelimitV1beta1ParamsResponse, -} from "./osmosis/ibcratelimit/v1beta1/query_pb.js"; -export { - QueryParamsService as OsmosisIbcratelimitV1beta1QueryParamsService, -} from "./osmosis/ibcratelimit/v1beta1/query_cosmes.js"; -export { - Params as OsmosisIbcratelimitV1beta1Params, -} from "./osmosis/ibcratelimit/v1beta1/params_pb.js"; -export { - GenesisState as OsmosisIbcratelimitV1beta1GenesisState, -} from "./osmosis/ibcratelimit/v1beta1/genesis_pb.js"; -export { - MsgEmitIBCAck as OsmosisIbchooksMsgEmitIBCAck, - MsgEmitIBCAckResponse as OsmosisIbchooksMsgEmitIBCAckResponse, -} from "./osmosis/ibchooks/tx_pb.js"; -export { - MsgEmitIBCAckService as OsmosisIbchooksMsgEmitIBCAckService, -} from "./osmosis/ibchooks/tx_cosmes.js"; -export { - Params as OsmosisIbchooksParams, -} from "./osmosis/ibchooks/params_pb.js"; -export { - GenesisState as OsmosisIbchooksGenesisState, -} from "./osmosis/ibchooks/genesis_pb.js"; -export { - QuerySpotPriceRequest as OsmosisGammV2QuerySpotPriceRequest, - QuerySpotPriceResponse as OsmosisGammV2QuerySpotPriceResponse, -} from "./osmosis/gamm/v2/query_pb.js"; -export { - QuerySpotPriceService as OsmosisGammV2QuerySpotPriceService, -} from "./osmosis/gamm/v2/query_cosmes.js"; -export { - MsgJoinPool as OsmosisGammV1beta1MsgJoinPool, - MsgJoinPoolResponse as OsmosisGammV1beta1MsgJoinPoolResponse, - MsgExitPool as OsmosisGammV1beta1MsgExitPool, - MsgExitPoolResponse as OsmosisGammV1beta1MsgExitPoolResponse, - MsgSwapExactAmountIn as OsmosisGammV1beta1MsgSwapExactAmountIn, - MsgSwapExactAmountInResponse as OsmosisGammV1beta1MsgSwapExactAmountInResponse, - MsgSwapExactAmountOut as OsmosisGammV1beta1MsgSwapExactAmountOut, - MsgSwapExactAmountOutResponse as OsmosisGammV1beta1MsgSwapExactAmountOutResponse, - MsgJoinSwapExternAmountIn as OsmosisGammV1beta1MsgJoinSwapExternAmountIn, - MsgJoinSwapExternAmountInResponse as OsmosisGammV1beta1MsgJoinSwapExternAmountInResponse, - MsgJoinSwapShareAmountOut as OsmosisGammV1beta1MsgJoinSwapShareAmountOut, - MsgJoinSwapShareAmountOutResponse as OsmosisGammV1beta1MsgJoinSwapShareAmountOutResponse, - MsgExitSwapShareAmountIn as OsmosisGammV1beta1MsgExitSwapShareAmountIn, - MsgExitSwapShareAmountInResponse as OsmosisGammV1beta1MsgExitSwapShareAmountInResponse, - MsgExitSwapExternAmountOut as OsmosisGammV1beta1MsgExitSwapExternAmountOut, - MsgExitSwapExternAmountOutResponse as OsmosisGammV1beta1MsgExitSwapExternAmountOutResponse, -} from "./osmosis/gamm/v1beta1/tx_pb.js"; -export { - MsgJoinPoolService as OsmosisGammV1beta1MsgJoinPoolService, - MsgExitPoolService as OsmosisGammV1beta1MsgExitPoolService, - MsgSwapExactAmountInService as OsmosisGammV1beta1MsgSwapExactAmountInService, - MsgSwapExactAmountOutService as OsmosisGammV1beta1MsgSwapExactAmountOutService, - MsgJoinSwapExternAmountInService as OsmosisGammV1beta1MsgJoinSwapExternAmountInService, - MsgJoinSwapShareAmountOutService as OsmosisGammV1beta1MsgJoinSwapShareAmountOutService, - MsgExitSwapExternAmountOutService as OsmosisGammV1beta1MsgExitSwapExternAmountOutService, - MsgExitSwapShareAmountInService as OsmosisGammV1beta1MsgExitSwapShareAmountInService, -} from "./osmosis/gamm/v1beta1/tx_cosmes.js"; -export { - MigrationRecords as OsmosisGammV1beta1MigrationRecords, - BalancerToConcentratedPoolLink as OsmosisGammV1beta1BalancerToConcentratedPoolLink, -} from "./osmosis/gamm/v1beta1/shared_pb.js"; -export { - ParamsRequest as OsmosisGammV1beta1ParamsRequest, - ParamsResponse as OsmosisGammV1beta1ParamsResponse, - QueryPoolRequest as OsmosisGammV1beta1QueryPoolRequest, - QueryPoolResponse as OsmosisGammV1beta1QueryPoolResponse, - QueryPoolsRequest as OsmosisGammV1beta1QueryPoolsRequest, - QueryPoolsResponse as OsmosisGammV1beta1QueryPoolsResponse, - QueryNumPoolsRequest as OsmosisGammV1beta1QueryNumPoolsRequest, - QueryNumPoolsResponse as OsmosisGammV1beta1QueryNumPoolsResponse, - QueryPoolTypeRequest as OsmosisGammV1beta1QueryPoolTypeRequest, - QueryPoolTypeResponse as OsmosisGammV1beta1QueryPoolTypeResponse, - QueryCalcJoinPoolSharesRequest as OsmosisGammV1beta1QueryCalcJoinPoolSharesRequest, - QueryCalcJoinPoolSharesResponse as OsmosisGammV1beta1QueryCalcJoinPoolSharesResponse, - QueryCalcExitPoolCoinsFromSharesRequest as OsmosisGammV1beta1QueryCalcExitPoolCoinsFromSharesRequest, - QueryCalcExitPoolCoinsFromSharesResponse as OsmosisGammV1beta1QueryCalcExitPoolCoinsFromSharesResponse, - QueryPoolParamsRequest as OsmosisGammV1beta1QueryPoolParamsRequest, - QueryPoolParamsResponse as OsmosisGammV1beta1QueryPoolParamsResponse, - QueryTotalPoolLiquidityRequest as OsmosisGammV1beta1QueryTotalPoolLiquidityRequest, - QueryTotalPoolLiquidityResponse as OsmosisGammV1beta1QueryTotalPoolLiquidityResponse, - QueryTotalSharesRequest as OsmosisGammV1beta1QueryTotalSharesRequest, - QueryTotalSharesResponse as OsmosisGammV1beta1QueryTotalSharesResponse, - QueryCalcJoinPoolNoSwapSharesRequest as OsmosisGammV1beta1QueryCalcJoinPoolNoSwapSharesRequest, - QueryCalcJoinPoolNoSwapSharesResponse as OsmosisGammV1beta1QueryCalcJoinPoolNoSwapSharesResponse, - QuerySpotPriceRequest as OsmosisGammV1beta1QuerySpotPriceRequest, - QueryPoolsWithFilterRequest as OsmosisGammV1beta1QueryPoolsWithFilterRequest, - QueryPoolsWithFilterResponse as OsmosisGammV1beta1QueryPoolsWithFilterResponse, - QuerySpotPriceResponse as OsmosisGammV1beta1QuerySpotPriceResponse, - QuerySwapExactAmountInRequest as OsmosisGammV1beta1QuerySwapExactAmountInRequest, - QuerySwapExactAmountInResponse as OsmosisGammV1beta1QuerySwapExactAmountInResponse, - QuerySwapExactAmountOutRequest as OsmosisGammV1beta1QuerySwapExactAmountOutRequest, - QuerySwapExactAmountOutResponse as OsmosisGammV1beta1QuerySwapExactAmountOutResponse, - QueryTotalLiquidityRequest as OsmosisGammV1beta1QueryTotalLiquidityRequest, - QueryTotalLiquidityResponse as OsmosisGammV1beta1QueryTotalLiquidityResponse, - QueryConcentratedPoolIdLinkFromCFMMRequest as OsmosisGammV1beta1QueryConcentratedPoolIdLinkFromCFMMRequest, - QueryConcentratedPoolIdLinkFromCFMMResponse as OsmosisGammV1beta1QueryConcentratedPoolIdLinkFromCFMMResponse, - QueryCFMMConcentratedPoolLinksRequest as OsmosisGammV1beta1QueryCFMMConcentratedPoolLinksRequest, - QueryCFMMConcentratedPoolLinksResponse as OsmosisGammV1beta1QueryCFMMConcentratedPoolLinksResponse, -} from "./osmosis/gamm/v1beta1/query_pb.js"; -export { - QueryPoolsService as OsmosisGammV1beta1QueryPoolsService, - QueryNumPoolsService as OsmosisGammV1beta1QueryNumPoolsService, - QueryTotalLiquidityService as OsmosisGammV1beta1QueryTotalLiquidityService, - QueryPoolsWithFilterService as OsmosisGammV1beta1QueryPoolsWithFilterService, - QueryPoolService as OsmosisGammV1beta1QueryPoolService, - QueryPoolTypeService as OsmosisGammV1beta1QueryPoolTypeService, - QueryCalcJoinPoolNoSwapSharesService as OsmosisGammV1beta1QueryCalcJoinPoolNoSwapSharesService, - QueryCalcJoinPoolSharesService as OsmosisGammV1beta1QueryCalcJoinPoolSharesService, - QueryCalcExitPoolCoinsFromSharesService as OsmosisGammV1beta1QueryCalcExitPoolCoinsFromSharesService, - QueryPoolParamsService as OsmosisGammV1beta1QueryPoolParamsService, - QueryTotalPoolLiquidityService as OsmosisGammV1beta1QueryTotalPoolLiquidityService, - QueryTotalSharesService as OsmosisGammV1beta1QueryTotalSharesService, - QuerySpotPriceService as OsmosisGammV1beta1QuerySpotPriceService, - QueryEstimateSwapExactAmountInService as OsmosisGammV1beta1QueryEstimateSwapExactAmountInService, - QueryEstimateSwapExactAmountOutService as OsmosisGammV1beta1QueryEstimateSwapExactAmountOutService, - QueryConcentratedPoolIdLinkFromCFMMService as OsmosisGammV1beta1QueryConcentratedPoolIdLinkFromCFMMService, - QueryCFMMConcentratedPoolLinksService as OsmosisGammV1beta1QueryCFMMConcentratedPoolLinksService, - QueryParamsService as OsmosisGammV1beta1QueryParamsService, -} from "./osmosis/gamm/v1beta1/query_cosmes.js"; -export { - Params as OsmosisGammV1beta1Params, -} from "./osmosis/gamm/v1beta1/params_pb.js"; -export { - ReplaceMigrationRecordsProposal as OsmosisGammV1beta1ReplaceMigrationRecordsProposal, - UpdateMigrationRecordsProposal as OsmosisGammV1beta1UpdateMigrationRecordsProposal, - PoolRecordWithCFMMLink as OsmosisGammV1beta1PoolRecordWithCFMMLink, - CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal as OsmosisGammV1beta1CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal, - SetScalingFactorControllerProposal as OsmosisGammV1beta1SetScalingFactorControllerProposal, -} from "./osmosis/gamm/v1beta1/gov_pb.js"; -export { - GenesisState as OsmosisGammV1beta1GenesisState, -} from "./osmosis/gamm/v1beta1/genesis_pb.js"; -export { - SmoothWeightChangeParams as OsmosisGammV1beta1SmoothWeightChangeParams, - PoolParams as OsmosisGammV1beta1PoolParams, - PoolAsset as OsmosisGammV1beta1PoolAsset, - Pool as OsmosisGammV1beta1Pool, -} from "./osmosis/gamm/v1beta1/balancerPool_pb.js"; -export { - MsgCreateStableswapPool as OsmosisGammPoolmodelsStableswapV1beta1MsgCreateStableswapPool, - MsgCreateStableswapPoolResponse as OsmosisGammPoolmodelsStableswapV1beta1MsgCreateStableswapPoolResponse, - MsgStableSwapAdjustScalingFactors as OsmosisGammPoolmodelsStableswapV1beta1MsgStableSwapAdjustScalingFactors, - MsgStableSwapAdjustScalingFactorsResponse as OsmosisGammPoolmodelsStableswapV1beta1MsgStableSwapAdjustScalingFactorsResponse, -} from "./osmosis/gamm/poolmodels/stableswap/v1beta1/tx_pb.js"; -export { - MsgCreateStableswapPoolService as OsmosisGammPoolmodelsStableswapV1beta1MsgCreateStableswapPoolService, - MsgStableSwapAdjustScalingFactorsService as OsmosisGammPoolmodelsStableswapV1beta1MsgStableSwapAdjustScalingFactorsService, -} from "./osmosis/gamm/poolmodels/stableswap/v1beta1/tx_cosmes.js"; -export { - PoolParams as OsmosisGammPoolmodelsStableswapV1beta1PoolParams, - Pool as OsmosisGammPoolmodelsStableswapV1beta1Pool, -} from "./osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool_pb.js"; -export { - MsgCreateBalancerPool as OsmosisGammPoolmodelsBalancerV1beta1MsgCreateBalancerPool, - MsgCreateBalancerPoolResponse as OsmosisGammPoolmodelsBalancerV1beta1MsgCreateBalancerPoolResponse, -} from "./osmosis/gamm/poolmodels/balancer/v1beta1/tx_pb.js"; -export { - MsgCreateBalancerPoolService as OsmosisGammPoolmodelsBalancerV1beta1MsgCreateBalancerPoolService, -} from "./osmosis/gamm/poolmodels/balancer/v1beta1/tx_cosmes.js"; -export { - QueryEpochsInfoRequest as OsmosisEpochsV1beta1QueryEpochsInfoRequest, - QueryEpochsInfoResponse as OsmosisEpochsV1beta1QueryEpochsInfoResponse, - QueryCurrentEpochRequest as OsmosisEpochsV1beta1QueryCurrentEpochRequest, - QueryCurrentEpochResponse as OsmosisEpochsV1beta1QueryCurrentEpochResponse, -} from "./osmosis/epochs/v1beta1/query_pb.js"; -export { - QueryEpochInfosService as OsmosisEpochsV1beta1QueryEpochInfosService, - QueryCurrentEpochService as OsmosisEpochsV1beta1QueryCurrentEpochService, -} from "./osmosis/epochs/v1beta1/query_cosmes.js"; -export { - EpochInfo as OsmosisEpochsV1beta1EpochInfo, - GenesisState as OsmosisEpochsV1beta1GenesisState, -} from "./osmosis/epochs/v1beta1/genesis_pb.js"; -export { - RecoveredSinceDowntimeOfLengthRequest as OsmosisDowntimedetectorV1beta1RecoveredSinceDowntimeOfLengthRequest, - RecoveredSinceDowntimeOfLengthResponse as OsmosisDowntimedetectorV1beta1RecoveredSinceDowntimeOfLengthResponse, -} from "./osmosis/downtimedetector/v1beta1/query_pb.js"; -export { - QueryRecoveredSinceDowntimeOfLengthService as OsmosisDowntimedetectorV1beta1QueryRecoveredSinceDowntimeOfLengthService, -} from "./osmosis/downtimedetector/v1beta1/query_cosmes.js"; -export { - GenesisDowntimeEntry as OsmosisDowntimedetectorV1beta1GenesisDowntimeEntry, - GenesisState as OsmosisDowntimedetectorV1beta1GenesisState, -} from "./osmosis/downtimedetector/v1beta1/genesis_pb.js"; -export { - Downtime as OsmosisDowntimedetectorV1beta1Downtime, -} from "./osmosis/downtimedetector/v1beta1/downtime_duration_pb.js"; -export { -} from "./osmosis/cosmwasmpool/v1beta1/tx_cosmes.js"; -export { - ParamsRequest as OsmosisCosmwasmpoolV1beta1ParamsRequest, - ParamsResponse as OsmosisCosmwasmpoolV1beta1ParamsResponse, - PoolsRequest as OsmosisCosmwasmpoolV1beta1PoolsRequest, - PoolsResponse as OsmosisCosmwasmpoolV1beta1PoolsResponse, - ContractInfoByPoolIdRequest as OsmosisCosmwasmpoolV1beta1ContractInfoByPoolIdRequest, - ContractInfoByPoolIdResponse as OsmosisCosmwasmpoolV1beta1ContractInfoByPoolIdResponse, - PoolRawFilteredStateRequest as OsmosisCosmwasmpoolV1beta1PoolRawFilteredStateRequest, - PoolRawFilteredStateResponse as OsmosisCosmwasmpoolV1beta1PoolRawFilteredStateResponse, -} from "./osmosis/cosmwasmpool/v1beta1/query_pb.js"; -export { - QueryPoolsService as OsmosisCosmwasmpoolV1beta1QueryPoolsService, - QueryParamsService as OsmosisCosmwasmpoolV1beta1QueryParamsService, - QueryContractInfoByPoolIdService as OsmosisCosmwasmpoolV1beta1QueryContractInfoByPoolIdService, - QueryPoolRawFilteredStateService as OsmosisCosmwasmpoolV1beta1QueryPoolRawFilteredStateService, -} from "./osmosis/cosmwasmpool/v1beta1/query_cosmes.js"; -export { - Params as OsmosisCosmwasmpoolV1beta1Params, -} from "./osmosis/cosmwasmpool/v1beta1/params_pb.js"; -export { - UploadCosmWasmPoolCodeAndWhiteListProposal as OsmosisCosmwasmpoolV1beta1UploadCosmWasmPoolCodeAndWhiteListProposal, - MigratePoolContractsProposal as OsmosisCosmwasmpoolV1beta1MigratePoolContractsProposal, -} from "./osmosis/cosmwasmpool/v1beta1/gov_pb.js"; -export { - GenesisState as OsmosisCosmwasmpoolV1beta1GenesisState, -} from "./osmosis/cosmwasmpool/v1beta1/genesis_pb.js"; -export { - MsgCreateCosmWasmPool as OsmosisCosmwasmpoolV1beta1ModelMsgCreateCosmWasmPool, - MsgCreateCosmWasmPoolResponse as OsmosisCosmwasmpoolV1beta1ModelMsgCreateCosmWasmPoolResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/tx_pb.js"; -export { - MsgCreatorCreateCosmWasmPoolService as OsmosisCosmwasmpoolV1beta1ModelMsgCreatorCreateCosmWasmPoolService, -} from "./osmosis/cosmwasmpool/v1beta1/model/tx_cosmes.js"; -export { - EmptyRequest as OsmosisCosmwasmpoolV1beta1ModelEmptyRequest, - JoinPoolExecuteMsgRequest as OsmosisCosmwasmpoolV1beta1ModelJoinPoolExecuteMsgRequest, - JoinPoolExecuteMsgResponse as OsmosisCosmwasmpoolV1beta1ModelJoinPoolExecuteMsgResponse, - ExitPoolExecuteMsgRequest as OsmosisCosmwasmpoolV1beta1ModelExitPoolExecuteMsgRequest, - ExitPoolExecuteMsgResponse as OsmosisCosmwasmpoolV1beta1ModelExitPoolExecuteMsgResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs_pb.js"; -export { - GetSwapFeeQueryMsg as OsmosisCosmwasmpoolV1beta1ModelGetSwapFeeQueryMsg, - GetSwapFeeQueryMsgResponse as OsmosisCosmwasmpoolV1beta1ModelGetSwapFeeQueryMsgResponse, - SpotPrice as OsmosisCosmwasmpoolV1beta1ModelSpotPrice, - SpotPriceQueryMsg as OsmosisCosmwasmpoolV1beta1ModelSpotPriceQueryMsg, - SpotPriceQueryMsgResponse as OsmosisCosmwasmpoolV1beta1ModelSpotPriceQueryMsgResponse, - EmptyStruct as OsmosisCosmwasmpoolV1beta1ModelEmptyStruct, - GetTotalPoolLiquidityQueryMsg as OsmosisCosmwasmpoolV1beta1ModelGetTotalPoolLiquidityQueryMsg, - GetTotalPoolLiquidityQueryMsgResponse as OsmosisCosmwasmpoolV1beta1ModelGetTotalPoolLiquidityQueryMsgResponse, - GetTotalSharesQueryMsg as OsmosisCosmwasmpoolV1beta1ModelGetTotalSharesQueryMsg, - GetTotalSharesQueryMsgResponse as OsmosisCosmwasmpoolV1beta1ModelGetTotalSharesQueryMsgResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/pool_query_msg_pb.js"; -export { - CosmWasmPool as OsmosisCosmwasmpoolV1beta1ModelCosmWasmPool, -} from "./osmosis/cosmwasmpool/v1beta1/model/pool_pb.js"; -export { - SwapExactAmountIn as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountIn, - SwapExactAmountInSudoMsg as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountInSudoMsg, - SwapExactAmountInSudoMsgResponse as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountInSudoMsgResponse, - SwapExactAmountOut as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountOut, - SwapExactAmountOutSudoMsg as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountOutSudoMsg, - SwapExactAmountOutSudoMsgResponse as OsmosisCosmwasmpoolV1beta1ModelSwapExactAmountOutSudoMsgResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg_pb.js"; -export { - CalcOutAmtGivenIn as OsmosisCosmwasmpoolV1beta1ModelCalcOutAmtGivenIn, - CalcOutAmtGivenInRequest as OsmosisCosmwasmpoolV1beta1ModelCalcOutAmtGivenInRequest, - CalcOutAmtGivenInResponse as OsmosisCosmwasmpoolV1beta1ModelCalcOutAmtGivenInResponse, - CalcInAmtGivenOut as OsmosisCosmwasmpoolV1beta1ModelCalcInAmtGivenOut, - CalcInAmtGivenOutRequest as OsmosisCosmwasmpoolV1beta1ModelCalcInAmtGivenOutRequest, - CalcInAmtGivenOutResponse as OsmosisCosmwasmpoolV1beta1ModelCalcInAmtGivenOutResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/module_query_msg_pb.js"; -export { - InstantiateMsg as OsmosisCosmwasmpoolV1beta1ModelInstantiateMsg, -} from "./osmosis/cosmwasmpool/v1beta1/model/instantiate_msg_pb.js"; -export { - ShareDenomResponse as OsmosisCosmwasmpoolV1beta1ModelV3ShareDenomResponse, - TotalPoolLiquidityResponse as OsmosisCosmwasmpoolV1beta1ModelV3TotalPoolLiquidityResponse, - AssetConfig as OsmosisCosmwasmpoolV1beta1ModelV3AssetConfig, - ListAssetConfigsResponse as OsmosisCosmwasmpoolV1beta1ModelV3ListAssetConfigsResponse, -} from "./osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg_pb.js"; -export { - Params as OsmosisConcentratedliquidityParams, -} from "./osmosis/concentratedliquidity/params_pb.js"; -export { - MsgCreatePosition as OsmosisConcentratedliquidityV1beta1MsgCreatePosition, - MsgCreatePositionResponse as OsmosisConcentratedliquidityV1beta1MsgCreatePositionResponse, - MsgAddToPosition as OsmosisConcentratedliquidityV1beta1MsgAddToPosition, - MsgAddToPositionResponse as OsmosisConcentratedliquidityV1beta1MsgAddToPositionResponse, - MsgWithdrawPosition as OsmosisConcentratedliquidityV1beta1MsgWithdrawPosition, - MsgWithdrawPositionResponse as OsmosisConcentratedliquidityV1beta1MsgWithdrawPositionResponse, - MsgCollectSpreadRewards as OsmosisConcentratedliquidityV1beta1MsgCollectSpreadRewards, - MsgCollectSpreadRewardsResponse as OsmosisConcentratedliquidityV1beta1MsgCollectSpreadRewardsResponse, - MsgCollectIncentives as OsmosisConcentratedliquidityV1beta1MsgCollectIncentives, - MsgCollectIncentivesResponse as OsmosisConcentratedliquidityV1beta1MsgCollectIncentivesResponse, - MsgFungifyChargedPositions as OsmosisConcentratedliquidityV1beta1MsgFungifyChargedPositions, - MsgFungifyChargedPositionsResponse as OsmosisConcentratedliquidityV1beta1MsgFungifyChargedPositionsResponse, - MsgTransferPositions as OsmosisConcentratedliquidityV1beta1MsgTransferPositions, - MsgTransferPositionsResponse as OsmosisConcentratedliquidityV1beta1MsgTransferPositionsResponse, -} from "./osmosis/concentratedliquidity/v1beta1/tx_pb.js"; -export { - MsgCreatePositionService as OsmosisConcentratedliquidityV1beta1MsgCreatePositionService, - MsgWithdrawPositionService as OsmosisConcentratedliquidityV1beta1MsgWithdrawPositionService, - MsgAddToPositionService as OsmosisConcentratedliquidityV1beta1MsgAddToPositionService, - MsgCollectSpreadRewardsService as OsmosisConcentratedliquidityV1beta1MsgCollectSpreadRewardsService, - MsgCollectIncentivesService as OsmosisConcentratedliquidityV1beta1MsgCollectIncentivesService, - MsgTransferPositionsService as OsmosisConcentratedliquidityV1beta1MsgTransferPositionsService, -} from "./osmosis/concentratedliquidity/v1beta1/tx_cosmes.js"; -export { - TickInfo as OsmosisConcentratedliquidityV1beta1TickInfo, - UptimeTrackers as OsmosisConcentratedliquidityV1beta1UptimeTrackers, - UptimeTracker as OsmosisConcentratedliquidityV1beta1UptimeTracker, -} from "./osmosis/concentratedliquidity/v1beta1/tick_info_pb.js"; -export { - UserPositionsRequest as OsmosisConcentratedliquidityV1beta1UserPositionsRequest, - UserPositionsResponse as OsmosisConcentratedliquidityV1beta1UserPositionsResponse, - PositionByIdRequest as OsmosisConcentratedliquidityV1beta1PositionByIdRequest, - PositionByIdResponse as OsmosisConcentratedliquidityV1beta1PositionByIdResponse, - NumPoolPositionsRequest as OsmosisConcentratedliquidityV1beta1NumPoolPositionsRequest, - NumPoolPositionsResponse as OsmosisConcentratedliquidityV1beta1NumPoolPositionsResponse, - PoolsRequest as OsmosisConcentratedliquidityV1beta1PoolsRequest, - PoolsResponse as OsmosisConcentratedliquidityV1beta1PoolsResponse, - ParamsRequest as OsmosisConcentratedliquidityV1beta1ParamsRequest, - ParamsResponse as OsmosisConcentratedliquidityV1beta1ParamsResponse, - TickLiquidityNet as OsmosisConcentratedliquidityV1beta1TickLiquidityNet, - LiquidityDepthWithRange as OsmosisConcentratedliquidityV1beta1LiquidityDepthWithRange, - LiquidityNetInDirectionRequest as OsmosisConcentratedliquidityV1beta1LiquidityNetInDirectionRequest, - LiquidityNetInDirectionResponse as OsmosisConcentratedliquidityV1beta1LiquidityNetInDirectionResponse, - LiquidityPerTickRangeRequest as OsmosisConcentratedliquidityV1beta1LiquidityPerTickRangeRequest, - LiquidityPerTickRangeResponse as OsmosisConcentratedliquidityV1beta1LiquidityPerTickRangeResponse, - ClaimableSpreadRewardsRequest as OsmosisConcentratedliquidityV1beta1ClaimableSpreadRewardsRequest, - ClaimableSpreadRewardsResponse as OsmosisConcentratedliquidityV1beta1ClaimableSpreadRewardsResponse, - ClaimableIncentivesRequest as OsmosisConcentratedliquidityV1beta1ClaimableIncentivesRequest, - ClaimableIncentivesResponse as OsmosisConcentratedliquidityV1beta1ClaimableIncentivesResponse, - PoolAccumulatorRewardsRequest as OsmosisConcentratedliquidityV1beta1PoolAccumulatorRewardsRequest, - PoolAccumulatorRewardsResponse as OsmosisConcentratedliquidityV1beta1PoolAccumulatorRewardsResponse, - TickAccumulatorTrackersRequest as OsmosisConcentratedliquidityV1beta1TickAccumulatorTrackersRequest, - TickAccumulatorTrackersResponse as OsmosisConcentratedliquidityV1beta1TickAccumulatorTrackersResponse, - IncentiveRecordsRequest as OsmosisConcentratedliquidityV1beta1IncentiveRecordsRequest, - IncentiveRecordsResponse as OsmosisConcentratedliquidityV1beta1IncentiveRecordsResponse, - CFMMPoolIdLinkFromConcentratedPoolIdRequest as OsmosisConcentratedliquidityV1beta1CFMMPoolIdLinkFromConcentratedPoolIdRequest, - CFMMPoolIdLinkFromConcentratedPoolIdResponse as OsmosisConcentratedliquidityV1beta1CFMMPoolIdLinkFromConcentratedPoolIdResponse, - UserUnbondingPositionsRequest as OsmosisConcentratedliquidityV1beta1UserUnbondingPositionsRequest, - UserUnbondingPositionsResponse as OsmosisConcentratedliquidityV1beta1UserUnbondingPositionsResponse, - GetTotalLiquidityRequest as OsmosisConcentratedliquidityV1beta1GetTotalLiquidityRequest, - GetTotalLiquidityResponse as OsmosisConcentratedliquidityV1beta1GetTotalLiquidityResponse, - NumNextInitializedTicksRequest as OsmosisConcentratedliquidityV1beta1NumNextInitializedTicksRequest, - NumNextInitializedTicksResponse as OsmosisConcentratedliquidityV1beta1NumNextInitializedTicksResponse, -} from "./osmosis/concentratedliquidity/v1beta1/query_pb.js"; -export { - QueryPoolsService as OsmosisConcentratedliquidityV1beta1QueryPoolsService, - QueryParamsService as OsmosisConcentratedliquidityV1beta1QueryParamsService, - QueryUserPositionsService as OsmosisConcentratedliquidityV1beta1QueryUserPositionsService, - QueryLiquidityPerTickRangeService as OsmosisConcentratedliquidityV1beta1QueryLiquidityPerTickRangeService, - QueryLiquidityNetInDirectionService as OsmosisConcentratedliquidityV1beta1QueryLiquidityNetInDirectionService, - QueryClaimableSpreadRewardsService as OsmosisConcentratedliquidityV1beta1QueryClaimableSpreadRewardsService, - QueryClaimableIncentivesService as OsmosisConcentratedliquidityV1beta1QueryClaimableIncentivesService, - QueryPositionByIdService as OsmosisConcentratedliquidityV1beta1QueryPositionByIdService, - QueryPoolAccumulatorRewardsService as OsmosisConcentratedliquidityV1beta1QueryPoolAccumulatorRewardsService, - QueryIncentiveRecordsService as OsmosisConcentratedliquidityV1beta1QueryIncentiveRecordsService, - QueryTickAccumulatorTrackersService as OsmosisConcentratedliquidityV1beta1QueryTickAccumulatorTrackersService, - QueryCFMMPoolIdLinkFromConcentratedPoolIdService as OsmosisConcentratedliquidityV1beta1QueryCFMMPoolIdLinkFromConcentratedPoolIdService, - QueryUserUnbondingPositionsService as OsmosisConcentratedliquidityV1beta1QueryUserUnbondingPositionsService, - QueryGetTotalLiquidityService as OsmosisConcentratedliquidityV1beta1QueryGetTotalLiquidityService, - QueryNumNextInitializedTicksService as OsmosisConcentratedliquidityV1beta1QueryNumNextInitializedTicksService, -} from "./osmosis/concentratedliquidity/v1beta1/query_cosmes.js"; -export { - Position as OsmosisConcentratedliquidityV1beta1Position, - FullPositionBreakdown as OsmosisConcentratedliquidityV1beta1FullPositionBreakdown, - PositionWithPeriodLock as OsmosisConcentratedliquidityV1beta1PositionWithPeriodLock, -} from "./osmosis/concentratedliquidity/v1beta1/position_pb.js"; -export { - Pool as OsmosisConcentratedliquidityV1beta1Pool, -} from "./osmosis/concentratedliquidity/v1beta1/pool_pb.js"; -export { - IncentiveRecord as OsmosisConcentratedliquidityV1beta1IncentiveRecord, - IncentiveRecordBody as OsmosisConcentratedliquidityV1beta1IncentiveRecordBody, -} from "./osmosis/concentratedliquidity/v1beta1/incentive_record_pb.js"; -export { - CreateConcentratedLiquidityPoolsProposal as OsmosisConcentratedliquidityV1beta1CreateConcentratedLiquidityPoolsProposal, - TickSpacingDecreaseProposal as OsmosisConcentratedliquidityV1beta1TickSpacingDecreaseProposal, - PoolIdToTickSpacingRecord as OsmosisConcentratedliquidityV1beta1PoolIdToTickSpacingRecord, - PoolRecord as OsmosisConcentratedliquidityV1beta1PoolRecord, -} from "./osmosis/concentratedliquidity/v1beta1/gov_pb.js"; -export { - FullTick as OsmosisConcentratedliquidityV1beta1FullTick, - PoolData as OsmosisConcentratedliquidityV1beta1PoolData, - PositionData as OsmosisConcentratedliquidityV1beta1PositionData, - GenesisState as OsmosisConcentratedliquidityV1beta1GenesisState, - AccumObject as OsmosisConcentratedliquidityV1beta1AccumObject, -} from "./osmosis/concentratedliquidity/v1beta1/genesis_pb.js"; -export { - MsgCreateConcentratedPool as OsmosisConcentratedliquidityPoolmodelConcentratedV1beta1MsgCreateConcentratedPool, - MsgCreateConcentratedPoolResponse as OsmosisConcentratedliquidityPoolmodelConcentratedV1beta1MsgCreateConcentratedPoolResponse, -} from "./osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_pb.js"; -export { - MsgCreateConcentratedPoolService as OsmosisConcentratedliquidityPoolmodelConcentratedV1beta1MsgCreateConcentratedPoolService, -} from "./osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_cosmes.js"; -export { - AccumulatorContent as OsmosisAccumV1beta1AccumulatorContent, - Options as OsmosisAccumV1beta1Options, - Record as OsmosisAccumV1beta1Record, -} from "./osmosis/accum/v1beta1/accum_pb.js"; -export { - ClientState as IbcLightclientsWasmV1ClientState, - ConsensusState as IbcLightclientsWasmV1ConsensusState, - ClientMessage as IbcLightclientsWasmV1ClientMessage, -} from "./ibc/lightclients/wasm/v1/wasm_pb.js"; -export { - MsgStoreCode as IbcLightclientsWasmV1MsgStoreCode, - MsgStoreCodeResponse as IbcLightclientsWasmV1MsgStoreCodeResponse, - MsgRemoveChecksum as IbcLightclientsWasmV1MsgRemoveChecksum, - MsgRemoveChecksumResponse as IbcLightclientsWasmV1MsgRemoveChecksumResponse, - MsgMigrateContract as IbcLightclientsWasmV1MsgMigrateContract, - MsgMigrateContractResponse as IbcLightclientsWasmV1MsgMigrateContractResponse, -} from "./ibc/lightclients/wasm/v1/tx_pb.js"; -export { - MsgStoreCodeService as IbcLightclientsWasmV1MsgStoreCodeService, - MsgRemoveChecksumService as IbcLightclientsWasmV1MsgRemoveChecksumService, - MsgMigrateContractService as IbcLightclientsWasmV1MsgMigrateContractService, -} from "./ibc/lightclients/wasm/v1/tx_cosmes.js"; -export { - QueryChecksumsRequest as IbcLightclientsWasmV1QueryChecksumsRequest, - QueryChecksumsResponse as IbcLightclientsWasmV1QueryChecksumsResponse, - QueryCodeRequest as IbcLightclientsWasmV1QueryCodeRequest, - QueryCodeResponse as IbcLightclientsWasmV1QueryCodeResponse, -} from "./ibc/lightclients/wasm/v1/query_pb.js"; -export { - QueryChecksumsService as IbcLightclientsWasmV1QueryChecksumsService, - QueryCodeService as IbcLightclientsWasmV1QueryCodeService, -} from "./ibc/lightclients/wasm/v1/query_cosmes.js"; -export { - GenesisState as IbcLightclientsWasmV1GenesisState, - Contract as IbcLightclientsWasmV1Contract, -} from "./ibc/lightclients/wasm/v1/genesis_pb.js"; -export { - ClientState as IbcLightclientsTendermintV1ClientState, - ConsensusState as IbcLightclientsTendermintV1ConsensusState, - Misbehaviour as IbcLightclientsTendermintV1Misbehaviour, - Header as IbcLightclientsTendermintV1Header, - Fraction as IbcLightclientsTendermintV1Fraction, -} from "./ibc/lightclients/tendermint/v1/tendermint_pb.js"; -export { - ClientState as IbcLightclientsSolomachineV3ClientState, - ConsensusState as IbcLightclientsSolomachineV3ConsensusState, - Header as IbcLightclientsSolomachineV3Header, - Misbehaviour as IbcLightclientsSolomachineV3Misbehaviour, - SignatureAndData as IbcLightclientsSolomachineV3SignatureAndData, - TimestampedSignatureData as IbcLightclientsSolomachineV3TimestampedSignatureData, - SignBytes as IbcLightclientsSolomachineV3SignBytes, - HeaderData as IbcLightclientsSolomachineV3HeaderData, -} from "./ibc/lightclients/solomachine/v3/solomachine_pb.js"; -export { - DataType as IbcLightclientsSolomachineV2DataType, - ClientState as IbcLightclientsSolomachineV2ClientState, - ConsensusState as IbcLightclientsSolomachineV2ConsensusState, - Header as IbcLightclientsSolomachineV2Header, - Misbehaviour as IbcLightclientsSolomachineV2Misbehaviour, - SignatureAndData as IbcLightclientsSolomachineV2SignatureAndData, - TimestampedSignatureData as IbcLightclientsSolomachineV2TimestampedSignatureData, - SignBytes as IbcLightclientsSolomachineV2SignBytes, - HeaderData as IbcLightclientsSolomachineV2HeaderData, - ClientStateData as IbcLightclientsSolomachineV2ClientStateData, - ConsensusStateData as IbcLightclientsSolomachineV2ConsensusStateData, - ConnectionStateData as IbcLightclientsSolomachineV2ConnectionStateData, - ChannelStateData as IbcLightclientsSolomachineV2ChannelStateData, - PacketCommitmentData as IbcLightclientsSolomachineV2PacketCommitmentData, - PacketAcknowledgementData as IbcLightclientsSolomachineV2PacketAcknowledgementData, - PacketReceiptAbsenceData as IbcLightclientsSolomachineV2PacketReceiptAbsenceData, - NextSequenceRecvData as IbcLightclientsSolomachineV2NextSequenceRecvData, -} from "./ibc/lightclients/solomachine/v2/solomachine_pb.js"; -export { - GenesisState as IbcCoreTypesV1GenesisState, -} from "./ibc/core/types/v1/genesis_pb.js"; -export { - MsgConnectionOpenInit as IbcCoreConnectionV1MsgConnectionOpenInit, - MsgConnectionOpenInitResponse as IbcCoreConnectionV1MsgConnectionOpenInitResponse, - MsgConnectionOpenTry as IbcCoreConnectionV1MsgConnectionOpenTry, - MsgConnectionOpenTryResponse as IbcCoreConnectionV1MsgConnectionOpenTryResponse, - MsgConnectionOpenAck as IbcCoreConnectionV1MsgConnectionOpenAck, - MsgConnectionOpenAckResponse as IbcCoreConnectionV1MsgConnectionOpenAckResponse, - MsgConnectionOpenConfirm as IbcCoreConnectionV1MsgConnectionOpenConfirm, - MsgConnectionOpenConfirmResponse as IbcCoreConnectionV1MsgConnectionOpenConfirmResponse, - MsgUpdateParams as IbcCoreConnectionV1MsgUpdateParams, - MsgUpdateParamsResponse as IbcCoreConnectionV1MsgUpdateParamsResponse, -} from "./ibc/core/connection/v1/tx_pb.js"; -export { - MsgConnectionOpenInitService as IbcCoreConnectionV1MsgConnectionOpenInitService, - MsgConnectionOpenTryService as IbcCoreConnectionV1MsgConnectionOpenTryService, - MsgConnectionOpenAckService as IbcCoreConnectionV1MsgConnectionOpenAckService, - MsgConnectionOpenConfirmService as IbcCoreConnectionV1MsgConnectionOpenConfirmService, - MsgUpdateConnectionParamsService as IbcCoreConnectionV1MsgUpdateConnectionParamsService, -} from "./ibc/core/connection/v1/tx_cosmes.js"; -export { - QueryConnectionRequest as IbcCoreConnectionV1QueryConnectionRequest, - QueryConnectionResponse as IbcCoreConnectionV1QueryConnectionResponse, - QueryConnectionsRequest as IbcCoreConnectionV1QueryConnectionsRequest, - QueryConnectionsResponse as IbcCoreConnectionV1QueryConnectionsResponse, - QueryClientConnectionsRequest as IbcCoreConnectionV1QueryClientConnectionsRequest, - QueryClientConnectionsResponse as IbcCoreConnectionV1QueryClientConnectionsResponse, - QueryConnectionClientStateRequest as IbcCoreConnectionV1QueryConnectionClientStateRequest, - QueryConnectionClientStateResponse as IbcCoreConnectionV1QueryConnectionClientStateResponse, - QueryConnectionConsensusStateRequest as IbcCoreConnectionV1QueryConnectionConsensusStateRequest, - QueryConnectionConsensusStateResponse as IbcCoreConnectionV1QueryConnectionConsensusStateResponse, - QueryConnectionParamsRequest as IbcCoreConnectionV1QueryConnectionParamsRequest, - QueryConnectionParamsResponse as IbcCoreConnectionV1QueryConnectionParamsResponse, -} from "./ibc/core/connection/v1/query_pb.js"; -export { - QueryConnectionService as IbcCoreConnectionV1QueryConnectionService, - QueryConnectionsService as IbcCoreConnectionV1QueryConnectionsService, - QueryClientConnectionsService as IbcCoreConnectionV1QueryClientConnectionsService, - QueryConnectionClientStateService as IbcCoreConnectionV1QueryConnectionClientStateService, - QueryConnectionConsensusStateService as IbcCoreConnectionV1QueryConnectionConsensusStateService, - QueryConnectionParamsService as IbcCoreConnectionV1QueryConnectionParamsService, -} from "./ibc/core/connection/v1/query_cosmes.js"; -export { - GenesisState as IbcCoreConnectionV1GenesisState, -} from "./ibc/core/connection/v1/genesis_pb.js"; -export { - State as IbcCoreConnectionV1State, - ConnectionEnd as IbcCoreConnectionV1ConnectionEnd, - IdentifiedConnection as IbcCoreConnectionV1IdentifiedConnection, - Counterparty as IbcCoreConnectionV1Counterparty, - ClientPaths as IbcCoreConnectionV1ClientPaths, - ConnectionPaths as IbcCoreConnectionV1ConnectionPaths, - Version as IbcCoreConnectionV1Version, - Params as IbcCoreConnectionV1Params, -} from "./ibc/core/connection/v1/connection_pb.js"; -export { - MerklePath as IbcCoreCommitmentV2MerklePath, -} from "./ibc/core/commitment/v2/commitment_pb.js"; -export { - MerkleRoot as IbcCoreCommitmentV1MerkleRoot, - MerklePrefix as IbcCoreCommitmentV1MerklePrefix, - MerkleProof as IbcCoreCommitmentV1MerkleProof, -} from "./ibc/core/commitment/v1/commitment_pb.js"; -export { - MsgRegisterCounterparty as IbcCoreClientV2MsgRegisterCounterparty, - MsgRegisterCounterpartyResponse as IbcCoreClientV2MsgRegisterCounterpartyResponse, - MsgUpdateClientConfig as IbcCoreClientV2MsgUpdateClientConfig, - MsgUpdateClientConfigResponse as IbcCoreClientV2MsgUpdateClientConfigResponse, -} from "./ibc/core/client/v2/tx_pb.js"; -export { - MsgRegisterCounterpartyService as IbcCoreClientV2MsgRegisterCounterpartyService, - MsgUpdateClientConfigService as IbcCoreClientV2MsgUpdateClientConfigService, -} from "./ibc/core/client/v2/tx_cosmes.js"; -export { - QueryCounterpartyInfoRequest as IbcCoreClientV2QueryCounterpartyInfoRequest, - QueryCounterpartyInfoResponse as IbcCoreClientV2QueryCounterpartyInfoResponse, - QueryConfigRequest as IbcCoreClientV2QueryConfigRequest, - QueryConfigResponse as IbcCoreClientV2QueryConfigResponse, -} from "./ibc/core/client/v2/query_pb.js"; -export { - QueryCounterpartyInfoService as IbcCoreClientV2QueryCounterpartyInfoService, - QueryConfigService as IbcCoreClientV2QueryConfigService, -} from "./ibc/core/client/v2/query_cosmes.js"; -export { - GenesisCounterpartyInfo as IbcCoreClientV2GenesisCounterpartyInfo, - GenesisState as IbcCoreClientV2GenesisState, -} from "./ibc/core/client/v2/genesis_pb.js"; -export { - CounterpartyInfo as IbcCoreClientV2CounterpartyInfo, -} from "./ibc/core/client/v2/counterparty_pb.js"; -export { - Config as IbcCoreClientV2Config, -} from "./ibc/core/client/v2/config_pb.js"; -export { - MsgCreateClient as IbcCoreClientV1MsgCreateClient, - MsgCreateClientResponse as IbcCoreClientV1MsgCreateClientResponse, - MsgUpdateClient as IbcCoreClientV1MsgUpdateClient, - MsgUpdateClientResponse as IbcCoreClientV1MsgUpdateClientResponse, - MsgUpgradeClient as IbcCoreClientV1MsgUpgradeClient, - MsgUpgradeClientResponse as IbcCoreClientV1MsgUpgradeClientResponse, - MsgRecoverClient as IbcCoreClientV1MsgRecoverClient, - MsgRecoverClientResponse as IbcCoreClientV1MsgRecoverClientResponse, - MsgIBCSoftwareUpgrade as IbcCoreClientV1MsgIBCSoftwareUpgrade, - MsgIBCSoftwareUpgradeResponse as IbcCoreClientV1MsgIBCSoftwareUpgradeResponse, - MsgUpdateParams as IbcCoreClientV1MsgUpdateParams, - MsgUpdateParamsResponse as IbcCoreClientV1MsgUpdateParamsResponse, - MsgDeleteClientCreator as IbcCoreClientV1MsgDeleteClientCreator, - MsgDeleteClientCreatorResponse as IbcCoreClientV1MsgDeleteClientCreatorResponse, -} from "./ibc/core/client/v1/tx_pb.js"; -export { - MsgCreateClientService as IbcCoreClientV1MsgCreateClientService, - MsgUpdateClientService as IbcCoreClientV1MsgUpdateClientService, - MsgUpgradeClientService as IbcCoreClientV1MsgUpgradeClientService, - MsgRecoverClientService as IbcCoreClientV1MsgRecoverClientService, - MsgIBCSoftwareUpgradeService as IbcCoreClientV1MsgIBCSoftwareUpgradeService, - MsgUpdateClientParamsService as IbcCoreClientV1MsgUpdateClientParamsService, - MsgDeleteClientCreatorService as IbcCoreClientV1MsgDeleteClientCreatorService, -} from "./ibc/core/client/v1/tx_cosmes.js"; -export { - QueryClientStateRequest as IbcCoreClientV1QueryClientStateRequest, - QueryClientStateResponse as IbcCoreClientV1QueryClientStateResponse, - QueryClientStatesRequest as IbcCoreClientV1QueryClientStatesRequest, - QueryClientStatesResponse as IbcCoreClientV1QueryClientStatesResponse, - QueryConsensusStateRequest as IbcCoreClientV1QueryConsensusStateRequest, - QueryConsensusStateResponse as IbcCoreClientV1QueryConsensusStateResponse, - QueryConsensusStatesRequest as IbcCoreClientV1QueryConsensusStatesRequest, - QueryConsensusStatesResponse as IbcCoreClientV1QueryConsensusStatesResponse, - QueryConsensusStateHeightsRequest as IbcCoreClientV1QueryConsensusStateHeightsRequest, - QueryConsensusStateHeightsResponse as IbcCoreClientV1QueryConsensusStateHeightsResponse, - QueryClientStatusRequest as IbcCoreClientV1QueryClientStatusRequest, - QueryClientStatusResponse as IbcCoreClientV1QueryClientStatusResponse, - QueryClientParamsRequest as IbcCoreClientV1QueryClientParamsRequest, - QueryClientParamsResponse as IbcCoreClientV1QueryClientParamsResponse, - QueryClientCreatorRequest as IbcCoreClientV1QueryClientCreatorRequest, - QueryClientCreatorResponse as IbcCoreClientV1QueryClientCreatorResponse, - QueryUpgradedClientStateRequest as IbcCoreClientV1QueryUpgradedClientStateRequest, - QueryUpgradedClientStateResponse as IbcCoreClientV1QueryUpgradedClientStateResponse, - QueryUpgradedConsensusStateRequest as IbcCoreClientV1QueryUpgradedConsensusStateRequest, - QueryUpgradedConsensusStateResponse as IbcCoreClientV1QueryUpgradedConsensusStateResponse, - QueryVerifyMembershipRequest as IbcCoreClientV1QueryVerifyMembershipRequest, - QueryVerifyMembershipResponse as IbcCoreClientV1QueryVerifyMembershipResponse, -} from "./ibc/core/client/v1/query_pb.js"; -export { - QueryClientStateService as IbcCoreClientV1QueryClientStateService, - QueryClientStatesService as IbcCoreClientV1QueryClientStatesService, - QueryConsensusStateService as IbcCoreClientV1QueryConsensusStateService, - QueryConsensusStatesService as IbcCoreClientV1QueryConsensusStatesService, - QueryConsensusStateHeightsService as IbcCoreClientV1QueryConsensusStateHeightsService, - QueryClientStatusService as IbcCoreClientV1QueryClientStatusService, - QueryClientParamsService as IbcCoreClientV1QueryClientParamsService, - QueryClientCreatorService as IbcCoreClientV1QueryClientCreatorService, - QueryUpgradedClientStateService as IbcCoreClientV1QueryUpgradedClientStateService, - QueryUpgradedConsensusStateService as IbcCoreClientV1QueryUpgradedConsensusStateService, - QueryVerifyMembershipService as IbcCoreClientV1QueryVerifyMembershipService, -} from "./ibc/core/client/v1/query_cosmes.js"; -export { - GenesisState as IbcCoreClientV1GenesisState, - GenesisMetadata as IbcCoreClientV1GenesisMetadata, - IdentifiedGenesisMetadata as IbcCoreClientV1IdentifiedGenesisMetadata, -} from "./ibc/core/client/v1/genesis_pb.js"; -export { - IdentifiedClientState as IbcCoreClientV1IdentifiedClientState, - ConsensusStateWithHeight as IbcCoreClientV1ConsensusStateWithHeight, - ClientConsensusStates as IbcCoreClientV1ClientConsensusStates, - Height as IbcCoreClientV1Height, - Params as IbcCoreClientV1Params, -} from "./ibc/core/client/v1/client_pb.js"; -export { - ResponseResultType as IbcCoreChannelV2ResponseResultType, - MsgSendPacket as IbcCoreChannelV2MsgSendPacket, - MsgSendPacketResponse as IbcCoreChannelV2MsgSendPacketResponse, - MsgRecvPacket as IbcCoreChannelV2MsgRecvPacket, - MsgRecvPacketResponse as IbcCoreChannelV2MsgRecvPacketResponse, - MsgTimeout as IbcCoreChannelV2MsgTimeout, - MsgTimeoutResponse as IbcCoreChannelV2MsgTimeoutResponse, - MsgAcknowledgement as IbcCoreChannelV2MsgAcknowledgement, - MsgAcknowledgementResponse as IbcCoreChannelV2MsgAcknowledgementResponse, -} from "./ibc/core/channel/v2/tx_pb.js"; -export { - MsgSendPacketService as IbcCoreChannelV2MsgSendPacketService, - MsgRecvPacketService as IbcCoreChannelV2MsgRecvPacketService, - MsgTimeoutService as IbcCoreChannelV2MsgTimeoutService, - MsgAcknowledgementService as IbcCoreChannelV2MsgAcknowledgementService, -} from "./ibc/core/channel/v2/tx_cosmes.js"; -export { - QueryNextSequenceSendRequest as IbcCoreChannelV2QueryNextSequenceSendRequest, - QueryNextSequenceSendResponse as IbcCoreChannelV2QueryNextSequenceSendResponse, - QueryPacketCommitmentRequest as IbcCoreChannelV2QueryPacketCommitmentRequest, - QueryPacketCommitmentResponse as IbcCoreChannelV2QueryPacketCommitmentResponse, - QueryPacketCommitmentsRequest as IbcCoreChannelV2QueryPacketCommitmentsRequest, - QueryPacketCommitmentsResponse as IbcCoreChannelV2QueryPacketCommitmentsResponse, - QueryPacketAcknowledgementRequest as IbcCoreChannelV2QueryPacketAcknowledgementRequest, - QueryPacketAcknowledgementResponse as IbcCoreChannelV2QueryPacketAcknowledgementResponse, - QueryPacketAcknowledgementsRequest as IbcCoreChannelV2QueryPacketAcknowledgementsRequest, - QueryPacketAcknowledgementsResponse as IbcCoreChannelV2QueryPacketAcknowledgementsResponse, - QueryPacketReceiptRequest as IbcCoreChannelV2QueryPacketReceiptRequest, - QueryPacketReceiptResponse as IbcCoreChannelV2QueryPacketReceiptResponse, - QueryUnreceivedPacketsRequest as IbcCoreChannelV2QueryUnreceivedPacketsRequest, - QueryUnreceivedPacketsResponse as IbcCoreChannelV2QueryUnreceivedPacketsResponse, - QueryUnreceivedAcksRequest as IbcCoreChannelV2QueryUnreceivedAcksRequest, - QueryUnreceivedAcksResponse as IbcCoreChannelV2QueryUnreceivedAcksResponse, -} from "./ibc/core/channel/v2/query_pb.js"; -export { - QueryNextSequenceSendService as IbcCoreChannelV2QueryNextSequenceSendService, - QueryPacketCommitmentService as IbcCoreChannelV2QueryPacketCommitmentService, - QueryPacketCommitmentsService as IbcCoreChannelV2QueryPacketCommitmentsService, - QueryPacketAcknowledgementService as IbcCoreChannelV2QueryPacketAcknowledgementService, - QueryPacketAcknowledgementsService as IbcCoreChannelV2QueryPacketAcknowledgementsService, - QueryPacketReceiptService as IbcCoreChannelV2QueryPacketReceiptService, - QueryUnreceivedPacketsService as IbcCoreChannelV2QueryUnreceivedPacketsService, - QueryUnreceivedAcksService as IbcCoreChannelV2QueryUnreceivedAcksService, -} from "./ibc/core/channel/v2/query_cosmes.js"; -export { - PacketStatus as IbcCoreChannelV2PacketStatus, - Packet as IbcCoreChannelV2Packet, - Payload as IbcCoreChannelV2Payload, - Acknowledgement as IbcCoreChannelV2Acknowledgement, - RecvPacketResult as IbcCoreChannelV2RecvPacketResult, -} from "./ibc/core/channel/v2/packet_pb.js"; -export { - GenesisState as IbcCoreChannelV2GenesisState, - PacketState as IbcCoreChannelV2PacketState, - PacketSequence as IbcCoreChannelV2PacketSequence, -} from "./ibc/core/channel/v2/genesis_pb.js"; -export { - ResponseResultType as IbcCoreChannelV1ResponseResultType, - MsgChannelOpenInit as IbcCoreChannelV1MsgChannelOpenInit, - MsgChannelOpenInitResponse as IbcCoreChannelV1MsgChannelOpenInitResponse, - MsgChannelOpenTry as IbcCoreChannelV1MsgChannelOpenTry, - MsgChannelOpenTryResponse as IbcCoreChannelV1MsgChannelOpenTryResponse, - MsgChannelOpenAck as IbcCoreChannelV1MsgChannelOpenAck, - MsgChannelOpenAckResponse as IbcCoreChannelV1MsgChannelOpenAckResponse, - MsgChannelOpenConfirm as IbcCoreChannelV1MsgChannelOpenConfirm, - MsgChannelOpenConfirmResponse as IbcCoreChannelV1MsgChannelOpenConfirmResponse, - MsgChannelCloseInit as IbcCoreChannelV1MsgChannelCloseInit, - MsgChannelCloseInitResponse as IbcCoreChannelV1MsgChannelCloseInitResponse, - MsgChannelCloseConfirm as IbcCoreChannelV1MsgChannelCloseConfirm, - MsgChannelCloseConfirmResponse as IbcCoreChannelV1MsgChannelCloseConfirmResponse, - MsgRecvPacket as IbcCoreChannelV1MsgRecvPacket, - MsgRecvPacketResponse as IbcCoreChannelV1MsgRecvPacketResponse, - MsgTimeout as IbcCoreChannelV1MsgTimeout, - MsgTimeoutResponse as IbcCoreChannelV1MsgTimeoutResponse, - MsgTimeoutOnClose as IbcCoreChannelV1MsgTimeoutOnClose, - MsgTimeoutOnCloseResponse as IbcCoreChannelV1MsgTimeoutOnCloseResponse, - MsgAcknowledgement as IbcCoreChannelV1MsgAcknowledgement, - MsgAcknowledgementResponse as IbcCoreChannelV1MsgAcknowledgementResponse, -} from "./ibc/core/channel/v1/tx_pb.js"; -export { - MsgChannelOpenInitService as IbcCoreChannelV1MsgChannelOpenInitService, - MsgChannelOpenTryService as IbcCoreChannelV1MsgChannelOpenTryService, - MsgChannelOpenAckService as IbcCoreChannelV1MsgChannelOpenAckService, - MsgChannelOpenConfirmService as IbcCoreChannelV1MsgChannelOpenConfirmService, - MsgChannelCloseInitService as IbcCoreChannelV1MsgChannelCloseInitService, - MsgChannelCloseConfirmService as IbcCoreChannelV1MsgChannelCloseConfirmService, - MsgRecvPacketService as IbcCoreChannelV1MsgRecvPacketService, - MsgTimeoutService as IbcCoreChannelV1MsgTimeoutService, - MsgTimeoutOnCloseService as IbcCoreChannelV1MsgTimeoutOnCloseService, - MsgAcknowledgementService as IbcCoreChannelV1MsgAcknowledgementService, -} from "./ibc/core/channel/v1/tx_cosmes.js"; -export { - QueryChannelRequest as IbcCoreChannelV1QueryChannelRequest, - QueryChannelResponse as IbcCoreChannelV1QueryChannelResponse, - QueryChannelsRequest as IbcCoreChannelV1QueryChannelsRequest, - QueryChannelsResponse as IbcCoreChannelV1QueryChannelsResponse, - QueryConnectionChannelsRequest as IbcCoreChannelV1QueryConnectionChannelsRequest, - QueryConnectionChannelsResponse as IbcCoreChannelV1QueryConnectionChannelsResponse, - QueryChannelClientStateRequest as IbcCoreChannelV1QueryChannelClientStateRequest, - QueryChannelClientStateResponse as IbcCoreChannelV1QueryChannelClientStateResponse, - QueryChannelConsensusStateRequest as IbcCoreChannelV1QueryChannelConsensusStateRequest, - QueryChannelConsensusStateResponse as IbcCoreChannelV1QueryChannelConsensusStateResponse, - QueryPacketCommitmentRequest as IbcCoreChannelV1QueryPacketCommitmentRequest, - QueryPacketCommitmentResponse as IbcCoreChannelV1QueryPacketCommitmentResponse, - QueryPacketCommitmentsRequest as IbcCoreChannelV1QueryPacketCommitmentsRequest, - QueryPacketCommitmentsResponse as IbcCoreChannelV1QueryPacketCommitmentsResponse, - QueryPacketReceiptRequest as IbcCoreChannelV1QueryPacketReceiptRequest, - QueryPacketReceiptResponse as IbcCoreChannelV1QueryPacketReceiptResponse, - QueryPacketAcknowledgementRequest as IbcCoreChannelV1QueryPacketAcknowledgementRequest, - QueryPacketAcknowledgementResponse as IbcCoreChannelV1QueryPacketAcknowledgementResponse, - QueryPacketAcknowledgementsRequest as IbcCoreChannelV1QueryPacketAcknowledgementsRequest, - QueryPacketAcknowledgementsResponse as IbcCoreChannelV1QueryPacketAcknowledgementsResponse, - QueryUnreceivedPacketsRequest as IbcCoreChannelV1QueryUnreceivedPacketsRequest, - QueryUnreceivedPacketsResponse as IbcCoreChannelV1QueryUnreceivedPacketsResponse, - QueryUnreceivedAcksRequest as IbcCoreChannelV1QueryUnreceivedAcksRequest, - QueryUnreceivedAcksResponse as IbcCoreChannelV1QueryUnreceivedAcksResponse, - QueryNextSequenceReceiveRequest as IbcCoreChannelV1QueryNextSequenceReceiveRequest, - QueryNextSequenceReceiveResponse as IbcCoreChannelV1QueryNextSequenceReceiveResponse, - QueryNextSequenceSendRequest as IbcCoreChannelV1QueryNextSequenceSendRequest, - QueryNextSequenceSendResponse as IbcCoreChannelV1QueryNextSequenceSendResponse, -} from "./ibc/core/channel/v1/query_pb.js"; -export { - QueryChannelService as IbcCoreChannelV1QueryChannelService, - QueryChannelsService as IbcCoreChannelV1QueryChannelsService, - QueryConnectionChannelsService as IbcCoreChannelV1QueryConnectionChannelsService, - QueryChannelClientStateService as IbcCoreChannelV1QueryChannelClientStateService, - QueryChannelConsensusStateService as IbcCoreChannelV1QueryChannelConsensusStateService, - QueryPacketCommitmentService as IbcCoreChannelV1QueryPacketCommitmentService, - QueryPacketCommitmentsService as IbcCoreChannelV1QueryPacketCommitmentsService, - QueryPacketReceiptService as IbcCoreChannelV1QueryPacketReceiptService, - QueryPacketAcknowledgementService as IbcCoreChannelV1QueryPacketAcknowledgementService, - QueryPacketAcknowledgementsService as IbcCoreChannelV1QueryPacketAcknowledgementsService, - QueryUnreceivedPacketsService as IbcCoreChannelV1QueryUnreceivedPacketsService, - QueryUnreceivedAcksService as IbcCoreChannelV1QueryUnreceivedAcksService, - QueryNextSequenceReceiveService as IbcCoreChannelV1QueryNextSequenceReceiveService, - QueryNextSequenceSendService as IbcCoreChannelV1QueryNextSequenceSendService, -} from "./ibc/core/channel/v1/query_cosmes.js"; -export { - GenesisState as IbcCoreChannelV1GenesisState, - PacketSequence as IbcCoreChannelV1PacketSequence, -} from "./ibc/core/channel/v1/genesis_pb.js"; -export { - State as IbcCoreChannelV1State, - Order as IbcCoreChannelV1Order, - Channel as IbcCoreChannelV1Channel, - IdentifiedChannel as IbcCoreChannelV1IdentifiedChannel, - Counterparty as IbcCoreChannelV1Counterparty, - Packet as IbcCoreChannelV1Packet, - PacketState as IbcCoreChannelV1PacketState, - PacketId as IbcCoreChannelV1PacketId, - Acknowledgement as IbcCoreChannelV1Acknowledgement, - Timeout as IbcCoreChannelV1Timeout, -} from "./ibc/core/channel/v1/channel_pb.js"; -export { - MsgTransfer as IbcApplicationsTransferV1MsgTransfer, - MsgTransferResponse as IbcApplicationsTransferV1MsgTransferResponse, - MsgUpdateParams as IbcApplicationsTransferV1MsgUpdateParams, - MsgUpdateParamsResponse as IbcApplicationsTransferV1MsgUpdateParamsResponse, -} from "./ibc/applications/transfer/v1/tx_pb.js"; -export { - MsgTransferService as IbcApplicationsTransferV1MsgTransferService, - MsgUpdateParamsService as IbcApplicationsTransferV1MsgUpdateParamsService, -} from "./ibc/applications/transfer/v1/tx_cosmes.js"; -export { - Params as IbcApplicationsTransferV1Params, -} from "./ibc/applications/transfer/v1/transfer_pb.js"; -export { - Token as IbcApplicationsTransferV1Token, - Denom as IbcApplicationsTransferV1Denom, - Hop as IbcApplicationsTransferV1Hop, -} from "./ibc/applications/transfer/v1/token_pb.js"; -export { - QueryParamsRequest as IbcApplicationsTransferV1QueryParamsRequest, - QueryParamsResponse as IbcApplicationsTransferV1QueryParamsResponse, - QueryDenomRequest as IbcApplicationsTransferV1QueryDenomRequest, - QueryDenomResponse as IbcApplicationsTransferV1QueryDenomResponse, - QueryDenomsRequest as IbcApplicationsTransferV1QueryDenomsRequest, - QueryDenomsResponse as IbcApplicationsTransferV1QueryDenomsResponse, - QueryDenomHashRequest as IbcApplicationsTransferV1QueryDenomHashRequest, - QueryDenomHashResponse as IbcApplicationsTransferV1QueryDenomHashResponse, - QueryEscrowAddressRequest as IbcApplicationsTransferV1QueryEscrowAddressRequest, - QueryEscrowAddressResponse as IbcApplicationsTransferV1QueryEscrowAddressResponse, - QueryTotalEscrowForDenomRequest as IbcApplicationsTransferV1QueryTotalEscrowForDenomRequest, - QueryTotalEscrowForDenomResponse as IbcApplicationsTransferV1QueryTotalEscrowForDenomResponse, -} from "./ibc/applications/transfer/v1/query_pb.js"; -export { - QueryParamsService as IbcApplicationsTransferV1QueryParamsService, - QueryDenomsService as IbcApplicationsTransferV1QueryDenomsService, - QueryDenomService as IbcApplicationsTransferV1QueryDenomService, - QueryDenomHashService as IbcApplicationsTransferV1QueryDenomHashService, - QueryEscrowAddressService as IbcApplicationsTransferV1QueryEscrowAddressService, - QueryTotalEscrowForDenomService as IbcApplicationsTransferV1QueryTotalEscrowForDenomService, -} from "./ibc/applications/transfer/v1/query_cosmes.js"; -export { - FungibleTokenPacketData as IbcApplicationsTransferV1FungibleTokenPacketData, -} from "./ibc/applications/transfer/v1/packet_pb.js"; -export { - GenesisState as IbcApplicationsTransferV1GenesisState, -} from "./ibc/applications/transfer/v1/genesis_pb.js"; -export { - DenomTrace as IbcApplicationsTransferV1DenomTrace, -} from "./ibc/applications/transfer/v1/denomtrace_pb.js"; -export { - Allocation as IbcApplicationsTransferV1Allocation, - TransferAuthorization as IbcApplicationsTransferV1TransferAuthorization, -} from "./ibc/applications/transfer/v1/authz_pb.js"; -export { - MsgAddRateLimit as IbcApplicationsRateLimitingV1MsgAddRateLimit, - MsgAddRateLimitResponse as IbcApplicationsRateLimitingV1MsgAddRateLimitResponse, - MsgUpdateRateLimit as IbcApplicationsRateLimitingV1MsgUpdateRateLimit, - MsgUpdateRateLimitResponse as IbcApplicationsRateLimitingV1MsgUpdateRateLimitResponse, - MsgRemoveRateLimit as IbcApplicationsRateLimitingV1MsgRemoveRateLimit, - MsgRemoveRateLimitResponse as IbcApplicationsRateLimitingV1MsgRemoveRateLimitResponse, - MsgResetRateLimit as IbcApplicationsRateLimitingV1MsgResetRateLimit, - MsgResetRateLimitResponse as IbcApplicationsRateLimitingV1MsgResetRateLimitResponse, -} from "./ibc/applications/rate_limiting/v1/tx_pb.js"; -export { - MsgAddRateLimitService as IbcApplicationsRateLimitingV1MsgAddRateLimitService, - MsgUpdateRateLimitService as IbcApplicationsRateLimitingV1MsgUpdateRateLimitService, - MsgRemoveRateLimitService as IbcApplicationsRateLimitingV1MsgRemoveRateLimitService, - MsgResetRateLimitService as IbcApplicationsRateLimitingV1MsgResetRateLimitService, -} from "./ibc/applications/rate_limiting/v1/tx_cosmes.js"; -export { - PacketDirection as IbcApplicationsRateLimitingV1PacketDirection, - Path as IbcApplicationsRateLimitingV1Path, - Quota as IbcApplicationsRateLimitingV1Quota, - Flow as IbcApplicationsRateLimitingV1Flow, - RateLimit as IbcApplicationsRateLimitingV1RateLimit, - WhitelistedAddressPair as IbcApplicationsRateLimitingV1WhitelistedAddressPair, - HourEpoch as IbcApplicationsRateLimitingV1HourEpoch, -} from "./ibc/applications/rate_limiting/v1/rate_limiting_pb.js"; -export { - QueryAllRateLimitsRequest as IbcApplicationsRateLimitingV1QueryAllRateLimitsRequest, - QueryAllRateLimitsResponse as IbcApplicationsRateLimitingV1QueryAllRateLimitsResponse, - QueryRateLimitRequest as IbcApplicationsRateLimitingV1QueryRateLimitRequest, - QueryRateLimitResponse as IbcApplicationsRateLimitingV1QueryRateLimitResponse, - QueryRateLimitsByChainIDRequest as IbcApplicationsRateLimitingV1QueryRateLimitsByChainIDRequest, - QueryRateLimitsByChainIDResponse as IbcApplicationsRateLimitingV1QueryRateLimitsByChainIDResponse, - QueryRateLimitsByChannelOrClientIDRequest as IbcApplicationsRateLimitingV1QueryRateLimitsByChannelOrClientIDRequest, - QueryRateLimitsByChannelOrClientIDResponse as IbcApplicationsRateLimitingV1QueryRateLimitsByChannelOrClientIDResponse, - QueryAllBlacklistedDenomsRequest as IbcApplicationsRateLimitingV1QueryAllBlacklistedDenomsRequest, - QueryAllBlacklistedDenomsResponse as IbcApplicationsRateLimitingV1QueryAllBlacklistedDenomsResponse, - QueryAllWhitelistedAddressesRequest as IbcApplicationsRateLimitingV1QueryAllWhitelistedAddressesRequest, - QueryAllWhitelistedAddressesResponse as IbcApplicationsRateLimitingV1QueryAllWhitelistedAddressesResponse, -} from "./ibc/applications/rate_limiting/v1/query_pb.js"; -export { - QueryAllRateLimitsService as IbcApplicationsRateLimitingV1QueryAllRateLimitsService, - QueryRateLimitService as IbcApplicationsRateLimitingV1QueryRateLimitService, - QueryRateLimitsByChainIDService as IbcApplicationsRateLimitingV1QueryRateLimitsByChainIDService, - QueryRateLimitsByChannelOrClientIDService as IbcApplicationsRateLimitingV1QueryRateLimitsByChannelOrClientIDService, - QueryAllBlacklistedDenomsService as IbcApplicationsRateLimitingV1QueryAllBlacklistedDenomsService, - QueryAllWhitelistedAddressesService as IbcApplicationsRateLimitingV1QueryAllWhitelistedAddressesService, -} from "./ibc/applications/rate_limiting/v1/query_cosmes.js"; -export { - GenesisState as IbcApplicationsRateLimitingV1GenesisState, -} from "./ibc/applications/rate_limiting/v1/genesis_pb.js"; -export { - GenesisState as IbcApplicationsPacketForwardMiddlewareV1GenesisState, - InFlightPacket as IbcApplicationsPacketForwardMiddlewareV1InFlightPacket, -} from "./ibc/applications/packet_forward_middleware/v1/genesis_pb.js"; -export { - Type as IbcApplicationsInterchainAccountsV1Type, - InterchainAccountPacketData as IbcApplicationsInterchainAccountsV1InterchainAccountPacketData, - CosmosTx as IbcApplicationsInterchainAccountsV1CosmosTx, -} from "./ibc/applications/interchain_accounts/v1/packet_pb.js"; -export { - Metadata as IbcApplicationsInterchainAccountsV1Metadata, -} from "./ibc/applications/interchain_accounts/v1/metadata_pb.js"; -export { - InterchainAccount as IbcApplicationsInterchainAccountsV1InterchainAccount, -} from "./ibc/applications/interchain_accounts/v1/account_pb.js"; -export { - MsgUpdateParams as IbcApplicationsInterchainAccountsHostV1MsgUpdateParams, - MsgUpdateParamsResponse as IbcApplicationsInterchainAccountsHostV1MsgUpdateParamsResponse, - MsgModuleQuerySafe as IbcApplicationsInterchainAccountsHostV1MsgModuleQuerySafe, - MsgModuleQuerySafeResponse as IbcApplicationsInterchainAccountsHostV1MsgModuleQuerySafeResponse, -} from "./ibc/applications/interchain_accounts/host/v1/tx_pb.js"; -export { - MsgUpdateParamsService as IbcApplicationsInterchainAccountsHostV1MsgUpdateParamsService, - MsgModuleQuerySafeService as IbcApplicationsInterchainAccountsHostV1MsgModuleQuerySafeService, -} from "./ibc/applications/interchain_accounts/host/v1/tx_cosmes.js"; -export { - QueryParamsRequest as IbcApplicationsInterchainAccountsHostV1QueryParamsRequest, - QueryParamsResponse as IbcApplicationsInterchainAccountsHostV1QueryParamsResponse, -} from "./ibc/applications/interchain_accounts/host/v1/query_pb.js"; -export { - QueryParamsService as IbcApplicationsInterchainAccountsHostV1QueryParamsService, -} from "./ibc/applications/interchain_accounts/host/v1/query_cosmes.js"; -export { - Params as IbcApplicationsInterchainAccountsHostV1Params, - QueryRequest as IbcApplicationsInterchainAccountsHostV1QueryRequest, -} from "./ibc/applications/interchain_accounts/host/v1/host_pb.js"; -export { - GenesisState as IbcApplicationsInterchainAccountsGenesisV1GenesisState, - ControllerGenesisState as IbcApplicationsInterchainAccountsGenesisV1ControllerGenesisState, - HostGenesisState as IbcApplicationsInterchainAccountsGenesisV1HostGenesisState, - ActiveChannel as IbcApplicationsInterchainAccountsGenesisV1ActiveChannel, - RegisteredInterchainAccount as IbcApplicationsInterchainAccountsGenesisV1RegisteredInterchainAccount, -} from "./ibc/applications/interchain_accounts/genesis/v1/genesis_pb.js"; -export { - MsgRegisterInterchainAccount as IbcApplicationsInterchainAccountsControllerV1MsgRegisterInterchainAccount, - MsgRegisterInterchainAccountResponse as IbcApplicationsInterchainAccountsControllerV1MsgRegisterInterchainAccountResponse, - MsgSendTx as IbcApplicationsInterchainAccountsControllerV1MsgSendTx, - MsgSendTxResponse as IbcApplicationsInterchainAccountsControllerV1MsgSendTxResponse, - MsgUpdateParams as IbcApplicationsInterchainAccountsControllerV1MsgUpdateParams, - MsgUpdateParamsResponse as IbcApplicationsInterchainAccountsControllerV1MsgUpdateParamsResponse, -} from "./ibc/applications/interchain_accounts/controller/v1/tx_pb.js"; -export { - MsgRegisterInterchainAccountService as IbcApplicationsInterchainAccountsControllerV1MsgRegisterInterchainAccountService, - MsgSendTxService as IbcApplicationsInterchainAccountsControllerV1MsgSendTxService, - MsgUpdateParamsService as IbcApplicationsInterchainAccountsControllerV1MsgUpdateParamsService, -} from "./ibc/applications/interchain_accounts/controller/v1/tx_cosmes.js"; -export { - QueryInterchainAccountRequest as IbcApplicationsInterchainAccountsControllerV1QueryInterchainAccountRequest, - QueryInterchainAccountResponse as IbcApplicationsInterchainAccountsControllerV1QueryInterchainAccountResponse, - QueryParamsRequest as IbcApplicationsInterchainAccountsControllerV1QueryParamsRequest, - QueryParamsResponse as IbcApplicationsInterchainAccountsControllerV1QueryParamsResponse, -} from "./ibc/applications/interchain_accounts/controller/v1/query_pb.js"; -export { - QueryInterchainAccountService as IbcApplicationsInterchainAccountsControllerV1QueryInterchainAccountService, - QueryParamsService as IbcApplicationsInterchainAccountsControllerV1QueryParamsService, -} from "./ibc/applications/interchain_accounts/controller/v1/query_cosmes.js"; -export { - Params as IbcApplicationsInterchainAccountsControllerV1Params, -} from "./ibc/applications/interchain_accounts/controller/v1/controller_pb.js"; -export { - ExtensionOptionsWeb3Tx as EthermintTypesV1ExtensionOptionsWeb3Tx, -} from "./ethermint/types/v1/web3_pb.js"; -export { - TxResult as EthermintTypesV1TxResult, -} from "./ethermint/types/v1/indexer_pb.js"; -export { - ExtensionOptionDynamicFeeTx as EthermintTypesV1ExtensionOptionDynamicFeeTx, -} from "./ethermint/types/v1/dynamic_fee_pb.js"; -export { - EthAccount as EthermintTypesV1EthAccount, -} from "./ethermint/types/v1/account_pb.js"; -export { - MsgUpdateParams as EthermintFeemarketV1MsgUpdateParams, - MsgUpdateParamsResponse as EthermintFeemarketV1MsgUpdateParamsResponse, -} from "./ethermint/feemarket/v1/tx_pb.js"; -export { - MsgUpdateParamsService as EthermintFeemarketV1MsgUpdateParamsService, -} from "./ethermint/feemarket/v1/tx_cosmes.js"; -export { - QueryParamsRequest as EthermintFeemarketV1QueryParamsRequest, - QueryParamsResponse as EthermintFeemarketV1QueryParamsResponse, - QueryBaseFeeRequest as EthermintFeemarketV1QueryBaseFeeRequest, - QueryBaseFeeResponse as EthermintFeemarketV1QueryBaseFeeResponse, - QueryBlockGasRequest as EthermintFeemarketV1QueryBlockGasRequest, - QueryBlockGasResponse as EthermintFeemarketV1QueryBlockGasResponse, -} from "./ethermint/feemarket/v1/query_pb.js"; -export { - QueryParamsService as EthermintFeemarketV1QueryParamsService, - QueryBaseFeeService as EthermintFeemarketV1QueryBaseFeeService, - QueryBlockGasService as EthermintFeemarketV1QueryBlockGasService, -} from "./ethermint/feemarket/v1/query_cosmes.js"; -export { - GenesisState as EthermintFeemarketV1GenesisState, -} from "./ethermint/feemarket/v1/genesis_pb.js"; -export { - Params as EthermintFeemarketV1Params, -} from "./ethermint/feemarket/v1/feemarket_pb.js"; -export { - EventFeeMarket as EthermintFeemarketV1EventFeeMarket, - EventBlockGas as EthermintFeemarketV1EventBlockGas, -} from "./ethermint/feemarket/v1/events_pb.js"; -export { - MsgEthereumTx as EthermintEvmV1MsgEthereumTx, - LegacyTx as EthermintEvmV1LegacyTx, - AccessListTx as EthermintEvmV1AccessListTx, - DynamicFeeTx as EthermintEvmV1DynamicFeeTx, - ExtensionOptionsEthereumTx as EthermintEvmV1ExtensionOptionsEthereumTx, - MsgEthereumTxResponse as EthermintEvmV1MsgEthereumTxResponse, - MsgUpdateParams as EthermintEvmV1MsgUpdateParams, - MsgUpdateParamsResponse as EthermintEvmV1MsgUpdateParamsResponse, -} from "./ethermint/evm/v1/tx_pb.js"; -export { - MsgEthereumTxService as EthermintEvmV1MsgEthereumTxService, - MsgUpdateParamsService as EthermintEvmV1MsgUpdateParamsService, -} from "./ethermint/evm/v1/tx_cosmes.js"; -export { - QueryAccountRequest as EthermintEvmV1QueryAccountRequest, - QueryAccountResponse as EthermintEvmV1QueryAccountResponse, - QueryCosmosAccountRequest as EthermintEvmV1QueryCosmosAccountRequest, - QueryCosmosAccountResponse as EthermintEvmV1QueryCosmosAccountResponse, - QueryValidatorAccountRequest as EthermintEvmV1QueryValidatorAccountRequest, - QueryValidatorAccountResponse as EthermintEvmV1QueryValidatorAccountResponse, - QueryBalanceRequest as EthermintEvmV1QueryBalanceRequest, - QueryBalanceResponse as EthermintEvmV1QueryBalanceResponse, - QueryStorageRequest as EthermintEvmV1QueryStorageRequest, - QueryStorageResponse as EthermintEvmV1QueryStorageResponse, - QueryCodeRequest as EthermintEvmV1QueryCodeRequest, - QueryCodeResponse as EthermintEvmV1QueryCodeResponse, - QueryTxLogsRequest as EthermintEvmV1QueryTxLogsRequest, - QueryTxLogsResponse as EthermintEvmV1QueryTxLogsResponse, - QueryParamsRequest as EthermintEvmV1QueryParamsRequest, - QueryParamsResponse as EthermintEvmV1QueryParamsResponse, - EthCallRequest as EthermintEvmV1EthCallRequest, - EstimateGasResponse as EthermintEvmV1EstimateGasResponse, - QueryTraceTxRequest as EthermintEvmV1QueryTraceTxRequest, - QueryTraceTxResponse as EthermintEvmV1QueryTraceTxResponse, - QueryTraceBlockRequest as EthermintEvmV1QueryTraceBlockRequest, - QueryTraceBlockResponse as EthermintEvmV1QueryTraceBlockResponse, - QueryBaseFeeRequest as EthermintEvmV1QueryBaseFeeRequest, - QueryBaseFeeResponse as EthermintEvmV1QueryBaseFeeResponse, -} from "./ethermint/evm/v1/query_pb.js"; -export { - QueryAccountService as EthermintEvmV1QueryAccountService, - QueryCosmosAccountService as EthermintEvmV1QueryCosmosAccountService, - QueryValidatorAccountService as EthermintEvmV1QueryValidatorAccountService, - QueryBalanceService as EthermintEvmV1QueryBalanceService, - QueryStorageService as EthermintEvmV1QueryStorageService, - QueryCodeService as EthermintEvmV1QueryCodeService, - QueryParamsService as EthermintEvmV1QueryParamsService, - QueryEthCallService as EthermintEvmV1QueryEthCallService, - QueryEstimateGasService as EthermintEvmV1QueryEstimateGasService, - QueryTraceTxService as EthermintEvmV1QueryTraceTxService, - QueryTraceBlockService as EthermintEvmV1QueryTraceBlockService, - QueryBaseFeeService as EthermintEvmV1QueryBaseFeeService, -} from "./ethermint/evm/v1/query_cosmes.js"; -export { - GenesisState as EthermintEvmV1GenesisState, - GenesisAccount as EthermintEvmV1GenesisAccount, -} from "./ethermint/evm/v1/genesis_pb.js"; -export { - Params as EthermintEvmV1Params, - ChainConfig as EthermintEvmV1ChainConfig, - State as EthermintEvmV1State, - TransactionLogs as EthermintEvmV1TransactionLogs, - Log as EthermintEvmV1Log, - TxResult as EthermintEvmV1TxResult, - AccessTuple as EthermintEvmV1AccessTuple, - TraceConfig as EthermintEvmV1TraceConfig, -} from "./ethermint/evm/v1/evm_pb.js"; -export { - EventEthereumTx as EthermintEvmV1EventEthereumTx, - EventTxLog as EthermintEvmV1EventTxLog, - EventMessage as EthermintEvmV1EventMessage, - EventBlockBloom as EthermintEvmV1EventBlockBloom, -} from "./ethermint/evm/v1/events_pb.js"; -export { - PubKey as EthermintCryptoV1Ethsecp256k1PubKey, - PrivKey as EthermintCryptoV1Ethsecp256k1PrivKey, -} from "./ethermint/crypto/v1/ethsecp256k1/keys_pb.js"; -export { - MsgUpdateParams as DwnV1MsgUpdateParams, - MsgUpdateParamsResponse as DwnV1MsgUpdateParamsResponse, - MsgRecordsWrite as DwnV1MsgRecordsWrite, - MsgRecordsWriteResponse as DwnV1MsgRecordsWriteResponse, - MsgRecordsDelete as DwnV1MsgRecordsDelete, - MsgRecordsDeleteResponse as DwnV1MsgRecordsDeleteResponse, - MsgProtocolsConfigure as DwnV1MsgProtocolsConfigure, - MsgProtocolsConfigureResponse as DwnV1MsgProtocolsConfigureResponse, - MsgPermissionsGrant as DwnV1MsgPermissionsGrant, - MsgPermissionsGrantResponse as DwnV1MsgPermissionsGrantResponse, - MsgPermissionsRevoke as DwnV1MsgPermissionsRevoke, - MsgPermissionsRevokeResponse as DwnV1MsgPermissionsRevokeResponse, - MsgRotateVaultKeys as DwnV1MsgRotateVaultKeys, - MsgRotateVaultKeysResponse as DwnV1MsgRotateVaultKeysResponse, -} from "./dwn/v1/tx_pb.js"; -export { - MsgUpdateParamsService as DwnV1MsgUpdateParamsService, - MsgRecordsWriteService as DwnV1MsgRecordsWriteService, - MsgRecordsDeleteService as DwnV1MsgRecordsDeleteService, - MsgProtocolsConfigureService as DwnV1MsgProtocolsConfigureService, - MsgPermissionsGrantService as DwnV1MsgPermissionsGrantService, - MsgPermissionsRevokeService as DwnV1MsgPermissionsRevokeService, - MsgRotateVaultKeysService as DwnV1MsgRotateVaultKeysService, -} from "./dwn/v1/tx_cosmes.js"; -export { - EncryptionMetadata as DwnV1EncryptionMetadata, - EncryptionKeyState as DwnV1EncryptionKeyState, - VRFConsensusRound as DwnV1VRFConsensusRound, - EncryptionStats as DwnV1EncryptionStats, - SaltStore as DwnV1SaltStore, - VRFContribution as DwnV1VRFContribution, - EncryptedDWNRecord as DwnV1EncryptedDWNRecord, - EnclaveData as DwnV1EnclaveData, - DWNMessageDescriptor as DwnV1DWNMessageDescriptor, - DWNRecord as DwnV1DWNRecord, - DWNProtocol as DwnV1DWNProtocol, - DWNPermission as DwnV1DWNPermission, - VaultState as DwnV1VaultState, -} from "./dwn/v1/state_pb.js"; -export { - QueryParamsRequest as DwnV1QueryParamsRequest, - QueryParamsResponse as DwnV1QueryParamsResponse, - QueryIPFSRequest as DwnV1QueryIPFSRequest, - QueryIPFSResponse as DwnV1QueryIPFSResponse, - QueryCIDRequest as DwnV1QueryCIDRequest, - QueryCIDResponse as DwnV1QueryCIDResponse, - QueryRecordsRequest as DwnV1QueryRecordsRequest, - QueryRecordsResponse as DwnV1QueryRecordsResponse, - QueryRecordRequest as DwnV1QueryRecordRequest, - QueryRecordResponse as DwnV1QueryRecordResponse, - QueryProtocolsRequest as DwnV1QueryProtocolsRequest, - QueryProtocolsResponse as DwnV1QueryProtocolsResponse, - QueryProtocolRequest as DwnV1QueryProtocolRequest, - QueryProtocolResponse as DwnV1QueryProtocolResponse, - QueryPermissionsRequest as DwnV1QueryPermissionsRequest, - QueryPermissionsResponse as DwnV1QueryPermissionsResponse, - QueryVaultRequest as DwnV1QueryVaultRequest, - QueryVaultResponse as DwnV1QueryVaultResponse, - QueryVaultsRequest as DwnV1QueryVaultsRequest, - QueryVaultsResponse as DwnV1QueryVaultsResponse, - QueryEncryptedRecordRequest as DwnV1QueryEncryptedRecordRequest, - QueryEncryptedRecordResponse as DwnV1QueryEncryptedRecordResponse, - QueryEncryptionStatusRequest as DwnV1QueryEncryptionStatusRequest, - QueryEncryptionStatusResponse as DwnV1QueryEncryptionStatusResponse, - QueryVRFContributionsRequest as DwnV1QueryVRFContributionsRequest, - QueryVRFContributionsResponse as DwnV1QueryVRFContributionsResponse, -} from "./dwn/v1/query_pb.js"; -export { - QueryParamsService as DwnV1QueryParamsService, - QueryIPFSService as DwnV1QueryIPFSService, - QueryCIDService as DwnV1QueryCIDService, - QueryRecordsService as DwnV1QueryRecordsService, - QueryRecordService as DwnV1QueryRecordService, - QueryProtocolsService as DwnV1QueryProtocolsService, - QueryProtocolService as DwnV1QueryProtocolService, - QueryPermissionsService as DwnV1QueryPermissionsService, - QueryVaultService as DwnV1QueryVaultService, - QueryVaultsService as DwnV1QueryVaultsService, - QueryEncryptedRecordService as DwnV1QueryEncryptedRecordService, - QueryEncryptionStatusService as DwnV1QueryEncryptionStatusService, - QueryVRFContributionsService as DwnV1QueryVRFContributionsService, -} from "./dwn/v1/query_cosmes.js"; -export { - GenesisState as DwnV1GenesisState, - Params as DwnV1Params, - IPFSStatus as DwnV1IPFSStatus, -} from "./dwn/v1/genesis_pb.js"; -export { - EventRecordWritten as DwnV1EventRecordWritten, - EventRecordDeleted as DwnV1EventRecordDeleted, - EventProtocolConfigured as DwnV1EventProtocolConfigured, - EventPermissionGranted as DwnV1EventPermissionGranted, - EventPermissionRevoked as DwnV1EventPermissionRevoked, - EventVaultCreated as DwnV1EventVaultCreated, - EventVaultKeysRotated as DwnV1EventVaultKeysRotated, - EventKeyRotation as DwnV1EventKeyRotation, -} from "./dwn/v1/events_pb.js"; -export { - Module as DwnModuleV1Module, -} from "./dwn/module/v1/module_pb.js"; -export { - VerificationMethod as DidV1VerificationMethod, - VerificationMethodReference as DidV1VerificationMethodReference, - Service as DidV1Service, - ServiceEndpoints as DidV1ServiceEndpoints, - WebAuthnCredential as DidV1WebAuthnCredential, - CredentialProof as DidV1CredentialProof, - CredentialStatus as DidV1CredentialStatus, -} from "./did/v1/types_pb.js"; -export { - MsgUpdateParams as DidV1MsgUpdateParams, - MsgUpdateParamsResponse as DidV1MsgUpdateParamsResponse, - MsgCreateDID as DidV1MsgCreateDID, - MsgCreateDIDResponse as DidV1MsgCreateDIDResponse, - MsgUpdateDID as DidV1MsgUpdateDID, - MsgUpdateDIDResponse as DidV1MsgUpdateDIDResponse, - MsgDeactivateDID as DidV1MsgDeactivateDID, - MsgDeactivateDIDResponse as DidV1MsgDeactivateDIDResponse, - MsgAddVerificationMethod as DidV1MsgAddVerificationMethod, - MsgAddVerificationMethodResponse as DidV1MsgAddVerificationMethodResponse, - MsgRemoveVerificationMethod as DidV1MsgRemoveVerificationMethod, - MsgRemoveVerificationMethodResponse as DidV1MsgRemoveVerificationMethodResponse, - MsgAddService as DidV1MsgAddService, - MsgAddServiceResponse as DidV1MsgAddServiceResponse, - MsgRemoveService as DidV1MsgRemoveService, - MsgRemoveServiceResponse as DidV1MsgRemoveServiceResponse, - MsgIssueVerifiableCredential as DidV1MsgIssueVerifiableCredential, - MsgIssueVerifiableCredentialResponse as DidV1MsgIssueVerifiableCredentialResponse, - MsgRevokeVerifiableCredential as DidV1MsgRevokeVerifiableCredential, - MsgRevokeVerifiableCredentialResponse as DidV1MsgRevokeVerifiableCredentialResponse, - MsgLinkExternalWallet as DidV1MsgLinkExternalWallet, - MsgLinkExternalWalletResponse as DidV1MsgLinkExternalWalletResponse, - MsgRegisterWebAuthnCredential as DidV1MsgRegisterWebAuthnCredential, - MsgRegisterWebAuthnCredentialResponse as DidV1MsgRegisterWebAuthnCredentialResponse, -} from "./did/v1/tx_pb.js"; -export { - MsgUpdateParamsService as DidV1MsgUpdateParamsService, - MsgCreateDIDService as DidV1MsgCreateDIDService, - MsgUpdateDIDService as DidV1MsgUpdateDIDService, - MsgDeactivateDIDService as DidV1MsgDeactivateDIDService, - MsgAddVerificationMethodService as DidV1MsgAddVerificationMethodService, - MsgRemoveVerificationMethodService as DidV1MsgRemoveVerificationMethodService, - MsgAddServiceService as DidV1MsgAddServiceService, - MsgRemoveServiceService as DidV1MsgRemoveServiceService, - MsgIssueVerifiableCredentialService as DidV1MsgIssueVerifiableCredentialService, - MsgRevokeVerifiableCredentialService as DidV1MsgRevokeVerifiableCredentialService, - MsgLinkExternalWalletService as DidV1MsgLinkExternalWalletService, - MsgRegisterWebAuthnCredentialService as DidV1MsgRegisterWebAuthnCredentialService, -} from "./did/v1/tx_cosmes.js"; -export { - Authentication as DidV1Authentication, - Assertion as DidV1Assertion, - Controller as DidV1Controller, - Delegation as DidV1Delegation, - Invocation as DidV1Invocation, - DIDDocument as DidV1DIDDocument, - DIDDocumentMetadata as DidV1DIDDocumentMetadata, - VerifiableCredential as DidV1VerifiableCredential, - DIDController as DidV1DIDController, -} from "./did/v1/state_pb.js"; -export { - QueryParamsRequest as DidV1QueryParamsRequest, - QueryParamsResponse as DidV1QueryParamsResponse, - QueryResolveDIDRequest as DidV1QueryResolveDIDRequest, - QueryResolveDIDResponse as DidV1QueryResolveDIDResponse, - QueryGetDIDDocumentRequest as DidV1QueryGetDIDDocumentRequest, - QueryGetDIDDocumentResponse as DidV1QueryGetDIDDocumentResponse, - QueryListDIDDocumentsRequest as DidV1QueryListDIDDocumentsRequest, - QueryListDIDDocumentsResponse as DidV1QueryListDIDDocumentsResponse, - QueryGetDIDDocumentsByControllerRequest as DidV1QueryGetDIDDocumentsByControllerRequest, - QueryGetDIDDocumentsByControllerResponse as DidV1QueryGetDIDDocumentsByControllerResponse, - QueryGetVerificationMethodRequest as DidV1QueryGetVerificationMethodRequest, - QueryGetVerificationMethodResponse as DidV1QueryGetVerificationMethodResponse, - QueryGetServiceRequest as DidV1QueryGetServiceRequest, - QueryGetServiceResponse as DidV1QueryGetServiceResponse, - QueryGetVerifiableCredentialRequest as DidV1QueryGetVerifiableCredentialRequest, - QueryGetVerifiableCredentialResponse as DidV1QueryGetVerifiableCredentialResponse, - QueryListVerifiableCredentialsRequest as DidV1QueryListVerifiableCredentialsRequest, - QueryListVerifiableCredentialsResponse as DidV1QueryListVerifiableCredentialsResponse, - CredentialInfo as DidV1CredentialInfo, - QueryGetCredentialsByDIDRequest as DidV1QueryGetCredentialsByDIDRequest, - QueryGetCredentialsByDIDResponse as DidV1QueryGetCredentialsByDIDResponse, - QueryRegisterStartRequest as DidV1QueryRegisterStartRequest, - QueryRegisterStartResponse as DidV1QueryRegisterStartResponse, - QueryLoginStartRequest as DidV1QueryLoginStartRequest, - QueryLoginStartResponse as DidV1QueryLoginStartResponse, -} from "./did/v1/query_pb.js"; -export { - QueryParamsService as DidV1QueryParamsService, - QueryResolveDIDService as DidV1QueryResolveDIDService, - QueryGetDIDDocumentService as DidV1QueryGetDIDDocumentService, - QueryListDIDDocumentsService as DidV1QueryListDIDDocumentsService, - QueryGetDIDDocumentsByControllerService as DidV1QueryGetDIDDocumentsByControllerService, - QueryGetVerificationMethodService as DidV1QueryGetVerificationMethodService, - QueryGetServiceService as DidV1QueryGetServiceService, - QueryGetVerifiableCredentialService as DidV1QueryGetVerifiableCredentialService, - QueryListVerifiableCredentialsService as DidV1QueryListVerifiableCredentialsService, - QueryGetCredentialsByDIDService as DidV1QueryGetCredentialsByDIDService, - QueryRegisterStartService as DidV1QueryRegisterStartService, - QueryLoginStartService as DidV1QueryLoginStartService, -} from "./did/v1/query_cosmes.js"; -export { - GenesisState as DidV1GenesisState, - Params as DidV1Params, - DocumentParams as DidV1DocumentParams, - WebauthnParams as DidV1WebauthnParams, -} from "./did/v1/genesis_pb.js"; -export { - EventDIDCreated as DidV1EventDIDCreated, - EventDIDUpdated as DidV1EventDIDUpdated, - EventDIDDeactivated as DidV1EventDIDDeactivated, - EventVerificationMethodAdded as DidV1EventVerificationMethodAdded, - EventVerificationMethodRemoved as DidV1EventVerificationMethodRemoved, - EventServiceAdded as DidV1EventServiceAdded, - EventServiceRemoved as DidV1EventServiceRemoved, - EventCredentialIssued as DidV1EventCredentialIssued, - EventCredentialRevoked as DidV1EventCredentialRevoked, - EventWebAuthnRegistered as DidV1EventWebAuthnRegistered, - EventExternalWalletLinked as DidV1EventExternalWalletLinked, -} from "./did/v1/events_pb.js"; -export { - Module as DidModuleV1Module, -} from "./did/module/v1/module_pb.js"; -export { - MsgRegisterDEXAccount as DexV1MsgRegisterDEXAccount, - MsgRegisterDEXAccountResponse as DexV1MsgRegisterDEXAccountResponse, - MsgExecuteSwap as DexV1MsgExecuteSwap, - MsgExecuteSwapResponse as DexV1MsgExecuteSwapResponse, - MsgProvideLiquidity as DexV1MsgProvideLiquidity, - MsgProvideLiquidityResponse as DexV1MsgProvideLiquidityResponse, - MsgRemoveLiquidity as DexV1MsgRemoveLiquidity, - MsgRemoveLiquidityResponse as DexV1MsgRemoveLiquidityResponse, - MsgCreateLimitOrder as DexV1MsgCreateLimitOrder, - MsgCreateLimitOrderResponse as DexV1MsgCreateLimitOrderResponse, - MsgCancelOrder as DexV1MsgCancelOrder, - MsgCancelOrderResponse as DexV1MsgCancelOrderResponse, -} from "./dex/v1/tx_pb.js"; -export { - MsgRegisterDEXAccountService as DexV1MsgRegisterDEXAccountService, - MsgExecuteSwapService as DexV1MsgExecuteSwapService, - MsgProvideLiquidityService as DexV1MsgProvideLiquidityService, - MsgRemoveLiquidityService as DexV1MsgRemoveLiquidityService, - MsgCreateLimitOrderService as DexV1MsgCreateLimitOrderService, - MsgCancelOrderService as DexV1MsgCancelOrderService, -} from "./dex/v1/tx_cosmes.js"; -export { - QueryParamsRequest as DexV1QueryParamsRequest, - QueryParamsResponse as DexV1QueryParamsResponse, - QueryAccountRequest as DexV1QueryAccountRequest, - QueryAccountResponse as DexV1QueryAccountResponse, - QueryAccountsRequest as DexV1QueryAccountsRequest, - QueryAccountsResponse as DexV1QueryAccountsResponse, - QueryBalanceRequest as DexV1QueryBalanceRequest, - QueryBalanceResponse as DexV1QueryBalanceResponse, - QueryPoolRequest as DexV1QueryPoolRequest, - QueryPoolResponse as DexV1QueryPoolResponse, - PoolInfo as DexV1PoolInfo, - QueryOrdersRequest as DexV1QueryOrdersRequest, - QueryOrdersResponse as DexV1QueryOrdersResponse, - Order as DexV1Order, - QueryHistoryRequest as DexV1QueryHistoryRequest, - QueryHistoryResponse as DexV1QueryHistoryResponse, - Transaction as DexV1Transaction, -} from "./dex/v1/query_pb.js"; -export { - QueryParamsService as DexV1QueryParamsService, - QueryAccountService as DexV1QueryAccountService, - QueryAccountsService as DexV1QueryAccountsService, - QueryBalanceService as DexV1QueryBalanceService, - QueryPoolService as DexV1QueryPoolService, - QueryOrdersService as DexV1QueryOrdersService, - QueryHistoryService as DexV1QueryHistoryService, -} from "./dex/v1/query_cosmes.js"; -export { - AccountStatus as DexV1AccountStatus, - DEXFeatures as DexV1DEXFeatures, - InterchainDEXAccount as DexV1InterchainDEXAccount, - DEXActivity as DexV1DEXActivity, -} from "./dex/v1/ica_pb.js"; -export { - GenesisState as DexV1GenesisState, - Params as DexV1Params, - RateLimitParams as DexV1RateLimitParams, - FeeParams as DexV1FeeParams, -} from "./dex/v1/genesis_pb.js"; -export { - EventDEXAccountRegistered as DexV1EventDEXAccountRegistered, - EventSwapExecuted as DexV1EventSwapExecuted, - EventLiquidityProvided as DexV1EventLiquidityProvided, - EventLiquidityRemoved as DexV1EventLiquidityRemoved, - EventOrderCreated as DexV1EventOrderCreated, - EventOrderCancelled as DexV1EventOrderCancelled, - EventOrderFilled as DexV1EventOrderFilled, - EventICAPacketSent as DexV1EventICAPacketSent, - EventICAPacketAcknowledged as DexV1EventICAPacketAcknowledged, -} from "./dex/v1/events_pb.js"; -export { - Module as DexModuleV1Module, -} from "./dex/module/v1/module_pb.js"; -export { - AccessType as CosmwasmWasmV1AccessType, - ContractCodeHistoryOperationType as CosmwasmWasmV1ContractCodeHistoryOperationType, - AccessTypeParam as CosmwasmWasmV1AccessTypeParam, - AccessConfig as CosmwasmWasmV1AccessConfig, - Params as CosmwasmWasmV1Params, - CodeInfo as CosmwasmWasmV1CodeInfo, - ContractInfo as CosmwasmWasmV1ContractInfo, - ContractCodeHistoryEntry as CosmwasmWasmV1ContractCodeHistoryEntry, - AbsoluteTxPosition as CosmwasmWasmV1AbsoluteTxPosition, - Model as CosmwasmWasmV1Model, -} from "./cosmwasm/wasm/v1/types_pb.js"; -export { - MsgStoreCode as CosmwasmWasmV1MsgStoreCode, - MsgStoreCodeResponse as CosmwasmWasmV1MsgStoreCodeResponse, - MsgInstantiateContract as CosmwasmWasmV1MsgInstantiateContract, - MsgInstantiateContractResponse as CosmwasmWasmV1MsgInstantiateContractResponse, - MsgInstantiateContract2 as CosmwasmWasmV1MsgInstantiateContract2, - MsgInstantiateContract2Response as CosmwasmWasmV1MsgInstantiateContract2Response, - MsgExecuteContract as CosmwasmWasmV1MsgExecuteContract, - MsgExecuteContractResponse as CosmwasmWasmV1MsgExecuteContractResponse, - MsgMigrateContract as CosmwasmWasmV1MsgMigrateContract, - MsgMigrateContractResponse as CosmwasmWasmV1MsgMigrateContractResponse, - MsgUpdateAdmin as CosmwasmWasmV1MsgUpdateAdmin, - MsgUpdateAdminResponse as CosmwasmWasmV1MsgUpdateAdminResponse, - MsgClearAdmin as CosmwasmWasmV1MsgClearAdmin, - MsgClearAdminResponse as CosmwasmWasmV1MsgClearAdminResponse, - MsgUpdateInstantiateConfig as CosmwasmWasmV1MsgUpdateInstantiateConfig, - MsgUpdateInstantiateConfigResponse as CosmwasmWasmV1MsgUpdateInstantiateConfigResponse, - MsgUpdateParams as CosmwasmWasmV1MsgUpdateParams, - MsgUpdateParamsResponse as CosmwasmWasmV1MsgUpdateParamsResponse, - MsgSudoContract as CosmwasmWasmV1MsgSudoContract, - MsgSudoContractResponse as CosmwasmWasmV1MsgSudoContractResponse, - MsgPinCodes as CosmwasmWasmV1MsgPinCodes, - MsgPinCodesResponse as CosmwasmWasmV1MsgPinCodesResponse, - MsgUnpinCodes as CosmwasmWasmV1MsgUnpinCodes, - MsgUnpinCodesResponse as CosmwasmWasmV1MsgUnpinCodesResponse, - MsgStoreAndInstantiateContract as CosmwasmWasmV1MsgStoreAndInstantiateContract, - MsgStoreAndInstantiateContractResponse as CosmwasmWasmV1MsgStoreAndInstantiateContractResponse, - MsgAddCodeUploadParamsAddresses as CosmwasmWasmV1MsgAddCodeUploadParamsAddresses, - MsgAddCodeUploadParamsAddressesResponse as CosmwasmWasmV1MsgAddCodeUploadParamsAddressesResponse, - MsgRemoveCodeUploadParamsAddresses as CosmwasmWasmV1MsgRemoveCodeUploadParamsAddresses, - MsgRemoveCodeUploadParamsAddressesResponse as CosmwasmWasmV1MsgRemoveCodeUploadParamsAddressesResponse, - MsgStoreAndMigrateContract as CosmwasmWasmV1MsgStoreAndMigrateContract, - MsgStoreAndMigrateContractResponse as CosmwasmWasmV1MsgStoreAndMigrateContractResponse, - MsgUpdateContractLabel as CosmwasmWasmV1MsgUpdateContractLabel, - MsgUpdateContractLabelResponse as CosmwasmWasmV1MsgUpdateContractLabelResponse, -} from "./cosmwasm/wasm/v1/tx_pb.js"; -export { - MsgStoreCodeService as CosmwasmWasmV1MsgStoreCodeService, - MsgInstantiateContractService as CosmwasmWasmV1MsgInstantiateContractService, - MsgInstantiateContract2Service as CosmwasmWasmV1MsgInstantiateContract2Service, - MsgExecuteContractService as CosmwasmWasmV1MsgExecuteContractService, - MsgMigrateContractService as CosmwasmWasmV1MsgMigrateContractService, - MsgUpdateAdminService as CosmwasmWasmV1MsgUpdateAdminService, - MsgClearAdminService as CosmwasmWasmV1MsgClearAdminService, - MsgUpdateInstantiateConfigService as CosmwasmWasmV1MsgUpdateInstantiateConfigService, - MsgUpdateParamsService as CosmwasmWasmV1MsgUpdateParamsService, - MsgSudoContractService as CosmwasmWasmV1MsgSudoContractService, - MsgPinCodesService as CosmwasmWasmV1MsgPinCodesService, - MsgUnpinCodesService as CosmwasmWasmV1MsgUnpinCodesService, - MsgStoreAndInstantiateContractService as CosmwasmWasmV1MsgStoreAndInstantiateContractService, - MsgRemoveCodeUploadParamsAddressesService as CosmwasmWasmV1MsgRemoveCodeUploadParamsAddressesService, - MsgAddCodeUploadParamsAddressesService as CosmwasmWasmV1MsgAddCodeUploadParamsAddressesService, - MsgStoreAndMigrateContractService as CosmwasmWasmV1MsgStoreAndMigrateContractService, - MsgUpdateContractLabelService as CosmwasmWasmV1MsgUpdateContractLabelService, -} from "./cosmwasm/wasm/v1/tx_cosmes.js"; -export { - QueryContractInfoRequest as CosmwasmWasmV1QueryContractInfoRequest, - QueryContractInfoResponse as CosmwasmWasmV1QueryContractInfoResponse, - QueryContractHistoryRequest as CosmwasmWasmV1QueryContractHistoryRequest, - QueryContractHistoryResponse as CosmwasmWasmV1QueryContractHistoryResponse, - QueryContractsByCodeRequest as CosmwasmWasmV1QueryContractsByCodeRequest, - QueryContractsByCodeResponse as CosmwasmWasmV1QueryContractsByCodeResponse, - QueryAllContractStateRequest as CosmwasmWasmV1QueryAllContractStateRequest, - QueryAllContractStateResponse as CosmwasmWasmV1QueryAllContractStateResponse, - QueryRawContractStateRequest as CosmwasmWasmV1QueryRawContractStateRequest, - QueryRawContractStateResponse as CosmwasmWasmV1QueryRawContractStateResponse, - QuerySmartContractStateRequest as CosmwasmWasmV1QuerySmartContractStateRequest, - QuerySmartContractStateResponse as CosmwasmWasmV1QuerySmartContractStateResponse, - QueryCodeRequest as CosmwasmWasmV1QueryCodeRequest, - QueryCodeInfoRequest as CosmwasmWasmV1QueryCodeInfoRequest, - QueryCodeInfoResponse as CosmwasmWasmV1QueryCodeInfoResponse, - CodeInfoResponse as CosmwasmWasmV1CodeInfoResponse, - QueryCodeResponse as CosmwasmWasmV1QueryCodeResponse, - QueryCodesRequest as CosmwasmWasmV1QueryCodesRequest, - QueryCodesResponse as CosmwasmWasmV1QueryCodesResponse, - QueryPinnedCodesRequest as CosmwasmWasmV1QueryPinnedCodesRequest, - QueryPinnedCodesResponse as CosmwasmWasmV1QueryPinnedCodesResponse, - QueryParamsRequest as CosmwasmWasmV1QueryParamsRequest, - QueryParamsResponse as CosmwasmWasmV1QueryParamsResponse, - QueryContractsByCreatorRequest as CosmwasmWasmV1QueryContractsByCreatorRequest, - QueryContractsByCreatorResponse as CosmwasmWasmV1QueryContractsByCreatorResponse, - QueryWasmLimitsConfigRequest as CosmwasmWasmV1QueryWasmLimitsConfigRequest, - QueryWasmLimitsConfigResponse as CosmwasmWasmV1QueryWasmLimitsConfigResponse, - QueryBuildAddressRequest as CosmwasmWasmV1QueryBuildAddressRequest, - QueryBuildAddressResponse as CosmwasmWasmV1QueryBuildAddressResponse, -} from "./cosmwasm/wasm/v1/query_pb.js"; -export { - QueryContractInfoService as CosmwasmWasmV1QueryContractInfoService, - QueryContractHistoryService as CosmwasmWasmV1QueryContractHistoryService, - QueryContractsByCodeService as CosmwasmWasmV1QueryContractsByCodeService, - QueryAllContractStateService as CosmwasmWasmV1QueryAllContractStateService, - QueryRawContractStateService as CosmwasmWasmV1QueryRawContractStateService, - QuerySmartContractStateService as CosmwasmWasmV1QuerySmartContractStateService, - QueryCodeService as CosmwasmWasmV1QueryCodeService, - QueryCodesService as CosmwasmWasmV1QueryCodesService, - QueryCodeInfoService as CosmwasmWasmV1QueryCodeInfoService, - QueryPinnedCodesService as CosmwasmWasmV1QueryPinnedCodesService, - QueryParamsService as CosmwasmWasmV1QueryParamsService, - QueryContractsByCreatorService as CosmwasmWasmV1QueryContractsByCreatorService, - QueryWasmLimitsConfigService as CosmwasmWasmV1QueryWasmLimitsConfigService, - QueryBuildAddressService as CosmwasmWasmV1QueryBuildAddressService, -} from "./cosmwasm/wasm/v1/query_cosmes.js"; -export { - StoreCodeProposal as CosmwasmWasmV1StoreCodeProposal, - InstantiateContractProposal as CosmwasmWasmV1InstantiateContractProposal, - InstantiateContract2Proposal as CosmwasmWasmV1InstantiateContract2Proposal, - MigrateContractProposal as CosmwasmWasmV1MigrateContractProposal, - SudoContractProposal as CosmwasmWasmV1SudoContractProposal, - ExecuteContractProposal as CosmwasmWasmV1ExecuteContractProposal, - UpdateAdminProposal as CosmwasmWasmV1UpdateAdminProposal, - ClearAdminProposal as CosmwasmWasmV1ClearAdminProposal, - PinCodesProposal as CosmwasmWasmV1PinCodesProposal, - UnpinCodesProposal as CosmwasmWasmV1UnpinCodesProposal, - AccessConfigUpdate as CosmwasmWasmV1AccessConfigUpdate, - UpdateInstantiateConfigProposal as CosmwasmWasmV1UpdateInstantiateConfigProposal, - StoreAndInstantiateContractProposal as CosmwasmWasmV1StoreAndInstantiateContractProposal, -} from "./cosmwasm/wasm/v1/proposal_legacy_pb.js"; -export { - MsgIBCSend as CosmwasmWasmV1MsgIBCSend, - MsgIBCSendResponse as CosmwasmWasmV1MsgIBCSendResponse, - MsgIBCWriteAcknowledgementResponse as CosmwasmWasmV1MsgIBCWriteAcknowledgementResponse, - MsgIBCCloseChannel as CosmwasmWasmV1MsgIBCCloseChannel, -} from "./cosmwasm/wasm/v1/ibc_pb.js"; -export { - GenesisState as CosmwasmWasmV1GenesisState, - Code as CosmwasmWasmV1Code, - Contract as CosmwasmWasmV1Contract, - Sequence as CosmwasmWasmV1Sequence, -} from "./cosmwasm/wasm/v1/genesis_pb.js"; -export { - StoreCodeAuthorization as CosmwasmWasmV1StoreCodeAuthorization, - ContractExecutionAuthorization as CosmwasmWasmV1ContractExecutionAuthorization, - ContractMigrationAuthorization as CosmwasmWasmV1ContractMigrationAuthorization, - CodeGrant as CosmwasmWasmV1CodeGrant, - ContractGrant as CosmwasmWasmV1ContractGrant, - MaxCallsLimit as CosmwasmWasmV1MaxCallsLimit, - MaxFundsLimit as CosmwasmWasmV1MaxFundsLimit, - CombinedLimit as CosmwasmWasmV1CombinedLimit, - AllowAllMessagesFilter as CosmwasmWasmV1AllowAllMessagesFilter, - AcceptedMessageKeysFilter as CosmwasmWasmV1AcceptedMessageKeysFilter, - AcceptedMessagesFilter as CosmwasmWasmV1AcceptedMessagesFilter, -} from "./cosmwasm/wasm/v1/authz_pb.js"; -export { - Tx as CosmosTxV1beta1Tx, - TxRaw as CosmosTxV1beta1TxRaw, - SignDoc as CosmosTxV1beta1SignDoc, - SignDocDirectAux as CosmosTxV1beta1SignDocDirectAux, - TxBody as CosmosTxV1beta1TxBody, - AuthInfo as CosmosTxV1beta1AuthInfo, - SignerInfo as CosmosTxV1beta1SignerInfo, - ModeInfo as CosmosTxV1beta1ModeInfo, - ModeInfo_Single as CosmosTxV1beta1ModeInfo_Single, - ModeInfo_Multi as CosmosTxV1beta1ModeInfo_Multi, - Fee as CosmosTxV1beta1Fee, - Tip as CosmosTxV1beta1Tip, - AuxSignerData as CosmosTxV1beta1AuxSignerData, -} from "./cosmos/tx/v1beta1/tx_pb.js"; -export { - OrderBy as CosmosTxV1beta1OrderBy, - BroadcastMode as CosmosTxV1beta1BroadcastMode, - GetTxsEventRequest as CosmosTxV1beta1GetTxsEventRequest, - GetTxsEventResponse as CosmosTxV1beta1GetTxsEventResponse, - BroadcastTxRequest as CosmosTxV1beta1BroadcastTxRequest, - BroadcastTxResponse as CosmosTxV1beta1BroadcastTxResponse, - SimulateRequest as CosmosTxV1beta1SimulateRequest, - SimulateResponse as CosmosTxV1beta1SimulateResponse, - GetTxRequest as CosmosTxV1beta1GetTxRequest, - GetTxResponse as CosmosTxV1beta1GetTxResponse, - GetBlockWithTxsRequest as CosmosTxV1beta1GetBlockWithTxsRequest, - GetBlockWithTxsResponse as CosmosTxV1beta1GetBlockWithTxsResponse, - TxDecodeRequest as CosmosTxV1beta1TxDecodeRequest, - TxDecodeResponse as CosmosTxV1beta1TxDecodeResponse, - TxEncodeRequest as CosmosTxV1beta1TxEncodeRequest, - TxEncodeResponse as CosmosTxV1beta1TxEncodeResponse, - TxEncodeAminoRequest as CosmosTxV1beta1TxEncodeAminoRequest, - TxEncodeAminoResponse as CosmosTxV1beta1TxEncodeAminoResponse, - TxDecodeAminoRequest as CosmosTxV1beta1TxDecodeAminoRequest, - TxDecodeAminoResponse as CosmosTxV1beta1TxDecodeAminoResponse, -} from "./cosmos/tx/v1beta1/service_pb.js"; -export { - ServiceSimulateService as CosmosTxV1beta1ServiceSimulateService, - ServiceGetTxService as CosmosTxV1beta1ServiceGetTxService, - ServiceBroadcastTxService as CosmosTxV1beta1ServiceBroadcastTxService, - ServiceGetTxsEventService as CosmosTxV1beta1ServiceGetTxsEventService, - ServiceGetBlockWithTxsService as CosmosTxV1beta1ServiceGetBlockWithTxsService, - ServiceTxDecodeService as CosmosTxV1beta1ServiceTxDecodeService, - ServiceTxEncodeService as CosmosTxV1beta1ServiceTxEncodeService, - ServiceTxEncodeAminoService as CosmosTxV1beta1ServiceTxEncodeAminoService, - ServiceTxDecodeAminoService as CosmosTxV1beta1ServiceTxDecodeAminoService, -} from "./cosmos/tx/v1beta1/service_cosmes.js"; -export { - SignMode as CosmosTxSigningV1beta1SignMode, - SignatureDescriptors as CosmosTxSigningV1beta1SignatureDescriptors, - SignatureDescriptor as CosmosTxSigningV1beta1SignatureDescriptor, - SignatureDescriptor_Data as CosmosTxSigningV1beta1SignatureDescriptor_Data, - SignatureDescriptor_Data_Single as CosmosTxSigningV1beta1SignatureDescriptor_Data_Single, - SignatureDescriptor_Data_Multi as CosmosTxSigningV1beta1SignatureDescriptor_Data_Multi, -} from "./cosmos/tx/signing/v1beta1/signing_pb.js"; -export { - Config as CosmosTxConfigV1Config, -} from "./cosmos/tx/config/v1/config_pb.js"; -export { - StoreKVPair as CosmosStoreV1beta1StoreKVPair, - BlockMetadata as CosmosStoreV1beta1BlockMetadata, -} from "./cosmos/store/v1beta1/listening_pb.js"; -export { - CommitInfo as CosmosStoreV1beta1CommitInfo, - StoreInfo as CosmosStoreV1beta1StoreInfo, - CommitID as CosmosStoreV1beta1CommitID, -} from "./cosmos/store/v1beta1/commit_info_pb.js"; -export { - ListenFinalizeBlockRequest as CosmosStoreStreamingAbciListenFinalizeBlockRequest, - ListenFinalizeBlockResponse as CosmosStoreStreamingAbciListenFinalizeBlockResponse, - ListenCommitRequest as CosmosStoreStreamingAbciListenCommitRequest, - ListenCommitResponse as CosmosStoreStreamingAbciListenCommitResponse, -} from "./cosmos/store/streaming/abci/grpc_pb.js"; -export { - ABCIListenerServiceListenFinalizeBlockService as CosmosStoreStreamingAbciABCIListenerServiceListenFinalizeBlockService, - ABCIListenerServiceListenCommitService as CosmosStoreStreamingAbciABCIListenerServiceListenCommitService, -} from "./cosmos/store/streaming/abci/grpc_cosmes.js"; -export { - Snapshot as CosmosStoreSnapshotsV1Snapshot, - Metadata as CosmosStoreSnapshotsV1Metadata, - SnapshotItem as CosmosStoreSnapshotsV1SnapshotItem, - SnapshotStoreItem as CosmosStoreSnapshotsV1SnapshotStoreItem, - SnapshotIAVLItem as CosmosStoreSnapshotsV1SnapshotIAVLItem, - SnapshotExtensionMeta as CosmosStoreSnapshotsV1SnapshotExtensionMeta, - SnapshotExtensionPayload as CosmosStoreSnapshotsV1SnapshotExtensionPayload, -} from "./cosmos/store/snapshots/v1/snapshot_pb.js"; -export { - Pairs as CosmosStoreInternalKvV1beta1Pairs, - Pair as CosmosStoreInternalKvV1beta1Pair, -} from "./cosmos/store/internal/kv/v1beta1/kv_pb.js"; -export { - FileDescriptorsRequest as CosmosReflectionV1FileDescriptorsRequest, - FileDescriptorsResponse as CosmosReflectionV1FileDescriptorsResponse, -} from "./cosmos/reflection/v1/reflection_pb.js"; -export { - ReflectionServiceFileDescriptorsService as CosmosReflectionV1ReflectionServiceFileDescriptorsService, -} from "./cosmos/reflection/v1/reflection_cosmes.js"; -export { - HashOp as CosmosIcs23V1HashOp, - LengthOp as CosmosIcs23V1LengthOp, - ExistenceProof as CosmosIcs23V1ExistenceProof, - NonExistenceProof as CosmosIcs23V1NonExistenceProof, - CommitmentProof as CosmosIcs23V1CommitmentProof, - LeafOp as CosmosIcs23V1LeafOp, - InnerOp as CosmosIcs23V1InnerOp, - ProofSpec as CosmosIcs23V1ProofSpec, - InnerSpec as CosmosIcs23V1InnerSpec, - BatchProof as CosmosIcs23V1BatchProof, - BatchEntry as CosmosIcs23V1BatchEntry, - CompressedBatchProof as CosmosIcs23V1CompressedBatchProof, - CompressedBatchEntry as CosmosIcs23V1CompressedBatchEntry, - CompressedExistenceProof as CosmosIcs23V1CompressedExistenceProof, - CompressedNonExistenceProof as CosmosIcs23V1CompressedNonExistenceProof, -} from "./cosmos/ics23/v1/proofs_pb.js"; -export { - PubKey as CosmosCryptoSecp256r1PubKey, - PrivKey as CosmosCryptoSecp256r1PrivKey, -} from "./cosmos/crypto/secp256r1/keys_pb.js"; -export { - PubKey as CosmosCryptoSecp256k1PubKey, - PrivKey as CosmosCryptoSecp256k1PrivKey, -} from "./cosmos/crypto/secp256k1/keys_pb.js"; -export { - LegacyAminoPubKey as CosmosCryptoMultisigLegacyAminoPubKey, -} from "./cosmos/crypto/multisig/keys_pb.js"; -export { - MultiSignature as CosmosCryptoMultisigV1beta1MultiSignature, - CompactBitArray as CosmosCryptoMultisigV1beta1CompactBitArray, -} from "./cosmos/crypto/multisig/v1beta1/multisig_pb.js"; -export { - Record as CosmosCryptoKeyringV1Record, - Record_Local as CosmosCryptoKeyringV1Record_Local, - Record_Ledger as CosmosCryptoKeyringV1Record_Ledger, - Record_Multi as CosmosCryptoKeyringV1Record_Multi, - Record_Offline as CosmosCryptoKeyringV1Record_Offline, -} from "./cosmos/crypto/keyring/v1/record_pb.js"; -export { - BIP44Params as CosmosCryptoHdV1BIP44Params, -} from "./cosmos/crypto/hd/v1/hd_pb.js"; -export { - PubKey as CosmosCryptoEd25519PubKey, - PrivKey as CosmosCryptoEd25519PrivKey, -} from "./cosmos/crypto/ed25519/keys_pb.js"; -export { - Coin as CosmosBaseV1beta1Coin, - DecCoin as CosmosBaseV1beta1DecCoin, - IntProto as CosmosBaseV1beta1IntProto, - DecProto as CosmosBaseV1beta1DecProto, -} from "./cosmos/base/v1beta1/coin_pb.js"; -export { - Block as CosmosBaseTendermintV1beta1Block, - Header as CosmosBaseTendermintV1beta1Header, -} from "./cosmos/base/tendermint/v1beta1/types_pb.js"; -export { - GetValidatorSetByHeightRequest as CosmosBaseTendermintV1beta1GetValidatorSetByHeightRequest, - GetValidatorSetByHeightResponse as CosmosBaseTendermintV1beta1GetValidatorSetByHeightResponse, - GetLatestValidatorSetRequest as CosmosBaseTendermintV1beta1GetLatestValidatorSetRequest, - GetLatestValidatorSetResponse as CosmosBaseTendermintV1beta1GetLatestValidatorSetResponse, - Validator as CosmosBaseTendermintV1beta1Validator, - GetBlockByHeightRequest as CosmosBaseTendermintV1beta1GetBlockByHeightRequest, - GetBlockByHeightResponse as CosmosBaseTendermintV1beta1GetBlockByHeightResponse, - GetLatestBlockRequest as CosmosBaseTendermintV1beta1GetLatestBlockRequest, - GetLatestBlockResponse as CosmosBaseTendermintV1beta1GetLatestBlockResponse, - GetSyncingRequest as CosmosBaseTendermintV1beta1GetSyncingRequest, - GetSyncingResponse as CosmosBaseTendermintV1beta1GetSyncingResponse, - GetNodeInfoRequest as CosmosBaseTendermintV1beta1GetNodeInfoRequest, - GetNodeInfoResponse as CosmosBaseTendermintV1beta1GetNodeInfoResponse, - VersionInfo as CosmosBaseTendermintV1beta1VersionInfo, - Module as CosmosBaseTendermintV1beta1Module, - ABCIQueryRequest as CosmosBaseTendermintV1beta1ABCIQueryRequest, - ABCIQueryResponse as CosmosBaseTendermintV1beta1ABCIQueryResponse, - ProofOp as CosmosBaseTendermintV1beta1ProofOp, - ProofOps as CosmosBaseTendermintV1beta1ProofOps, -} from "./cosmos/base/tendermint/v1beta1/query_pb.js"; -export { - ServiceGetNodeInfoService as CosmosBaseTendermintV1beta1ServiceGetNodeInfoService, - ServiceGetSyncingService as CosmosBaseTendermintV1beta1ServiceGetSyncingService, - ServiceGetLatestBlockService as CosmosBaseTendermintV1beta1ServiceGetLatestBlockService, - ServiceGetBlockByHeightService as CosmosBaseTendermintV1beta1ServiceGetBlockByHeightService, - ServiceGetLatestValidatorSetService as CosmosBaseTendermintV1beta1ServiceGetLatestValidatorSetService, - ServiceGetValidatorSetByHeightService as CosmosBaseTendermintV1beta1ServiceGetValidatorSetByHeightService, - ServiceABCIQueryService as CosmosBaseTendermintV1beta1ServiceABCIQueryService, -} from "./cosmos/base/tendermint/v1beta1/query_cosmes.js"; -export { - AppDescriptor as CosmosBaseReflectionV2alpha1AppDescriptor, - TxDescriptor as CosmosBaseReflectionV2alpha1TxDescriptor, - AuthnDescriptor as CosmosBaseReflectionV2alpha1AuthnDescriptor, - SigningModeDescriptor as CosmosBaseReflectionV2alpha1SigningModeDescriptor, - ChainDescriptor as CosmosBaseReflectionV2alpha1ChainDescriptor, - CodecDescriptor as CosmosBaseReflectionV2alpha1CodecDescriptor, - InterfaceDescriptor as CosmosBaseReflectionV2alpha1InterfaceDescriptor, - InterfaceImplementerDescriptor as CosmosBaseReflectionV2alpha1InterfaceImplementerDescriptor, - InterfaceAcceptingMessageDescriptor as CosmosBaseReflectionV2alpha1InterfaceAcceptingMessageDescriptor, - ConfigurationDescriptor as CosmosBaseReflectionV2alpha1ConfigurationDescriptor, - MsgDescriptor as CosmosBaseReflectionV2alpha1MsgDescriptor, - GetAuthnDescriptorRequest as CosmosBaseReflectionV2alpha1GetAuthnDescriptorRequest, - GetAuthnDescriptorResponse as CosmosBaseReflectionV2alpha1GetAuthnDescriptorResponse, - GetChainDescriptorRequest as CosmosBaseReflectionV2alpha1GetChainDescriptorRequest, - GetChainDescriptorResponse as CosmosBaseReflectionV2alpha1GetChainDescriptorResponse, - GetCodecDescriptorRequest as CosmosBaseReflectionV2alpha1GetCodecDescriptorRequest, - GetCodecDescriptorResponse as CosmosBaseReflectionV2alpha1GetCodecDescriptorResponse, - GetConfigurationDescriptorRequest as CosmosBaseReflectionV2alpha1GetConfigurationDescriptorRequest, - GetConfigurationDescriptorResponse as CosmosBaseReflectionV2alpha1GetConfigurationDescriptorResponse, - GetQueryServicesDescriptorRequest as CosmosBaseReflectionV2alpha1GetQueryServicesDescriptorRequest, - GetQueryServicesDescriptorResponse as CosmosBaseReflectionV2alpha1GetQueryServicesDescriptorResponse, - GetTxDescriptorRequest as CosmosBaseReflectionV2alpha1GetTxDescriptorRequest, - GetTxDescriptorResponse as CosmosBaseReflectionV2alpha1GetTxDescriptorResponse, - QueryServicesDescriptor as CosmosBaseReflectionV2alpha1QueryServicesDescriptor, - QueryServiceDescriptor as CosmosBaseReflectionV2alpha1QueryServiceDescriptor, - QueryMethodDescriptor as CosmosBaseReflectionV2alpha1QueryMethodDescriptor, -} from "./cosmos/base/reflection/v2alpha1/reflection_pb.js"; -export { - ReflectionServiceGetAuthnDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetAuthnDescriptorService, - ReflectionServiceGetChainDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetChainDescriptorService, - ReflectionServiceGetCodecDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetCodecDescriptorService, - ReflectionServiceGetConfigurationDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetConfigurationDescriptorService, - ReflectionServiceGetQueryServicesDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetQueryServicesDescriptorService, - ReflectionServiceGetTxDescriptorService as CosmosBaseReflectionV2alpha1ReflectionServiceGetTxDescriptorService, -} from "./cosmos/base/reflection/v2alpha1/reflection_cosmes.js"; -export { - ListAllInterfacesRequest as CosmosBaseReflectionV1beta1ListAllInterfacesRequest, - ListAllInterfacesResponse as CosmosBaseReflectionV1beta1ListAllInterfacesResponse, - ListImplementationsRequest as CosmosBaseReflectionV1beta1ListImplementationsRequest, - ListImplementationsResponse as CosmosBaseReflectionV1beta1ListImplementationsResponse, -} from "./cosmos/base/reflection/v1beta1/reflection_pb.js"; -export { - ReflectionServiceListAllInterfacesService as CosmosBaseReflectionV1beta1ReflectionServiceListAllInterfacesService, - ReflectionServiceListImplementationsService as CosmosBaseReflectionV1beta1ReflectionServiceListImplementationsService, -} from "./cosmos/base/reflection/v1beta1/reflection_cosmes.js"; -export { - PageRequest as CosmosBaseQueryV1beta1PageRequest, - PageResponse as CosmosBaseQueryV1beta1PageResponse, -} from "./cosmos/base/query/v1beta1/pagination_pb.js"; -export { - ConfigRequest as CosmosBaseNodeV1beta1ConfigRequest, - ConfigResponse as CosmosBaseNodeV1beta1ConfigResponse, - StatusRequest as CosmosBaseNodeV1beta1StatusRequest, - StatusResponse as CosmosBaseNodeV1beta1StatusResponse, -} from "./cosmos/base/node/v1beta1/query_pb.js"; -export { - ServiceConfigService as CosmosBaseNodeV1beta1ServiceConfigService, - ServiceStatusService as CosmosBaseNodeV1beta1ServiceStatusService, -} from "./cosmos/base/node/v1beta1/query_cosmes.js"; -export { - TxResponse as CosmosBaseAbciV1beta1TxResponse, - ABCIMessageLog as CosmosBaseAbciV1beta1ABCIMessageLog, - StringEvent as CosmosBaseAbciV1beta1StringEvent, - Attribute as CosmosBaseAbciV1beta1Attribute, - GasInfo as CosmosBaseAbciV1beta1GasInfo, - Result as CosmosBaseAbciV1beta1Result, - SimulationResponse as CosmosBaseAbciV1beta1SimulationResponse, - MsgData as CosmosBaseAbciV1beta1MsgData, - TxMsgData as CosmosBaseAbciV1beta1TxMsgData, - SearchTxsResult as CosmosBaseAbciV1beta1SearchTxsResult, - SearchBlocksResult as CosmosBaseAbciV1beta1SearchBlocksResult, -} from "./cosmos/base/abci/v1beta1/abci_pb.js"; -export { - AppOptionsRequest as CosmosAutocliV1AppOptionsRequest, - AppOptionsResponse as CosmosAutocliV1AppOptionsResponse, -} from "./cosmos/autocli/v1/query_pb.js"; -export { - QueryAppOptionsService as CosmosAutocliV1QueryAppOptionsService, -} from "./cosmos/autocli/v1/query_cosmes.js"; -export { - ModuleOptions as CosmosAutocliV1ModuleOptions, - ServiceCommandDescriptor as CosmosAutocliV1ServiceCommandDescriptor, - RpcCommandOptions as CosmosAutocliV1RpcCommandOptions, - FlagOptions as CosmosAutocliV1FlagOptions, - PositionalArgDescriptor as CosmosAutocliV1PositionalArgDescriptor, -} from "./cosmos/autocli/v1/options_pb.js"; -export { - QueryConfigRequest as CosmosAppV1alpha1QueryConfigRequest, - QueryConfigResponse as CosmosAppV1alpha1QueryConfigResponse, -} from "./cosmos/app/v1alpha1/query_pb.js"; -export { - QueryConfigService as CosmosAppV1alpha1QueryConfigService, -} from "./cosmos/app/v1alpha1/query_cosmes.js"; -export { - ModuleDescriptor as CosmosAppV1alpha1ModuleDescriptor, - PackageReference as CosmosAppV1alpha1PackageReference, - MigrateFromInfo as CosmosAppV1alpha1MigrateFromInfo, -} from "./cosmos/app/v1alpha1/module_pb.js"; -export { - Config as CosmosAppV1alpha1Config, - ModuleConfig as CosmosAppV1alpha1ModuleConfig, - GolangBinding as CosmosAppV1alpha1GolangBinding, -} from "./cosmos/app/v1alpha1/config_pb.js"; -export { - Module as CosmosAppRuntimeV1alpha1Module, - StoreKeyConfig as CosmosAppRuntimeV1alpha1StoreKeyConfig, -} from "./cosmos/app/runtime/v1alpha1/module_pb.js"; diff --git a/packages/es/src/protobufs/osmosis/accum/v1beta1/accum_pb.ts b/packages/es/src/protobufs/osmosis/accum/v1beta1/accum_pb.ts deleted file mode 100644 index 92df760d8..000000000 --- a/packages/es/src/protobufs/osmosis/accum/v1beta1/accum_pb.ts +++ /dev/null @@ -1,172 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/accum/v1beta1/accum.proto (package osmosis.accum.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { DecCoin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * AccumulatorContent is the state-entry for the global accumulator. - * It contains the name of the global accumulator and the total value of - * shares belonging to it from all positions. - * - * @generated from message osmosis.accum.v1beta1.AccumulatorContent - */ -export class AccumulatorContent extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.DecCoin accum_value = 1; - */ - accumValue: DecCoin[] = []; - - /** - * @generated from field: string total_shares = 2; - */ - totalShares = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.accum.v1beta1.AccumulatorContent"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "accum_value", kind: "message", T: DecCoin, repeated: true }, - { no: 2, name: "total_shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccumulatorContent { - return new AccumulatorContent().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccumulatorContent { - return new AccumulatorContent().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccumulatorContent { - return new AccumulatorContent().fromJsonString(jsonString, options); - } - - static equals(a: AccumulatorContent | PlainMessage | undefined, b: AccumulatorContent | PlainMessage | undefined): boolean { - return proto3.util.equals(AccumulatorContent, a, b); - } -} - -/** - * @generated from message osmosis.accum.v1beta1.Options - */ -export class Options extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.accum.v1beta1.Options"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Options { - return new Options().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Options { - return new Options().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Options { - return new Options().fromJsonString(jsonString, options); - } - - static equals(a: Options | PlainMessage | undefined, b: Options | PlainMessage | undefined): boolean { - return proto3.util.equals(Options, a, b); - } -} - -/** - * Record corresponds to an individual position value belonging to the - * global accumulator. - * - * @generated from message osmosis.accum.v1beta1.Record - */ -export class Record extends Message { - /** - * num_shares is the number of shares belonging to the position associated - * with this record. - * - * @generated from field: string num_shares = 1; - */ - numShares = ""; - - /** - * accum_value_per_share is the subset of coins per shar of the global - * accumulator value that allows to infer how much a position is entitled to - * per share that it owns. - * - * In the default case with no intervals, this value equals to the global - * accumulator value at the time of the position creation, the last update or - * reward claim. - * - * In the interval case such as concentrated liquidity, this value equals to - * the global growth of rewards inside the interval during one of: the time of - * the position creation, the last update or reward claim. Note, that - * immediately prior to claiming or updating rewards, this value must be - * updated to "the growth inside at the time of last update + the growth - * outside at the time of the current block". This is so that the claiming - * logic can subtract this updated value from the global accumulator value to - * get the growth inside the interval from the time of last update up until - * the current block time. - * - * @generated from field: repeated cosmos.base.v1beta1.DecCoin accum_value_per_share = 2; - */ - accumValuePerShare: DecCoin[] = []; - - /** - * unclaimed_rewards_total is the total amount of unclaimed rewards that the - * position is entitled to. This value is updated whenever shares are added or - * removed from an existing position. We also expose API for manually updating - * this value for some custom use cases such as merging pre-existing positions - * into a single one. - * - * @generated from field: repeated cosmos.base.v1beta1.DecCoin unclaimed_rewards_total = 3; - */ - unclaimedRewardsTotal: DecCoin[] = []; - - /** - * @generated from field: osmosis.accum.v1beta1.Options options = 4; - */ - options?: Options; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.accum.v1beta1.Record"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "num_shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "accum_value_per_share", kind: "message", T: DecCoin, repeated: true }, - { no: 3, name: "unclaimed_rewards_total", kind: "message", T: DecCoin, repeated: true }, - { no: 4, name: "options", kind: "message", T: Options }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Record { - return new Record().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Record { - return new Record().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Record { - return new Record().fromJsonString(jsonString, options); - } - - static equals(a: Record | PlainMessage | undefined, b: Record | PlainMessage | undefined): boolean { - return proto3.util.equals(Record, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/params_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/params_pb.ts deleted file mode 100644 index 9be285f4b..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/params_pb.ts +++ /dev/null @@ -1,120 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/params.proto (package osmosis.concentratedliquidity, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.concentratedliquidity.Params - */ -export class Params extends Message { - /** - * authorized_tick_spacing is an array of uint64s that represents the tick - * spacing values concentrated-liquidity pools can be created with. For - * example, an authorized_tick_spacing of [1, 10, 30] allows for pools - * to be created with tick spacing of 1, 10, or 30. - * - * @generated from field: repeated uint64 authorized_tick_spacing = 1; - */ - authorizedTickSpacing: bigint[] = []; - - /** - * @generated from field: repeated string authorized_spread_factors = 2; - */ - authorizedSpreadFactors: string[] = []; - - /** - * balancer_shares_reward_discount is the rate by which incentives flowing - * from CL to Balancer pools will be discounted to encourage LPs to migrate. - * e.g. a rate of 0.05 means Balancer LPs get 5% less incentives than full - * range CL LPs. - * This field can range from (0,1]. If set to 1, it indicates that all - * incentives stay at cl pool. - * - * @generated from field: string balancer_shares_reward_discount = 3; - */ - balancerSharesRewardDiscount = ""; - - /** - * DEPRECATED: authorized_quote_denoms is a list of quote denoms that can be - * used as token1 when creating a pool. We limit the quote assets to a small - * set for the purposes of having convenient price increments stemming from - * tick to price conversion. These increments are in a human readable - * magnitude only for token1 as a quote. For limit orders in the future, this - * will be a desirable property in terms of UX as to allow users to set limit - * orders at prices in terms of token1 (quote asset) that are easy to reason - * about. - * - * @generated from field: repeated string authorized_quote_denoms = 4 [deprecated = true]; - * @deprecated - */ - authorizedQuoteDenoms: string[] = []; - - /** - * @generated from field: repeated google.protobuf.Duration authorized_uptimes = 5; - */ - authorizedUptimes: Duration[] = []; - - /** - * is_permissionless_pool_creation_enabled is a boolean that determines if - * concentrated liquidity pools can be created via message. At launch, - * we consider allowing only governance to create pools, and then later - * allowing permissionless pool creation by switching this flag to true - * with a governance proposal. - * - * @generated from field: bool is_permissionless_pool_creation_enabled = 6; - */ - isPermissionlessPoolCreationEnabled = false; - - /** - * unrestricted_pool_creator_whitelist is a list of addresses that are - * allowed to bypass restrictions on permissionless supercharged pool - * creation, like pool_creation_enabled, restricted quote assets, no - * double creation of pools, etc. - * - * @generated from field: repeated string unrestricted_pool_creator_whitelist = 7; - */ - unrestrictedPoolCreatorWhitelist: string[] = []; - - /** - * @generated from field: uint64 hook_gas_limit = 8; - */ - hookGasLimit = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authorized_tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "authorized_spread_factors", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 3, name: "balancer_shares_reward_discount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "authorized_quote_denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "authorized_uptimes", kind: "message", T: Duration, repeated: true }, - { no: 6, name: "is_permissionless_pool_creation_enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 7, name: "unrestricted_pool_creator_whitelist", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 8, name: "hook_gas_limit", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_cosmes.ts deleted file mode 100644 index d8fcf0bb5..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx.proto (package osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCreateConcentratedPool, MsgCreateConcentratedPoolResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.Msg.CreateConcentratedPool - */ -export const MsgCreateConcentratedPoolService = { - typeName: TYPE_NAME, - method: "CreateConcentratedPool", - Request: MsgCreateConcentratedPool, - Response: MsgCreateConcentratedPoolResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_pb.ts deleted file mode 100644 index 03d5b72aa..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx_pb.ts +++ /dev/null @@ -1,110 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/poolmodel/concentrated/v1beta1/tx.proto (package osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * ===================== MsgCreateConcentratedPool - * - * @generated from message osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.MsgCreateConcentratedPool - */ -export class MsgCreateConcentratedPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: string denom0 = 2; - */ - denom0 = ""; - - /** - * @generated from field: string denom1 = 3; - */ - denom1 = ""; - - /** - * @generated from field: uint64 tick_spacing = 4; - */ - tickSpacing = protoInt64.zero; - - /** - * @generated from field: string spread_factor = 5; - */ - spreadFactor = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.MsgCreateConcentratedPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "denom1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "spread_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateConcentratedPool { - return new MsgCreateConcentratedPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateConcentratedPool { - return new MsgCreateConcentratedPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateConcentratedPool { - return new MsgCreateConcentratedPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateConcentratedPool | PlainMessage | undefined, b: MsgCreateConcentratedPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateConcentratedPool, a, b); - } -} - -/** - * Returns a unique poolID to identify the pool with. - * - * @generated from message osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.MsgCreateConcentratedPoolResponse - */ -export class MsgCreateConcentratedPoolResponse extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.poolmodel.concentrated.v1beta1.MsgCreateConcentratedPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateConcentratedPoolResponse { - return new MsgCreateConcentratedPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateConcentratedPoolResponse { - return new MsgCreateConcentratedPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateConcentratedPoolResponse { - return new MsgCreateConcentratedPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateConcentratedPoolResponse | PlainMessage | undefined, b: MsgCreateConcentratedPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateConcentratedPoolResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/genesis_pb.ts deleted file mode 100644 index c105b5a6a..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,324 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/genesis.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { TickInfo } from "./tick_info_pb.js"; -import { IncentiveRecord } from "./incentive_record_pb.js"; -import { Position } from "./position_pb.js"; -import { AccumulatorContent, Record } from "../../accum/v1beta1/accum_pb.js"; -import { Params } from "../params_pb.js"; - -/** - * FullTick contains tick index and pool id along with other tick model - * information. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.FullTick - */ -export class FullTick extends Message { - /** - * pool id associated with the tick. - * - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * tick's index. - * - * @generated from field: int64 tick_index = 2; - */ - tickIndex = protoInt64.zero; - - /** - * tick's info. - * - * @generated from field: osmosis.concentratedliquidity.v1beta1.TickInfo info = 3; - */ - info?: TickInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.FullTick"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "tick_index", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "info", kind: "message", T: TickInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FullTick { - return new FullTick().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FullTick { - return new FullTick().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FullTick { - return new FullTick().fromJsonString(jsonString, options); - } - - static equals(a: FullTick | PlainMessage | undefined, b: FullTick | PlainMessage | undefined): boolean { - return proto3.util.equals(FullTick, a, b); - } -} - -/** - * PoolData represents a serialized pool along with its ticks - * for genesis state. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolData - */ -export class PoolData extends Message { - /** - * pool struct - * - * @generated from field: google.protobuf.Any pool = 1; - */ - pool?: Any; - - /** - * pool's ticks - * - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.FullTick ticks = 2; - */ - ticks: FullTick[] = []; - - /** - * @generated from field: osmosis.concentratedliquidity.v1beta1.AccumObject spread_reward_accumulator = 3; - */ - spreadRewardAccumulator?: AccumObject; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.AccumObject incentives_accumulators = 4; - */ - incentivesAccumulators: AccumObject[] = []; - - /** - * incentive records to be set - * - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.IncentiveRecord incentive_records = 5; - */ - incentiveRecords: IncentiveRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool", kind: "message", T: Any }, - { no: 2, name: "ticks", kind: "message", T: FullTick, repeated: true }, - { no: 3, name: "spread_reward_accumulator", kind: "message", T: AccumObject }, - { no: 4, name: "incentives_accumulators", kind: "message", T: AccumObject, repeated: true }, - { no: 5, name: "incentive_records", kind: "message", T: IncentiveRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolData { - return new PoolData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolData { - return new PoolData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolData { - return new PoolData().fromJsonString(jsonString, options); - } - - static equals(a: PoolData | PlainMessage | undefined, b: PoolData | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolData, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PositionData - */ -export class PositionData extends Message { - /** - * @generated from field: osmosis.concentratedliquidity.v1beta1.Position position = 1; - */ - position?: Position; - - /** - * @generated from field: uint64 lock_id = 2; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: osmosis.accum.v1beta1.Record spread_reward_accum_record = 3; - */ - spreadRewardAccumRecord?: Record; - - /** - * @generated from field: repeated osmosis.accum.v1beta1.Record uptime_accum_records = 4; - */ - uptimeAccumRecords: Record[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PositionData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position", kind: "message", T: Position }, - { no: 2, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "spread_reward_accum_record", kind: "message", T: Record }, - { no: 4, name: "uptime_accum_records", kind: "message", T: Record, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PositionData { - return new PositionData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PositionData { - return new PositionData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PositionData { - return new PositionData().fromJsonString(jsonString, options); - } - - static equals(a: PositionData | PlainMessage | undefined, b: PositionData | PlainMessage | undefined): boolean { - return proto3.util.equals(PositionData, a, b); - } -} - -/** - * GenesisState defines the concentrated liquidity module's genesis state. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params are all the parameters of the module - * - * @generated from field: osmosis.concentratedliquidity.Params params = 1; - */ - params?: Params; - - /** - * pool data containing serialized pool struct and ticks. - * - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.PoolData pool_data = 2; - */ - poolData: PoolData[] = []; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.PositionData position_data = 3; - */ - positionData: PositionData[] = []; - - /** - * @generated from field: uint64 next_position_id = 4; - */ - nextPositionId = protoInt64.zero; - - /** - * @generated from field: uint64 next_incentive_record_id = 5; - */ - nextIncentiveRecordId = protoInt64.zero; - - /** - * @generated from field: uint64 incentives_accumulator_pool_id_migration_threshold = 6; - */ - incentivesAccumulatorPoolIdMigrationThreshold = protoInt64.zero; - - /** - * @generated from field: uint64 spread_factor_pool_id_migration_threshold = 7; - */ - spreadFactorPoolIdMigrationThreshold = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "pool_data", kind: "message", T: PoolData, repeated: true }, - { no: 3, name: "position_data", kind: "message", T: PositionData, repeated: true }, - { no: 4, name: "next_position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "next_incentive_record_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "incentives_accumulator_pool_id_migration_threshold", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "spread_factor_pool_id_migration_threshold", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * In original struct of Accum object, store.KVStore is stored together. - * For handling genesis, we do not need to include store.KVStore since we use - * CL module's KVStore. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.AccumObject - */ -export class AccumObject extends Message { - /** - * Accumulator's name (pulled from AccumulatorContent) - * - * @generated from field: string name = 1; - */ - name = ""; - - /** - * @generated from field: osmosis.accum.v1beta1.AccumulatorContent accum_content = 2; - */ - accumContent?: AccumulatorContent; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.AccumObject"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "accum_content", kind: "message", T: AccumulatorContent }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccumObject { - return new AccumObject().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccumObject { - return new AccumObject().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccumObject { - return new AccumObject().fromJsonString(jsonString, options); - } - - static equals(a: AccumObject | PlainMessage | undefined, b: AccumObject | PlainMessage | undefined): boolean { - return proto3.util.equals(AccumObject, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/gov_pb.ts deleted file mode 100644 index 2e96e03f9..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/gov_pb.ts +++ /dev/null @@ -1,216 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/gov.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * CreateConcentratedLiquidityPoolsProposal is a gov Content type for creating - * concentrated liquidity pools. If a CreateConcentratedLiquidityPoolsProposal - * passes, the pools are created via pool manager module account. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.CreateConcentratedLiquidityPoolsProposal - */ -export class CreateConcentratedLiquidityPoolsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.PoolRecord pool_records = 3; - */ - poolRecords: PoolRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.CreateConcentratedLiquidityPoolsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_records", kind: "message", T: PoolRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CreateConcentratedLiquidityPoolsProposal { - return new CreateConcentratedLiquidityPoolsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CreateConcentratedLiquidityPoolsProposal { - return new CreateConcentratedLiquidityPoolsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CreateConcentratedLiquidityPoolsProposal { - return new CreateConcentratedLiquidityPoolsProposal().fromJsonString(jsonString, options); - } - - static equals(a: CreateConcentratedLiquidityPoolsProposal | PlainMessage | undefined, b: CreateConcentratedLiquidityPoolsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(CreateConcentratedLiquidityPoolsProposal, a, b); - } -} - -/** - * TickSpacingDecreaseProposal is a gov Content type for proposing a tick - * spacing decrease for a pool. The proposal will fail if one of the pools do - * not exist, or if the new tick spacing is not less than the current tick - * spacing. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.TickSpacingDecreaseProposal - */ -export class TickSpacingDecreaseProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.PoolIdToTickSpacingRecord pool_id_to_tick_spacing_records = 3; - */ - poolIdToTickSpacingRecords: PoolIdToTickSpacingRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.TickSpacingDecreaseProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id_to_tick_spacing_records", kind: "message", T: PoolIdToTickSpacingRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TickSpacingDecreaseProposal { - return new TickSpacingDecreaseProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TickSpacingDecreaseProposal { - return new TickSpacingDecreaseProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TickSpacingDecreaseProposal { - return new TickSpacingDecreaseProposal().fromJsonString(jsonString, options); - } - - static equals(a: TickSpacingDecreaseProposal | PlainMessage | undefined, b: TickSpacingDecreaseProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(TickSpacingDecreaseProposal, a, b); - } -} - -/** - * PoolIdToTickSpacingRecord is a struct that contains a pool id to new tick - * spacing pair. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolIdToTickSpacingRecord - */ -export class PoolIdToTickSpacingRecord extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: uint64 new_tick_spacing = 2; - */ - newTickSpacing = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolIdToTickSpacingRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "new_tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolIdToTickSpacingRecord { - return new PoolIdToTickSpacingRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolIdToTickSpacingRecord { - return new PoolIdToTickSpacingRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolIdToTickSpacingRecord { - return new PoolIdToTickSpacingRecord().fromJsonString(jsonString, options); - } - - static equals(a: PoolIdToTickSpacingRecord | PlainMessage | undefined, b: PoolIdToTickSpacingRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolIdToTickSpacingRecord, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolRecord - */ -export class PoolRecord extends Message { - /** - * @generated from field: string denom0 = 1; - */ - denom0 = ""; - - /** - * @generated from field: string denom1 = 2; - */ - denom1 = ""; - - /** - * @generated from field: uint64 tick_spacing = 3; - */ - tickSpacing = protoInt64.zero; - - /** - * @generated from field: string spread_factor = 5; - */ - spreadFactor = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "spread_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolRecord { - return new PoolRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolRecord { - return new PoolRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolRecord { - return new PoolRecord().fromJsonString(jsonString, options); - } - - static equals(a: PoolRecord | PlainMessage | undefined, b: PoolRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolRecord, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/incentive_record_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/incentive_record_pb.ts deleted file mode 100644 index 107a222b3..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/incentive_record_pb.ts +++ /dev/null @@ -1,135 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/incentive_record.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { DecCoin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * IncentiveRecord is the high-level struct we use to deal with an independent - * incentive being distributed on a pool. Note that PoolId, Denom, and MinUptime - * are included in the key so we avoid storing them in state, hence the - * distinction between IncentiveRecord and IncentiveRecordBody. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.IncentiveRecord - */ -export class IncentiveRecord extends Message { - /** - * incentive_id is the id uniquely identifying this incentive record. - * - * @generated from field: uint64 incentive_id = 1; - */ - incentiveId = protoInt64.zero; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * incentive record body holds necessary - * - * @generated from field: osmosis.concentratedliquidity.v1beta1.IncentiveRecordBody incentive_record_body = 4; - */ - incentiveRecordBody?: IncentiveRecordBody; - - /** - * min_uptime is the minimum uptime required for liquidity to qualify for this - * incentive. It should be always be one of the supported uptimes in - * types.SupportedUptimes - * - * @generated from field: google.protobuf.Duration min_uptime = 5; - */ - minUptime?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.IncentiveRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "incentive_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "incentive_record_body", kind: "message", T: IncentiveRecordBody }, - { no: 5, name: "min_uptime", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IncentiveRecord { - return new IncentiveRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IncentiveRecord { - return new IncentiveRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IncentiveRecord { - return new IncentiveRecord().fromJsonString(jsonString, options); - } - - static equals(a: IncentiveRecord | PlainMessage | undefined, b: IncentiveRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(IncentiveRecord, a, b); - } -} - -/** - * IncentiveRecordBody represents the body stored in state for each individual - * record. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.IncentiveRecordBody - */ -export class IncentiveRecordBody extends Message { - /** - * remaining_coin is the total amount of incentives to be distributed - * - * @generated from field: cosmos.base.v1beta1.DecCoin remaining_coin = 1; - */ - remainingCoin?: DecCoin; - - /** - * emission_rate is the incentive emission rate per second - * - * @generated from field: string emission_rate = 2; - */ - emissionRate = ""; - - /** - * start_time is the time when the incentive starts distributing - * - * @generated from field: google.protobuf.Timestamp start_time = 3; - */ - startTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.IncentiveRecordBody"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "remaining_coin", kind: "message", T: DecCoin }, - { no: 2, name: "emission_rate", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "start_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IncentiveRecordBody { - return new IncentiveRecordBody().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IncentiveRecordBody { - return new IncentiveRecordBody().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IncentiveRecordBody { - return new IncentiveRecordBody().fromJsonString(jsonString, options); - } - - static equals(a: IncentiveRecordBody | PlainMessage | undefined, b: IncentiveRecordBody | PlainMessage | undefined): boolean { - return proto3.util.equals(IncentiveRecordBody, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/pool_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/pool_pb.ts deleted file mode 100644 index 382a8c45e..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/pool_pb.ts +++ /dev/null @@ -1,138 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/pool.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -// This is a legacy package that requires additional migration logic -// in order to use the correct package. Decision made to use legacy package path -// until clear steps for migration logic and the unknowns for state breaking are -// investigated for changing proto package. - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.Pool - */ -export class Pool extends Message { - /** - * pool's address holding all liquidity tokens. - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * address holding the incentives liquidity. - * - * @generated from field: string incentives_address = 2; - */ - incentivesAddress = ""; - - /** - * address holding spread rewards from swaps. - * - * @generated from field: string spread_rewards_address = 3; - */ - spreadRewardsAddress = ""; - - /** - * @generated from field: uint64 id = 4; - */ - id = protoInt64.zero; - - /** - * Amount of total liquidity - * - * @generated from field: string current_tick_liquidity = 5; - */ - currentTickLiquidity = ""; - - /** - * @generated from field: string token0 = 6; - */ - token0 = ""; - - /** - * @generated from field: string token1 = 7; - */ - token1 = ""; - - /** - * @generated from field: string current_sqrt_price = 8; - */ - currentSqrtPrice = ""; - - /** - * @generated from field: int64 current_tick = 9; - */ - currentTick = protoInt64.zero; - - /** - * tick_spacing must be one of the authorized_tick_spacing values set in the - * concentrated-liquidity parameters - * - * @generated from field: uint64 tick_spacing = 10; - */ - tickSpacing = protoInt64.zero; - - /** - * @generated from field: int64 exponent_at_price_one = 11; - */ - exponentAtPriceOne = protoInt64.zero; - - /** - * spread_factor is the ratio that is charged on the amount of token in. - * - * @generated from field: string spread_factor = 12; - */ - spreadFactor = ""; - - /** - * last_liquidity_update is the last time either the pool liquidity or the - * active tick changed - * - * @generated from field: google.protobuf.Timestamp last_liquidity_update = 13; - */ - lastLiquidityUpdate?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.Pool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "incentives_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "spread_rewards_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "current_tick_liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "token0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "token1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "current_sqrt_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "current_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 10, name: "tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 11, name: "exponent_at_price_one", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "spread_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 13, name: "last_liquidity_update", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Pool { - return new Pool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Pool { - return new Pool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Pool { - return new Pool().fromJsonString(jsonString, options); - } - - static equals(a: Pool | PlainMessage | undefined, b: Pool | PlainMessage | undefined): boolean { - return proto3.util.equals(Pool, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/position_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/position_pb.ts deleted file mode 100644 index 410eca72b..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/position_pb.ts +++ /dev/null @@ -1,209 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/position.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -// this is a legacy package that requires additional migration logic -// in order to use the correct package. Decision made to use legacy package path -// until clear steps for migration logic and the unknowns for state breaking are -// investigated for changing proto package. - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { PeriodLock } from "../../lockup/lock_pb.js"; - -/** - * Position contains position's id, address, pool id, lower tick, upper tick - * join time, and liquidity. - * - * @generated from message osmosis.concentratedliquidity.v1beta1.Position - */ -export class Position extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string address = 2; - */ - address = ""; - - /** - * @generated from field: uint64 pool_id = 3; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: int64 lower_tick = 4; - */ - lowerTick = protoInt64.zero; - - /** - * @generated from field: int64 upper_tick = 5; - */ - upperTick = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Timestamp join_time = 6; - */ - joinTime?: Timestamp; - - /** - * @generated from field: string liquidity = 7; - */ - liquidity = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.Position"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "lower_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "upper_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "join_time", kind: "message", T: Timestamp }, - { no: 7, name: "liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Position { - return new Position().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Position { - return new Position().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Position { - return new Position().fromJsonString(jsonString, options); - } - - static equals(a: Position | PlainMessage | undefined, b: Position | PlainMessage | undefined): boolean { - return proto3.util.equals(Position, a, b); - } -} - -/** - * FullPositionBreakdown returns: - * - the position itself - * - the amount the position translates in terms of asset0 and asset1 - * - the amount of claimable fees - * - the amount of claimable incentives - * - the amount of incentives that would be forfeited if the position was closed - * now - * - * @generated from message osmosis.concentratedliquidity.v1beta1.FullPositionBreakdown - */ -export class FullPositionBreakdown extends Message { - /** - * @generated from field: osmosis.concentratedliquidity.v1beta1.Position position = 1; - */ - position?: Position; - - /** - * @generated from field: cosmos.base.v1beta1.Coin asset0 = 2; - */ - asset0?: Coin; - - /** - * @generated from field: cosmos.base.v1beta1.Coin asset1 = 3; - */ - asset1?: Coin; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin claimable_spread_rewards = 4; - */ - claimableSpreadRewards: Coin[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin claimable_incentives = 5; - */ - claimableIncentives: Coin[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin forfeited_incentives = 6; - */ - forfeitedIncentives: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.FullPositionBreakdown"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position", kind: "message", T: Position }, - { no: 2, name: "asset0", kind: "message", T: Coin }, - { no: 3, name: "asset1", kind: "message", T: Coin }, - { no: 4, name: "claimable_spread_rewards", kind: "message", T: Coin, repeated: true }, - { no: 5, name: "claimable_incentives", kind: "message", T: Coin, repeated: true }, - { no: 6, name: "forfeited_incentives", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FullPositionBreakdown { - return new FullPositionBreakdown().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FullPositionBreakdown { - return new FullPositionBreakdown().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FullPositionBreakdown { - return new FullPositionBreakdown().fromJsonString(jsonString, options); - } - - static equals(a: FullPositionBreakdown | PlainMessage | undefined, b: FullPositionBreakdown | PlainMessage | undefined): boolean { - return proto3.util.equals(FullPositionBreakdown, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PositionWithPeriodLock - */ -export class PositionWithPeriodLock extends Message { - /** - * @generated from field: osmosis.concentratedliquidity.v1beta1.Position position = 1; - */ - position?: Position; - - /** - * @generated from field: osmosis.lockup.PeriodLock locks = 2; - */ - locks?: PeriodLock; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PositionWithPeriodLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position", kind: "message", T: Position }, - { no: 2, name: "locks", kind: "message", T: PeriodLock }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PositionWithPeriodLock { - return new PositionWithPeriodLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PositionWithPeriodLock { - return new PositionWithPeriodLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PositionWithPeriodLock { - return new PositionWithPeriodLock().fromJsonString(jsonString, options); - } - - static equals(a: PositionWithPeriodLock | PlainMessage | undefined, b: PositionWithPeriodLock | PlainMessage | undefined): boolean { - return proto3.util.equals(PositionWithPeriodLock, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_cosmes.ts deleted file mode 100644 index 13e1877f1..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,199 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/query.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { CFMMPoolIdLinkFromConcentratedPoolIdRequest, CFMMPoolIdLinkFromConcentratedPoolIdResponse, ClaimableIncentivesRequest, ClaimableIncentivesResponse, ClaimableSpreadRewardsRequest, ClaimableSpreadRewardsResponse, GetTotalLiquidityRequest, GetTotalLiquidityResponse, IncentiveRecordsRequest, IncentiveRecordsResponse, LiquidityNetInDirectionRequest, LiquidityNetInDirectionResponse, LiquidityPerTickRangeRequest, LiquidityPerTickRangeResponse, NumNextInitializedTicksRequest, NumNextInitializedTicksResponse, ParamsRequest, ParamsResponse, PoolAccumulatorRewardsRequest, PoolAccumulatorRewardsResponse, PoolsRequest, PoolsResponse, PositionByIdRequest, PositionByIdResponse, TickAccumulatorTrackersRequest, TickAccumulatorTrackersResponse, UserPositionsRequest, UserPositionsResponse, UserUnbondingPositionsRequest, UserUnbondingPositionsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.concentratedliquidity.v1beta1.Query"; - -/** - * Pools returns all concentrated liquidity pools - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.Pools - */ -export const QueryPoolsService = { - typeName: TYPE_NAME, - method: "Pools", - Request: PoolsRequest, - Response: PoolsResponse, -} as const; - -/** - * Params returns concentrated liquidity module params. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - -/** - * UserPositions returns all concentrated positions of some address. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.UserPositions - */ -export const QueryUserPositionsService = { - typeName: TYPE_NAME, - method: "UserPositions", - Request: UserPositionsRequest, - Response: UserPositionsResponse, -} as const; - -/** - * LiquidityPerTickRange returns the amount of liquidity per every tick range - * existing within the given pool - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.LiquidityPerTickRange - */ -export const QueryLiquidityPerTickRangeService = { - typeName: TYPE_NAME, - method: "LiquidityPerTickRange", - Request: LiquidityPerTickRangeRequest, - Response: LiquidityPerTickRangeResponse, -} as const; - -/** - * LiquidityNetInDirection returns liquidity net in the direction given. - * Uses the bound if specified, if not uses either min tick / max tick - * depending on the direction. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.LiquidityNetInDirection - */ -export const QueryLiquidityNetInDirectionService = { - typeName: TYPE_NAME, - method: "LiquidityNetInDirection", - Request: LiquidityNetInDirectionRequest, - Response: LiquidityNetInDirectionResponse, -} as const; - -/** - * ClaimableSpreadRewards returns the amount of spread rewards that can be - * claimed by a position with the given id. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.ClaimableSpreadRewards - */ -export const QueryClaimableSpreadRewardsService = { - typeName: TYPE_NAME, - method: "ClaimableSpreadRewards", - Request: ClaimableSpreadRewardsRequest, - Response: ClaimableSpreadRewardsResponse, -} as const; - -/** - * ClaimableIncentives returns the amount of incentives that can be claimed - * and how many would be forfeited by a position with the given id. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.ClaimableIncentives - */ -export const QueryClaimableIncentivesService = { - typeName: TYPE_NAME, - method: "ClaimableIncentives", - Request: ClaimableIncentivesRequest, - Response: ClaimableIncentivesResponse, -} as const; - -/** - * PositionById returns a position with the given id. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.PositionById - */ -export const QueryPositionByIdService = { - typeName: TYPE_NAME, - method: "PositionById", - Request: PositionByIdRequest, - Response: PositionByIdResponse, -} as const; - -/** - * PoolAccumulatorRewards returns the pool-global accumulator rewards. - * Contains spread factor rewards and uptime rewards. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.PoolAccumulatorRewards - */ -export const QueryPoolAccumulatorRewardsService = { - typeName: TYPE_NAME, - method: "PoolAccumulatorRewards", - Request: PoolAccumulatorRewardsRequest, - Response: PoolAccumulatorRewardsResponse, -} as const; - -/** - * IncentiveRecords returns the incentive records for a given poolId - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.IncentiveRecords - */ -export const QueryIncentiveRecordsService = { - typeName: TYPE_NAME, - method: "IncentiveRecords", - Request: IncentiveRecordsRequest, - Response: IncentiveRecordsResponse, -} as const; - -/** - * TickAccumulatorTrackers returns the tick accumulator trackers. - * Contains spread factor and uptime accumulator trackers. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.TickAccumulatorTrackers - */ -export const QueryTickAccumulatorTrackersService = { - typeName: TYPE_NAME, - method: "TickAccumulatorTrackers", - Request: TickAccumulatorTrackersRequest, - Response: TickAccumulatorTrackersResponse, -} as const; - -/** - * CFMMPoolIdLinkFromConcentratedPoolId returns the pool id of the CFMM - * pool that is linked with the given concentrated pool. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.CFMMPoolIdLinkFromConcentratedPoolId - */ -export const QueryCFMMPoolIdLinkFromConcentratedPoolIdService = { - typeName: TYPE_NAME, - method: "CFMMPoolIdLinkFromConcentratedPoolId", - Request: CFMMPoolIdLinkFromConcentratedPoolIdRequest, - Response: CFMMPoolIdLinkFromConcentratedPoolIdResponse, -} as const; - -/** - * UserUnbondingPositions returns the position and lock info of unbonding - * positions of the given address. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.UserUnbondingPositions - */ -export const QueryUserUnbondingPositionsService = { - typeName: TYPE_NAME, - method: "UserUnbondingPositions", - Request: UserUnbondingPositionsRequest, - Response: UserUnbondingPositionsResponse, -} as const; - -/** - * GetTotalLiquidity returns total liquidity across all cl pools. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.GetTotalLiquidity - */ -export const QueryGetTotalLiquidityService = { - typeName: TYPE_NAME, - method: "GetTotalLiquidity", - Request: GetTotalLiquidityRequest, - Response: GetTotalLiquidityResponse, -} as const; - -/** - * NumNextInitializedTicks returns the provided number of next initialized - * ticks in the direction of swapping the token in denom. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Query.NumNextInitializedTicks - */ -export const QueryNumNextInitializedTicksService = { - typeName: TYPE_NAME, - method: "NumNextInitializedTicks", - Request: NumNextInitializedTicksRequest, - Response: NumNextInitializedTicksResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_pb.ts deleted file mode 100644 index 48596f29f..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/query_pb.ts +++ /dev/null @@ -1,1452 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/query.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { PageRequest, PageResponse } from "../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { FullPositionBreakdown, PositionWithPeriodLock } from "./position_pb.js"; -import { Params } from "../params_pb.js"; -import { Coin, DecCoin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { UptimeTracker } from "./tick_info_pb.js"; -import { IncentiveRecord } from "./incentive_record_pb.js"; - -/** - * =============================== UserPositions - * - * @generated from message osmosis.concentratedliquidity.v1beta1.UserPositionsRequest - */ -export class UserPositionsRequest extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UserPositionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserPositionsRequest { - return new UserPositionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserPositionsRequest { - return new UserPositionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserPositionsRequest { - return new UserPositionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: UserPositionsRequest | PlainMessage | undefined, b: UserPositionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UserPositionsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.UserPositionsResponse - */ -export class UserPositionsResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.FullPositionBreakdown positions = 1; - */ - positions: FullPositionBreakdown[] = []; - - /** - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UserPositionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "positions", kind: "message", T: FullPositionBreakdown, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserPositionsResponse { - return new UserPositionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserPositionsResponse { - return new UserPositionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserPositionsResponse { - return new UserPositionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: UserPositionsResponse | PlainMessage | undefined, b: UserPositionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UserPositionsResponse, a, b); - } -} - -/** - * =============================== PositionById - * - * @generated from message osmosis.concentratedliquidity.v1beta1.PositionByIdRequest - */ -export class PositionByIdRequest extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PositionByIdRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PositionByIdRequest { - return new PositionByIdRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PositionByIdRequest { - return new PositionByIdRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PositionByIdRequest { - return new PositionByIdRequest().fromJsonString(jsonString, options); - } - - static equals(a: PositionByIdRequest | PlainMessage | undefined, b: PositionByIdRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PositionByIdRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PositionByIdResponse - */ -export class PositionByIdResponse extends Message { - /** - * @generated from field: osmosis.concentratedliquidity.v1beta1.FullPositionBreakdown position = 1; - */ - position?: FullPositionBreakdown; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PositionByIdResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position", kind: "message", T: FullPositionBreakdown }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PositionByIdResponse { - return new PositionByIdResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PositionByIdResponse { - return new PositionByIdResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PositionByIdResponse { - return new PositionByIdResponse().fromJsonString(jsonString, options); - } - - static equals(a: PositionByIdResponse | PlainMessage | undefined, b: PositionByIdResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PositionByIdResponse, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.NumPoolPositionsRequest - */ -export class NumPoolPositionsRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.NumPoolPositionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumPoolPositionsRequest { - return new NumPoolPositionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumPoolPositionsRequest { - return new NumPoolPositionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumPoolPositionsRequest { - return new NumPoolPositionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: NumPoolPositionsRequest | PlainMessage | undefined, b: NumPoolPositionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(NumPoolPositionsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.NumPoolPositionsResponse - */ -export class NumPoolPositionsResponse extends Message { - /** - * @generated from field: uint64 position_count = 1; - */ - positionCount = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.NumPoolPositionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_count", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumPoolPositionsResponse { - return new NumPoolPositionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumPoolPositionsResponse { - return new NumPoolPositionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumPoolPositionsResponse { - return new NumPoolPositionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: NumPoolPositionsResponse | PlainMessage | undefined, b: NumPoolPositionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(NumPoolPositionsResponse, a, b); - } -} - -/** - * =============================== Pools - * - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolsRequest - */ -export class PoolsRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolsRequest { - return new PoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolsRequest { - return new PoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolsRequest { - return new PoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: PoolsRequest | PlainMessage | undefined, b: PoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolsResponse - */ -export class PoolsResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolsResponse { - return new PoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolsResponse { - return new PoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolsResponse { - return new PoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: PoolsResponse | PlainMessage | undefined, b: PoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolsResponse, a, b); - } -} - -/** - * =============================== ModuleParams - * - * @generated from message osmosis.concentratedliquidity.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.concentratedliquidity.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.TickLiquidityNet - */ -export class TickLiquidityNet extends Message { - /** - * @generated from field: string liquidity_net = 1; - */ - liquidityNet = ""; - - /** - * @generated from field: int64 tick_index = 2; - */ - tickIndex = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.TickLiquidityNet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity_net", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "tick_index", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TickLiquidityNet { - return new TickLiquidityNet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TickLiquidityNet { - return new TickLiquidityNet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TickLiquidityNet { - return new TickLiquidityNet().fromJsonString(jsonString, options); - } - - static equals(a: TickLiquidityNet | PlainMessage | undefined, b: TickLiquidityNet | PlainMessage | undefined): boolean { - return proto3.util.equals(TickLiquidityNet, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.LiquidityDepthWithRange - */ -export class LiquidityDepthWithRange extends Message { - /** - * @generated from field: string liquidity_amount = 1; - */ - liquidityAmount = ""; - - /** - * @generated from field: int64 lower_tick = 2; - */ - lowerTick = protoInt64.zero; - - /** - * @generated from field: int64 upper_tick = 3; - */ - upperTick = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.LiquidityDepthWithRange"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lower_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "upper_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LiquidityDepthWithRange { - return new LiquidityDepthWithRange().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LiquidityDepthWithRange { - return new LiquidityDepthWithRange().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LiquidityDepthWithRange { - return new LiquidityDepthWithRange().fromJsonString(jsonString, options); - } - - static equals(a: LiquidityDepthWithRange | PlainMessage | undefined, b: LiquidityDepthWithRange | PlainMessage | undefined): boolean { - return proto3.util.equals(LiquidityDepthWithRange, a, b); - } -} - -/** - * =============================== LiquidityNetInDirection - * - * @generated from message osmosis.concentratedliquidity.v1beta1.LiquidityNetInDirectionRequest - */ -export class LiquidityNetInDirectionRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in = 2; - */ - tokenIn = ""; - - /** - * @generated from field: int64 start_tick = 3; - */ - startTick = protoInt64.zero; - - /** - * @generated from field: bool use_cur_tick = 4; - */ - useCurTick = false; - - /** - * @generated from field: int64 bound_tick = 5; - */ - boundTick = protoInt64.zero; - - /** - * @generated from field: bool use_no_bound = 6; - */ - useNoBound = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.LiquidityNetInDirectionRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "start_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: "use_cur_tick", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 5, name: "bound_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "use_no_bound", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LiquidityNetInDirectionRequest { - return new LiquidityNetInDirectionRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LiquidityNetInDirectionRequest { - return new LiquidityNetInDirectionRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LiquidityNetInDirectionRequest { - return new LiquidityNetInDirectionRequest().fromJsonString(jsonString, options); - } - - static equals(a: LiquidityNetInDirectionRequest | PlainMessage | undefined, b: LiquidityNetInDirectionRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(LiquidityNetInDirectionRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.LiquidityNetInDirectionResponse - */ -export class LiquidityNetInDirectionResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.TickLiquidityNet liquidity_depths = 1; - */ - liquidityDepths: TickLiquidityNet[] = []; - - /** - * @generated from field: int64 current_tick = 2; - */ - currentTick = protoInt64.zero; - - /** - * @generated from field: string current_liquidity = 3; - */ - currentLiquidity = ""; - - /** - * @generated from field: string current_sqrt_price = 4; - */ - currentSqrtPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.LiquidityNetInDirectionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity_depths", kind: "message", T: TickLiquidityNet, repeated: true }, - { no: 2, name: "current_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "current_liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "current_sqrt_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LiquidityNetInDirectionResponse { - return new LiquidityNetInDirectionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LiquidityNetInDirectionResponse { - return new LiquidityNetInDirectionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LiquidityNetInDirectionResponse { - return new LiquidityNetInDirectionResponse().fromJsonString(jsonString, options); - } - - static equals(a: LiquidityNetInDirectionResponse | PlainMessage | undefined, b: LiquidityNetInDirectionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(LiquidityNetInDirectionResponse, a, b); - } -} - -/** - * =============================== LiquidityPerTickRange - * - * @generated from message osmosis.concentratedliquidity.v1beta1.LiquidityPerTickRangeRequest - */ -export class LiquidityPerTickRangeRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.LiquidityPerTickRangeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LiquidityPerTickRangeRequest { - return new LiquidityPerTickRangeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LiquidityPerTickRangeRequest { - return new LiquidityPerTickRangeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LiquidityPerTickRangeRequest { - return new LiquidityPerTickRangeRequest().fromJsonString(jsonString, options); - } - - static equals(a: LiquidityPerTickRangeRequest | PlainMessage | undefined, b: LiquidityPerTickRangeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(LiquidityPerTickRangeRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.LiquidityPerTickRangeResponse - */ -export class LiquidityPerTickRangeResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.LiquidityDepthWithRange liquidity = 1; - */ - liquidity: LiquidityDepthWithRange[] = []; - - /** - * @generated from field: int64 bucket_index = 2; - */ - bucketIndex = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.LiquidityPerTickRangeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity", kind: "message", T: LiquidityDepthWithRange, repeated: true }, - { no: 2, name: "bucket_index", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LiquidityPerTickRangeResponse { - return new LiquidityPerTickRangeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LiquidityPerTickRangeResponse { - return new LiquidityPerTickRangeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LiquidityPerTickRangeResponse { - return new LiquidityPerTickRangeResponse().fromJsonString(jsonString, options); - } - - static equals(a: LiquidityPerTickRangeResponse | PlainMessage | undefined, b: LiquidityPerTickRangeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(LiquidityPerTickRangeResponse, a, b); - } -} - -/** - * ===================== QueryClaimableSpreadRewards - * - * @generated from message osmosis.concentratedliquidity.v1beta1.ClaimableSpreadRewardsRequest - */ -export class ClaimableSpreadRewardsRequest extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ClaimableSpreadRewardsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClaimableSpreadRewardsRequest { - return new ClaimableSpreadRewardsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClaimableSpreadRewardsRequest { - return new ClaimableSpreadRewardsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClaimableSpreadRewardsRequest { - return new ClaimableSpreadRewardsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ClaimableSpreadRewardsRequest | PlainMessage | undefined, b: ClaimableSpreadRewardsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ClaimableSpreadRewardsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.ClaimableSpreadRewardsResponse - */ -export class ClaimableSpreadRewardsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin claimable_spread_rewards = 1; - */ - claimableSpreadRewards: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ClaimableSpreadRewardsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "claimable_spread_rewards", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClaimableSpreadRewardsResponse { - return new ClaimableSpreadRewardsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClaimableSpreadRewardsResponse { - return new ClaimableSpreadRewardsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClaimableSpreadRewardsResponse { - return new ClaimableSpreadRewardsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ClaimableSpreadRewardsResponse | PlainMessage | undefined, b: ClaimableSpreadRewardsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ClaimableSpreadRewardsResponse, a, b); - } -} - -/** - * ===================== QueryClaimableIncentives - * - * @generated from message osmosis.concentratedliquidity.v1beta1.ClaimableIncentivesRequest - */ -export class ClaimableIncentivesRequest extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ClaimableIncentivesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClaimableIncentivesRequest { - return new ClaimableIncentivesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClaimableIncentivesRequest { - return new ClaimableIncentivesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClaimableIncentivesRequest { - return new ClaimableIncentivesRequest().fromJsonString(jsonString, options); - } - - static equals(a: ClaimableIncentivesRequest | PlainMessage | undefined, b: ClaimableIncentivesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ClaimableIncentivesRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.ClaimableIncentivesResponse - */ -export class ClaimableIncentivesResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin claimable_incentives = 1; - */ - claimableIncentives: Coin[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin forfeited_incentives = 2; - */ - forfeitedIncentives: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.ClaimableIncentivesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "claimable_incentives", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "forfeited_incentives", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ClaimableIncentivesResponse { - return new ClaimableIncentivesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ClaimableIncentivesResponse { - return new ClaimableIncentivesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ClaimableIncentivesResponse { - return new ClaimableIncentivesResponse().fromJsonString(jsonString, options); - } - - static equals(a: ClaimableIncentivesResponse | PlainMessage | undefined, b: ClaimableIncentivesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ClaimableIncentivesResponse, a, b); - } -} - -/** - * ===================== QueryPoolAccumulatorRewards - * - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolAccumulatorRewardsRequest - */ -export class PoolAccumulatorRewardsRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolAccumulatorRewardsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolAccumulatorRewardsRequest { - return new PoolAccumulatorRewardsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolAccumulatorRewardsRequest { - return new PoolAccumulatorRewardsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolAccumulatorRewardsRequest { - return new PoolAccumulatorRewardsRequest().fromJsonString(jsonString, options); - } - - static equals(a: PoolAccumulatorRewardsRequest | PlainMessage | undefined, b: PoolAccumulatorRewardsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolAccumulatorRewardsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.PoolAccumulatorRewardsResponse - */ -export class PoolAccumulatorRewardsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.DecCoin spread_reward_growth_global = 1; - */ - spreadRewardGrowthGlobal: DecCoin[] = []; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.UptimeTracker uptime_growth_global = 2; - */ - uptimeGrowthGlobal: UptimeTracker[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.PoolAccumulatorRewardsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spread_reward_growth_global", kind: "message", T: DecCoin, repeated: true }, - { no: 2, name: "uptime_growth_global", kind: "message", T: UptimeTracker, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolAccumulatorRewardsResponse { - return new PoolAccumulatorRewardsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolAccumulatorRewardsResponse { - return new PoolAccumulatorRewardsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolAccumulatorRewardsResponse { - return new PoolAccumulatorRewardsResponse().fromJsonString(jsonString, options); - } - - static equals(a: PoolAccumulatorRewardsResponse | PlainMessage | undefined, b: PoolAccumulatorRewardsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolAccumulatorRewardsResponse, a, b); - } -} - -/** - * ===================== QueryTickAccumulatorTrackers - * - * @generated from message osmosis.concentratedliquidity.v1beta1.TickAccumulatorTrackersRequest - */ -export class TickAccumulatorTrackersRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: int64 tick_index = 2; - */ - tickIndex = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.TickAccumulatorTrackersRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "tick_index", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TickAccumulatorTrackersRequest { - return new TickAccumulatorTrackersRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TickAccumulatorTrackersRequest { - return new TickAccumulatorTrackersRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TickAccumulatorTrackersRequest { - return new TickAccumulatorTrackersRequest().fromJsonString(jsonString, options); - } - - static equals(a: TickAccumulatorTrackersRequest | PlainMessage | undefined, b: TickAccumulatorTrackersRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TickAccumulatorTrackersRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.TickAccumulatorTrackersResponse - */ -export class TickAccumulatorTrackersResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.DecCoin spread_reward_growth_opposite_direction_of_last_traversal = 1; - */ - spreadRewardGrowthOppositeDirectionOfLastTraversal: DecCoin[] = []; - - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.UptimeTracker uptime_trackers = 2; - */ - uptimeTrackers: UptimeTracker[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.TickAccumulatorTrackersResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spread_reward_growth_opposite_direction_of_last_traversal", kind: "message", T: DecCoin, repeated: true }, - { no: 2, name: "uptime_trackers", kind: "message", T: UptimeTracker, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TickAccumulatorTrackersResponse { - return new TickAccumulatorTrackersResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TickAccumulatorTrackersResponse { - return new TickAccumulatorTrackersResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TickAccumulatorTrackersResponse { - return new TickAccumulatorTrackersResponse().fromJsonString(jsonString, options); - } - - static equals(a: TickAccumulatorTrackersResponse | PlainMessage | undefined, b: TickAccumulatorTrackersResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TickAccumulatorTrackersResponse, a, b); - } -} - -/** - * ===================== QueryIncentiveRecords - * - * @generated from message osmosis.concentratedliquidity.v1beta1.IncentiveRecordsRequest - */ -export class IncentiveRecordsRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.IncentiveRecordsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IncentiveRecordsRequest { - return new IncentiveRecordsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IncentiveRecordsRequest { - return new IncentiveRecordsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IncentiveRecordsRequest { - return new IncentiveRecordsRequest().fromJsonString(jsonString, options); - } - - static equals(a: IncentiveRecordsRequest | PlainMessage | undefined, b: IncentiveRecordsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(IncentiveRecordsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.IncentiveRecordsResponse - */ -export class IncentiveRecordsResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.IncentiveRecord incentive_records = 1; - */ - incentiveRecords: IncentiveRecord[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.IncentiveRecordsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "incentive_records", kind: "message", T: IncentiveRecord, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IncentiveRecordsResponse { - return new IncentiveRecordsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IncentiveRecordsResponse { - return new IncentiveRecordsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IncentiveRecordsResponse { - return new IncentiveRecordsResponse().fromJsonString(jsonString, options); - } - - static equals(a: IncentiveRecordsResponse | PlainMessage | undefined, b: IncentiveRecordsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(IncentiveRecordsResponse, a, b); - } -} - -/** - * =============================== CFMMPoolIdLinkFromConcentratedPoolId - * - * @generated from message osmosis.concentratedliquidity.v1beta1.CFMMPoolIdLinkFromConcentratedPoolIdRequest - */ -export class CFMMPoolIdLinkFromConcentratedPoolIdRequest extends Message { - /** - * @generated from field: uint64 concentrated_pool_id = 1; - */ - concentratedPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.CFMMPoolIdLinkFromConcentratedPoolIdRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "concentrated_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdRequest { - return new CFMMPoolIdLinkFromConcentratedPoolIdRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdRequest { - return new CFMMPoolIdLinkFromConcentratedPoolIdRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdRequest { - return new CFMMPoolIdLinkFromConcentratedPoolIdRequest().fromJsonString(jsonString, options); - } - - static equals(a: CFMMPoolIdLinkFromConcentratedPoolIdRequest | PlainMessage | undefined, b: CFMMPoolIdLinkFromConcentratedPoolIdRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(CFMMPoolIdLinkFromConcentratedPoolIdRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.CFMMPoolIdLinkFromConcentratedPoolIdResponse - */ -export class CFMMPoolIdLinkFromConcentratedPoolIdResponse extends Message { - /** - * @generated from field: uint64 cfmm_pool_id = 1; - */ - cfmmPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.CFMMPoolIdLinkFromConcentratedPoolIdResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cfmm_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdResponse { - return new CFMMPoolIdLinkFromConcentratedPoolIdResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdResponse { - return new CFMMPoolIdLinkFromConcentratedPoolIdResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CFMMPoolIdLinkFromConcentratedPoolIdResponse { - return new CFMMPoolIdLinkFromConcentratedPoolIdResponse().fromJsonString(jsonString, options); - } - - static equals(a: CFMMPoolIdLinkFromConcentratedPoolIdResponse | PlainMessage | undefined, b: CFMMPoolIdLinkFromConcentratedPoolIdResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(CFMMPoolIdLinkFromConcentratedPoolIdResponse, a, b); - } -} - -/** - * =============================== UserUnbondingPositions - * - * @generated from message osmosis.concentratedliquidity.v1beta1.UserUnbondingPositionsRequest - */ -export class UserUnbondingPositionsRequest extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UserUnbondingPositionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserUnbondingPositionsRequest { - return new UserUnbondingPositionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserUnbondingPositionsRequest { - return new UserUnbondingPositionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserUnbondingPositionsRequest { - return new UserUnbondingPositionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: UserUnbondingPositionsRequest | PlainMessage | undefined, b: UserUnbondingPositionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UserUnbondingPositionsRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.UserUnbondingPositionsResponse - */ -export class UserUnbondingPositionsResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.PositionWithPeriodLock positions_with_period_lock = 1; - */ - positionsWithPeriodLock: PositionWithPeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UserUnbondingPositionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "positions_with_period_lock", kind: "message", T: PositionWithPeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserUnbondingPositionsResponse { - return new UserUnbondingPositionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserUnbondingPositionsResponse { - return new UserUnbondingPositionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserUnbondingPositionsResponse { - return new UserUnbondingPositionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: UserUnbondingPositionsResponse | PlainMessage | undefined, b: UserUnbondingPositionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UserUnbondingPositionsResponse, a, b); - } -} - -/** - * =============================== GetTotalLiquidity - * - * @generated from message osmosis.concentratedliquidity.v1beta1.GetTotalLiquidityRequest - */ -export class GetTotalLiquidityRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.GetTotalLiquidityRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalLiquidityRequest { - return new GetTotalLiquidityRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalLiquidityRequest { - return new GetTotalLiquidityRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalLiquidityRequest { - return new GetTotalLiquidityRequest().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalLiquidityRequest | PlainMessage | undefined, b: GetTotalLiquidityRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalLiquidityRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.GetTotalLiquidityResponse - */ -export class GetTotalLiquidityResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin total_liquidity = 1; - */ - totalLiquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.GetTotalLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalLiquidityResponse { - return new GetTotalLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalLiquidityResponse { - return new GetTotalLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalLiquidityResponse { - return new GetTotalLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalLiquidityResponse | PlainMessage | undefined, b: GetTotalLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalLiquidityResponse, a, b); - } -} - -/** - * =============================== NumNextInitializedTicks - * - * @generated from message osmosis.concentratedliquidity.v1beta1.NumNextInitializedTicksRequest - */ -export class NumNextInitializedTicksRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in_denom = 2; - */ - tokenInDenom = ""; - - /** - * @generated from field: uint64 num_next_initialized_ticks = 3; - */ - numNextInitializedTicks = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.NumNextInitializedTicksRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "num_next_initialized_ticks", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumNextInitializedTicksRequest { - return new NumNextInitializedTicksRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumNextInitializedTicksRequest { - return new NumNextInitializedTicksRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumNextInitializedTicksRequest { - return new NumNextInitializedTicksRequest().fromJsonString(jsonString, options); - } - - static equals(a: NumNextInitializedTicksRequest | PlainMessage | undefined, b: NumNextInitializedTicksRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(NumNextInitializedTicksRequest, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.NumNextInitializedTicksResponse - */ -export class NumNextInitializedTicksResponse extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.TickLiquidityNet liquidity_depths = 1; - */ - liquidityDepths: TickLiquidityNet[] = []; - - /** - * @generated from field: int64 current_tick = 2; - */ - currentTick = protoInt64.zero; - - /** - * @generated from field: string current_liquidity = 3; - */ - currentLiquidity = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.NumNextInitializedTicksResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity_depths", kind: "message", T: TickLiquidityNet, repeated: true }, - { no: 2, name: "current_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "current_liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumNextInitializedTicksResponse { - return new NumNextInitializedTicksResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumNextInitializedTicksResponse { - return new NumNextInitializedTicksResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumNextInitializedTicksResponse { - return new NumNextInitializedTicksResponse().fromJsonString(jsonString, options); - } - - static equals(a: NumNextInitializedTicksResponse | PlainMessage | undefined, b: NumNextInitializedTicksResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(NumNextInitializedTicksResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tick_info_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tick_info_pb.ts deleted file mode 100644 index 4395280c4..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tick_info_pb.ts +++ /dev/null @@ -1,164 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/tick_info.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -// this is a legacy package that requires additional migration logic -// in order to use the correct package. Decision made to use legacy package path -// until clear steps for migration logic and the unknowns for state breaking are -// investigated for changing proto package. - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { DecCoin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.TickInfo - */ -export class TickInfo extends Message { - /** - * @generated from field: string liquidity_gross = 1; - */ - liquidityGross = ""; - - /** - * @generated from field: string liquidity_net = 2; - */ - liquidityNet = ""; - - /** - * Total spread rewards accumulated in the opposite direction that the tick - * was last crossed. i.e. if the current tick is to the right of this tick - * (meaning its currently a greater price), then this is the total spread - * rewards accumulated below the tick. If the current tick is to the left of - * this tick (meaning its currently at a lower price), then this is the total - * spread rewards accumulated above the tick. - * - * Note: the way this value is used depends on the direction of spread rewards - * we are calculating for. If we are calculating spread rewards below the - * lower tick and the lower tick is the active tick, then this is the - * spreadRewardGrowthGlobal - the lower tick's - * spreadRewardGrowthOppositeDirectionOfLastTraversal. If we are calculating - * spread rewards above the upper tick and the upper tick is the active tick, - * then this is just the tick's - * spreadRewardGrowthOppositeDirectionOfLastTraversal value. - * - * @generated from field: repeated cosmos.base.v1beta1.DecCoin spread_reward_growth_opposite_direction_of_last_traversal = 3; - */ - spreadRewardGrowthOppositeDirectionOfLastTraversal: DecCoin[] = []; - - /** - * uptime_trackers is a container encapsulating the uptime trackers. - * We use a container instead of a "repeated UptimeTracker" directly - * because we need the ability to serialize and deserialize the - * container easily for events when crossing a tick. - * - * @generated from field: osmosis.concentratedliquidity.v1beta1.UptimeTrackers uptime_trackers = 4; - */ - uptimeTrackers?: UptimeTrackers; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.TickInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity_gross", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "liquidity_net", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "spread_reward_growth_opposite_direction_of_last_traversal", kind: "message", T: DecCoin, repeated: true }, - { no: 4, name: "uptime_trackers", kind: "message", T: UptimeTrackers }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TickInfo { - return new TickInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TickInfo { - return new TickInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TickInfo { - return new TickInfo().fromJsonString(jsonString, options); - } - - static equals(a: TickInfo | PlainMessage | undefined, b: TickInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(TickInfo, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.UptimeTrackers - */ -export class UptimeTrackers extends Message { - /** - * @generated from field: repeated osmosis.concentratedliquidity.v1beta1.UptimeTracker list = 1; - */ - list: UptimeTracker[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UptimeTrackers"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "list", kind: "message", T: UptimeTracker, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UptimeTrackers { - return new UptimeTrackers().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UptimeTrackers { - return new UptimeTrackers().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UptimeTrackers { - return new UptimeTrackers().fromJsonString(jsonString, options); - } - - static equals(a: UptimeTrackers | PlainMessage | undefined, b: UptimeTrackers | PlainMessage | undefined): boolean { - return proto3.util.equals(UptimeTrackers, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.UptimeTracker - */ -export class UptimeTracker extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.DecCoin uptime_growth_outside = 1; - */ - uptimeGrowthOutside: DecCoin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.UptimeTracker"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "uptime_growth_outside", kind: "message", T: DecCoin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UptimeTracker { - return new UptimeTracker().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UptimeTracker { - return new UptimeTracker().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UptimeTracker { - return new UptimeTracker().fromJsonString(jsonString, options); - } - - static equals(a: UptimeTracker | PlainMessage | undefined, b: UptimeTracker | PlainMessage | undefined): boolean { - return proto3.util.equals(UptimeTracker, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_cosmes.ts deleted file mode 100644 index c1ce1ea28..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,78 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/tx.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddToPosition, MsgAddToPositionResponse, MsgCollectIncentives, MsgCollectIncentivesResponse, MsgCollectSpreadRewards, MsgCollectSpreadRewardsResponse, MsgCreatePosition, MsgCreatePositionResponse, MsgTransferPositions, MsgTransferPositionsResponse, MsgWithdrawPosition, MsgWithdrawPositionResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.concentratedliquidity.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.CreatePosition - */ -export const MsgCreatePositionService = { - typeName: TYPE_NAME, - method: "CreatePosition", - Request: MsgCreatePosition, - Response: MsgCreatePositionResponse, -} as const; - -/** - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.WithdrawPosition - */ -export const MsgWithdrawPositionService = { - typeName: TYPE_NAME, - method: "WithdrawPosition", - Request: MsgWithdrawPosition, - Response: MsgWithdrawPositionResponse, -} as const; - -/** - * AddToPosition attempts to add amount0 and amount1 to a position - * with the given position id. - * To maintain backwards-compatibility with future implementations of - * charging, this function deletes the old position and creates a new one with - * the resulting amount after addition. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.AddToPosition - */ -export const MsgAddToPositionService = { - typeName: TYPE_NAME, - method: "AddToPosition", - Request: MsgAddToPosition, - Response: MsgAddToPositionResponse, -} as const; - -/** - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.CollectSpreadRewards - */ -export const MsgCollectSpreadRewardsService = { - typeName: TYPE_NAME, - method: "CollectSpreadRewards", - Request: MsgCollectSpreadRewards, - Response: MsgCollectSpreadRewardsResponse, -} as const; - -/** - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.CollectIncentives - */ -export const MsgCollectIncentivesService = { - typeName: TYPE_NAME, - method: "CollectIncentives", - Request: MsgCollectIncentives, - Response: MsgCollectIncentivesResponse, -} as const; - -/** - * TransferPositions transfers ownership of a set of one or more positions - * from a sender to a recipient. - * - * @generated from rpc osmosis.concentratedliquidity.v1beta1.Msg.TransferPositions - */ -export const MsgTransferPositionsService = { - typeName: TYPE_NAME, - method: "TransferPositions", - Request: MsgTransferPositions, - Response: MsgTransferPositionsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_pb.ts deleted file mode 100644 index 0efcf911d..000000000 --- a/packages/es/src/protobufs/osmosis/concentratedliquidity/v1beta1/tx_pb.ts +++ /dev/null @@ -1,721 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/concentratedliquidity/v1beta1/tx.proto (package osmosis.concentratedliquidity.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== MsgCreatePosition - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCreatePosition - */ -export class MsgCreatePosition extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * @generated from field: int64 lower_tick = 3; - */ - lowerTick = protoInt64.zero; - - /** - * @generated from field: int64 upper_tick = 4; - */ - upperTick = protoInt64.zero; - - /** - * tokens_provided is the amount of tokens provided for the position. - * It must at a minimum be of length 1 (for a single sided position) - * and at a maximum be of length 2 (for a position that straddles the current - * tick). - * - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_provided = 5; - */ - tokensProvided: Coin[] = []; - - /** - * @generated from field: string token_min_amount0 = 6; - */ - tokenMinAmount0 = ""; - - /** - * @generated from field: string token_min_amount1 = 7; - */ - tokenMinAmount1 = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCreatePosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "lower_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: "upper_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "tokens_provided", kind: "message", T: Coin, repeated: true }, - { no: 6, name: "token_min_amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "token_min_amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreatePosition { - return new MsgCreatePosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreatePosition { - return new MsgCreatePosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreatePosition { - return new MsgCreatePosition().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreatePosition | PlainMessage | undefined, b: MsgCreatePosition | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreatePosition, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCreatePositionResponse - */ -export class MsgCreatePositionResponse extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string amount0 = 2; - */ - amount0 = ""; - - /** - * @generated from field: string amount1 = 3; - */ - amount1 = ""; - - /** - * @generated from field: string liquidity_created = 5; - */ - liquidityCreated = ""; - - /** - * the lower and upper tick are in the response because there are - * instances in which multiple ticks represent the same price, so - * we may move their provided tick to the canonical tick that represents - * the same price. - * - * @generated from field: int64 lower_tick = 6; - */ - lowerTick = protoInt64.zero; - - /** - * @generated from field: int64 upper_tick = 7; - */ - upperTick = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCreatePositionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "liquidity_created", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "lower_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "upper_tick", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreatePositionResponse { - return new MsgCreatePositionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreatePositionResponse { - return new MsgCreatePositionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreatePositionResponse { - return new MsgCreatePositionResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreatePositionResponse | PlainMessage | undefined, b: MsgCreatePositionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreatePositionResponse, a, b); - } -} - -/** - * ===================== MsgAddToPosition - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgAddToPosition - */ -export class MsgAddToPosition extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * amount0 represents the amount of token0 willing to put in. - * - * @generated from field: string amount0 = 3; - */ - amount0 = ""; - - /** - * amount1 represents the amount of token1 willing to put in. - * - * @generated from field: string amount1 = 4; - */ - amount1 = ""; - - /** - * token_min_amount0 represents the minimum amount of token0 desired from the - * new position being created. Note that this field indicates the min amount0 - * corresponding to the liquidity that is being added, not the total - * liquidity of the position. - * - * @generated from field: string token_min_amount0 = 5; - */ - tokenMinAmount0 = ""; - - /** - * token_min_amount1 represents the minimum amount of token1 desired from the - * new position being created. Note that this field indicates the min amount1 - * corresponding to the liquidity that is being added, not the total - * liquidity of the position. - * - * @generated from field: string token_min_amount1 = 6; - */ - tokenMinAmount1 = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgAddToPosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "token_min_amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "token_min_amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToPosition { - return new MsgAddToPosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToPosition { - return new MsgAddToPosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToPosition { - return new MsgAddToPosition().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToPosition | PlainMessage | undefined, b: MsgAddToPosition | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToPosition, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgAddToPositionResponse - */ -export class MsgAddToPositionResponse extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string amount0 = 2; - */ - amount0 = ""; - - /** - * @generated from field: string amount1 = 3; - */ - amount1 = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgAddToPositionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToPositionResponse { - return new MsgAddToPositionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToPositionResponse { - return new MsgAddToPositionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToPositionResponse { - return new MsgAddToPositionResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToPositionResponse | PlainMessage | undefined, b: MsgAddToPositionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToPositionResponse, a, b); - } -} - -/** - * ===================== MsgWithdrawPosition - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgWithdrawPosition - */ -export class MsgWithdrawPosition extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * @generated from field: string liquidity_amount = 3; - */ - liquidityAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgWithdrawPosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "liquidity_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgWithdrawPosition { - return new MsgWithdrawPosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgWithdrawPosition { - return new MsgWithdrawPosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgWithdrawPosition { - return new MsgWithdrawPosition().fromJsonString(jsonString, options); - } - - static equals(a: MsgWithdrawPosition | PlainMessage | undefined, b: MsgWithdrawPosition | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgWithdrawPosition, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgWithdrawPositionResponse - */ -export class MsgWithdrawPositionResponse extends Message { - /** - * @generated from field: string amount0 = 1; - */ - amount0 = ""; - - /** - * @generated from field: string amount1 = 2; - */ - amount1 = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgWithdrawPositionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgWithdrawPositionResponse { - return new MsgWithdrawPositionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgWithdrawPositionResponse { - return new MsgWithdrawPositionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgWithdrawPositionResponse { - return new MsgWithdrawPositionResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgWithdrawPositionResponse | PlainMessage | undefined, b: MsgWithdrawPositionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgWithdrawPositionResponse, a, b); - } -} - -/** - * ===================== MsgCollectSpreadRewards - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCollectSpreadRewards - */ -export class MsgCollectSpreadRewards extends Message { - /** - * @generated from field: repeated uint64 position_ids = 1; - */ - positionIds: bigint[] = []; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCollectSpreadRewards"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCollectSpreadRewards { - return new MsgCollectSpreadRewards().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCollectSpreadRewards { - return new MsgCollectSpreadRewards().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCollectSpreadRewards { - return new MsgCollectSpreadRewards().fromJsonString(jsonString, options); - } - - static equals(a: MsgCollectSpreadRewards | PlainMessage | undefined, b: MsgCollectSpreadRewards | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCollectSpreadRewards, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCollectSpreadRewardsResponse - */ -export class MsgCollectSpreadRewardsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin collected_spread_rewards = 1; - */ - collectedSpreadRewards: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCollectSpreadRewardsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "collected_spread_rewards", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCollectSpreadRewardsResponse { - return new MsgCollectSpreadRewardsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCollectSpreadRewardsResponse { - return new MsgCollectSpreadRewardsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCollectSpreadRewardsResponse { - return new MsgCollectSpreadRewardsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCollectSpreadRewardsResponse | PlainMessage | undefined, b: MsgCollectSpreadRewardsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCollectSpreadRewardsResponse, a, b); - } -} - -/** - * ===================== MsgCollectIncentives - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCollectIncentives - */ -export class MsgCollectIncentives extends Message { - /** - * @generated from field: repeated uint64 position_ids = 1; - */ - positionIds: bigint[] = []; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCollectIncentives"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCollectIncentives { - return new MsgCollectIncentives().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCollectIncentives { - return new MsgCollectIncentives().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCollectIncentives { - return new MsgCollectIncentives().fromJsonString(jsonString, options); - } - - static equals(a: MsgCollectIncentives | PlainMessage | undefined, b: MsgCollectIncentives | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCollectIncentives, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgCollectIncentivesResponse - */ -export class MsgCollectIncentivesResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin collected_incentives = 1; - */ - collectedIncentives: Coin[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin forfeited_incentives = 2; - */ - forfeitedIncentives: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgCollectIncentivesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "collected_incentives", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "forfeited_incentives", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCollectIncentivesResponse { - return new MsgCollectIncentivesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCollectIncentivesResponse { - return new MsgCollectIncentivesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCollectIncentivesResponse { - return new MsgCollectIncentivesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCollectIncentivesResponse | PlainMessage | undefined, b: MsgCollectIncentivesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCollectIncentivesResponse, a, b); - } -} - -/** - * ===================== MsgFungifyChargedPositions - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgFungifyChargedPositions - */ -export class MsgFungifyChargedPositions extends Message { - /** - * @generated from field: repeated uint64 position_ids = 1; - */ - positionIds: bigint[] = []; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgFungifyChargedPositions"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgFungifyChargedPositions { - return new MsgFungifyChargedPositions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgFungifyChargedPositions { - return new MsgFungifyChargedPositions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgFungifyChargedPositions { - return new MsgFungifyChargedPositions().fromJsonString(jsonString, options); - } - - static equals(a: MsgFungifyChargedPositions | PlainMessage | undefined, b: MsgFungifyChargedPositions | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgFungifyChargedPositions, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgFungifyChargedPositionsResponse - */ -export class MsgFungifyChargedPositionsResponse extends Message { - /** - * @generated from field: uint64 new_position_id = 1; - */ - newPositionId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgFungifyChargedPositionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "new_position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgFungifyChargedPositionsResponse { - return new MsgFungifyChargedPositionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgFungifyChargedPositionsResponse { - return new MsgFungifyChargedPositionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgFungifyChargedPositionsResponse { - return new MsgFungifyChargedPositionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgFungifyChargedPositionsResponse | PlainMessage | undefined, b: MsgFungifyChargedPositionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgFungifyChargedPositionsResponse, a, b); - } -} - -/** - * ===================== MsgTransferPositions - * - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgTransferPositions - */ -export class MsgTransferPositions extends Message { - /** - * @generated from field: repeated uint64 position_ids = 1; - */ - positionIds: bigint[] = []; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * @generated from field: string new_owner = 3; - */ - newOwner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgTransferPositions"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "new_owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTransferPositions { - return new MsgTransferPositions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTransferPositions { - return new MsgTransferPositions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTransferPositions { - return new MsgTransferPositions().fromJsonString(jsonString, options); - } - - static equals(a: MsgTransferPositions | PlainMessage | undefined, b: MsgTransferPositions | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTransferPositions, a, b); - } -} - -/** - * @generated from message osmosis.concentratedliquidity.v1beta1.MsgTransferPositionsResponse - */ -export class MsgTransferPositionsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.concentratedliquidity.v1beta1.MsgTransferPositionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgTransferPositionsResponse { - return new MsgTransferPositionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgTransferPositionsResponse { - return new MsgTransferPositionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgTransferPositionsResponse { - return new MsgTransferPositionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgTransferPositionsResponse | PlainMessage | undefined, b: MsgTransferPositionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgTransferPositionsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/genesis_pb.ts deleted file mode 100644 index 516a016df..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/genesis.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; - -/** - * GenesisState defines the cosmwasmpool module's genesis state. - * - * @generated from message osmosis.cosmwasmpool.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params is the container of cosmwasmpool parameters. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.Params params = 1; - */ - params?: Params; - - /** - * @generated from field: repeated google.protobuf.Any pools = 2; - */ - pools: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "pools", kind: "message", T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/gov_pb.ts deleted file mode 100644 index 45aa8d420..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/gov_pb.ts +++ /dev/null @@ -1,171 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/gov.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * UploadCosmWasmPoolCodeAndWhiteListProposal is a gov Content type for - * uploading coswasm pool code and adding it to internal whitelist. Only the - * code ids created by this message are eligible for being x/cosmwasmpool pools. - * - * @generated from message osmosis.cosmwasmpool.v1beta1.UploadCosmWasmPoolCodeAndWhiteListProposal - */ -export class UploadCosmWasmPoolCodeAndWhiteListProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * WASMByteCode can be raw or gzip compressed - * - * @generated from field: bytes wasm_byte_code = 3; - */ - wasmByteCode = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.UploadCosmWasmPoolCodeAndWhiteListProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UploadCosmWasmPoolCodeAndWhiteListProposal { - return new UploadCosmWasmPoolCodeAndWhiteListProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UploadCosmWasmPoolCodeAndWhiteListProposal { - return new UploadCosmWasmPoolCodeAndWhiteListProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UploadCosmWasmPoolCodeAndWhiteListProposal { - return new UploadCosmWasmPoolCodeAndWhiteListProposal().fromJsonString(jsonString, options); - } - - static equals(a: UploadCosmWasmPoolCodeAndWhiteListProposal | PlainMessage | undefined, b: UploadCosmWasmPoolCodeAndWhiteListProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UploadCosmWasmPoolCodeAndWhiteListProposal, a, b); - } -} - -/** - * MigratePoolContractsProposal is a gov Content type for - * migrating given pools to the new contract code and adding to internal - * whitelist if needed. It has two options to perform the migration: - * - * 1. If the codeID is non-zero, it will migrate the pool contracts to a given - * codeID assuming that it has already been uploaded. uploadByteCode must be - * empty in such a case. Fails if codeID does not exist. Fails if uploadByteCode - * is not empty. - * - * 2. If the codeID is zero, it will upload the given uploadByteCode and use the - * new resulting code id to migrate the pool to. Errors if uploadByteCode is - * empty or invalid. - * - * In both cases, if one of the pools specified by the given poolID does not - * exist, the proposal fails. - * - * The reason for having poolIDs be a slice of ids is to account for the - * potential need for emergency migration of all old code ids associated with - * particular pools to new code ids, or simply having the flexibility of - * migrating multiple older pool contracts to a new one at once when there is a - * release. - * - * poolD count to be submitted at once is gated by a governance paramets (20 at - * launch). The proposal fails if more. Note that 20 was chosen arbitrarily to - * have a constant bound on the number of pools migrated at once. This size will - * be configured by a module parameter so it can be changed by a constant. - * - * @generated from message osmosis.cosmwasmpool.v1beta1.MigratePoolContractsProposal - */ -export class MigratePoolContractsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * pool_ids are the pool ids of the contracts to be migrated - * either to the new_code_id that is already uploaded to chain or to - * the given wasm_byte_code. - * - * @generated from field: repeated uint64 pool_ids = 3; - */ - poolIds: bigint[] = []; - - /** - * new_code_id is the code id of the contract code to migrate to. - * Assumes that the code is already uploaded to chain. Only one of - * new_code_id and wasm_byte_code should be set. - * - * @generated from field: uint64 new_code_id = 4; - */ - newCodeId = protoInt64.zero; - - /** - * WASMByteCode can be raw or gzip compressed. Assumes that the code id - * has not been uploaded yet so uploads the given code and migrates to it. - * Only one of new_code_id and wasm_byte_code should be set. - * - * @generated from field: bytes wasm_byte_code = 5; - */ - wasmByteCode = new Uint8Array(0); - - /** - * MigrateMsg migrate message to be used for migrating the pool contracts. - * - * @generated from field: bytes migrate_msg = 6; - */ - migrateMsg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.MigratePoolContractsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 4, name: "new_code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "wasm_byte_code", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 6, name: "migrate_msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MigratePoolContractsProposal { - return new MigratePoolContractsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MigratePoolContractsProposal { - return new MigratePoolContractsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MigratePoolContractsProposal { - return new MigratePoolContractsProposal().fromJsonString(jsonString, options); - } - - static equals(a: MigratePoolContractsProposal | PlainMessage | undefined, b: MigratePoolContractsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(MigratePoolContractsProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/instantiate_msg_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/instantiate_msg_pb.ts deleted file mode 100644 index 221a918e6..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/instantiate_msg_pb.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/instantiate_msg.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * ===================== InstantiateMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.InstantiateMsg - */ -export class InstantiateMsg extends Message { - /** - * pool_asset_denoms is the list of asset denoms that are initialized - * at pool creation time. - * - * @generated from field: repeated string pool_asset_denoms = 1; - */ - poolAssetDenoms: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.InstantiateMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_asset_denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InstantiateMsg { - return new InstantiateMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InstantiateMsg { - return new InstantiateMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InstantiateMsg { - return new InstantiateMsg().fromJsonString(jsonString, options); - } - - static equals(a: InstantiateMsg | PlainMessage | undefined, b: InstantiateMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(InstantiateMsg, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_query_msg_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_query_msg_pb.ts deleted file mode 100644 index 89b746288..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_query_msg_pb.ts +++ /dev/null @@ -1,281 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/module_query_msg.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== CalcOutAmtGivenIn - * - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenIn - */ -export class CalcOutAmtGivenIn extends Message { - /** - * token_in is the token to be sent to the pool. - * - * @generated from field: cosmos.base.v1beta1.Coin token_in = 1; - */ - tokenIn?: Coin; - - /** - * token_out_denom is the token denom to be received from the pool. - * - * @generated from field: string token_out_denom = 2; - */ - tokenOutDenom = ""; - - /** - * swap_fee is the swap fee for this swap estimate. - * - * @generated from field: string swap_fee = 3; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in", kind: "message", T: Coin }, - { no: 2, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcOutAmtGivenIn { - return new CalcOutAmtGivenIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcOutAmtGivenIn { - return new CalcOutAmtGivenIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcOutAmtGivenIn { - return new CalcOutAmtGivenIn().fromJsonString(jsonString, options); - } - - static equals(a: CalcOutAmtGivenIn | PlainMessage | undefined, b: CalcOutAmtGivenIn | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcOutAmtGivenIn, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenInRequest - */ -export class CalcOutAmtGivenInRequest extends Message { - /** - * calc_out_amt_given_in is the structure containing all the request - * information for this query. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenIn calc_out_amt_given_in = 1; - */ - calcOutAmtGivenIn?: CalcOutAmtGivenIn; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenInRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "calc_out_amt_given_in", kind: "message", T: CalcOutAmtGivenIn }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcOutAmtGivenInRequest { - return new CalcOutAmtGivenInRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcOutAmtGivenInRequest { - return new CalcOutAmtGivenInRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcOutAmtGivenInRequest { - return new CalcOutAmtGivenInRequest().fromJsonString(jsonString, options); - } - - static equals(a: CalcOutAmtGivenInRequest | PlainMessage | undefined, b: CalcOutAmtGivenInRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcOutAmtGivenInRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenInResponse - */ -export class CalcOutAmtGivenInResponse extends Message { - /** - * token_out is the token out computed from this swap estimate call. - * - * @generated from field: cosmos.base.v1beta1.Coin token_out = 1; - */ - tokenOut?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcOutAmtGivenInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcOutAmtGivenInResponse { - return new CalcOutAmtGivenInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcOutAmtGivenInResponse { - return new CalcOutAmtGivenInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcOutAmtGivenInResponse { - return new CalcOutAmtGivenInResponse().fromJsonString(jsonString, options); - } - - static equals(a: CalcOutAmtGivenInResponse | PlainMessage | undefined, b: CalcOutAmtGivenInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcOutAmtGivenInResponse, a, b); - } -} - -/** - * ===================== CalcInAmtGivenOut - * - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOut - */ -export class CalcInAmtGivenOut extends Message { - /** - * token_out is the token out to be receoved from the pool. - * - * @generated from field: cosmos.base.v1beta1.Coin token_out = 1; - */ - tokenOut?: Coin; - - /** - * token_in_denom is the token denom to be sentt to the pool. - * - * @generated from field: string token_in_denom = 2; - */ - tokenInDenom = ""; - - /** - * swap_fee is the swap fee for this swap estimate. - * - * @generated from field: string swap_fee = 3; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out", kind: "message", T: Coin }, - { no: 2, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcInAmtGivenOut { - return new CalcInAmtGivenOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcInAmtGivenOut { - return new CalcInAmtGivenOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcInAmtGivenOut { - return new CalcInAmtGivenOut().fromJsonString(jsonString, options); - } - - static equals(a: CalcInAmtGivenOut | PlainMessage | undefined, b: CalcInAmtGivenOut | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcInAmtGivenOut, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOutRequest - */ -export class CalcInAmtGivenOutRequest extends Message { - /** - * calc_in_amt_given_out is the structure containing all the request - * information for this query. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOut calc_in_amt_given_out = 1; - */ - calcInAmtGivenOut?: CalcInAmtGivenOut; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOutRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "calc_in_amt_given_out", kind: "message", T: CalcInAmtGivenOut }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcInAmtGivenOutRequest { - return new CalcInAmtGivenOutRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcInAmtGivenOutRequest { - return new CalcInAmtGivenOutRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcInAmtGivenOutRequest { - return new CalcInAmtGivenOutRequest().fromJsonString(jsonString, options); - } - - static equals(a: CalcInAmtGivenOutRequest | PlainMessage | undefined, b: CalcInAmtGivenOutRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcInAmtGivenOutRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOutResponse - */ -export class CalcInAmtGivenOutResponse extends Message { - /** - * token_in is the token in computed from this swap estimate call. - * - * @generated from field: cosmos.base.v1beta1.Coin token_in = 1; - */ - tokenIn?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CalcInAmtGivenOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CalcInAmtGivenOutResponse { - return new CalcInAmtGivenOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CalcInAmtGivenOutResponse { - return new CalcInAmtGivenOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CalcInAmtGivenOutResponse { - return new CalcInAmtGivenOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: CalcInAmtGivenOutResponse | PlainMessage | undefined, b: CalcInAmtGivenOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(CalcInAmtGivenOutResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg_pb.ts deleted file mode 100644 index 9423ed26c..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg_pb.ts +++ /dev/null @@ -1,311 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/module_sudo_msg.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== SwapExactAmountIn - * - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountIn - */ -export class SwapExactAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * token_in is the token to be sent to the pool. - * - * @generated from field: cosmos.base.v1beta1.Coin token_in = 2; - */ - tokenIn?: Coin; - - /** - * token_out_denom is the token denom to be received from the pool. - * - * @generated from field: string token_out_denom = 3; - */ - tokenOutDenom = ""; - - /** - * token_out_min_amount is the minimum amount of token_out to be received from - * the pool. - * - * @generated from field: string token_out_min_amount = 4; - */ - tokenOutMinAmount = ""; - - /** - * swap_fee is the swap fee for this swap estimate. - * - * @generated from field: string swap_fee = 5; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "token_in", kind: "message", T: Coin }, - { no: 3, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountIn { - return new SwapExactAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountIn { - return new SwapExactAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountIn { - return new SwapExactAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountIn | PlainMessage | undefined, b: SwapExactAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountInSudoMsg - */ -export class SwapExactAmountInSudoMsg extends Message { - /** - * swap_exact_amount_in is the structure containing all the request - * information for this message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.SwapExactAmountIn swap_exact_amount_in = 1; - */ - swapExactAmountIn?: SwapExactAmountIn; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountInSudoMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "swap_exact_amount_in", kind: "message", T: SwapExactAmountIn }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountInSudoMsg { - return new SwapExactAmountInSudoMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountInSudoMsg { - return new SwapExactAmountInSudoMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountInSudoMsg { - return new SwapExactAmountInSudoMsg().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountInSudoMsg | PlainMessage | undefined, b: SwapExactAmountInSudoMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountInSudoMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountInSudoMsgResponse - */ -export class SwapExactAmountInSudoMsgResponse extends Message { - /** - * token_out_amount is the token out computed from this swap estimate call. - * - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountInSudoMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountInSudoMsgResponse { - return new SwapExactAmountInSudoMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountInSudoMsgResponse { - return new SwapExactAmountInSudoMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountInSudoMsgResponse { - return new SwapExactAmountInSudoMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountInSudoMsgResponse | PlainMessage | undefined, b: SwapExactAmountInSudoMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountInSudoMsgResponse, a, b); - } -} - -/** - * ===================== SwapExactAmountOut - * - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountOut - */ -export class SwapExactAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * token_out is the token to be sent out of the pool. - * - * @generated from field: cosmos.base.v1beta1.Coin token_out = 2; - */ - tokenOut?: Coin; - - /** - * token_in_denom is the token denom to be sent too the pool. - * - * @generated from field: string token_in_denom = 3; - */ - tokenInDenom = ""; - - /** - * token_in_max_amount is the maximum amount of token_in to be sent to the - * pool. - * - * @generated from field: string token_in_max_amount = 4; - */ - tokenInMaxAmount = ""; - - /** - * swap_fee is the swap fee for this swap estimate. - * - * @generated from field: string swap_fee = 5; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "token_out", kind: "message", T: Coin }, - { no: 3, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountOut { - return new SwapExactAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountOut { - return new SwapExactAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountOut { - return new SwapExactAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountOut | PlainMessage | undefined, b: SwapExactAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountOutSudoMsg - */ -export class SwapExactAmountOutSudoMsg extends Message { - /** - * swap_exact_amount_out is the structure containing all the request - * information for this message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.SwapExactAmountOut swap_exact_amount_out = 1; - */ - swapExactAmountOut?: SwapExactAmountOut; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountOutSudoMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "swap_exact_amount_out", kind: "message", T: SwapExactAmountOut }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountOutSudoMsg { - return new SwapExactAmountOutSudoMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountOutSudoMsg { - return new SwapExactAmountOutSudoMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountOutSudoMsg { - return new SwapExactAmountOutSudoMsg().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountOutSudoMsg | PlainMessage | undefined, b: SwapExactAmountOutSudoMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountOutSudoMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SwapExactAmountOutSudoMsgResponse - */ -export class SwapExactAmountOutSudoMsgResponse extends Message { - /** - * token_in_amount is the token in computed from this swap estimate call. - * - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SwapExactAmountOutSudoMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapExactAmountOutSudoMsgResponse { - return new SwapExactAmountOutSudoMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapExactAmountOutSudoMsgResponse { - return new SwapExactAmountOutSudoMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapExactAmountOutSudoMsgResponse { - return new SwapExactAmountOutSudoMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: SwapExactAmountOutSudoMsgResponse | PlainMessage | undefined, b: SwapExactAmountOutSudoMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapExactAmountOutSudoMsgResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_pb.ts deleted file mode 100644 index 04a7b1eac..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_pb.ts +++ /dev/null @@ -1,80 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/pool.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * CosmWasmPool represents the data serialized into state for each CW pool. - * - * Note: CW Pool has 2 pool models: - * - CosmWasmPool which is a proto-generated store model used for serialization - * into state. - * - Pool struct that encapsulates the CosmWasmPool and wasmKeeper for calling - * the contract. - * - * CosmWasmPool implements the poolmanager.PoolI interface but it panics on all - * methods. The reason is that access to wasmKeeper is required to call the - * contract. - * - * Instead, all interactions and poolmanager.PoolI methods are to be performed - * on the Pool struct. The reason why we cannot have a Pool struct only is - * because it cannot be serialized into state due to having a non-serializable - * wasmKeeper field. - * - * @generated from message osmosis.cosmwasmpool.v1beta1.CosmWasmPool - */ -export class CosmWasmPool extends Message { - /** - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: uint64 code_id = 3; - */ - codeId = protoInt64.zero; - - /** - * @generated from field: bytes instantiate_msg = 4; - */ - instantiateMsg = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.CosmWasmPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "instantiate_msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CosmWasmPool { - return new CosmWasmPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CosmWasmPool { - return new CosmWasmPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CosmWasmPool { - return new CosmWasmPool().fromJsonString(jsonString, options); - } - - static equals(a: CosmWasmPool | PlainMessage | undefined, b: CosmWasmPool | PlainMessage | undefined): boolean { - return proto3.util.equals(CosmWasmPool, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_query_msg_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_query_msg_pb.ts deleted file mode 100644 index 81183b89b..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/pool_query_msg_pb.ts +++ /dev/null @@ -1,411 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/pool_query_msg.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== GetSwapFeeQueryMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.GetSwapFeeQueryMsg - */ -export class GetSwapFeeQueryMsg extends Message { - /** - * get_swap_fee is the query structure to get swap fee. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.EmptyStruct get_swap_fee = 1; - */ - getSwapFee?: EmptyStruct; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetSwapFeeQueryMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "get_swap_fee", kind: "message", T: EmptyStruct }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetSwapFeeQueryMsg { - return new GetSwapFeeQueryMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetSwapFeeQueryMsg { - return new GetSwapFeeQueryMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetSwapFeeQueryMsg { - return new GetSwapFeeQueryMsg().fromJsonString(jsonString, options); - } - - static equals(a: GetSwapFeeQueryMsg | PlainMessage | undefined, b: GetSwapFeeQueryMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(GetSwapFeeQueryMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.GetSwapFeeQueryMsgResponse - */ -export class GetSwapFeeQueryMsgResponse extends Message { - /** - * swap_fee is the swap fee for this swap estimate. - * - * @generated from field: string swap_fee = 3; - */ - swapFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetSwapFeeQueryMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 3, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetSwapFeeQueryMsgResponse { - return new GetSwapFeeQueryMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetSwapFeeQueryMsgResponse { - return new GetSwapFeeQueryMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetSwapFeeQueryMsgResponse { - return new GetSwapFeeQueryMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetSwapFeeQueryMsgResponse | PlainMessage | undefined, b: GetSwapFeeQueryMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetSwapFeeQueryMsgResponse, a, b); - } -} - -/** - * ===================== SpotPriceQueryMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.SpotPrice - */ -export class SpotPrice extends Message { - /** - * quote_asset_denom is the quote asset of the spot query. - * - * @generated from field: string quote_asset_denom = 1; - */ - quoteAssetDenom = ""; - - /** - * base_asset_denom is the base asset of the spot query. - * - * @generated from field: string base_asset_denom = 2; - */ - baseAssetDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SpotPrice"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "quote_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "base_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPrice { - return new SpotPrice().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPrice { - return new SpotPrice().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPrice { - return new SpotPrice().fromJsonString(jsonString, options); - } - - static equals(a: SpotPrice | PlainMessage | undefined, b: SpotPrice | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPrice, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SpotPriceQueryMsg - */ -export class SpotPriceQueryMsg extends Message { - /** - * spot_price is the structure containing request field of the spot price - * query message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.SpotPrice spot_price = 1; - */ - spotPrice?: SpotPrice; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SpotPriceQueryMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "message", T: SpotPrice }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceQueryMsg { - return new SpotPriceQueryMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceQueryMsg { - return new SpotPriceQueryMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceQueryMsg { - return new SpotPriceQueryMsg().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceQueryMsg | PlainMessage | undefined, b: SpotPriceQueryMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceQueryMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.SpotPriceQueryMsgResponse - */ -export class SpotPriceQueryMsgResponse extends Message { - /** - * spot_price is the spot price returned. - * - * @generated from field: string spot_price = 1; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.SpotPriceQueryMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceQueryMsgResponse { - return new SpotPriceQueryMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceQueryMsgResponse { - return new SpotPriceQueryMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceQueryMsgResponse { - return new SpotPriceQueryMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceQueryMsgResponse | PlainMessage | undefined, b: SpotPriceQueryMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceQueryMsgResponse, a, b); - } -} - -/** - * ===================== GetTotalPoolLiquidityQueryMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.EmptyStruct - */ -export class EmptyStruct extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.EmptyStruct"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EmptyStruct { - return new EmptyStruct().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EmptyStruct { - return new EmptyStruct().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EmptyStruct { - return new EmptyStruct().fromJsonString(jsonString, options); - } - - static equals(a: EmptyStruct | PlainMessage | undefined, b: EmptyStruct | PlainMessage | undefined): boolean { - return proto3.util.equals(EmptyStruct, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.GetTotalPoolLiquidityQueryMsg - */ -export class GetTotalPoolLiquidityQueryMsg extends Message { - /** - * get_total_pool_liquidity is the structure containing request field of the - * total pool liquidity query message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.EmptyStruct get_total_pool_liquidity = 1; - */ - getTotalPoolLiquidity?: EmptyStruct; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetTotalPoolLiquidityQueryMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "get_total_pool_liquidity", kind: "message", T: EmptyStruct }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalPoolLiquidityQueryMsg { - return new GetTotalPoolLiquidityQueryMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalPoolLiquidityQueryMsg { - return new GetTotalPoolLiquidityQueryMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalPoolLiquidityQueryMsg { - return new GetTotalPoolLiquidityQueryMsg().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalPoolLiquidityQueryMsg | PlainMessage | undefined, b: GetTotalPoolLiquidityQueryMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalPoolLiquidityQueryMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.GetTotalPoolLiquidityQueryMsgResponse - */ -export class GetTotalPoolLiquidityQueryMsgResponse extends Message { - /** - * total_pool_liquidity is the total liquidity in the pool denominated in - * coins. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin total_pool_liquidity = 1; - */ - totalPoolLiquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetTotalPoolLiquidityQueryMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_pool_liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalPoolLiquidityQueryMsgResponse { - return new GetTotalPoolLiquidityQueryMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalPoolLiquidityQueryMsgResponse { - return new GetTotalPoolLiquidityQueryMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalPoolLiquidityQueryMsgResponse { - return new GetTotalPoolLiquidityQueryMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalPoolLiquidityQueryMsgResponse | PlainMessage | undefined, b: GetTotalPoolLiquidityQueryMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalPoolLiquidityQueryMsgResponse, a, b); - } -} - -/** - * ===================== GetTotalSharesQueryMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.GetTotalSharesQueryMsg - */ -export class GetTotalSharesQueryMsg extends Message { - /** - * get_total_shares is the structure containing request field of the - * total shares query message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.EmptyStruct get_total_shares = 1; - */ - getTotalShares?: EmptyStruct; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetTotalSharesQueryMsg"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "get_total_shares", kind: "message", T: EmptyStruct }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalSharesQueryMsg { - return new GetTotalSharesQueryMsg().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalSharesQueryMsg { - return new GetTotalSharesQueryMsg().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalSharesQueryMsg { - return new GetTotalSharesQueryMsg().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalSharesQueryMsg | PlainMessage | undefined, b: GetTotalSharesQueryMsg | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalSharesQueryMsg, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.GetTotalSharesQueryMsgResponse - */ -export class GetTotalSharesQueryMsgResponse extends Message { - /** - * total_shares is the amount of shares returned. - * - * @generated from field: string total_shares = 1; - */ - totalShares = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.GetTotalSharesQueryMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_shares", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetTotalSharesQueryMsgResponse { - return new GetTotalSharesQueryMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetTotalSharesQueryMsgResponse { - return new GetTotalSharesQueryMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetTotalSharesQueryMsgResponse { - return new GetTotalSharesQueryMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetTotalSharesQueryMsgResponse | PlainMessage | undefined, b: GetTotalSharesQueryMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetTotalSharesQueryMsgResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs_pb.ts deleted file mode 100644 index 59665fa23..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs_pb.ts +++ /dev/null @@ -1,185 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/transmuter_msgs.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * ===================== JoinPoolExecuteMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.EmptyRequest - */ -export class EmptyRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.EmptyRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EmptyRequest { - return new EmptyRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EmptyRequest { - return new EmptyRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EmptyRequest { - return new EmptyRequest().fromJsonString(jsonString, options); - } - - static equals(a: EmptyRequest | PlainMessage | undefined, b: EmptyRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EmptyRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.JoinPoolExecuteMsgRequest - */ -export class JoinPoolExecuteMsgRequest extends Message { - /** - * join_pool is the structure containing all request fields of the join pool - * execute message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.EmptyRequest join_pool = 1; - */ - joinPool?: EmptyRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.JoinPoolExecuteMsgRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "join_pool", kind: "message", T: EmptyRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): JoinPoolExecuteMsgRequest { - return new JoinPoolExecuteMsgRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): JoinPoolExecuteMsgRequest { - return new JoinPoolExecuteMsgRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): JoinPoolExecuteMsgRequest { - return new JoinPoolExecuteMsgRequest().fromJsonString(jsonString, options); - } - - static equals(a: JoinPoolExecuteMsgRequest | PlainMessage | undefined, b: JoinPoolExecuteMsgRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(JoinPoolExecuteMsgRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.JoinPoolExecuteMsgResponse - */ -export class JoinPoolExecuteMsgResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.JoinPoolExecuteMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): JoinPoolExecuteMsgResponse { - return new JoinPoolExecuteMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): JoinPoolExecuteMsgResponse { - return new JoinPoolExecuteMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): JoinPoolExecuteMsgResponse { - return new JoinPoolExecuteMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: JoinPoolExecuteMsgResponse | PlainMessage | undefined, b: JoinPoolExecuteMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(JoinPoolExecuteMsgResponse, a, b); - } -} - -/** - * ===================== ExitPoolExecuteMsg - * - * @generated from message osmosis.cosmwasmpool.v1beta1.ExitPoolExecuteMsgRequest - */ -export class ExitPoolExecuteMsgRequest extends Message { - /** - * exit_pool is the structure containing all request fields of the exit pool - * execute message. - * - * @generated from field: osmosis.cosmwasmpool.v1beta1.EmptyRequest exit_pool = 1; - */ - exitPool?: EmptyRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ExitPoolExecuteMsgRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "exit_pool", kind: "message", T: EmptyRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExitPoolExecuteMsgRequest { - return new ExitPoolExecuteMsgRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExitPoolExecuteMsgRequest { - return new ExitPoolExecuteMsgRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExitPoolExecuteMsgRequest { - return new ExitPoolExecuteMsgRequest().fromJsonString(jsonString, options); - } - - static equals(a: ExitPoolExecuteMsgRequest | PlainMessage | undefined, b: ExitPoolExecuteMsgRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ExitPoolExecuteMsgRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.ExitPoolExecuteMsgResponse - */ -export class ExitPoolExecuteMsgResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ExitPoolExecuteMsgResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ExitPoolExecuteMsgResponse { - return new ExitPoolExecuteMsgResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ExitPoolExecuteMsgResponse { - return new ExitPoolExecuteMsgResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ExitPoolExecuteMsgResponse { - return new ExitPoolExecuteMsgResponse().fromJsonString(jsonString, options); - } - - static equals(a: ExitPoolExecuteMsgResponse | PlainMessage | undefined, b: ExitPoolExecuteMsgResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ExitPoolExecuteMsgResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_cosmes.ts deleted file mode 100644 index ccb152386..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_cosmes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/tx.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCreateCosmWasmPool, MsgCreateCosmWasmPoolResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.cosmwasmpool.v1beta1.MsgCreator"; - -/** - * @generated from rpc osmosis.cosmwasmpool.v1beta1.MsgCreator.CreateCosmWasmPool - */ -export const MsgCreatorCreateCosmWasmPoolService = { - typeName: TYPE_NAME, - method: "CreateCosmWasmPool", - Request: MsgCreateCosmWasmPool, - Response: MsgCreateCosmWasmPoolResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_pb.ts deleted file mode 100644 index add60cb27..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/tx_pb.ts +++ /dev/null @@ -1,98 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/tx.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * ===================== MsgCreateCosmwasmPool - * - * @generated from message osmosis.cosmwasmpool.v1beta1.MsgCreateCosmWasmPool - */ -export class MsgCreateCosmWasmPool extends Message { - /** - * @generated from field: uint64 code_id = 1; - */ - codeId = protoInt64.zero; - - /** - * @generated from field: bytes instantiate_msg = 2; - */ - instantiateMsg = new Uint8Array(0); - - /** - * @generated from field: string sender = 3; - */ - sender = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.MsgCreateCosmWasmPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "instantiate_msg", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateCosmWasmPool { - return new MsgCreateCosmWasmPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateCosmWasmPool { - return new MsgCreateCosmWasmPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateCosmWasmPool { - return new MsgCreateCosmWasmPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateCosmWasmPool | PlainMessage | undefined, b: MsgCreateCosmWasmPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateCosmWasmPool, a, b); - } -} - -/** - * Returns a unique poolID to identify the pool with. - * - * @generated from message osmosis.cosmwasmpool.v1beta1.MsgCreateCosmWasmPoolResponse - */ -export class MsgCreateCosmWasmPoolResponse extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.MsgCreateCosmWasmPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateCosmWasmPoolResponse { - return new MsgCreateCosmWasmPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateCosmWasmPoolResponse { - return new MsgCreateCosmWasmPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateCosmWasmPoolResponse { - return new MsgCreateCosmWasmPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateCosmWasmPoolResponse | PlainMessage | undefined, b: MsgCreateCosmWasmPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateCosmWasmPoolResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg_pb.ts deleted file mode 100644 index accd5f6ce..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg_pb.ts +++ /dev/null @@ -1,182 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/model/v3/pool_query_msg.proto (package osmosis.cosmwasmpool.v1beta1.model.v3, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== ShareDenomResponse - * - * @generated from message osmosis.cosmwasmpool.v1beta1.model.v3.ShareDenomResponse - */ -export class ShareDenomResponse extends Message { - /** - * share_denom is the share denomination. - * - * @generated from field: string share_denom = 1; - */ - shareDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.model.v3.ShareDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "share_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ShareDenomResponse { - return new ShareDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ShareDenomResponse { - return new ShareDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ShareDenomResponse { - return new ShareDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: ShareDenomResponse | PlainMessage | undefined, b: ShareDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ShareDenomResponse, a, b); - } -} - -/** - * ===================== TotalPoolLiquidityResponse - * - * @generated from message osmosis.cosmwasmpool.v1beta1.model.v3.TotalPoolLiquidityResponse - */ -export class TotalPoolLiquidityResponse extends Message { - /** - * total_pool_liquidity is the total liquidity in the pool denominated in - * coins. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin total_pool_liquidity = 1; - */ - totalPoolLiquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.model.v3.TotalPoolLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_pool_liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: TotalPoolLiquidityResponse | PlainMessage | undefined, b: TotalPoolLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalPoolLiquidityResponse, a, b); - } -} - -/** - * ===================== AssetConfig - * - * @generated from message osmosis.cosmwasmpool.v1beta1.model.v3.AssetConfig - */ -export class AssetConfig extends Message { - /** - * denom is the asset denomination. - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * normalization_factor is the normalization factor for the asset. - * - * @generated from field: string normalization_factor = 2; - */ - normalizationFactor = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.model.v3.AssetConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "normalization_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AssetConfig { - return new AssetConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AssetConfig { - return new AssetConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AssetConfig { - return new AssetConfig().fromJsonString(jsonString, options); - } - - static equals(a: AssetConfig | PlainMessage | undefined, b: AssetConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(AssetConfig, a, b); - } -} - -/** - * ===================== ListAssetConfigsResponse - * - * @generated from message osmosis.cosmwasmpool.v1beta1.model.v3.ListAssetConfigsResponse - */ -export class ListAssetConfigsResponse extends Message { - /** - * asset_configs is the list of asset configurations. - * - * @generated from field: repeated osmosis.cosmwasmpool.v1beta1.model.v3.AssetConfig asset_configs = 1; - */ - assetConfigs: AssetConfig[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.model.v3.ListAssetConfigsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "asset_configs", kind: "message", T: AssetConfig, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ListAssetConfigsResponse { - return new ListAssetConfigsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ListAssetConfigsResponse { - return new ListAssetConfigsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ListAssetConfigsResponse { - return new ListAssetConfigsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ListAssetConfigsResponse | PlainMessage | undefined, b: ListAssetConfigsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ListAssetConfigsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/params_pb.ts deleted file mode 100644 index 60bea3c12..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/params_pb.ts +++ /dev/null @@ -1,59 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/params.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.Params - */ -export class Params extends Message { - /** - * code_ide_whitelist contains the list of code ids that are allowed to be - * instantiated. - * - * @generated from field: repeated uint64 code_id_whitelist = 1; - */ - codeIdWhitelist: bigint[] = []; - - /** - * pool_migration_limit is the maximum number of pools that can be migrated - * at once via governance proposal. This is to have a constant bound on the - * number of pools that can be migrated at once and remove the possibility - * of an unlikely scenario of causing a chain halt due to a large migration. - * - * @generated from field: uint64 pool_migration_limit = 2; - */ - poolMigrationLimit = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "code_id_whitelist", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 2, name: "pool_migration_limit", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_cosmes.ts deleted file mode 100644 index c789a841f..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,53 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/query.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ContractInfoByPoolIdRequest, ContractInfoByPoolIdResponse, ParamsRequest, ParamsResponse, PoolRawFilteredStateRequest, PoolRawFilteredStateResponse, PoolsRequest, PoolsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.cosmwasmpool.v1beta1.Query"; - -/** - * Pools returns all cosmwasm pools - * - * @generated from rpc osmosis.cosmwasmpool.v1beta1.Query.Pools - */ -export const QueryPoolsService = { - typeName: TYPE_NAME, - method: "Pools", - Request: PoolsRequest, - Response: PoolsResponse, -} as const; - -/** - * Params returns the parameters of the x/cosmwasmpool module. - * - * @generated from rpc osmosis.cosmwasmpool.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - -/** - * @generated from rpc osmosis.cosmwasmpool.v1beta1.Query.ContractInfoByPoolId - */ -export const QueryContractInfoByPoolIdService = { - typeName: TYPE_NAME, - method: "ContractInfoByPoolId", - Request: ContractInfoByPoolIdRequest, - Response: ContractInfoByPoolIdResponse, -} as const; - -/** - * @generated from rpc osmosis.cosmwasmpool.v1beta1.Query.PoolRawFilteredState - */ -export const QueryPoolRawFilteredStateService = { - typeName: TYPE_NAME, - method: "PoolRawFilteredState", - Request: PoolRawFilteredStateRequest, - Response: PoolRawFilteredStateResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_pb.ts deleted file mode 100644 index 374887ba0..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/query_pb.ts +++ /dev/null @@ -1,351 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/query.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { PageRequest, PageResponse } from "../../../cosmos/base/query/v1beta1/pagination_pb.js"; - -/** - * =============================== ContractInfoByPoolId - * - * @generated from message osmosis.cosmwasmpool.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.cosmwasmpool.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - -/** - * =============================== Pools - * - * @generated from message osmosis.cosmwasmpool.v1beta1.PoolsRequest - */ -export class PoolsRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.PoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolsRequest { - return new PoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolsRequest { - return new PoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolsRequest { - return new PoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: PoolsRequest | PlainMessage | undefined, b: PoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.PoolsResponse - */ -export class PoolsResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.PoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolsResponse { - return new PoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolsResponse { - return new PoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolsResponse { - return new PoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: PoolsResponse | PlainMessage | undefined, b: PoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolsResponse, a, b); - } -} - -/** - * =============================== ContractInfoByPoolId - * - * @generated from message osmosis.cosmwasmpool.v1beta1.ContractInfoByPoolIdRequest - */ -export class ContractInfoByPoolIdRequest extends Message { - /** - * pool_id is the pool id of the requested pool. - * - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ContractInfoByPoolIdRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractInfoByPoolIdRequest { - return new ContractInfoByPoolIdRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractInfoByPoolIdRequest { - return new ContractInfoByPoolIdRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractInfoByPoolIdRequest { - return new ContractInfoByPoolIdRequest().fromJsonString(jsonString, options); - } - - static equals(a: ContractInfoByPoolIdRequest | PlainMessage | undefined, b: ContractInfoByPoolIdRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractInfoByPoolIdRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.ContractInfoByPoolIdResponse - */ -export class ContractInfoByPoolIdResponse extends Message { - /** - * contract_address is the pool address and contract address - * of the requested pool id. - * - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - /** - * code_id is the code id of the requested pool id. - * - * @generated from field: uint64 code_id = 2; - */ - codeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.ContractInfoByPoolIdResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "code_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ContractInfoByPoolIdResponse { - return new ContractInfoByPoolIdResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ContractInfoByPoolIdResponse { - return new ContractInfoByPoolIdResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ContractInfoByPoolIdResponse { - return new ContractInfoByPoolIdResponse().fromJsonString(jsonString, options); - } - - static equals(a: ContractInfoByPoolIdResponse | PlainMessage | undefined, b: ContractInfoByPoolIdResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ContractInfoByPoolIdResponse, a, b); - } -} - -/** - * =============================== PoolRawFilteredState - * - * @generated from message osmosis.cosmwasmpool.v1beta1.PoolRawFilteredStateRequest - */ -export class PoolRawFilteredStateRequest extends Message { - /** - * pool_id is the pool id of the requested pool. - * - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * key_filter is the key filter of the requested pool. - * - * @generated from field: string key_filter = 2; - */ - keyFilter = ""; - - /** - * value_filter is the value filter of the requested pool. - * - * @generated from field: string value_filter = 3; - */ - valueFilter = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.PoolRawFilteredStateRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "key_filter", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "value_filter", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolRawFilteredStateRequest { - return new PoolRawFilteredStateRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolRawFilteredStateRequest { - return new PoolRawFilteredStateRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolRawFilteredStateRequest { - return new PoolRawFilteredStateRequest().fromJsonString(jsonString, options); - } - - static equals(a: PoolRawFilteredStateRequest | PlainMessage | undefined, b: PoolRawFilteredStateRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolRawFilteredStateRequest, a, b); - } -} - -/** - * @generated from message osmosis.cosmwasmpool.v1beta1.PoolRawFilteredStateResponse - */ -export class PoolRawFilteredStateResponse extends Message { - /** - * values represents the list of values in the pool. - * - * @generated from field: repeated bytes values = 1; - */ - values: Uint8Array[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.cosmwasmpool.v1beta1.PoolRawFilteredStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "values", kind: "scalar", T: 12 /* ScalarType.BYTES */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolRawFilteredStateResponse { - return new PoolRawFilteredStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolRawFilteredStateResponse { - return new PoolRawFilteredStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolRawFilteredStateResponse { - return new PoolRawFilteredStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: PoolRawFilteredStateResponse | PlainMessage | undefined, b: PoolRawFilteredStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolRawFilteredStateResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/tx_cosmes.ts deleted file mode 100644 index 22acfbdcc..000000000 --- a/packages/es/src/protobufs/osmosis/cosmwasmpool/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,7 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/cosmwasmpool/v1beta1/tx.proto (package osmosis.cosmwasmpool.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -const TYPE_NAME = "osmosis.cosmwasmpool.v1beta1.Msg"; - diff --git a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/downtime_duration_pb.ts b/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/downtime_duration_pb.ts deleted file mode 100644 index b26286dd6..000000000 --- a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/downtime_duration_pb.ts +++ /dev/null @@ -1,165 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/downtimedetector/v1beta1/downtime_duration.proto (package osmosis.downtimedetector.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { proto3 } from "@bufbuild/protobuf"; - -/** - * @generated from enum osmosis.downtimedetector.v1beta1.Downtime - */ -export enum Downtime { - /** - * @generated from enum value: DURATION_30S = 0; - */ - DURATION_30S = 0, - - /** - * @generated from enum value: DURATION_1M = 1; - */ - DURATION_1M = 1, - - /** - * @generated from enum value: DURATION_2M = 2; - */ - DURATION_2M = 2, - - /** - * @generated from enum value: DURATION_3M = 3; - */ - DURATION_3M = 3, - - /** - * @generated from enum value: DURATION_4M = 4; - */ - DURATION_4M = 4, - - /** - * @generated from enum value: DURATION_5M = 5; - */ - DURATION_5M = 5, - - /** - * @generated from enum value: DURATION_10M = 6; - */ - DURATION_10M = 6, - - /** - * @generated from enum value: DURATION_20M = 7; - */ - DURATION_20M = 7, - - /** - * @generated from enum value: DURATION_30M = 8; - */ - DURATION_30M = 8, - - /** - * @generated from enum value: DURATION_40M = 9; - */ - DURATION_40M = 9, - - /** - * @generated from enum value: DURATION_50M = 10; - */ - DURATION_50M = 10, - - /** - * @generated from enum value: DURATION_1H = 11; - */ - DURATION_1H = 11, - - /** - * @generated from enum value: DURATION_1_5H = 12; - */ - DURATION_1_5H = 12, - - /** - * @generated from enum value: DURATION_2H = 13; - */ - DURATION_2H = 13, - - /** - * @generated from enum value: DURATION_2_5H = 14; - */ - DURATION_2_5H = 14, - - /** - * @generated from enum value: DURATION_3H = 15; - */ - DURATION_3H = 15, - - /** - * @generated from enum value: DURATION_4H = 16; - */ - DURATION_4H = 16, - - /** - * @generated from enum value: DURATION_5H = 17; - */ - DURATION_5H = 17, - - /** - * @generated from enum value: DURATION_6H = 18; - */ - DURATION_6H = 18, - - /** - * @generated from enum value: DURATION_9H = 19; - */ - DURATION_9H = 19, - - /** - * @generated from enum value: DURATION_12H = 20; - */ - DURATION_12H = 20, - - /** - * @generated from enum value: DURATION_18H = 21; - */ - DURATION_18H = 21, - - /** - * @generated from enum value: DURATION_24H = 22; - */ - DURATION_24H = 22, - - /** - * @generated from enum value: DURATION_36H = 23; - */ - DURATION_36H = 23, - - /** - * @generated from enum value: DURATION_48H = 24; - */ - DURATION_48H = 24, -} -// Retrieve enum metadata with: proto3.getEnumType(Downtime) -proto3.util.setEnumType(Downtime, "osmosis.downtimedetector.v1beta1.Downtime", [ - { no: 0, name: "DURATION_30S" }, - { no: 1, name: "DURATION_1M" }, - { no: 2, name: "DURATION_2M" }, - { no: 3, name: "DURATION_3M" }, - { no: 4, name: "DURATION_4M" }, - { no: 5, name: "DURATION_5M" }, - { no: 6, name: "DURATION_10M" }, - { no: 7, name: "DURATION_20M" }, - { no: 8, name: "DURATION_30M" }, - { no: 9, name: "DURATION_40M" }, - { no: 10, name: "DURATION_50M" }, - { no: 11, name: "DURATION_1H" }, - { no: 12, name: "DURATION_1_5H" }, - { no: 13, name: "DURATION_2H" }, - { no: 14, name: "DURATION_2_5H" }, - { no: 15, name: "DURATION_3H" }, - { no: 16, name: "DURATION_4H" }, - { no: 17, name: "DURATION_5H" }, - { no: 18, name: "DURATION_6H" }, - { no: 19, name: "DURATION_9H" }, - { no: 20, name: "DURATION_12H" }, - { no: 21, name: "DURATION_18H" }, - { no: 22, name: "DURATION_24H" }, - { no: 23, name: "DURATION_36H" }, - { no: 24, name: "DURATION_48H" }, -]); - diff --git a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/genesis_pb.ts deleted file mode 100644 index e38e98582..000000000 --- a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,97 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/downtimedetector/v1beta1/genesis.proto (package osmosis.downtimedetector.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, Timestamp } from "@bufbuild/protobuf"; -import { Downtime } from "./downtime_duration_pb.js"; - -/** - * @generated from message osmosis.downtimedetector.v1beta1.GenesisDowntimeEntry - */ -export class GenesisDowntimeEntry extends Message { - /** - * @generated from field: osmosis.downtimedetector.v1beta1.Downtime duration = 1; - */ - duration = Downtime.DURATION_30S; - - /** - * @generated from field: google.protobuf.Timestamp last_downtime = 2; - */ - lastDowntime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.downtimedetector.v1beta1.GenesisDowntimeEntry"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "duration", kind: "enum", T: proto3.getEnumType(Downtime) }, - { no: 2, name: "last_downtime", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisDowntimeEntry { - return new GenesisDowntimeEntry().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisDowntimeEntry { - return new GenesisDowntimeEntry().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisDowntimeEntry { - return new GenesisDowntimeEntry().fromJsonString(jsonString, options); - } - - static equals(a: GenesisDowntimeEntry | PlainMessage | undefined, b: GenesisDowntimeEntry | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisDowntimeEntry, a, b); - } -} - -/** - * GenesisState defines the twap module's genesis state. - * - * @generated from message osmosis.downtimedetector.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated osmosis.downtimedetector.v1beta1.GenesisDowntimeEntry downtimes = 1; - */ - downtimes: GenesisDowntimeEntry[] = []; - - /** - * @generated from field: google.protobuf.Timestamp last_block_time = 2; - */ - lastBlockTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.downtimedetector.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "downtimes", kind: "message", T: GenesisDowntimeEntry, repeated: true }, - { no: 2, name: "last_block_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_cosmes.ts deleted file mode 100644 index 38292778f..000000000 --- a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/downtimedetector/v1beta1/query.proto (package osmosis.downtimedetector.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { RecoveredSinceDowntimeOfLengthRequest, RecoveredSinceDowntimeOfLengthResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.downtimedetector.v1beta1.Query"; - -/** - * @generated from rpc osmosis.downtimedetector.v1beta1.Query.RecoveredSinceDowntimeOfLength - */ -export const QueryRecoveredSinceDowntimeOfLengthService = { - typeName: TYPE_NAME, - method: "RecoveredSinceDowntimeOfLength", - Request: RecoveredSinceDowntimeOfLengthRequest, - Response: RecoveredSinceDowntimeOfLengthResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_pb.ts deleted file mode 100644 index b40dada44..000000000 --- a/packages/es/src/protobufs/osmosis/downtimedetector/v1beta1/query_pb.ts +++ /dev/null @@ -1,92 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/downtimedetector/v1beta1/query.proto (package osmosis.downtimedetector.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3 } from "@bufbuild/protobuf"; -import { Downtime } from "./downtime_duration_pb.js"; - -/** - * Query for has it been at least $RECOVERY_DURATION units of time, - * since the chain has been down for $DOWNTIME_DURATION. - * - * @generated from message osmosis.downtimedetector.v1beta1.RecoveredSinceDowntimeOfLengthRequest - */ -export class RecoveredSinceDowntimeOfLengthRequest extends Message { - /** - * @generated from field: osmosis.downtimedetector.v1beta1.Downtime downtime = 1; - */ - downtime = Downtime.DURATION_30S; - - /** - * @generated from field: google.protobuf.Duration recovery = 2; - */ - recovery?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.downtimedetector.v1beta1.RecoveredSinceDowntimeOfLengthRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "downtime", kind: "enum", T: proto3.getEnumType(Downtime) }, - { no: 2, name: "recovery", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RecoveredSinceDowntimeOfLengthRequest { - return new RecoveredSinceDowntimeOfLengthRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RecoveredSinceDowntimeOfLengthRequest { - return new RecoveredSinceDowntimeOfLengthRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RecoveredSinceDowntimeOfLengthRequest { - return new RecoveredSinceDowntimeOfLengthRequest().fromJsonString(jsonString, options); - } - - static equals(a: RecoveredSinceDowntimeOfLengthRequest | PlainMessage | undefined, b: RecoveredSinceDowntimeOfLengthRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(RecoveredSinceDowntimeOfLengthRequest, a, b); - } -} - -/** - * @generated from message osmosis.downtimedetector.v1beta1.RecoveredSinceDowntimeOfLengthResponse - */ -export class RecoveredSinceDowntimeOfLengthResponse extends Message { - /** - * @generated from field: bool succesfully_recovered = 1; - */ - succesfullyRecovered = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.downtimedetector.v1beta1.RecoveredSinceDowntimeOfLengthResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "succesfully_recovered", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RecoveredSinceDowntimeOfLengthResponse { - return new RecoveredSinceDowntimeOfLengthResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RecoveredSinceDowntimeOfLengthResponse { - return new RecoveredSinceDowntimeOfLengthResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RecoveredSinceDowntimeOfLengthResponse { - return new RecoveredSinceDowntimeOfLengthResponse().fromJsonString(jsonString, options); - } - - static equals(a: RecoveredSinceDowntimeOfLengthResponse | PlainMessage | undefined, b: RecoveredSinceDowntimeOfLengthResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(RecoveredSinceDowntimeOfLengthResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/epochs/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/epochs/v1beta1/genesis_pb.ts deleted file mode 100644 index 0ba001d18..000000000 --- a/packages/es/src/protobufs/osmosis/epochs/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,163 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/epochs/v1beta1/genesis.proto (package osmosis.epochs.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * EpochInfo is a struct that describes the data going into - * a timer defined by the x/epochs module. - * - * @generated from message osmosis.epochs.v1beta1.EpochInfo - */ -export class EpochInfo extends Message { - /** - * identifier is a unique reference to this particular timer. - * - * @generated from field: string identifier = 1; - */ - identifier = ""; - - /** - * start_time is the time at which the timer first ever ticks. - * If start_time is in the future, the epoch will not begin until the start - * time. - * - * @generated from field: google.protobuf.Timestamp start_time = 2; - */ - startTime?: Timestamp; - - /** - * duration is the time in between epoch ticks. - * In order for intended behavior to be met, duration should - * be greater than the chains expected block time. - * Duration must be non-zero. - * - * @generated from field: google.protobuf.Duration duration = 3; - */ - duration?: Duration; - - /** - * current_epoch is the current epoch number, or in other words, - * how many times has the timer 'ticked'. - * The first tick (current_epoch=1) is defined as - * the first block whose blocktime is greater than the EpochInfo start_time. - * - * @generated from field: int64 current_epoch = 4; - */ - currentEpoch = protoInt64.zero; - - /** - * current_epoch_start_time describes the start time of the current timer - * interval. The interval is (current_epoch_start_time, - * current_epoch_start_time + duration] When the timer ticks, this is set to - * current_epoch_start_time = last_epoch_start_time + duration only one timer - * tick for a given identifier can occur per block. - * - * NOTE! The current_epoch_start_time may diverge significantly from the - * wall-clock time the epoch began at. Wall-clock time of epoch start may be - * >> current_epoch_start_time. Suppose current_epoch_start_time = 10, - * duration = 5. Suppose the chain goes offline at t=14, and comes back online - * at t=30, and produces blocks at every successive time. (t=31, 32, etc.) - * * The t=30 block will start the epoch for (10, 15] - * * The t=31 block will start the epoch for (15, 20] - * * The t=32 block will start the epoch for (20, 25] - * * The t=33 block will start the epoch for (25, 30] - * * The t=34 block will start the epoch for (30, 35] - * * The **t=36** block will start the epoch for (35, 40] - * - * @generated from field: google.protobuf.Timestamp current_epoch_start_time = 5; - */ - currentEpochStartTime?: Timestamp; - - /** - * epoch_counting_started is a boolean, that indicates whether this - * epoch timer has began yet. - * - * @generated from field: bool epoch_counting_started = 6; - */ - epochCountingStarted = false; - - /** - * current_epoch_start_height is the block height at which the current epoch - * started. (The block height at which the timer last ticked) - * - * @generated from field: int64 current_epoch_start_height = 8; - */ - currentEpochStartHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.EpochInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "start_time", kind: "message", T: Timestamp }, - { no: 3, name: "duration", kind: "message", T: Duration }, - { no: 4, name: "current_epoch", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "current_epoch_start_time", kind: "message", T: Timestamp }, - { no: 6, name: "epoch_counting_started", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 8, name: "current_epoch_start_height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EpochInfo { - return new EpochInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EpochInfo { - return new EpochInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EpochInfo { - return new EpochInfo().fromJsonString(jsonString, options); - } - - static equals(a: EpochInfo | PlainMessage | undefined, b: EpochInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(EpochInfo, a, b); - } -} - -/** - * GenesisState defines the epochs module's genesis state. - * - * @generated from message osmosis.epochs.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated osmosis.epochs.v1beta1.EpochInfo epochs = 1; - */ - epochs: EpochInfo[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epochs", kind: "message", T: EpochInfo, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_cosmes.ts deleted file mode 100644 index 598a6b611..000000000 --- a/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/epochs/v1beta1/query.proto (package osmosis.epochs.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryCurrentEpochRequest, QueryCurrentEpochResponse, QueryEpochsInfoRequest, QueryEpochsInfoResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.epochs.v1beta1.Query"; - -/** - * EpochInfos provide running epochInfos - * - * @generated from rpc osmosis.epochs.v1beta1.Query.EpochInfos - */ -export const QueryEpochInfosService = { - typeName: TYPE_NAME, - method: "EpochInfos", - Request: QueryEpochsInfoRequest, - Response: QueryEpochsInfoResponse, -} as const; - -/** - * CurrentEpoch provide current epoch of specified identifier - * - * @generated from rpc osmosis.epochs.v1beta1.Query.CurrentEpoch - */ -export const QueryCurrentEpochService = { - typeName: TYPE_NAME, - method: "CurrentEpoch", - Request: QueryCurrentEpochRequest, - Response: QueryCurrentEpochResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_pb.ts deleted file mode 100644 index 93930ced3..000000000 --- a/packages/es/src/protobufs/osmosis/epochs/v1beta1/query_pb.ts +++ /dev/null @@ -1,151 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/epochs/v1beta1/query.proto (package osmosis.epochs.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { EpochInfo } from "./genesis_pb.js"; - -/** - * @generated from message osmosis.epochs.v1beta1.QueryEpochsInfoRequest - */ -export class QueryEpochsInfoRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.QueryEpochsInfoRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEpochsInfoRequest { - return new QueryEpochsInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEpochsInfoRequest { - return new QueryEpochsInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEpochsInfoRequest { - return new QueryEpochsInfoRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEpochsInfoRequest | PlainMessage | undefined, b: QueryEpochsInfoRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEpochsInfoRequest, a, b); - } -} - -/** - * @generated from message osmosis.epochs.v1beta1.QueryEpochsInfoResponse - */ -export class QueryEpochsInfoResponse extends Message { - /** - * @generated from field: repeated osmosis.epochs.v1beta1.EpochInfo epochs = 1; - */ - epochs: EpochInfo[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.QueryEpochsInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epochs", kind: "message", T: EpochInfo, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEpochsInfoResponse { - return new QueryEpochsInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEpochsInfoResponse { - return new QueryEpochsInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEpochsInfoResponse { - return new QueryEpochsInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEpochsInfoResponse | PlainMessage | undefined, b: QueryEpochsInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEpochsInfoResponse, a, b); - } -} - -/** - * @generated from message osmosis.epochs.v1beta1.QueryCurrentEpochRequest - */ -export class QueryCurrentEpochRequest extends Message { - /** - * @generated from field: string identifier = 1; - */ - identifier = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.QueryCurrentEpochRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCurrentEpochRequest { - return new QueryCurrentEpochRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCurrentEpochRequest { - return new QueryCurrentEpochRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCurrentEpochRequest { - return new QueryCurrentEpochRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCurrentEpochRequest | PlainMessage | undefined, b: QueryCurrentEpochRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCurrentEpochRequest, a, b); - } -} - -/** - * @generated from message osmosis.epochs.v1beta1.QueryCurrentEpochResponse - */ -export class QueryCurrentEpochResponse extends Message { - /** - * @generated from field: int64 current_epoch = 1; - */ - currentEpoch = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.epochs.v1beta1.QueryCurrentEpochResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "current_epoch", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCurrentEpochResponse { - return new QueryCurrentEpochResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCurrentEpochResponse { - return new QueryCurrentEpochResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCurrentEpochResponse { - return new QueryCurrentEpochResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCurrentEpochResponse | PlainMessage | undefined, b: QueryCurrentEpochResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCurrentEpochResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_cosmes.ts deleted file mode 100644 index 58d0d3864..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/gamm/poolmodels/balancer/v1beta1/tx.proto (package osmosis.gamm.poolmodels.balancer.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCreateBalancerPool, MsgCreateBalancerPoolResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.gamm.poolmodels.balancer.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.gamm.poolmodels.balancer.v1beta1.Msg.CreateBalancerPool - */ -export const MsgCreateBalancerPoolService = { - typeName: TYPE_NAME, - method: "CreateBalancerPool", - Request: MsgCreateBalancerPool, - Response: MsgCreateBalancerPoolResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_pb.ts deleted file mode 100644 index e42e9d5e0..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/poolmodels/balancer/v1beta1/tx_pb.ts +++ /dev/null @@ -1,105 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/poolmodels/balancer/v1beta1/tx.proto (package osmosis.gamm.poolmodels.balancer.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { PoolAsset, PoolParams } from "../../../v1beta1/balancerPool_pb.js"; - -/** - * ===================== MsgCreatePool - * - * @generated from message osmosis.gamm.poolmodels.balancer.v1beta1.MsgCreateBalancerPool - */ -export class MsgCreateBalancerPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: osmosis.gamm.v1beta1.PoolParams pool_params = 2; - */ - poolParams?: PoolParams; - - /** - * @generated from field: repeated osmosis.gamm.v1beta1.PoolAsset pool_assets = 3; - */ - poolAssets: PoolAsset[] = []; - - /** - * @generated from field: string future_pool_governor = 4; - */ - futurePoolGovernor = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.balancer.v1beta1.MsgCreateBalancerPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_params", kind: "message", T: PoolParams }, - { no: 3, name: "pool_assets", kind: "message", T: PoolAsset, repeated: true }, - { no: 4, name: "future_pool_governor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateBalancerPool { - return new MsgCreateBalancerPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateBalancerPool { - return new MsgCreateBalancerPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateBalancerPool { - return new MsgCreateBalancerPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateBalancerPool | PlainMessage | undefined, b: MsgCreateBalancerPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateBalancerPool, a, b); - } -} - -/** - * Returns the poolID - * - * @generated from message osmosis.gamm.poolmodels.balancer.v1beta1.MsgCreateBalancerPoolResponse - */ -export class MsgCreateBalancerPoolResponse extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.balancer.v1beta1.MsgCreateBalancerPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateBalancerPoolResponse { - return new MsgCreateBalancerPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateBalancerPoolResponse { - return new MsgCreateBalancerPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateBalancerPoolResponse { - return new MsgCreateBalancerPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateBalancerPoolResponse | PlainMessage | undefined, b: MsgCreateBalancerPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateBalancerPoolResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool_pb.ts b/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool_pb.ts deleted file mode 100644 index 1854763b3..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool_pb.ts +++ /dev/null @@ -1,159 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/poolmodels/stableswap/v1beta1/stableswap_pool.proto (package osmosis.gamm.poolmodels.stableswap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * PoolParams defined the parameters that will be managed by the pool - * governance in the future. This params are not managed by the chain - * governance. Instead they will be managed by the token holders of the pool. - * The pool's token holders are specified in future_pool_governor. - * - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.PoolParams - */ -export class PoolParams extends Message { - /** - * @generated from field: string swap_fee = 1; - */ - swapFee = ""; - - /** - * N.B.: exit fee is disabled during pool creation in x/poolmanager. While old - * pools can maintain a non-zero fee. No new pool can be created with non-zero - * fee anymore - * - * @generated from field: string exit_fee = 2; - */ - exitFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.PoolParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "exit_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolParams { - return new PoolParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolParams { - return new PoolParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolParams { - return new PoolParams().fromJsonString(jsonString, options); - } - - static equals(a: PoolParams | PlainMessage | undefined, b: PoolParams | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolParams, a, b); - } -} - -/** - * Pool is the stableswap Pool struct - * - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.Pool - */ -export class Pool extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: uint64 id = 2; - */ - id = protoInt64.zero; - - /** - * @generated from field: osmosis.gamm.poolmodels.stableswap.v1beta1.PoolParams pool_params = 3; - */ - poolParams?: PoolParams; - - /** - * This string specifies who will govern the pool in the future. - * Valid forms of this are: - * {token name},{duration} - * {duration} - * where {token name} if specified is the token which determines the - * governor, and if not specified is the LP token for this pool.duration is - * a time specified as 0w,1w,2w, etc. which specifies how long the token - * would need to be locked up to count in governance. 0w means no lockup. - * - * @generated from field: string future_pool_governor = 4; - */ - futurePoolGovernor = ""; - - /** - * sum of all LP shares - * - * @generated from field: cosmos.base.v1beta1.Coin total_shares = 5; - */ - totalShares?: Coin; - - /** - * assets in the pool - * - * @generated from field: repeated cosmos.base.v1beta1.Coin pool_liquidity = 6; - */ - poolLiquidity: Coin[] = []; - - /** - * for calculation amongst assets with different precisions - * - * @generated from field: repeated uint64 scaling_factors = 7; - */ - scalingFactors: bigint[] = []; - - /** - * scaling_factor_controller is the address can adjust pool scaling factors - * - * @generated from field: string scaling_factor_controller = 8; - */ - scalingFactorController = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.Pool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "pool_params", kind: "message", T: PoolParams }, - { no: 4, name: "future_pool_governor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "total_shares", kind: "message", T: Coin }, - { no: 6, name: "pool_liquidity", kind: "message", T: Coin, repeated: true }, - { no: 7, name: "scaling_factors", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 8, name: "scaling_factor_controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Pool { - return new Pool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Pool { - return new Pool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Pool { - return new Pool().fromJsonString(jsonString, options); - } - - static equals(a: Pool | PlainMessage | undefined, b: Pool | PlainMessage | undefined): boolean { - return proto3.util.equals(Pool, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_cosmes.ts deleted file mode 100644 index 4d08f475c..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,29 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/gamm/poolmodels/stableswap/v1beta1/tx.proto (package osmosis.gamm.poolmodels.stableswap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgCreateStableswapPool, MsgCreateStableswapPoolResponse, MsgStableSwapAdjustScalingFactors, MsgStableSwapAdjustScalingFactorsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.gamm.poolmodels.stableswap.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.gamm.poolmodels.stableswap.v1beta1.Msg.CreateStableswapPool - */ -export const MsgCreateStableswapPoolService = { - typeName: TYPE_NAME, - method: "CreateStableswapPool", - Request: MsgCreateStableswapPool, - Response: MsgCreateStableswapPoolResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.poolmodels.stableswap.v1beta1.Msg.StableSwapAdjustScalingFactors - */ -export const MsgStableSwapAdjustScalingFactorsService = { - typeName: TYPE_NAME, - method: "StableSwapAdjustScalingFactors", - Request: MsgStableSwapAdjustScalingFactors, - Response: MsgStableSwapAdjustScalingFactorsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_pb.ts deleted file mode 100644 index d3077f5aa..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/poolmodels/stableswap/v1beta1/tx_pb.ts +++ /dev/null @@ -1,201 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/poolmodels/stableswap/v1beta1/tx.proto (package osmosis.gamm.poolmodels.stableswap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { PoolParams } from "./stableswap_pool_pb.js"; -import { Coin } from "../../../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== MsgCreatePool - * - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.MsgCreateStableswapPool - */ -export class MsgCreateStableswapPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: osmosis.gamm.poolmodels.stableswap.v1beta1.PoolParams pool_params = 2; - */ - poolParams?: PoolParams; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin initial_pool_liquidity = 3; - */ - initialPoolLiquidity: Coin[] = []; - - /** - * @generated from field: repeated uint64 scaling_factors = 4; - */ - scalingFactors: bigint[] = []; - - /** - * @generated from field: string future_pool_governor = 5; - */ - futurePoolGovernor = ""; - - /** - * @generated from field: string scaling_factor_controller = 6; - */ - scalingFactorController = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.MsgCreateStableswapPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_params", kind: "message", T: PoolParams }, - { no: 3, name: "initial_pool_liquidity", kind: "message", T: Coin, repeated: true }, - { no: 4, name: "scaling_factors", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 5, name: "future_pool_governor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "scaling_factor_controller", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateStableswapPool { - return new MsgCreateStableswapPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateStableswapPool { - return new MsgCreateStableswapPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateStableswapPool { - return new MsgCreateStableswapPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateStableswapPool | PlainMessage | undefined, b: MsgCreateStableswapPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateStableswapPool, a, b); - } -} - -/** - * Returns a poolID with custom poolName. - * - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.MsgCreateStableswapPoolResponse - */ -export class MsgCreateStableswapPoolResponse extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.MsgCreateStableswapPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateStableswapPoolResponse { - return new MsgCreateStableswapPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateStableswapPoolResponse { - return new MsgCreateStableswapPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateStableswapPoolResponse { - return new MsgCreateStableswapPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateStableswapPoolResponse | PlainMessage | undefined, b: MsgCreateStableswapPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateStableswapPoolResponse, a, b); - } -} - -/** - * Sender must be the pool's scaling_factor_governor in order for the tx to - * succeed. Adjusts stableswap scaling factors. - * - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.MsgStableSwapAdjustScalingFactors - */ -export class MsgStableSwapAdjustScalingFactors extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated uint64 scaling_factors = 3; - */ - scalingFactors: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.MsgStableSwapAdjustScalingFactors"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "scaling_factors", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStableSwapAdjustScalingFactors { - return new MsgStableSwapAdjustScalingFactors().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStableSwapAdjustScalingFactors { - return new MsgStableSwapAdjustScalingFactors().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStableSwapAdjustScalingFactors { - return new MsgStableSwapAdjustScalingFactors().fromJsonString(jsonString, options); - } - - static equals(a: MsgStableSwapAdjustScalingFactors | PlainMessage | undefined, b: MsgStableSwapAdjustScalingFactors | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStableSwapAdjustScalingFactors, a, b); - } -} - -/** - * @generated from message osmosis.gamm.poolmodels.stableswap.v1beta1.MsgStableSwapAdjustScalingFactorsResponse - */ -export class MsgStableSwapAdjustScalingFactorsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.poolmodels.stableswap.v1beta1.MsgStableSwapAdjustScalingFactorsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgStableSwapAdjustScalingFactorsResponse { - return new MsgStableSwapAdjustScalingFactorsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgStableSwapAdjustScalingFactorsResponse { - return new MsgStableSwapAdjustScalingFactorsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgStableSwapAdjustScalingFactorsResponse { - return new MsgStableSwapAdjustScalingFactorsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgStableSwapAdjustScalingFactorsResponse | PlainMessage | undefined, b: MsgStableSwapAdjustScalingFactorsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgStableSwapAdjustScalingFactorsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/balancerPool_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/balancerPool_pb.ts deleted file mode 100644 index 864eb3e0b..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/balancerPool_pb.ts +++ /dev/null @@ -1,307 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/balancerPool.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -// this is a legacy package that requires additional migration logic -// in order to use the correct package. Decision made to use legacy package path -// until clear steps for migration logic and the unknowns for state breaking are -// investigated for changing proto package. - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Parameters for changing the weights in a balancer pool smoothly from - * a start weight and end weight over a period of time. - * Currently, the only smooth change supported is linear changing between - * the two weights, but more types may be added in the future. - * When these parameters are set, the weight w(t) for pool time `t` is the - * following: - * t <= start_time: w(t) = initial_pool_weights - * start_time < t <= start_time + duration: - * w(t) = initial_pool_weights + (t - start_time) * - * (target_pool_weights - initial_pool_weights) / (duration) - * t > start_time + duration: w(t) = target_pool_weights - * - * @generated from message osmosis.gamm.v1beta1.SmoothWeightChangeParams - */ -export class SmoothWeightChangeParams extends Message { - /** - * The start time for beginning the weight change. - * If a parameter change / pool instantiation leaves this blank, - * it should be generated by the state_machine as the current time. - * - * @generated from field: google.protobuf.Timestamp start_time = 1; - */ - startTime?: Timestamp; - - /** - * Duration for the weights to change over - * - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - /** - * The initial pool weights. These are copied from the pool's settings - * at the time of weight change instantiation. - * The amount PoolAsset.token.amount field is ignored if present, - * future type refactorings should just have a type with the denom & weight - * here. - * - * @generated from field: repeated osmosis.gamm.v1beta1.PoolAsset initial_pool_weights = 3; - */ - initialPoolWeights: PoolAsset[] = []; - - /** - * The target pool weights. The pool weights will change linearly with respect - * to time between start_time, and start_time + duration. The amount - * PoolAsset.token.amount field is ignored if present, future type - * refactorings should just have a type with the denom & weight here. - * - * Intermediate variable for the 'slope' of pool weights. This is equal to - * (target_pool_weights - initial_pool_weights) / (duration) - * TODO: Work out precision, and decide if this is good to add - * repeated PoolAsset poolWeightSlope = 5 [ - * (gogoproto.moretags) = "yaml:\"pool_weight_slope\"", - * (gogoproto.nullable) = false - * ]; - * - * @generated from field: repeated osmosis.gamm.v1beta1.PoolAsset target_pool_weights = 4; - */ - targetPoolWeights: PoolAsset[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.SmoothWeightChangeParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "start_time", kind: "message", T: Timestamp }, - { no: 2, name: "duration", kind: "message", T: Duration }, - { no: 3, name: "initial_pool_weights", kind: "message", T: PoolAsset, repeated: true }, - { no: 4, name: "target_pool_weights", kind: "message", T: PoolAsset, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SmoothWeightChangeParams { - return new SmoothWeightChangeParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SmoothWeightChangeParams { - return new SmoothWeightChangeParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SmoothWeightChangeParams { - return new SmoothWeightChangeParams().fromJsonString(jsonString, options); - } - - static equals(a: SmoothWeightChangeParams | PlainMessage | undefined, b: SmoothWeightChangeParams | PlainMessage | undefined): boolean { - return proto3.util.equals(SmoothWeightChangeParams, a, b); - } -} - -/** - * PoolParams defined the parameters that will be managed by the pool - * governance in the future. This params are not managed by the chain - * governance. Instead they will be managed by the token holders of the pool. - * The pool's token holders are specified in future_pool_governor. - * - * @generated from message osmosis.gamm.v1beta1.PoolParams - */ -export class PoolParams extends Message { - /** - * @generated from field: string swap_fee = 1; - */ - swapFee = ""; - - /** - * N.B.: exit fee is disabled during pool creation in x/poolmanager. While old - * pools can maintain a non-zero fee. No new pool can be created with non-zero - * fee anymore - * - * @generated from field: string exit_fee = 2; - */ - exitFee = ""; - - /** - * @generated from field: osmosis.gamm.v1beta1.SmoothWeightChangeParams smooth_weight_change_params = 3; - */ - smoothWeightChangeParams?: SmoothWeightChangeParams; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.PoolParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "swap_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "exit_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "smooth_weight_change_params", kind: "message", T: SmoothWeightChangeParams }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolParams { - return new PoolParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolParams { - return new PoolParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolParams { - return new PoolParams().fromJsonString(jsonString, options); - } - - static equals(a: PoolParams | PlainMessage | undefined, b: PoolParams | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolParams, a, b); - } -} - -/** - * Pool asset is an internal struct that combines the amount of the - * token in the pool, and its balancer weight. - * This is an awkward packaging of data, - * and should be revisited in a future state migration. - * - * @generated from message osmosis.gamm.v1beta1.PoolAsset - */ -export class PoolAsset extends Message { - /** - * Coins we are talking about, - * the denomination must be unique amongst all PoolAssets for this pool. - * - * @generated from field: cosmos.base.v1beta1.Coin token = 1; - */ - token?: Coin; - - /** - * Weight that is not normalized. This weight must be less than 2^50 - * - * @generated from field: string weight = 2; - */ - weight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.PoolAsset"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token", kind: "message", T: Coin }, - { no: 2, name: "weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolAsset { - return new PoolAsset().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolAsset { - return new PoolAsset().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolAsset { - return new PoolAsset().fromJsonString(jsonString, options); - } - - static equals(a: PoolAsset | PlainMessage | undefined, b: PoolAsset | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolAsset, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.Pool - */ -export class Pool extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: uint64 id = 2; - */ - id = protoInt64.zero; - - /** - * @generated from field: osmosis.gamm.v1beta1.PoolParams pool_params = 3; - */ - poolParams?: PoolParams; - - /** - * This string specifies who will govern the pool in the future. - * Valid forms of this are: - * {token name},{duration} - * {duration} - * where {token name} if specified is the token which determines the - * governor, and if not specified is the LP token for this pool.duration is - * a time specified as 0w,1w,2w, etc. which specifies how long the token - * would need to be locked up to count in governance. 0w means no lockup. - * TODO: Further improve these docs - * - * @generated from field: string future_pool_governor = 4; - */ - futurePoolGovernor = ""; - - /** - * sum of all LP tokens sent out - * - * @generated from field: cosmos.base.v1beta1.Coin total_shares = 5; - */ - totalShares?: Coin; - - /** - * These are assumed to be sorted by denomiation. - * They contain the pool asset and the information about the weight - * - * @generated from field: repeated osmosis.gamm.v1beta1.PoolAsset pool_assets = 6; - */ - poolAssets: PoolAsset[] = []; - - /** - * sum of all non-normalized pool weights - * - * @generated from field: string total_weight = 7; - */ - totalWeight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.Pool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "pool_params", kind: "message", T: PoolParams }, - { no: 4, name: "future_pool_governor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "total_shares", kind: "message", T: Coin }, - { no: 6, name: "pool_assets", kind: "message", T: PoolAsset, repeated: true }, - { no: 7, name: "total_weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Pool { - return new Pool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Pool { - return new Pool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Pool { - return new Pool().fromJsonString(jsonString, options); - } - - static equals(a: Pool | PlainMessage | undefined, b: Pool | PlainMessage | undefined): boolean { - return proto3.util.equals(Pool, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/genesis_pb.ts deleted file mode 100644 index 212c6bc31..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,69 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/genesis.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { MigrationRecords } from "./shared_pb.js"; - -/** - * GenesisState defines the gamm module's genesis state. - * - * @generated from message osmosis.gamm.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - /** - * will be renamed to next_pool_id in an upcoming version - * - * @generated from field: uint64 next_pool_number = 2; - */ - nextPoolNumber = protoInt64.zero; - - /** - * @generated from field: osmosis.gamm.v1beta1.Params params = 3; - */ - params?: Params; - - /** - * @generated from field: osmosis.gamm.v1beta1.MigrationRecords migration_records = 4; - */ - migrationRecords?: MigrationRecords; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - { no: 2, name: "next_pool_number", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "params", kind: "message", T: Params }, - { no: 4, name: "migration_records", kind: "message", T: MigrationRecords }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/gov_pb.ts deleted file mode 100644 index d10315616..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/gov_pb.ts +++ /dev/null @@ -1,299 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/gov.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { BalancerToConcentratedPoolLink } from "./shared_pb.js"; - -/** - * ReplaceMigrationRecordsProposal is a gov Content type for updating the - * migration records. If a ReplaceMigrationRecordsProposal passes, the - * proposal’s records override the existing MigrationRecords set in the module. - * Each record specifies a single connection between a single balancer pool and - * a single concentrated pool. - * - * @generated from message osmosis.gamm.v1beta1.ReplaceMigrationRecordsProposal - */ -export class ReplaceMigrationRecordsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.gamm.v1beta1.BalancerToConcentratedPoolLink records = 3; - */ - records: BalancerToConcentratedPoolLink[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.ReplaceMigrationRecordsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "records", kind: "message", T: BalancerToConcentratedPoolLink, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ReplaceMigrationRecordsProposal { - return new ReplaceMigrationRecordsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ReplaceMigrationRecordsProposal { - return new ReplaceMigrationRecordsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ReplaceMigrationRecordsProposal { - return new ReplaceMigrationRecordsProposal().fromJsonString(jsonString, options); - } - - static equals(a: ReplaceMigrationRecordsProposal | PlainMessage | undefined, b: ReplaceMigrationRecordsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(ReplaceMigrationRecordsProposal, a, b); - } -} - -/** - * For example: if the existing DistrRecords were: - * [(Balancer 1, CL 5), (Balancer 2, CL 6), (Balancer 3, CL 7)] - * And an UpdateMigrationRecordsProposal includes - * [(Balancer 2, CL 0), (Balancer 3, CL 4), (Balancer 4, CL 10)] - * This would leave Balancer 1 record, delete Balancer 2 record, - * Edit Balancer 3 record, and Add Balancer 4 record - * The result MigrationRecords in state would be: - * [(Balancer 1, CL 5), (Balancer 3, CL 4), (Balancer 4, CL 10)] - * - * @generated from message osmosis.gamm.v1beta1.UpdateMigrationRecordsProposal - */ -export class UpdateMigrationRecordsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.gamm.v1beta1.BalancerToConcentratedPoolLink records = 3; - */ - records: BalancerToConcentratedPoolLink[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.UpdateMigrationRecordsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "records", kind: "message", T: BalancerToConcentratedPoolLink, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdateMigrationRecordsProposal { - return new UpdateMigrationRecordsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdateMigrationRecordsProposal { - return new UpdateMigrationRecordsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdateMigrationRecordsProposal { - return new UpdateMigrationRecordsProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdateMigrationRecordsProposal | PlainMessage | undefined, b: UpdateMigrationRecordsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdateMigrationRecordsProposal, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.PoolRecordWithCFMMLink - */ -export class PoolRecordWithCFMMLink extends Message { - /** - * @generated from field: string denom0 = 1; - */ - denom0 = ""; - - /** - * @generated from field: string denom1 = 2; - */ - denom1 = ""; - - /** - * @generated from field: uint64 tick_spacing = 3; - */ - tickSpacing = protoInt64.zero; - - /** - * @generated from field: string exponent_at_price_one = 4; - */ - exponentAtPriceOne = ""; - - /** - * @generated from field: string spread_factor = 5; - */ - spreadFactor = ""; - - /** - * @generated from field: uint64 balancer_pool_id = 6; - */ - balancerPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.PoolRecordWithCFMMLink"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "tick_spacing", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "exponent_at_price_one", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "spread_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "balancer_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolRecordWithCFMMLink { - return new PoolRecordWithCFMMLink().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolRecordWithCFMMLink { - return new PoolRecordWithCFMMLink().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolRecordWithCFMMLink { - return new PoolRecordWithCFMMLink().fromJsonString(jsonString, options); - } - - static equals(a: PoolRecordWithCFMMLink | PlainMessage | undefined, b: PoolRecordWithCFMMLink | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolRecordWithCFMMLink, a, b); - } -} - -/** - * CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal is a gov Content type - * for creating concentrated liquidity pools and linking it to a CFMM pool. - * - * @generated from message osmosis.gamm.v1beta1.CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal - */ -export class CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.gamm.v1beta1.PoolRecordWithCFMMLink pool_records_with_cfmm_link = 3; - */ - poolRecordsWithCfmmLink: PoolRecordWithCFMMLink[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_records_with_cfmm_link", kind: "message", T: PoolRecordWithCFMMLink, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal { - return new CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal { - return new CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal { - return new CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal().fromJsonString(jsonString, options); - } - - static equals(a: CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal | PlainMessage | undefined, b: CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(CreateConcentratedLiquidityPoolsAndLinktoCFMMProposal, a, b); - } -} - -/** - * SetScalingFactorControllerProposal is a gov Content type for updating the - * scaling factor controller address of a stableswap pool - * - * @generated from message osmosis.gamm.v1beta1.SetScalingFactorControllerProposal - */ -export class SetScalingFactorControllerProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: uint64 pool_id = 3; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string controller_address = 4; - */ - controllerAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.SetScalingFactorControllerProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "controller_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SetScalingFactorControllerProposal { - return new SetScalingFactorControllerProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SetScalingFactorControllerProposal { - return new SetScalingFactorControllerProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SetScalingFactorControllerProposal { - return new SetScalingFactorControllerProposal().fromJsonString(jsonString, options); - } - - static equals(a: SetScalingFactorControllerProposal | PlainMessage | undefined, b: SetScalingFactorControllerProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(SetScalingFactorControllerProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/params_pb.ts deleted file mode 100644 index e5c07588a..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/params_pb.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/params.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Params holds parameters for the incentives module - * - * @generated from message osmosis.gamm.v1beta1.Params - */ -export class Params extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin pool_creation_fee = 1; - */ - poolCreationFee: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_creation_fee", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_cosmes.ts deleted file mode 100644 index 3f0a5790f..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,226 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/query.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ParamsRequest, ParamsResponse, QueryCalcExitPoolCoinsFromSharesRequest, QueryCalcExitPoolCoinsFromSharesResponse, QueryCalcJoinPoolNoSwapSharesRequest, QueryCalcJoinPoolNoSwapSharesResponse, QueryCalcJoinPoolSharesRequest, QueryCalcJoinPoolSharesResponse, QueryCFMMConcentratedPoolLinksRequest, QueryCFMMConcentratedPoolLinksResponse, QueryConcentratedPoolIdLinkFromCFMMRequest, QueryConcentratedPoolIdLinkFromCFMMResponse, QueryNumPoolsRequest, QueryNumPoolsResponse, QueryPoolParamsRequest, QueryPoolParamsResponse, QueryPoolRequest, QueryPoolResponse, QueryPoolsRequest, QueryPoolsResponse, QueryPoolsWithFilterRequest, QueryPoolsWithFilterResponse, QueryPoolTypeRequest, QueryPoolTypeResponse, QuerySpotPriceRequest, QuerySpotPriceResponse, QuerySwapExactAmountInRequest, QuerySwapExactAmountInResponse, QuerySwapExactAmountOutRequest, QuerySwapExactAmountOutResponse, QueryTotalLiquidityRequest, QueryTotalLiquidityResponse, QueryTotalPoolLiquidityRequest, QueryTotalPoolLiquidityResponse, QueryTotalSharesRequest, QueryTotalSharesResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.gamm.v1beta1.Query"; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.Pools - */ -export const QueryPoolsService = { - typeName: TYPE_NAME, - method: "Pools", - Request: QueryPoolsRequest, - Response: QueryPoolsResponse, -} as const; - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from rpc osmosis.gamm.v1beta1.Query.NumPools - * @deprecated - */ -export const QueryNumPoolsService = { - typeName: TYPE_NAME, - method: "NumPools", - Request: QueryNumPoolsRequest, - Response: QueryNumPoolsResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.TotalLiquidity - */ -export const QueryTotalLiquidityService = { - typeName: TYPE_NAME, - method: "TotalLiquidity", - Request: QueryTotalLiquidityRequest, - Response: QueryTotalLiquidityResponse, -} as const; - -/** - * PoolsWithFilter allows you to query specific pools with requested - * parameters - * - * @generated from rpc osmosis.gamm.v1beta1.Query.PoolsWithFilter - */ -export const QueryPoolsWithFilterService = { - typeName: TYPE_NAME, - method: "PoolsWithFilter", - Request: QueryPoolsWithFilterRequest, - Response: QueryPoolsWithFilterResponse, -} as const; - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from rpc osmosis.gamm.v1beta1.Query.Pool - * @deprecated - */ -export const QueryPoolService = { - typeName: TYPE_NAME, - method: "Pool", - Request: QueryPoolRequest, - Response: QueryPoolResponse, -} as const; - -/** - * PoolType returns the type of the pool. - * Returns "Balancer" as a string literal when the pool is a balancer pool. - * Errors if the pool is failed to be type caseted. - * - * @generated from rpc osmosis.gamm.v1beta1.Query.PoolType - */ -export const QueryPoolTypeService = { - typeName: TYPE_NAME, - method: "PoolType", - Request: QueryPoolTypeRequest, - Response: QueryPoolTypeResponse, -} as const; - -/** - * Simulates joining pool without a swap. Returns the amount of shares you'd - * get and tokens needed to provide - * - * @generated from rpc osmosis.gamm.v1beta1.Query.CalcJoinPoolNoSwapShares - */ -export const QueryCalcJoinPoolNoSwapSharesService = { - typeName: TYPE_NAME, - method: "CalcJoinPoolNoSwapShares", - Request: QueryCalcJoinPoolNoSwapSharesRequest, - Response: QueryCalcJoinPoolNoSwapSharesResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.CalcJoinPoolShares - */ -export const QueryCalcJoinPoolSharesService = { - typeName: TYPE_NAME, - method: "CalcJoinPoolShares", - Request: QueryCalcJoinPoolSharesRequest, - Response: QueryCalcJoinPoolSharesResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.CalcExitPoolCoinsFromShares - */ -export const QueryCalcExitPoolCoinsFromSharesService = { - typeName: TYPE_NAME, - method: "CalcExitPoolCoinsFromShares", - Request: QueryCalcExitPoolCoinsFromSharesRequest, - Response: QueryCalcExitPoolCoinsFromSharesResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.PoolParams - */ -export const QueryPoolParamsService = { - typeName: TYPE_NAME, - method: "PoolParams", - Request: QueryPoolParamsRequest, - Response: QueryPoolParamsResponse, -} as const; - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from rpc osmosis.gamm.v1beta1.Query.TotalPoolLiquidity - * @deprecated - */ -export const QueryTotalPoolLiquidityService = { - typeName: TYPE_NAME, - method: "TotalPoolLiquidity", - Request: QueryTotalPoolLiquidityRequest, - Response: QueryTotalPoolLiquidityResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Query.TotalShares - */ -export const QueryTotalSharesService = { - typeName: TYPE_NAME, - method: "TotalShares", - Request: QueryTotalSharesRequest, - Response: QueryTotalSharesResponse, -} as const; - -/** - * SpotPrice defines a gRPC query handler that returns the spot price given - * a base denomination and a quote denomination. - * - * @generated from rpc osmosis.gamm.v1beta1.Query.SpotPrice - * @deprecated - */ -export const QuerySpotPriceService = { - typeName: TYPE_NAME, - method: "SpotPrice", - Request: QuerySpotPriceRequest, - Response: QuerySpotPriceResponse, -} as const; - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from rpc osmosis.gamm.v1beta1.Query.EstimateSwapExactAmountIn - * @deprecated - */ -export const QueryEstimateSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountIn", - Request: QuerySwapExactAmountInRequest, - Response: QuerySwapExactAmountInResponse, -} as const; - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from rpc osmosis.gamm.v1beta1.Query.EstimateSwapExactAmountOut - * @deprecated - */ -export const QueryEstimateSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountOut", - Request: QuerySwapExactAmountOutRequest, - Response: QuerySwapExactAmountOutResponse, -} as const; - -/** - * ConcentratedPoolIdLinkFromBalancer returns the pool id of the concentrated - * pool that is linked with the given CFMM pool. - * - * @generated from rpc osmosis.gamm.v1beta1.Query.ConcentratedPoolIdLinkFromCFMM - */ -export const QueryConcentratedPoolIdLinkFromCFMMService = { - typeName: TYPE_NAME, - method: "ConcentratedPoolIdLinkFromCFMM", - Request: QueryConcentratedPoolIdLinkFromCFMMRequest, - Response: QueryConcentratedPoolIdLinkFromCFMMResponse, -} as const; - -/** - * CFMMConcentratedPoolLinks returns migration links between CFMM and - * Concentrated pools. - * - * @generated from rpc osmosis.gamm.v1beta1.Query.CFMMConcentratedPoolLinks - */ -export const QueryCFMMConcentratedPoolLinksService = { - typeName: TYPE_NAME, - method: "CFMMConcentratedPoolLinks", - Request: QueryCFMMConcentratedPoolLinksRequest, - Response: QueryCFMMConcentratedPoolLinksResponse, -} as const; - -/** - * Params returns gamm module params. - * - * @generated from rpc osmosis.gamm.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_pb.ts deleted file mode 100644 index eb0189a69..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/query_pb.ts +++ /dev/null @@ -1,1497 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/query.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { PageRequest, PageResponse } from "../../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { SwapAmountInRoute, SwapAmountOutRoute } from "../../poolmanager/v1beta1/swap_route_pb.js"; -import { MigrationRecords } from "./shared_pb.js"; - -/** - * =============================== Params - * - * @generated from message osmosis.gamm.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.gamm.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - -/** - * =============================== Pool - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from message osmosis.gamm.v1beta1.QueryPoolRequest - * @deprecated - */ -export class QueryPoolRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolRequest { - return new QueryPoolRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolRequest | PlainMessage | undefined, b: QueryPoolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolRequest, a, b); - } -} - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from message osmosis.gamm.v1beta1.QueryPoolResponse - * @deprecated - */ -export class QueryPoolResponse extends Message { - /** - * @generated from field: google.protobuf.Any pool = 1; - */ - pool?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolResponse { - return new QueryPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolResponse | PlainMessage | undefined, b: QueryPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolResponse, a, b); - } -} - -/** - * =============================== Pools - * - * @generated from message osmosis.gamm.v1beta1.QueryPoolsRequest - */ -export class QueryPoolsRequest extends Message { - /** - * pagination defines an optional pagination for the request. - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolsRequest { - return new QueryPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolsRequest { - return new QueryPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolsRequest { - return new QueryPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolsRequest | PlainMessage | undefined, b: QueryPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryPoolsResponse - */ -export class QueryPoolsResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolsResponse { - return new QueryPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolsResponse { - return new QueryPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolsResponse { - return new QueryPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolsResponse | PlainMessage | undefined, b: QueryPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolsResponse, a, b); - } -} - -/** - * =============================== NumPools - * - * @generated from message osmosis.gamm.v1beta1.QueryNumPoolsRequest - * @deprecated - */ -export class QueryNumPoolsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryNumPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNumPoolsRequest { - return new QueryNumPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNumPoolsRequest { - return new QueryNumPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNumPoolsRequest { - return new QueryNumPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryNumPoolsRequest | PlainMessage | undefined, b: QueryNumPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNumPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryNumPoolsResponse - * @deprecated - */ -export class QueryNumPoolsResponse extends Message { - /** - * @generated from field: uint64 num_pools = 1; - */ - numPools = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryNumPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "num_pools", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryNumPoolsResponse { - return new QueryNumPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryNumPoolsResponse { - return new QueryNumPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryNumPoolsResponse { - return new QueryNumPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryNumPoolsResponse | PlainMessage | undefined, b: QueryNumPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryNumPoolsResponse, a, b); - } -} - -/** - * =============================== PoolType - * - * @generated from message osmosis.gamm.v1beta1.QueryPoolTypeRequest - */ -export class QueryPoolTypeRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolTypeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolTypeRequest { - return new QueryPoolTypeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolTypeRequest { - return new QueryPoolTypeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolTypeRequest { - return new QueryPoolTypeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolTypeRequest | PlainMessage | undefined, b: QueryPoolTypeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolTypeRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryPoolTypeResponse - */ -export class QueryPoolTypeResponse extends Message { - /** - * @generated from field: string pool_type = 1; - */ - poolType = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolTypeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolTypeResponse { - return new QueryPoolTypeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolTypeResponse { - return new QueryPoolTypeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolTypeResponse { - return new QueryPoolTypeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolTypeResponse | PlainMessage | undefined, b: QueryPoolTypeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolTypeResponse, a, b); - } -} - -/** - * =============================== CalcJoinPoolShares - * - * @generated from message osmosis.gamm.v1beta1.QueryCalcJoinPoolSharesRequest - */ -export class QueryCalcJoinPoolSharesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_in = 2; - */ - tokensIn: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcJoinPoolSharesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "tokens_in", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcJoinPoolSharesRequest { - return new QueryCalcJoinPoolSharesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcJoinPoolSharesRequest { - return new QueryCalcJoinPoolSharesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcJoinPoolSharesRequest { - return new QueryCalcJoinPoolSharesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcJoinPoolSharesRequest | PlainMessage | undefined, b: QueryCalcJoinPoolSharesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcJoinPoolSharesRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryCalcJoinPoolSharesResponse - */ -export class QueryCalcJoinPoolSharesResponse extends Message { - /** - * @generated from field: string share_out_amount = 1; - */ - shareOutAmount = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_out = 2; - */ - tokensOut: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcJoinPoolSharesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "share_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "tokens_out", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcJoinPoolSharesResponse { - return new QueryCalcJoinPoolSharesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcJoinPoolSharesResponse { - return new QueryCalcJoinPoolSharesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcJoinPoolSharesResponse { - return new QueryCalcJoinPoolSharesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcJoinPoolSharesResponse | PlainMessage | undefined, b: QueryCalcJoinPoolSharesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcJoinPoolSharesResponse, a, b); - } -} - -/** - * =============================== CalcExitPoolCoinsFromShares - * - * @generated from message osmosis.gamm.v1beta1.QueryCalcExitPoolCoinsFromSharesRequest - */ -export class QueryCalcExitPoolCoinsFromSharesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string share_in_amount = 2; - */ - shareInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcExitPoolCoinsFromSharesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "share_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcExitPoolCoinsFromSharesRequest { - return new QueryCalcExitPoolCoinsFromSharesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcExitPoolCoinsFromSharesRequest { - return new QueryCalcExitPoolCoinsFromSharesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcExitPoolCoinsFromSharesRequest { - return new QueryCalcExitPoolCoinsFromSharesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcExitPoolCoinsFromSharesRequest | PlainMessage | undefined, b: QueryCalcExitPoolCoinsFromSharesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcExitPoolCoinsFromSharesRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryCalcExitPoolCoinsFromSharesResponse - */ -export class QueryCalcExitPoolCoinsFromSharesResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_out = 1; - */ - tokensOut: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcExitPoolCoinsFromSharesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tokens_out", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcExitPoolCoinsFromSharesResponse { - return new QueryCalcExitPoolCoinsFromSharesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcExitPoolCoinsFromSharesResponse { - return new QueryCalcExitPoolCoinsFromSharesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcExitPoolCoinsFromSharesResponse { - return new QueryCalcExitPoolCoinsFromSharesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcExitPoolCoinsFromSharesResponse | PlainMessage | undefined, b: QueryCalcExitPoolCoinsFromSharesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcExitPoolCoinsFromSharesResponse, a, b); - } -} - -/** - * =============================== PoolParams - * - * @generated from message osmosis.gamm.v1beta1.QueryPoolParamsRequest - */ -export class QueryPoolParamsRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolParamsRequest { - return new QueryPoolParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolParamsRequest { - return new QueryPoolParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolParamsRequest { - return new QueryPoolParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolParamsRequest | PlainMessage | undefined, b: QueryPoolParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryPoolParamsResponse - */ -export class QueryPoolParamsResponse extends Message { - /** - * @generated from field: google.protobuf.Any params = 1; - */ - params?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolParamsResponse { - return new QueryPoolParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolParamsResponse { - return new QueryPoolParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolParamsResponse { - return new QueryPoolParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolParamsResponse | PlainMessage | undefined, b: QueryPoolParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolParamsResponse, a, b); - } -} - -/** - * =============================== PoolLiquidity - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from message osmosis.gamm.v1beta1.QueryTotalPoolLiquidityRequest - * @deprecated - */ -export class QueryTotalPoolLiquidityRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalPoolLiquidityRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalPoolLiquidityRequest { - return new QueryTotalPoolLiquidityRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalPoolLiquidityRequest { - return new QueryTotalPoolLiquidityRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalPoolLiquidityRequest { - return new QueryTotalPoolLiquidityRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalPoolLiquidityRequest | PlainMessage | undefined, b: QueryTotalPoolLiquidityRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalPoolLiquidityRequest, a, b); - } -} - -/** - * Deprecated: please use the alternative in x/poolmanager - * - * @generated from message osmosis.gamm.v1beta1.QueryTotalPoolLiquidityResponse - * @deprecated - */ -export class QueryTotalPoolLiquidityResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin liquidity = 1; - */ - liquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalPoolLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalPoolLiquidityResponse { - return new QueryTotalPoolLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalPoolLiquidityResponse { - return new QueryTotalPoolLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalPoolLiquidityResponse { - return new QueryTotalPoolLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalPoolLiquidityResponse | PlainMessage | undefined, b: QueryTotalPoolLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalPoolLiquidityResponse, a, b); - } -} - -/** - * =============================== TotalShares - * - * @generated from message osmosis.gamm.v1beta1.QueryTotalSharesRequest - */ -export class QueryTotalSharesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalSharesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalSharesRequest { - return new QueryTotalSharesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalSharesRequest { - return new QueryTotalSharesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalSharesRequest { - return new QueryTotalSharesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalSharesRequest | PlainMessage | undefined, b: QueryTotalSharesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalSharesRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryTotalSharesResponse - */ -export class QueryTotalSharesResponse extends Message { - /** - * @generated from field: cosmos.base.v1beta1.Coin total_shares = 1; - */ - totalShares?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalSharesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_shares", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalSharesResponse { - return new QueryTotalSharesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalSharesResponse { - return new QueryTotalSharesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalSharesResponse { - return new QueryTotalSharesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalSharesResponse | PlainMessage | undefined, b: QueryTotalSharesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalSharesResponse, a, b); - } -} - -/** - * =============================== CalcJoinPoolNoSwapShares - * - * @generated from message osmosis.gamm.v1beta1.QueryCalcJoinPoolNoSwapSharesRequest - */ -export class QueryCalcJoinPoolNoSwapSharesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_in = 2; - */ - tokensIn: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcJoinPoolNoSwapSharesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "tokens_in", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcJoinPoolNoSwapSharesRequest { - return new QueryCalcJoinPoolNoSwapSharesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcJoinPoolNoSwapSharesRequest { - return new QueryCalcJoinPoolNoSwapSharesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcJoinPoolNoSwapSharesRequest { - return new QueryCalcJoinPoolNoSwapSharesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcJoinPoolNoSwapSharesRequest | PlainMessage | undefined, b: QueryCalcJoinPoolNoSwapSharesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcJoinPoolNoSwapSharesRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryCalcJoinPoolNoSwapSharesResponse - */ -export class QueryCalcJoinPoolNoSwapSharesResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tokens_out = 1; - */ - tokensOut: Coin[] = []; - - /** - * @generated from field: string shares_out = 2; - */ - sharesOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCalcJoinPoolNoSwapSharesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tokens_out", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "shares_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCalcJoinPoolNoSwapSharesResponse { - return new QueryCalcJoinPoolNoSwapSharesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCalcJoinPoolNoSwapSharesResponse { - return new QueryCalcJoinPoolNoSwapSharesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCalcJoinPoolNoSwapSharesResponse { - return new QueryCalcJoinPoolNoSwapSharesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCalcJoinPoolNoSwapSharesResponse | PlainMessage | undefined, b: QueryCalcJoinPoolNoSwapSharesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCalcJoinPoolNoSwapSharesResponse, a, b); - } -} - -/** - * QuerySpotPriceRequest defines the gRPC request structure for a SpotPrice - * query. - * - * @generated from message osmosis.gamm.v1beta1.QuerySpotPriceRequest - * @deprecated - */ -export class QuerySpotPriceRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset_denom = 2; - */ - baseAssetDenom = ""; - - /** - * @generated from field: string quote_asset_denom = 3; - */ - quoteAssetDenom = ""; - - /** - * DEPRECATED - * - * @generated from field: bool withSwapFee = 4 [deprecated = true]; - * @deprecated - */ - withSwapFee = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySpotPriceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "withSwapFee", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QuerySpotPriceRequest | PlainMessage | undefined, b: QuerySpotPriceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySpotPriceRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryPoolsWithFilterRequest - */ -export class QueryPoolsWithFilterRequest extends Message { - /** - * String of the coins in single string separated by comma. Ex) - * 10uatom,100uosmo - * - * @generated from field: string min_liquidity = 1; - */ - minLiquidity = ""; - - /** - * @generated from field: string pool_type = 2; - */ - poolType = ""; - - /** - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 3; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolsWithFilterRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "min_liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolsWithFilterRequest { - return new QueryPoolsWithFilterRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolsWithFilterRequest { - return new QueryPoolsWithFilterRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolsWithFilterRequest { - return new QueryPoolsWithFilterRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolsWithFilterRequest | PlainMessage | undefined, b: QueryPoolsWithFilterRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolsWithFilterRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryPoolsWithFilterResponse - */ -export class QueryPoolsWithFilterResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - /** - * pagination defines the pagination in the response. - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryPoolsWithFilterResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryPoolsWithFilterResponse { - return new QueryPoolsWithFilterResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryPoolsWithFilterResponse { - return new QueryPoolsWithFilterResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryPoolsWithFilterResponse { - return new QueryPoolsWithFilterResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryPoolsWithFilterResponse | PlainMessage | undefined, b: QueryPoolsWithFilterResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryPoolsWithFilterResponse, a, b); - } -} - -/** - * QuerySpotPriceResponse defines the gRPC response structure for a SpotPrice - * query. - * - * @generated from message osmosis.gamm.v1beta1.QuerySpotPriceResponse - * @deprecated - */ -export class QuerySpotPriceResponse extends Message { - /** - * String of the Dec. Ex) 10.203uatom - * - * @generated from field: string spot_price = 1; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySpotPriceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QuerySpotPriceResponse | PlainMessage | undefined, b: QuerySpotPriceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySpotPriceResponse, a, b); - } -} - -/** - * =============================== EstimateSwapExactAmountIn - * - * @generated from message osmosis.gamm.v1beta1.QuerySwapExactAmountInRequest - * @deprecated - */ -export class QuerySwapExactAmountInRequest extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in = 3; - */ - tokenIn = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInRoute routes = 4; - */ - routes: SwapAmountInRoute[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySwapExactAmountInRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "routes", kind: "message", T: SwapAmountInRoute, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySwapExactAmountInRequest { - return new QuerySwapExactAmountInRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySwapExactAmountInRequest { - return new QuerySwapExactAmountInRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySwapExactAmountInRequest { - return new QuerySwapExactAmountInRequest().fromJsonString(jsonString, options); - } - - static equals(a: QuerySwapExactAmountInRequest | PlainMessage | undefined, b: QuerySwapExactAmountInRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySwapExactAmountInRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QuerySwapExactAmountInResponse - * @deprecated - */ -export class QuerySwapExactAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySwapExactAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySwapExactAmountInResponse { - return new QuerySwapExactAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySwapExactAmountInResponse { - return new QuerySwapExactAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySwapExactAmountInResponse { - return new QuerySwapExactAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: QuerySwapExactAmountInResponse | PlainMessage | undefined, b: QuerySwapExactAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySwapExactAmountInResponse, a, b); - } -} - -/** - * =============================== EstimateSwapExactAmountOut - * - * @generated from message osmosis.gamm.v1beta1.QuerySwapExactAmountOutRequest - * @deprecated - */ -export class QuerySwapExactAmountOutRequest extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutRoute routes = 3; - */ - routes: SwapAmountOutRoute[] = []; - - /** - * @generated from field: string token_out = 4; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySwapExactAmountOutRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "routes", kind: "message", T: SwapAmountOutRoute, repeated: true }, - { no: 4, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySwapExactAmountOutRequest { - return new QuerySwapExactAmountOutRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySwapExactAmountOutRequest { - return new QuerySwapExactAmountOutRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySwapExactAmountOutRequest { - return new QuerySwapExactAmountOutRequest().fromJsonString(jsonString, options); - } - - static equals(a: QuerySwapExactAmountOutRequest | PlainMessage | undefined, b: QuerySwapExactAmountOutRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySwapExactAmountOutRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QuerySwapExactAmountOutResponse - * @deprecated - */ -export class QuerySwapExactAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QuerySwapExactAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySwapExactAmountOutResponse { - return new QuerySwapExactAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySwapExactAmountOutResponse { - return new QuerySwapExactAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySwapExactAmountOutResponse { - return new QuerySwapExactAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: QuerySwapExactAmountOutResponse | PlainMessage | undefined, b: QuerySwapExactAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySwapExactAmountOutResponse, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryTotalLiquidityRequest - */ -export class QueryTotalLiquidityRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalLiquidityRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalLiquidityRequest { - return new QueryTotalLiquidityRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalLiquidityRequest { - return new QueryTotalLiquidityRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalLiquidityRequest { - return new QueryTotalLiquidityRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalLiquidityRequest | PlainMessage | undefined, b: QueryTotalLiquidityRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalLiquidityRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryTotalLiquidityResponse - */ -export class QueryTotalLiquidityResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin liquidity = 1; - */ - liquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryTotalLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalLiquidityResponse { - return new QueryTotalLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalLiquidityResponse { - return new QueryTotalLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalLiquidityResponse { - return new QueryTotalLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalLiquidityResponse | PlainMessage | undefined, b: QueryTotalLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalLiquidityResponse, a, b); - } -} - -/** - * =============================== QueryConcentratedPoolIdLinkFromCFMM - * - * @generated from message osmosis.gamm.v1beta1.QueryConcentratedPoolIdLinkFromCFMMRequest - */ -export class QueryConcentratedPoolIdLinkFromCFMMRequest extends Message { - /** - * @generated from field: uint64 cfmm_pool_id = 1; - */ - cfmmPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryConcentratedPoolIdLinkFromCFMMRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cfmm_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMRequest { - return new QueryConcentratedPoolIdLinkFromCFMMRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMRequest { - return new QueryConcentratedPoolIdLinkFromCFMMRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMRequest { - return new QueryConcentratedPoolIdLinkFromCFMMRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryConcentratedPoolIdLinkFromCFMMRequest | PlainMessage | undefined, b: QueryConcentratedPoolIdLinkFromCFMMRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConcentratedPoolIdLinkFromCFMMRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryConcentratedPoolIdLinkFromCFMMResponse - */ -export class QueryConcentratedPoolIdLinkFromCFMMResponse extends Message { - /** - * @generated from field: uint64 concentrated_pool_id = 1; - */ - concentratedPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryConcentratedPoolIdLinkFromCFMMResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "concentrated_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMResponse { - return new QueryConcentratedPoolIdLinkFromCFMMResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMResponse { - return new QueryConcentratedPoolIdLinkFromCFMMResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryConcentratedPoolIdLinkFromCFMMResponse { - return new QueryConcentratedPoolIdLinkFromCFMMResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryConcentratedPoolIdLinkFromCFMMResponse | PlainMessage | undefined, b: QueryConcentratedPoolIdLinkFromCFMMResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryConcentratedPoolIdLinkFromCFMMResponse, a, b); - } -} - -/** - * =============================== QueryCFMMConcentratedPoolLinks - * - * @generated from message osmosis.gamm.v1beta1.QueryCFMMConcentratedPoolLinksRequest - */ -export class QueryCFMMConcentratedPoolLinksRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCFMMConcentratedPoolLinksRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCFMMConcentratedPoolLinksRequest { - return new QueryCFMMConcentratedPoolLinksRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCFMMConcentratedPoolLinksRequest { - return new QueryCFMMConcentratedPoolLinksRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCFMMConcentratedPoolLinksRequest { - return new QueryCFMMConcentratedPoolLinksRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCFMMConcentratedPoolLinksRequest | PlainMessage | undefined, b: QueryCFMMConcentratedPoolLinksRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCFMMConcentratedPoolLinksRequest, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.QueryCFMMConcentratedPoolLinksResponse - */ -export class QueryCFMMConcentratedPoolLinksResponse extends Message { - /** - * @generated from field: osmosis.gamm.v1beta1.MigrationRecords migration_records = 1; - */ - migrationRecords?: MigrationRecords; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.QueryCFMMConcentratedPoolLinksResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "migration_records", kind: "message", T: MigrationRecords }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCFMMConcentratedPoolLinksResponse { - return new QueryCFMMConcentratedPoolLinksResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCFMMConcentratedPoolLinksResponse { - return new QueryCFMMConcentratedPoolLinksResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCFMMConcentratedPoolLinksResponse { - return new QueryCFMMConcentratedPoolLinksResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCFMMConcentratedPoolLinksResponse | PlainMessage | undefined, b: QueryCFMMConcentratedPoolLinksResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCFMMConcentratedPoolLinksResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/shared_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/shared_pb.ts deleted file mode 100644 index a52f0d823..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/shared_pb.ts +++ /dev/null @@ -1,98 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/shared.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * MigrationRecords contains all the links between balancer and concentrated - * pools - * - * @generated from message osmosis.gamm.v1beta1.MigrationRecords - */ -export class MigrationRecords extends Message { - /** - * @generated from field: repeated osmosis.gamm.v1beta1.BalancerToConcentratedPoolLink balancer_to_concentrated_pool_links = 1; - */ - balancerToConcentratedPoolLinks: BalancerToConcentratedPoolLink[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MigrationRecords"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balancer_to_concentrated_pool_links", kind: "message", T: BalancerToConcentratedPoolLink, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MigrationRecords { - return new MigrationRecords().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MigrationRecords { - return new MigrationRecords().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MigrationRecords { - return new MigrationRecords().fromJsonString(jsonString, options); - } - - static equals(a: MigrationRecords | PlainMessage | undefined, b: MigrationRecords | PlainMessage | undefined): boolean { - return proto3.util.equals(MigrationRecords, a, b); - } -} - -/** - * BalancerToConcentratedPoolLink defines a single link between a single - * balancer pool and a single concentrated liquidity pool. This link is used to - * allow a balancer pool to migrate to a single canonical full range - * concentrated liquidity pool position - * A balancer pool can be linked to a maximum of one cl pool, and a cl pool can - * be linked to a maximum of one balancer pool. - * - * @generated from message osmosis.gamm.v1beta1.BalancerToConcentratedPoolLink - */ -export class BalancerToConcentratedPoolLink extends Message { - /** - * @generated from field: uint64 balancer_pool_id = 1; - */ - balancerPoolId = protoInt64.zero; - - /** - * @generated from field: uint64 cl_pool_id = 2; - */ - clPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.BalancerToConcentratedPoolLink"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balancer_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "cl_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromJsonString(jsonString, options); - } - - static equals(a: BalancerToConcentratedPoolLink | PlainMessage | undefined, b: BalancerToConcentratedPoolLink | PlainMessage | undefined): boolean { - return proto3.util.equals(BalancerToConcentratedPoolLink, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_cosmes.ts deleted file mode 100644 index 9d5c82c8b..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,89 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/tx.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgExitPool, MsgExitPoolResponse, MsgExitSwapExternAmountOut, MsgExitSwapExternAmountOutResponse, MsgExitSwapShareAmountIn, MsgExitSwapShareAmountInResponse, MsgJoinPool, MsgJoinPoolResponse, MsgJoinSwapExternAmountIn, MsgJoinSwapExternAmountInResponse, MsgJoinSwapShareAmountOut, MsgJoinSwapShareAmountOutResponse, MsgSwapExactAmountIn, MsgSwapExactAmountInResponse, MsgSwapExactAmountOut, MsgSwapExactAmountOutResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.gamm.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.JoinPool - */ -export const MsgJoinPoolService = { - typeName: TYPE_NAME, - method: "JoinPool", - Request: MsgJoinPool, - Response: MsgJoinPoolResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.ExitPool - */ -export const MsgExitPoolService = { - typeName: TYPE_NAME, - method: "ExitPool", - Request: MsgExitPool, - Response: MsgExitPoolResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.SwapExactAmountIn - */ -export const MsgSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "SwapExactAmountIn", - Request: MsgSwapExactAmountIn, - Response: MsgSwapExactAmountInResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.SwapExactAmountOut - */ -export const MsgSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "SwapExactAmountOut", - Request: MsgSwapExactAmountOut, - Response: MsgSwapExactAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.JoinSwapExternAmountIn - */ -export const MsgJoinSwapExternAmountInService = { - typeName: TYPE_NAME, - method: "JoinSwapExternAmountIn", - Request: MsgJoinSwapExternAmountIn, - Response: MsgJoinSwapExternAmountInResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.JoinSwapShareAmountOut - */ -export const MsgJoinSwapShareAmountOutService = { - typeName: TYPE_NAME, - method: "JoinSwapShareAmountOut", - Request: MsgJoinSwapShareAmountOut, - Response: MsgJoinSwapShareAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.ExitSwapExternAmountOut - */ -export const MsgExitSwapExternAmountOutService = { - typeName: TYPE_NAME, - method: "ExitSwapExternAmountOut", - Request: MsgExitSwapExternAmountOut, - Response: MsgExitSwapExternAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.gamm.v1beta1.Msg.ExitSwapShareAmountIn - */ -export const MsgExitSwapShareAmountInService = { - typeName: TYPE_NAME, - method: "ExitSwapShareAmountIn", - Request: MsgExitSwapShareAmountIn, - Response: MsgExitSwapShareAmountInResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_pb.ts deleted file mode 100644 index d641210bb..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v1beta1/tx_pb.ts +++ /dev/null @@ -1,785 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v1beta1/tx.proto (package osmosis.gamm.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { SwapAmountInRoute, SwapAmountOutRoute } from "../../poolmanager/v1beta1/swap_route_pb.js"; - -/** - * ===================== MsgJoinPool - * This is really MsgJoinPoolNoSwap - * - * @generated from message osmosis.gamm.v1beta1.MsgJoinPool - */ -export class MsgJoinPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string share_out_amount = 3; - */ - shareOutAmount = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin token_in_maxs = 4; - */ - tokenInMaxs: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "share_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_in_maxs", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinPool { - return new MsgJoinPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinPool { - return new MsgJoinPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinPool { - return new MsgJoinPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinPool | PlainMessage | undefined, b: MsgJoinPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinPool, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgJoinPoolResponse - */ -export class MsgJoinPoolResponse extends Message { - /** - * @generated from field: string share_out_amount = 1; - */ - shareOutAmount = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin token_in = 2; - */ - tokenIn: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "share_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "token_in", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinPoolResponse { - return new MsgJoinPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinPoolResponse { - return new MsgJoinPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinPoolResponse { - return new MsgJoinPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinPoolResponse | PlainMessage | undefined, b: MsgJoinPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinPoolResponse, a, b); - } -} - -/** - * ===================== MsgExitPool - * - * @generated from message osmosis.gamm.v1beta1.MsgExitPool - */ -export class MsgExitPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string share_in_amount = 3; - */ - shareInAmount = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin token_out_mins = 4; - */ - tokenOutMins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "share_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_out_mins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitPool { - return new MsgExitPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitPool { - return new MsgExitPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitPool { - return new MsgExitPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitPool | PlainMessage | undefined, b: MsgExitPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitPool, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgExitPoolResponse - */ -export class MsgExitPoolResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin token_out = 1; - */ - tokenOut: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitPoolResponse { - return new MsgExitPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitPoolResponse { - return new MsgExitPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitPoolResponse { - return new MsgExitPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitPoolResponse | PlainMessage | undefined, b: MsgExitPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitPoolResponse, a, b); - } -} - -/** - * ===================== MsgSwapExactAmountIn - * - * @generated from message osmosis.gamm.v1beta1.MsgSwapExactAmountIn - */ -export class MsgSwapExactAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInRoute routes = 2; - */ - routes: SwapAmountInRoute[] = []; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_in = 3; - */ - tokenIn?: Coin; - - /** - * @generated from field: string token_out_min_amount = 4; - */ - tokenOutMinAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgSwapExactAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountInRoute, repeated: true }, - { no: 3, name: "token_in", kind: "message", T: Coin }, - { no: 4, name: "token_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountIn | PlainMessage | undefined, b: MsgSwapExactAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgSwapExactAmountInResponse - */ -export class MsgSwapExactAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgSwapExactAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountInResponse | PlainMessage | undefined, b: MsgSwapExactAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountInResponse, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgSwapExactAmountOut - */ -export class MsgSwapExactAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutRoute routes = 2; - */ - routes: SwapAmountOutRoute[] = []; - - /** - * @generated from field: string token_in_max_amount = 3; - */ - tokenInMaxAmount = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_out = 4; - */ - tokenOut?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgSwapExactAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountOutRoute, repeated: true }, - { no: 3, name: "token_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_out", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountOut | PlainMessage | undefined, b: MsgSwapExactAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgSwapExactAmountOutResponse - */ -export class MsgSwapExactAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgSwapExactAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountOutResponse | PlainMessage | undefined, b: MsgSwapExactAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountOutResponse, a, b); - } -} - -/** - * ===================== MsgJoinSwapExternAmountIn - * TODO: Rename to MsgJoinSwapExactAmountIn - * - * @generated from message osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn - */ -export class MsgJoinSwapExternAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_in = 3; - */ - tokenIn?: Coin; - - /** - * repeated cosmos.base.v1beta1.Coin tokensIn = 5 [ - * (gogoproto.moretags) = "yaml:\"tokens_in\"", - * (gogoproto.nullable) = false - * ]; - * - * @generated from field: string share_out_min_amount = 4; - */ - shareOutMinAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_in", kind: "message", T: Coin }, - { no: 4, name: "share_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinSwapExternAmountIn { - return new MsgJoinSwapExternAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinSwapExternAmountIn { - return new MsgJoinSwapExternAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinSwapExternAmountIn { - return new MsgJoinSwapExternAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinSwapExternAmountIn | PlainMessage | undefined, b: MsgJoinSwapExternAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinSwapExternAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgJoinSwapExternAmountInResponse - */ -export class MsgJoinSwapExternAmountInResponse extends Message { - /** - * @generated from field: string share_out_amount = 1; - */ - shareOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinSwapExternAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "share_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinSwapExternAmountInResponse { - return new MsgJoinSwapExternAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinSwapExternAmountInResponse { - return new MsgJoinSwapExternAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinSwapExternAmountInResponse { - return new MsgJoinSwapExternAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinSwapExternAmountInResponse | PlainMessage | undefined, b: MsgJoinSwapExternAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinSwapExternAmountInResponse, a, b); - } -} - -/** - * ===================== MsgJoinSwapShareAmountOut - * - * @generated from message osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut - */ -export class MsgJoinSwapShareAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in_denom = 3; - */ - tokenInDenom = ""; - - /** - * @generated from field: string share_out_amount = 4; - */ - shareOutAmount = ""; - - /** - * @generated from field: string token_in_max_amount = 5; - */ - tokenInMaxAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "share_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "token_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinSwapShareAmountOut { - return new MsgJoinSwapShareAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinSwapShareAmountOut { - return new MsgJoinSwapShareAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinSwapShareAmountOut { - return new MsgJoinSwapShareAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinSwapShareAmountOut | PlainMessage | undefined, b: MsgJoinSwapShareAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinSwapShareAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOutResponse - */ -export class MsgJoinSwapShareAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgJoinSwapShareAmountOutResponse { - return new MsgJoinSwapShareAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgJoinSwapShareAmountOutResponse { - return new MsgJoinSwapShareAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgJoinSwapShareAmountOutResponse { - return new MsgJoinSwapShareAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgJoinSwapShareAmountOutResponse | PlainMessage | undefined, b: MsgJoinSwapShareAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgJoinSwapShareAmountOutResponse, a, b); - } -} - -/** - * ===================== MsgExitSwapShareAmountIn - * - * @generated from message osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn - */ -export class MsgExitSwapShareAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_out_denom = 3; - */ - tokenOutDenom = ""; - - /** - * @generated from field: string share_in_amount = 4; - */ - shareInAmount = ""; - - /** - * @generated from field: string token_out_min_amount = 5; - */ - tokenOutMinAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "share_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "token_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitSwapShareAmountIn { - return new MsgExitSwapShareAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitSwapShareAmountIn { - return new MsgExitSwapShareAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitSwapShareAmountIn { - return new MsgExitSwapShareAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitSwapShareAmountIn | PlainMessage | undefined, b: MsgExitSwapShareAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitSwapShareAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgExitSwapShareAmountInResponse - */ -export class MsgExitSwapShareAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitSwapShareAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitSwapShareAmountInResponse { - return new MsgExitSwapShareAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitSwapShareAmountInResponse { - return new MsgExitSwapShareAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitSwapShareAmountInResponse { - return new MsgExitSwapShareAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitSwapShareAmountInResponse | PlainMessage | undefined, b: MsgExitSwapShareAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitSwapShareAmountInResponse, a, b); - } -} - -/** - * ===================== MsgExitSwapExternAmountOut - * - * @generated from message osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut - */ -export class MsgExitSwapExternAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_out = 3; - */ - tokenOut?: Coin; - - /** - * @generated from field: string share_in_max_amount = 4; - */ - shareInMaxAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_out", kind: "message", T: Coin }, - { no: 4, name: "share_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitSwapExternAmountOut { - return new MsgExitSwapExternAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitSwapExternAmountOut { - return new MsgExitSwapExternAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitSwapExternAmountOut { - return new MsgExitSwapExternAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitSwapExternAmountOut | PlainMessage | undefined, b: MsgExitSwapExternAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitSwapExternAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.gamm.v1beta1.MsgExitSwapExternAmountOutResponse - */ -export class MsgExitSwapExternAmountOutResponse extends Message { - /** - * @generated from field: string share_in_amount = 1; - */ - shareInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v1beta1.MsgExitSwapExternAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "share_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExitSwapExternAmountOutResponse { - return new MsgExitSwapExternAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExitSwapExternAmountOutResponse { - return new MsgExitSwapExternAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExitSwapExternAmountOutResponse { - return new MsgExitSwapExternAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExitSwapExternAmountOutResponse | PlainMessage | undefined, b: MsgExitSwapExternAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExitSwapExternAmountOutResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/gamm/v2/query_cosmes.ts b/packages/es/src/protobufs/osmosis/gamm/v2/query_cosmes.ts deleted file mode 100644 index 68f3e2966..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v2/query_cosmes.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/gamm/v2/query.proto (package osmosis.gamm.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QuerySpotPriceRequest, QuerySpotPriceResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.gamm.v2.Query"; - -/** - * Deprecated: please use alternate in x/poolmanager - * - * @generated from rpc osmosis.gamm.v2.Query.SpotPrice - * @deprecated - */ -export const QuerySpotPriceService = { - typeName: TYPE_NAME, - method: "SpotPrice", - Request: QuerySpotPriceRequest, - Response: QuerySpotPriceResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/gamm/v2/query_pb.ts b/packages/es/src/protobufs/osmosis/gamm/v2/query_pb.ts deleted file mode 100644 index 0efbee65c..000000000 --- a/packages/es/src/protobufs/osmosis/gamm/v2/query_pb.ts +++ /dev/null @@ -1,111 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/gamm/v2/query.proto (package osmosis.gamm.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Deprecated: please use alternate in x/poolmanager - * - * @generated from message osmosis.gamm.v2.QuerySpotPriceRequest - * @deprecated - */ -export class QuerySpotPriceRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset_denom = 2; - */ - baseAssetDenom = ""; - - /** - * @generated from field: string quote_asset_denom = 3; - */ - quoteAssetDenom = ""; - - /** - * DEPRECATED - * - * @generated from field: bool withSwapFee = 4 [deprecated = true]; - * @deprecated - */ - withSwapFee = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v2.QuerySpotPriceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "withSwapFee", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySpotPriceRequest { - return new QuerySpotPriceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QuerySpotPriceRequest | PlainMessage | undefined, b: QuerySpotPriceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySpotPriceRequest, a, b); - } -} - -/** - * Deprecated: please use alternate in x/poolmanager - * - * @generated from message osmosis.gamm.v2.QuerySpotPriceResponse - * @deprecated - */ -export class QuerySpotPriceResponse extends Message { - /** - * String of the Dec. Ex) 10.203uatom - * - * @generated from field: string spot_price = 1; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.gamm.v2.QuerySpotPriceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QuerySpotPriceResponse { - return new QuerySpotPriceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QuerySpotPriceResponse | PlainMessage | undefined, b: QuerySpotPriceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QuerySpotPriceResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibchooks/genesis_pb.ts b/packages/es/src/protobufs/osmosis/ibchooks/genesis_pb.ts deleted file mode 100644 index d95a29c83..000000000 --- a/packages/es/src/protobufs/osmosis/ibchooks/genesis_pb.ts +++ /dev/null @@ -1,46 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibchooks/genesis.proto (package osmosis.ibchooks, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; - -/** - * @generated from message osmosis.ibchooks.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: osmosis.ibchooks.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibchooks.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibchooks/params_pb.ts b/packages/es/src/protobufs/osmosis/ibchooks/params_pb.ts deleted file mode 100644 index c1e93460e..000000000 --- a/packages/es/src/protobufs/osmosis/ibchooks/params_pb.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibchooks/params.proto (package osmosis.ibchooks, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.ibchooks.Params - */ -export class Params extends Message { - /** - * @generated from field: repeated string allowed_async_ack_contracts = 1; - */ - allowedAsyncAckContracts: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibchooks.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "allowed_async_ack_contracts", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibchooks/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/ibchooks/tx_cosmes.ts deleted file mode 100644 index 4889ce487..000000000 --- a/packages/es/src/protobufs/osmosis/ibchooks/tx_cosmes.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/ibchooks/tx.proto (package osmosis.ibchooks, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgEmitIBCAck, MsgEmitIBCAckResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.ibchooks.Msg"; - -/** - * EmitIBCAck checks the sender can emit the ack and writes the IBC - * acknowledgement - * - * @generated from rpc osmosis.ibchooks.Msg.EmitIBCAck - */ -export const MsgEmitIBCAckService = { - typeName: TYPE_NAME, - method: "EmitIBCAck", - Request: MsgEmitIBCAck, - Response: MsgEmitIBCAckResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/ibchooks/tx_pb.ts b/packages/es/src/protobufs/osmosis/ibchooks/tx_pb.ts deleted file mode 100644 index 00a92cc49..000000000 --- a/packages/es/src/protobufs/osmosis/ibchooks/tx_pb.ts +++ /dev/null @@ -1,100 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibchooks/tx.proto (package osmosis.ibchooks, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.ibchooks.MsgEmitIBCAck - */ -export class MsgEmitIBCAck extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 packet_sequence = 2; - */ - packetSequence = protoInt64.zero; - - /** - * @generated from field: string channel = 3; - */ - channel = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibchooks.MsgEmitIBCAck"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "packet_sequence", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "channel", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgEmitIBCAck { - return new MsgEmitIBCAck().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgEmitIBCAck { - return new MsgEmitIBCAck().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgEmitIBCAck { - return new MsgEmitIBCAck().fromJsonString(jsonString, options); - } - - static equals(a: MsgEmitIBCAck | PlainMessage | undefined, b: MsgEmitIBCAck | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgEmitIBCAck, a, b); - } -} - -/** - * @generated from message osmosis.ibchooks.MsgEmitIBCAckResponse - */ -export class MsgEmitIBCAckResponse extends Message { - /** - * @generated from field: string contract_result = 1; - */ - contractResult = ""; - - /** - * @generated from field: string ibc_ack = 2; - */ - ibcAck = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibchooks.MsgEmitIBCAckResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_result", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "ibc_ack", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgEmitIBCAckResponse { - return new MsgEmitIBCAckResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgEmitIBCAckResponse { - return new MsgEmitIBCAckResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgEmitIBCAckResponse { - return new MsgEmitIBCAckResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgEmitIBCAckResponse | PlainMessage | undefined, b: MsgEmitIBCAckResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgEmitIBCAckResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/genesis_pb.ts deleted file mode 100644 index d30ec6719..000000000 --- a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,50 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibcratelimit/v1beta1/genesis.proto (package osmosis.ibcratelimit.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; - -/** - * GenesisState defines the ibc-rate-limit module's genesis state. - * - * @generated from message osmosis.ibcratelimit.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params are all the parameters of the module - * - * @generated from field: osmosis.ibcratelimit.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibcratelimit.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/params_pb.ts deleted file mode 100644 index e70f27cb3..000000000 --- a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/params_pb.ts +++ /dev/null @@ -1,47 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibcratelimit/v1beta1/params.proto (package osmosis.ibcratelimit.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params defines the parameters for the ibc-rate-limit module. - * - * @generated from message osmosis.ibcratelimit.v1beta1.Params - */ -export class Params extends Message { - /** - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibcratelimit.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_cosmes.ts deleted file mode 100644 index 90d5ab27a..000000000 --- a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/ibcratelimit/v1beta1/query.proto (package osmosis.ibcratelimit.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ParamsRequest, ParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.ibcratelimit.v1beta1.Query"; - -/** - * Params defines a gRPC query method that returns the ibc-rate-limit module's - * parameters. - * - * @generated from rpc osmosis.ibcratelimit.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_pb.ts deleted file mode 100644 index 9addfc792..000000000 --- a/packages/es/src/protobufs/osmosis/ibcratelimit/v1beta1/query_pb.ts +++ /dev/null @@ -1,83 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ibcratelimit/v1beta1/query.proto (package osmosis.ibcratelimit.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; - -/** - * ParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message osmosis.ibcratelimit.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibcratelimit.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * aramsResponse is the response type for the Query/Params RPC method. - * - * @generated from message osmosis.ibcratelimit.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: osmosis.ibcratelimit.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ibcratelimit.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/gauge_pb.ts b/packages/es/src/protobufs/osmosis/incentives/gauge_pb.ts deleted file mode 100644 index 458211099..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/gauge_pb.ts +++ /dev/null @@ -1,156 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/gauge.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { QueryCondition } from "../lockup/lock_pb.js"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Gauge is an object that stores and distributes yields to recipients who - * satisfy certain conditions. Currently gauges support conditions around the - * duration for which a given denom is locked. - * - * @generated from message osmosis.incentives.Gauge - */ -export class Gauge extends Message { - /** - * id is the unique ID of a Gauge - * - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - /** - * is_perpetual is a flag to show if it's a perpetual or non-perpetual gauge - * Non-perpetual gauges distribute their tokens equally per epoch while the - * gauge is in the active period. Perpetual gauges distribute all their tokens - * at a single time and only distribute their tokens again once the gauge is - * refilled, Intended for use with incentives that get refilled daily. - * - * @generated from field: bool is_perpetual = 2; - */ - isPerpetual = false; - - /** - * distribute_to is where the gauge rewards are distributed to. - * This is queried via lock duration or by timestamp - * - * @generated from field: osmosis.lockup.QueryCondition distribute_to = 3; - */ - distributeTo?: QueryCondition; - - /** - * coins is the total amount of coins that have been in the gauge - * Can distribute multiple coin denoms - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 4; - */ - coins: Coin[] = []; - - /** - * start_time is the distribution start time - * - * @generated from field: google.protobuf.Timestamp start_time = 5; - */ - startTime?: Timestamp; - - /** - * num_epochs_paid_over is the number of total epochs distribution will be - * completed over - * - * @generated from field: uint64 num_epochs_paid_over = 6; - */ - numEpochsPaidOver = protoInt64.zero; - - /** - * filled_epochs is the number of epochs distribution has been completed on - * already - * - * @generated from field: uint64 filled_epochs = 7; - */ - filledEpochs = protoInt64.zero; - - /** - * distributed_coins are coins that have been distributed already - * - * @generated from field: repeated cosmos.base.v1beta1.Coin distributed_coins = 8; - */ - distributedCoins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.Gauge"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "is_perpetual", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "distribute_to", kind: "message", T: QueryCondition }, - { no: 4, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 5, name: "start_time", kind: "message", T: Timestamp }, - { no: 6, name: "num_epochs_paid_over", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "filled_epochs", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 8, name: "distributed_coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Gauge { - return new Gauge().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Gauge { - return new Gauge().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Gauge { - return new Gauge().fromJsonString(jsonString, options); - } - - static equals(a: Gauge | PlainMessage | undefined, b: Gauge | PlainMessage | undefined): boolean { - return proto3.util.equals(Gauge, a, b); - } -} - -/** - * @generated from message osmosis.incentives.LockableDurationsInfo - */ -export class LockableDurationsInfo extends Message { - /** - * List of incentivised durations that gauges will pay out to - * - * @generated from field: repeated google.protobuf.Duration lockable_durations = 1; - */ - lockableDurations: Duration[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.LockableDurationsInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromJsonString(jsonString, options); - } - - static equals(a: LockableDurationsInfo | PlainMessage | undefined, b: LockableDurationsInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(LockableDurationsInfo, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/genesis_pb.ts b/packages/es/src/protobufs/osmosis/incentives/genesis_pb.ts deleted file mode 100644 index 9f7759d76..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/genesis_pb.ts +++ /dev/null @@ -1,96 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/genesis.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { Gauge } from "./gauge_pb.js"; -import { Group } from "./group_pb.js"; - -/** - * GenesisState defines the incentives module's various parameters when first - * initialized - * - * @generated from message osmosis.incentives.GenesisState - */ -export class GenesisState extends Message { - /** - * params are all the parameters of the module - * - * @generated from field: osmosis.incentives.Params params = 1; - */ - params?: Params; - - /** - * gauges are all gauges (not including group gauges) that should exist at - * genesis - * - * @generated from field: repeated osmosis.incentives.Gauge gauges = 2; - */ - gauges: Gauge[] = []; - - /** - * lockable_durations are all lockup durations that gauges can be locked for - * in order to receive incentives - * - * @generated from field: repeated google.protobuf.Duration lockable_durations = 3; - */ - lockableDurations: Duration[] = []; - - /** - * last_gauge_id is what the gauge number will increment from when creating - * the next gauge after genesis - * - * @generated from field: uint64 last_gauge_id = 4; - */ - lastGaugeId = protoInt64.zero; - - /** - * gauges are all group gauges that should exist at genesis - * - * @generated from field: repeated osmosis.incentives.Gauge group_gauges = 5; - */ - groupGauges: Gauge[] = []; - - /** - * groups are all the groups that should exist at genesis - * - * @generated from field: repeated osmosis.incentives.Group groups = 6; - */ - groups: Group[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "gauges", kind: "message", T: Gauge, repeated: true }, - { no: 3, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - { no: 4, name: "last_gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 5, name: "group_gauges", kind: "message", T: Gauge, repeated: true }, - { no: 6, name: "groups", kind: "message", T: Group, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/gov_pb.ts b/packages/es/src/protobufs/osmosis/incentives/gov_pb.ts deleted file mode 100644 index dc85520cc..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/gov_pb.ts +++ /dev/null @@ -1,62 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/gov.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { CreateGroup } from "./group_pb.js"; - -/** - * CreateGroupsProposal is a type for creating one or more groups via - * governance. This is useful for creating groups without having to pay - * creation fees. - * - * @generated from message osmosis.incentives.CreateGroupsProposal - */ -export class CreateGroupsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.incentives.CreateGroup create_groups = 3; - */ - createGroups: CreateGroup[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.CreateGroupsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "create_groups", kind: "message", T: CreateGroup, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CreateGroupsProposal { - return new CreateGroupsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CreateGroupsProposal { - return new CreateGroupsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CreateGroupsProposal { - return new CreateGroupsProposal().fromJsonString(jsonString, options); - } - - static equals(a: CreateGroupsProposal | PlainMessage | undefined, b: CreateGroupsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(CreateGroupsProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/group_pb.ts b/packages/es/src/protobufs/osmosis/incentives/group_pb.ts deleted file mode 100644 index 5ec134fd5..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/group_pb.ts +++ /dev/null @@ -1,272 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/group.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Gauge } from "./gauge_pb.js"; - -/** - * SplittingPolicy determines the way we want to split incentives in groupGauges - * - * @generated from enum osmosis.incentives.SplittingPolicy - */ -export enum SplittingPolicy { - /** - * @generated from enum value: ByVolume = 0; - */ - ByVolume = 0, -} -// Retrieve enum metadata with: proto3.getEnumType(SplittingPolicy) -proto3.util.setEnumType(SplittingPolicy, "osmosis.incentives.SplittingPolicy", [ - { no: 0, name: "ByVolume" }, -]); - -/** - * Note that while both InternalGaugeInfo and InternalGaugeRecord could - * technically be replaced by DistrInfo and DistrRecord from the pool-incentives - * module, we create separate types here to keep our abstractions clean and - * readable (pool-incentives distribution abstractions are used in a very - * specific way that does not directly relate to gauge logic). This also helps - * us sidestep a refactor to avoid an import cycle. - * - * @generated from message osmosis.incentives.InternalGaugeInfo - */ -export class InternalGaugeInfo extends Message { - /** - * @generated from field: string total_weight = 1; - */ - totalWeight = ""; - - /** - * @generated from field: repeated osmosis.incentives.InternalGaugeRecord gauge_records = 2; - */ - gaugeRecords: InternalGaugeRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.InternalGaugeInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "gauge_records", kind: "message", T: InternalGaugeRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InternalGaugeInfo { - return new InternalGaugeInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InternalGaugeInfo { - return new InternalGaugeInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InternalGaugeInfo { - return new InternalGaugeInfo().fromJsonString(jsonString, options); - } - - static equals(a: InternalGaugeInfo | PlainMessage | undefined, b: InternalGaugeInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(InternalGaugeInfo, a, b); - } -} - -/** - * @generated from message osmosis.incentives.InternalGaugeRecord - */ -export class InternalGaugeRecord extends Message { - /** - * @generated from field: uint64 gauge_id = 1; - */ - gaugeId = protoInt64.zero; - - /** - * CurrentWeight is the current weight of this gauge being distributed to for - * this epoch. For instance, for volume splitting policy, this stores the - * volume generated in the last epoch of the linked pool. - * - * @generated from field: string current_weight = 2; - */ - currentWeight = ""; - - /** - * CumulativeWeight serves as a snapshot of the accumulator being tracked - * based on splitting policy. For instance, for volume splitting policy, this - * stores the cumulative volume for the linked pool at time of last update. - * - * @generated from field: string cumulative_weight = 3; - */ - cumulativeWeight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.InternalGaugeRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "current_weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "cumulative_weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InternalGaugeRecord { - return new InternalGaugeRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InternalGaugeRecord { - return new InternalGaugeRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InternalGaugeRecord { - return new InternalGaugeRecord().fromJsonString(jsonString, options); - } - - static equals(a: InternalGaugeRecord | PlainMessage | undefined, b: InternalGaugeRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(InternalGaugeRecord, a, b); - } -} - -/** - * Group is an object that stores a 1:1 mapped gauge ID, a list of pool gauge - * info, and a splitting policy. These are grouped into a single abstraction to - * allow for distribution of group incentives to internal gauges according to - * the specified splitting policy. - * - * @generated from message osmosis.incentives.Group - */ -export class Group extends Message { - /** - * @generated from field: uint64 group_gauge_id = 1; - */ - groupGaugeId = protoInt64.zero; - - /** - * @generated from field: osmosis.incentives.InternalGaugeInfo internal_gauge_info = 2; - */ - internalGaugeInfo?: InternalGaugeInfo; - - /** - * @generated from field: osmosis.incentives.SplittingPolicy splitting_policy = 3; - */ - splittingPolicy = SplittingPolicy.ByVolume; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.Group"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "group_gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "internal_gauge_info", kind: "message", T: InternalGaugeInfo }, - { no: 3, name: "splitting_policy", kind: "enum", T: proto3.getEnumType(SplittingPolicy) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Group { - return new Group().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Group { - return new Group().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Group { - return new Group().fromJsonString(jsonString, options); - } - - static equals(a: Group | PlainMessage | undefined, b: Group | PlainMessage | undefined): boolean { - return proto3.util.equals(Group, a, b); - } -} - -/** - * CreateGroup is called via governance to create a new group. - * It takes an array of pool IDs to split the incentives across. - * - * @generated from message osmosis.incentives.CreateGroup - */ -export class CreateGroup extends Message { - /** - * @generated from field: repeated uint64 pool_ids = 1; - */ - poolIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.CreateGroup"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CreateGroup { - return new CreateGroup().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CreateGroup { - return new CreateGroup().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CreateGroup { - return new CreateGroup().fromJsonString(jsonString, options); - } - - static equals(a: CreateGroup | PlainMessage | undefined, b: CreateGroup | PlainMessage | undefined): boolean { - return proto3.util.equals(CreateGroup, a, b); - } -} - -/** - * GroupsWithGauge is a helper struct that stores a group and its - * associated gauge. - * - * @generated from message osmosis.incentives.GroupsWithGauge - */ -export class GroupsWithGauge extends Message { - /** - * @generated from field: osmosis.incentives.Group group = 1; - */ - group?: Group; - - /** - * @generated from field: osmosis.incentives.Gauge gauge = 2; - */ - gauge?: Gauge; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GroupsWithGauge"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "group", kind: "message", T: Group }, - { no: 2, name: "gauge", kind: "message", T: Gauge }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GroupsWithGauge { - return new GroupsWithGauge().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GroupsWithGauge { - return new GroupsWithGauge().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GroupsWithGauge { - return new GroupsWithGauge().fromJsonString(jsonString, options); - } - - static equals(a: GroupsWithGauge | PlainMessage | undefined, b: GroupsWithGauge | PlainMessage | undefined): boolean { - return proto3.util.equals(GroupsWithGauge, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/params_pb.ts b/packages/es/src/protobufs/osmosis/incentives/params_pb.ts deleted file mode 100644 index 8c1c13bb5..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/params_pb.ts +++ /dev/null @@ -1,101 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/params.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Params holds parameters for the incentives module - * - * @generated from message osmosis.incentives.Params - */ -export class Params extends Message { - /** - * distr_epoch_identifier is what epoch type distribution will be triggered by - * (day, week, etc.) - * - * @generated from field: string distr_epoch_identifier = 1; - */ - distrEpochIdentifier = ""; - - /** - * group_creation_fee is the fee required to create a new group - * It is only charged to all addresses other than incentive module account - * or addresses in the unrestricted_creator_whitelist - * - * @generated from field: repeated cosmos.base.v1beta1.Coin group_creation_fee = 2; - */ - groupCreationFee: Coin[] = []; - - /** - * unrestricted_creator_whitelist is a list of addresses that are - * allowed to bypass restrictions on permissionless Group - * creation. In the future, we might expand these to creating gauges - * as well. - * The goal of this is to allow a subdao to manage incentives efficiently - * without being stopped by 5 day governance process or a high fee. - * At the same time, it prevents spam by having a fee for all - * other users. - * - * @generated from field: repeated string unrestricted_creator_whitelist = 3; - */ - unrestrictedCreatorWhitelist: string[] = []; - - /** - * internal_uptime is the uptime used for internal incentives on pools that - * use NoLock gauges (currently only Concentrated Liquidity pools). - * - * Since Group gauges route through internal gauges, this parameter affects - * the uptime of those incentives as well (i.e. distributions through volume - * splitting incentives will use this uptime). - * - * @generated from field: google.protobuf.Duration internal_uptime = 4; - */ - internalUptime?: Duration; - - /** - * min_value_for_distribution is the minimum amount a token must be worth - * in order to be eligible for distribution. If the token is worth - * less than this amount (or the route between the two denoms is not - * registered), it will not be distributed and is forfeited to the remaining - * distributees that are eligible. - * - * @generated from field: cosmos.base.v1beta1.Coin min_value_for_distribution = 5; - */ - minValueForDistribution?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "distr_epoch_identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "group_creation_fee", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "unrestricted_creator_whitelist", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "internal_uptime", kind: "message", T: Duration }, - { no: 5, name: "min_value_for_distribution", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/query_cosmes.ts b/packages/es/src/protobufs/osmosis/incentives/query_cosmes.ts deleted file mode 100644 index 6d64d4b89..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/query_cosmes.ts +++ /dev/null @@ -1,224 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/incentives/query.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ActiveGaugesPerDenomRequest, ActiveGaugesPerDenomResponse, ActiveGaugesRequest, ActiveGaugesResponse, GaugeByIDRequest, GaugeByIDResponse, GaugesRequest, GaugesResponse, ModuleToDistributeCoinsRequest, ModuleToDistributeCoinsResponse, ParamsRequest, ParamsResponse, QueryAllGroupsGaugesRequest, QueryAllGroupsGaugesResponse, QueryAllGroupsRequest, QueryAllGroupsResponse, QueryAllGroupsWithGaugeRequest, QueryAllGroupsWithGaugeResponse, QueryCurrentWeightByGroupGaugeIDRequest, QueryCurrentWeightByGroupGaugeIDResponse, QueryExternalGaugesRequest, QueryExternalGaugesResponse, QueryGaugesByPoolIDRequest, QueryGaugesByPoolIDResponse, QueryGroupByGroupGaugeIDRequest, QueryGroupByGroupGaugeIDResponse, QueryInternalGaugesRequest, QueryInternalGaugesResponse, QueryLockableDurationsRequest, QueryLockableDurationsResponse, RewardsEstRequest, RewardsEstResponse, UpcomingGaugesPerDenomRequest, UpcomingGaugesPerDenomResponse, UpcomingGaugesRequest, UpcomingGaugesResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.incentives.Query"; - -/** - * ModuleToDistributeCoins returns coins that are going to be distributed - * - * @generated from rpc osmosis.incentives.Query.ModuleToDistributeCoins - */ -export const QueryModuleToDistributeCoinsService = { - typeName: TYPE_NAME, - method: "ModuleToDistributeCoins", - Request: ModuleToDistributeCoinsRequest, - Response: ModuleToDistributeCoinsResponse, -} as const; - -/** - * GaugeByID returns gauges by their respective ID - * - * @generated from rpc osmosis.incentives.Query.GaugeByID - */ -export const QueryGaugeByIDService = { - typeName: TYPE_NAME, - method: "GaugeByID", - Request: GaugeByIDRequest, - Response: GaugeByIDResponse, -} as const; - -/** - * Gauges returns both upcoming and active gauges - * - * @generated from rpc osmosis.incentives.Query.Gauges - */ -export const QueryGaugesService = { - typeName: TYPE_NAME, - method: "Gauges", - Request: GaugesRequest, - Response: GaugesResponse, -} as const; - -/** - * ActiveGauges returns active gauges - * - * @generated from rpc osmosis.incentives.Query.ActiveGauges - */ -export const QueryActiveGaugesService = { - typeName: TYPE_NAME, - method: "ActiveGauges", - Request: ActiveGaugesRequest, - Response: ActiveGaugesResponse, -} as const; - -/** - * ActiveGaugesPerDenom returns active gauges by denom - * - * @generated from rpc osmosis.incentives.Query.ActiveGaugesPerDenom - */ -export const QueryActiveGaugesPerDenomService = { - typeName: TYPE_NAME, - method: "ActiveGaugesPerDenom", - Request: ActiveGaugesPerDenomRequest, - Response: ActiveGaugesPerDenomResponse, -} as const; - -/** - * Returns scheduled gauges that have not yet occurred - * - * @generated from rpc osmosis.incentives.Query.UpcomingGauges - */ -export const QueryUpcomingGaugesService = { - typeName: TYPE_NAME, - method: "UpcomingGauges", - Request: UpcomingGaugesRequest, - Response: UpcomingGaugesResponse, -} as const; - -/** - * UpcomingGaugesPerDenom returns scheduled gauges that have not yet occurred - * by denom - * - * @generated from rpc osmosis.incentives.Query.UpcomingGaugesPerDenom - */ -export const QueryUpcomingGaugesPerDenomService = { - typeName: TYPE_NAME, - method: "UpcomingGaugesPerDenom", - Request: UpcomingGaugesPerDenomRequest, - Response: UpcomingGaugesPerDenomResponse, -} as const; - -/** - * RewardsEst returns an estimate of the rewards from now until a specified - * time in the future The querier either provides an address or a set of locks - * for which they want to find the associated rewards - * - * @generated from rpc osmosis.incentives.Query.RewardsEst - */ -export const QueryRewardsEstService = { - typeName: TYPE_NAME, - method: "RewardsEst", - Request: RewardsEstRequest, - Response: RewardsEstResponse, -} as const; - -/** - * LockableDurations returns lockable durations that are valid to distribute - * incentives for - * - * @generated from rpc osmosis.incentives.Query.LockableDurations - */ -export const QueryLockableDurationsService = { - typeName: TYPE_NAME, - method: "LockableDurations", - Request: QueryLockableDurationsRequest, - Response: QueryLockableDurationsResponse, -} as const; - -/** - * AllGroups returns all groups - * - * @generated from rpc osmosis.incentives.Query.AllGroups - */ -export const QueryAllGroupsService = { - typeName: TYPE_NAME, - method: "AllGroups", - Request: QueryAllGroupsRequest, - Response: QueryAllGroupsResponse, -} as const; - -/** - * AllGroupsGauges returns all group gauges - * - * @generated from rpc osmosis.incentives.Query.AllGroupsGauges - */ -export const QueryAllGroupsGaugesService = { - typeName: TYPE_NAME, - method: "AllGroupsGauges", - Request: QueryAllGroupsGaugesRequest, - Response: QueryAllGroupsGaugesResponse, -} as const; - -/** - * AllGroupsWithGauge returns all groups with their group gauge - * - * @generated from rpc osmosis.incentives.Query.AllGroupsWithGauge - */ -export const QueryAllGroupsWithGaugeService = { - typeName: TYPE_NAME, - method: "AllGroupsWithGauge", - Request: QueryAllGroupsWithGaugeRequest, - Response: QueryAllGroupsWithGaugeResponse, -} as const; - -/** - * GroupByGroupGaugeID returns a group given its group gauge ID - * - * @generated from rpc osmosis.incentives.Query.GroupByGroupGaugeID - */ -export const QueryGroupByGroupGaugeIDService = { - typeName: TYPE_NAME, - method: "GroupByGroupGaugeID", - Request: QueryGroupByGroupGaugeIDRequest, - Response: QueryGroupByGroupGaugeIDResponse, -} as const; - -/** - * CurrentWeightByGroupGaugeID returns the current weight since the - * the last epoch given a group gauge ID - * - * @generated from rpc osmosis.incentives.Query.CurrentWeightByGroupGaugeID - */ -export const QueryCurrentWeightByGroupGaugeIDService = { - typeName: TYPE_NAME, - method: "CurrentWeightByGroupGaugeID", - Request: QueryCurrentWeightByGroupGaugeIDRequest, - Response: QueryCurrentWeightByGroupGaugeIDResponse, -} as const; - -/** - * @generated from rpc osmosis.incentives.Query.InternalGauges - */ -export const QueryInternalGaugesService = { - typeName: TYPE_NAME, - method: "InternalGauges", - Request: QueryInternalGaugesRequest, - Response: QueryInternalGaugesResponse, -} as const; - -/** - * @generated from rpc osmosis.incentives.Query.ExternalGauges - */ -export const QueryExternalGaugesService = { - typeName: TYPE_NAME, - method: "ExternalGauges", - Request: QueryExternalGaugesRequest, - Response: QueryExternalGaugesResponse, -} as const; - -/** - * @generated from rpc osmosis.incentives.Query.GaugesByPoolID - */ -export const QueryGaugesByPoolIDService = { - typeName: TYPE_NAME, - method: "GaugesByPoolID", - Request: QueryGaugesByPoolIDRequest, - Response: QueryGaugesByPoolIDResponse, -} as const; - -/** - * Params returns incentives module params. - * - * @generated from rpc osmosis.incentives.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/incentives/query_pb.ts b/packages/es/src/protobufs/osmosis/incentives/query_pb.ts deleted file mode 100644 index 199b52fc3..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/query_pb.ts +++ /dev/null @@ -1,1494 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/query.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; -import { Gauge } from "./gauge_pb.js"; -import { PageRequest, PageResponse } from "../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Group, GroupsWithGauge } from "./group_pb.js"; -import { Params } from "./params_pb.js"; - -/** - * @generated from message osmosis.incentives.ModuleToDistributeCoinsRequest - */ -export class ModuleToDistributeCoinsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ModuleToDistributeCoinsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleToDistributeCoinsRequest { - return new ModuleToDistributeCoinsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleToDistributeCoinsRequest { - return new ModuleToDistributeCoinsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleToDistributeCoinsRequest { - return new ModuleToDistributeCoinsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ModuleToDistributeCoinsRequest | PlainMessage | undefined, b: ModuleToDistributeCoinsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleToDistributeCoinsRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ModuleToDistributeCoinsResponse - */ -export class ModuleToDistributeCoinsResponse extends Message { - /** - * Coins that have yet to be distributed - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ModuleToDistributeCoinsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleToDistributeCoinsResponse { - return new ModuleToDistributeCoinsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleToDistributeCoinsResponse { - return new ModuleToDistributeCoinsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleToDistributeCoinsResponse { - return new ModuleToDistributeCoinsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ModuleToDistributeCoinsResponse | PlainMessage | undefined, b: ModuleToDistributeCoinsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleToDistributeCoinsResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.GaugeByIDRequest - */ -export class GaugeByIDRequest extends Message { - /** - * Gauge ID being queried - * - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GaugeByIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GaugeByIDRequest { - return new GaugeByIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GaugeByIDRequest { - return new GaugeByIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GaugeByIDRequest { - return new GaugeByIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: GaugeByIDRequest | PlainMessage | undefined, b: GaugeByIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GaugeByIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.GaugeByIDResponse - */ -export class GaugeByIDResponse extends Message { - /** - * Gauge that corresponds to provided gauge ID - * - * @generated from field: osmosis.incentives.Gauge gauge = 1; - */ - gauge?: Gauge; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GaugeByIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge", kind: "message", T: Gauge }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GaugeByIDResponse { - return new GaugeByIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GaugeByIDResponse { - return new GaugeByIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GaugeByIDResponse { - return new GaugeByIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: GaugeByIDResponse | PlainMessage | undefined, b: GaugeByIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GaugeByIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.GaugesRequest - */ -export class GaugesRequest extends Message { - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GaugesRequest { - return new GaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GaugesRequest { - return new GaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GaugesRequest { - return new GaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: GaugesRequest | PlainMessage | undefined, b: GaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.GaugesResponse - */ -export class GaugesResponse extends Message { - /** - * Upcoming and active gauges - * - * @generated from field: repeated osmosis.incentives.Gauge data = 1; - */ - data: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GaugesResponse { - return new GaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GaugesResponse { - return new GaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GaugesResponse { - return new GaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: GaugesResponse | PlainMessage | undefined, b: GaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ActiveGaugesRequest - */ -export class ActiveGaugesRequest extends Message { - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ActiveGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ActiveGaugesRequest { - return new ActiveGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ActiveGaugesRequest { - return new ActiveGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ActiveGaugesRequest { - return new ActiveGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: ActiveGaugesRequest | PlainMessage | undefined, b: ActiveGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ActiveGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ActiveGaugesResponse - */ -export class ActiveGaugesResponse extends Message { - /** - * Active gauges only - * - * @generated from field: repeated osmosis.incentives.Gauge data = 1; - */ - data: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ActiveGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ActiveGaugesResponse { - return new ActiveGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ActiveGaugesResponse { - return new ActiveGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ActiveGaugesResponse { - return new ActiveGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: ActiveGaugesResponse | PlainMessage | undefined, b: ActiveGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ActiveGaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ActiveGaugesPerDenomRequest - */ -export class ActiveGaugesPerDenomRequest extends Message { - /** - * Desired denom when querying active gauges - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ActiveGaugesPerDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ActiveGaugesPerDenomRequest { - return new ActiveGaugesPerDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ActiveGaugesPerDenomRequest { - return new ActiveGaugesPerDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ActiveGaugesPerDenomRequest { - return new ActiveGaugesPerDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: ActiveGaugesPerDenomRequest | PlainMessage | undefined, b: ActiveGaugesPerDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ActiveGaugesPerDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ActiveGaugesPerDenomResponse - */ -export class ActiveGaugesPerDenomResponse extends Message { - /** - * Active gauges that match denom in query - * - * @generated from field: repeated osmosis.incentives.Gauge data = 1; - */ - data: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ActiveGaugesPerDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ActiveGaugesPerDenomResponse { - return new ActiveGaugesPerDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ActiveGaugesPerDenomResponse { - return new ActiveGaugesPerDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ActiveGaugesPerDenomResponse { - return new ActiveGaugesPerDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: ActiveGaugesPerDenomResponse | PlainMessage | undefined, b: ActiveGaugesPerDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ActiveGaugesPerDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.UpcomingGaugesRequest - */ -export class UpcomingGaugesRequest extends Message { - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.UpcomingGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpcomingGaugesRequest { - return new UpcomingGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpcomingGaugesRequest { - return new UpcomingGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpcomingGaugesRequest { - return new UpcomingGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: UpcomingGaugesRequest | PlainMessage | undefined, b: UpcomingGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UpcomingGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.UpcomingGaugesResponse - */ -export class UpcomingGaugesResponse extends Message { - /** - * Gauges whose distribution is upcoming - * - * @generated from field: repeated osmosis.incentives.Gauge data = 1; - */ - data: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.UpcomingGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpcomingGaugesResponse { - return new UpcomingGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpcomingGaugesResponse { - return new UpcomingGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpcomingGaugesResponse { - return new UpcomingGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: UpcomingGaugesResponse | PlainMessage | undefined, b: UpcomingGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UpcomingGaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.UpcomingGaugesPerDenomRequest - */ -export class UpcomingGaugesPerDenomRequest extends Message { - /** - * Filter for upcoming gauges that match specific denom - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.UpcomingGaugesPerDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpcomingGaugesPerDenomRequest { - return new UpcomingGaugesPerDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpcomingGaugesPerDenomRequest { - return new UpcomingGaugesPerDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpcomingGaugesPerDenomRequest { - return new UpcomingGaugesPerDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: UpcomingGaugesPerDenomRequest | PlainMessage | undefined, b: UpcomingGaugesPerDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UpcomingGaugesPerDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.UpcomingGaugesPerDenomResponse - */ -export class UpcomingGaugesPerDenomResponse extends Message { - /** - * Upcoming gauges that match denom in query - * - * @generated from field: repeated osmosis.incentives.Gauge upcoming_gauges = 1; - */ - upcomingGauges: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.UpcomingGaugesPerDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "upcoming_gauges", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpcomingGaugesPerDenomResponse { - return new UpcomingGaugesPerDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpcomingGaugesPerDenomResponse { - return new UpcomingGaugesPerDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpcomingGaugesPerDenomResponse { - return new UpcomingGaugesPerDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: UpcomingGaugesPerDenomResponse | PlainMessage | undefined, b: UpcomingGaugesPerDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UpcomingGaugesPerDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.RewardsEstRequest - */ -export class RewardsEstRequest extends Message { - /** - * Address that is being queried for future estimated rewards - * - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * Lock IDs included in future reward estimation - * - * @generated from field: repeated uint64 lock_ids = 2; - */ - lockIds: bigint[] = []; - - /** - * Upper time limit of reward estimation - * Lower limit is current epoch - * - * @generated from field: int64 end_epoch = 3; - */ - endEpoch = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.RewardsEstRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 3, name: "end_epoch", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RewardsEstRequest { - return new RewardsEstRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RewardsEstRequest { - return new RewardsEstRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RewardsEstRequest { - return new RewardsEstRequest().fromJsonString(jsonString, options); - } - - static equals(a: RewardsEstRequest | PlainMessage | undefined, b: RewardsEstRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(RewardsEstRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.RewardsEstResponse - */ -export class RewardsEstResponse extends Message { - /** - * Estimated coin rewards that will be received at provided address - * from specified locks between current time and end epoch - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.RewardsEstResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RewardsEstResponse { - return new RewardsEstResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RewardsEstResponse { - return new RewardsEstResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RewardsEstResponse { - return new RewardsEstResponse().fromJsonString(jsonString, options); - } - - static equals(a: RewardsEstResponse | PlainMessage | undefined, b: RewardsEstResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(RewardsEstResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryLockableDurationsRequest - */ -export class QueryLockableDurationsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryLockableDurationsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryLockableDurationsRequest | PlainMessage | undefined, b: QueryLockableDurationsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLockableDurationsRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryLockableDurationsResponse - */ -export class QueryLockableDurationsResponse extends Message { - /** - * Time durations that users can lock coins for in order to receive rewards - * - * @generated from field: repeated google.protobuf.Duration lockable_durations = 1; - */ - lockableDurations: Duration[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryLockableDurationsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryLockableDurationsResponse | PlainMessage | undefined, b: QueryLockableDurationsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLockableDurationsResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsRequest - */ -export class QueryAllGroupsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsRequest { - return new QueryAllGroupsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsRequest { - return new QueryAllGroupsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsRequest { - return new QueryAllGroupsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsRequest | PlainMessage | undefined, b: QueryAllGroupsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsResponse - */ -export class QueryAllGroupsResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Group groups = 1; - */ - groups: Group[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "groups", kind: "message", T: Group, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsResponse { - return new QueryAllGroupsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsResponse { - return new QueryAllGroupsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsResponse { - return new QueryAllGroupsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsResponse | PlainMessage | undefined, b: QueryAllGroupsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsGaugesRequest - */ -export class QueryAllGroupsGaugesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsGaugesRequest { - return new QueryAllGroupsGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsGaugesRequest { - return new QueryAllGroupsGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsGaugesRequest { - return new QueryAllGroupsGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsGaugesRequest | PlainMessage | undefined, b: QueryAllGroupsGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsGaugesResponse - */ -export class QueryAllGroupsGaugesResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Gauge gauges = 1; - */ - gauges: Gauge[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauges", kind: "message", T: Gauge, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsGaugesResponse { - return new QueryAllGroupsGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsGaugesResponse { - return new QueryAllGroupsGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsGaugesResponse { - return new QueryAllGroupsGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsGaugesResponse | PlainMessage | undefined, b: QueryAllGroupsGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsGaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsWithGaugeRequest - */ -export class QueryAllGroupsWithGaugeRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsWithGaugeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsWithGaugeRequest { - return new QueryAllGroupsWithGaugeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsWithGaugeRequest { - return new QueryAllGroupsWithGaugeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsWithGaugeRequest { - return new QueryAllGroupsWithGaugeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsWithGaugeRequest | PlainMessage | undefined, b: QueryAllGroupsWithGaugeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsWithGaugeRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryAllGroupsWithGaugeResponse - */ -export class QueryAllGroupsWithGaugeResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.GroupsWithGauge groups_with_gauge = 1; - */ - groupsWithGauge: GroupsWithGauge[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryAllGroupsWithGaugeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "groups_with_gauge", kind: "message", T: GroupsWithGauge, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllGroupsWithGaugeResponse { - return new QueryAllGroupsWithGaugeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllGroupsWithGaugeResponse { - return new QueryAllGroupsWithGaugeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllGroupsWithGaugeResponse { - return new QueryAllGroupsWithGaugeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllGroupsWithGaugeResponse | PlainMessage | undefined, b: QueryAllGroupsWithGaugeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllGroupsWithGaugeResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryGroupByGroupGaugeIDRequest - */ -export class QueryGroupByGroupGaugeIDRequest extends Message { - /** - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryGroupByGroupGaugeIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGroupByGroupGaugeIDRequest { - return new QueryGroupByGroupGaugeIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGroupByGroupGaugeIDRequest { - return new QueryGroupByGroupGaugeIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGroupByGroupGaugeIDRequest { - return new QueryGroupByGroupGaugeIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGroupByGroupGaugeIDRequest | PlainMessage | undefined, b: QueryGroupByGroupGaugeIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGroupByGroupGaugeIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryGroupByGroupGaugeIDResponse - */ -export class QueryGroupByGroupGaugeIDResponse extends Message { - /** - * @generated from field: osmosis.incentives.Group group = 1; - */ - group?: Group; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryGroupByGroupGaugeIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "group", kind: "message", T: Group }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGroupByGroupGaugeIDResponse { - return new QueryGroupByGroupGaugeIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGroupByGroupGaugeIDResponse { - return new QueryGroupByGroupGaugeIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGroupByGroupGaugeIDResponse { - return new QueryGroupByGroupGaugeIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGroupByGroupGaugeIDResponse | PlainMessage | undefined, b: QueryGroupByGroupGaugeIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGroupByGroupGaugeIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryCurrentWeightByGroupGaugeIDRequest - */ -export class QueryCurrentWeightByGroupGaugeIDRequest extends Message { - /** - * @generated from field: uint64 group_gauge_id = 1; - */ - groupGaugeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryCurrentWeightByGroupGaugeIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "group_gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCurrentWeightByGroupGaugeIDRequest { - return new QueryCurrentWeightByGroupGaugeIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCurrentWeightByGroupGaugeIDRequest { - return new QueryCurrentWeightByGroupGaugeIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCurrentWeightByGroupGaugeIDRequest { - return new QueryCurrentWeightByGroupGaugeIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryCurrentWeightByGroupGaugeIDRequest | PlainMessage | undefined, b: QueryCurrentWeightByGroupGaugeIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCurrentWeightByGroupGaugeIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryCurrentWeightByGroupGaugeIDResponse - */ -export class QueryCurrentWeightByGroupGaugeIDResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.GaugeWeight gauge_weight = 1; - */ - gaugeWeight: GaugeWeight[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryCurrentWeightByGroupGaugeIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_weight", kind: "message", T: GaugeWeight, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCurrentWeightByGroupGaugeIDResponse { - return new QueryCurrentWeightByGroupGaugeIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCurrentWeightByGroupGaugeIDResponse { - return new QueryCurrentWeightByGroupGaugeIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCurrentWeightByGroupGaugeIDResponse { - return new QueryCurrentWeightByGroupGaugeIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryCurrentWeightByGroupGaugeIDResponse | PlainMessage | undefined, b: QueryCurrentWeightByGroupGaugeIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCurrentWeightByGroupGaugeIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.GaugeWeight - */ -export class GaugeWeight extends Message { - /** - * @generated from field: uint64 gauge_id = 1; - */ - gaugeId = protoInt64.zero; - - /** - * @generated from field: string weight_ratio = 2; - */ - weightRatio = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.GaugeWeight"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "weight_ratio", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GaugeWeight { - return new GaugeWeight().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GaugeWeight { - return new GaugeWeight().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GaugeWeight { - return new GaugeWeight().fromJsonString(jsonString, options); - } - - static equals(a: GaugeWeight | PlainMessage | undefined, b: GaugeWeight | PlainMessage | undefined): boolean { - return proto3.util.equals(GaugeWeight, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryInternalGaugesRequest - */ -export class QueryInternalGaugesRequest extends Message { - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryInternalGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInternalGaugesRequest { - return new QueryInternalGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInternalGaugesRequest { - return new QueryInternalGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInternalGaugesRequest { - return new QueryInternalGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryInternalGaugesRequest | PlainMessage | undefined, b: QueryInternalGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInternalGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryInternalGaugesResponse - */ -export class QueryInternalGaugesResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Gauge gauges = 1; - */ - gauges: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryInternalGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauges", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInternalGaugesResponse { - return new QueryInternalGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInternalGaugesResponse { - return new QueryInternalGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInternalGaugesResponse { - return new QueryInternalGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryInternalGaugesResponse | PlainMessage | undefined, b: QueryInternalGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInternalGaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryExternalGaugesRequest - */ -export class QueryExternalGaugesRequest extends Message { - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryExternalGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryExternalGaugesRequest { - return new QueryExternalGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryExternalGaugesRequest { - return new QueryExternalGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryExternalGaugesRequest { - return new QueryExternalGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryExternalGaugesRequest | PlainMessage | undefined, b: QueryExternalGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryExternalGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryExternalGaugesResponse - */ -export class QueryExternalGaugesResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Gauge gauges = 1; - */ - gauges: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryExternalGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauges", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryExternalGaugesResponse { - return new QueryExternalGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryExternalGaugesResponse { - return new QueryExternalGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryExternalGaugesResponse { - return new QueryExternalGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryExternalGaugesResponse | PlainMessage | undefined, b: QueryExternalGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryExternalGaugesResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryGaugesByPoolIDRequest - */ -export class QueryGaugesByPoolIDRequest extends Message { - /** - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - /** - * Pagination defines pagination for the request - * - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 2; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryGaugesByPoolIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGaugesByPoolIDRequest { - return new QueryGaugesByPoolIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGaugesByPoolIDRequest { - return new QueryGaugesByPoolIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGaugesByPoolIDRequest { - return new QueryGaugesByPoolIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGaugesByPoolIDRequest | PlainMessage | undefined, b: QueryGaugesByPoolIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGaugesByPoolIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.QueryGaugesByPoolIDResponse - */ -export class QueryGaugesByPoolIDResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Gauge gauges = 1; - */ - gauges: Gauge[] = []; - - /** - * Pagination defines pagination for the response - * - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.QueryGaugesByPoolIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauges", kind: "message", T: Gauge, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGaugesByPoolIDResponse { - return new QueryGaugesByPoolIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGaugesByPoolIDResponse { - return new QueryGaugesByPoolIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGaugesByPoolIDResponse { - return new QueryGaugesByPoolIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGaugesByPoolIDResponse | PlainMessage | undefined, b: QueryGaugesByPoolIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGaugesByPoolIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.incentives.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.incentives.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/incentives/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/incentives/tx_cosmes.ts deleted file mode 100644 index 9228a1f8f..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/tx_cosmes.ts +++ /dev/null @@ -1,39 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/incentives/tx.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddToGauge, MsgAddToGaugeResponse, MsgCreateGauge, MsgCreateGaugeResponse, MsgCreateGroup, MsgCreateGroupResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.incentives.Msg"; - -/** - * @generated from rpc osmosis.incentives.Msg.CreateGauge - */ -export const MsgCreateGaugeService = { - typeName: TYPE_NAME, - method: "CreateGauge", - Request: MsgCreateGauge, - Response: MsgCreateGaugeResponse, -} as const; - -/** - * @generated from rpc osmosis.incentives.Msg.AddToGauge - */ -export const MsgAddToGaugeService = { - typeName: TYPE_NAME, - method: "AddToGauge", - Request: MsgAddToGauge, - Response: MsgAddToGaugeResponse, -} as const; - -/** - * @generated from rpc osmosis.incentives.Msg.CreateGroup - */ -export const MsgCreateGroupService = { - typeName: TYPE_NAME, - method: "CreateGroup", - Request: MsgCreateGroup, - Response: MsgCreateGroupResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/incentives/tx_pb.ts b/packages/es/src/protobufs/osmosis/incentives/tx_pb.ts deleted file mode 100644 index 6ab453db9..000000000 --- a/packages/es/src/protobufs/osmosis/incentives/tx_pb.ts +++ /dev/null @@ -1,335 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/incentives/tx.proto (package osmosis.incentives, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { QueryCondition } from "../lockup/lock_pb.js"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * MsgCreateGauge creates a gauge to distribute rewards to users - * - * @generated from message osmosis.incentives.MsgCreateGauge - */ -export class MsgCreateGauge extends Message { - /** - * is_perpetual shows if it's a perpetual or non-perpetual gauge - * Non-perpetual gauges distribute their tokens equally per epoch while the - * gauge is in the active period. Perpetual gauges distribute all their tokens - * at a single time and only distribute their tokens again once the gauge is - * refilled - * - * @generated from field: bool is_perpetual = 1; - */ - isPerpetual = false; - - /** - * owner is the address of gauge creator - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * distribute_to show which lock the gauge should distribute to by time - * duration or by timestamp - * - * @generated from field: osmosis.lockup.QueryCondition distribute_to = 3; - */ - distributeTo?: QueryCondition; - - /** - * coins are coin(s) to be distributed by the gauge - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 4; - */ - coins: Coin[] = []; - - /** - * start_time is the distribution start time - * - * @generated from field: google.protobuf.Timestamp start_time = 5; - */ - startTime?: Timestamp; - - /** - * num_epochs_paid_over is the number of epochs distribution will be completed - * over - * - * @generated from field: uint64 num_epochs_paid_over = 6; - */ - numEpochsPaidOver = protoInt64.zero; - - /** - * pool_id is the ID of the pool that the gauge is meant to be associated - * with. if pool_id is set, then the "QueryCondition.LockQueryType" must be - * "NoLock" with all other fields of the "QueryCondition.LockQueryType" struct - * unset, including "QueryCondition.Denom". However, note that, internally, - * the empty string in "QueryCondition.Denom" ends up being overwritten with - * incentivestypes.NoLockExternalGaugeDenom() so that the gauges - * associated with a pool can be queried by this prefix if needed. - * - * @generated from field: uint64 pool_id = 7; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgCreateGauge"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "is_perpetual", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "distribute_to", kind: "message", T: QueryCondition }, - { no: 4, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 5, name: "start_time", kind: "message", T: Timestamp }, - { no: 6, name: "num_epochs_paid_over", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 7, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateGauge { - return new MsgCreateGauge().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateGauge { - return new MsgCreateGauge().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateGauge { - return new MsgCreateGauge().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateGauge | PlainMessage | undefined, b: MsgCreateGauge | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateGauge, a, b); - } -} - -/** - * @generated from message osmosis.incentives.MsgCreateGaugeResponse - */ -export class MsgCreateGaugeResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgCreateGaugeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateGaugeResponse { - return new MsgCreateGaugeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateGaugeResponse { - return new MsgCreateGaugeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateGaugeResponse { - return new MsgCreateGaugeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateGaugeResponse | PlainMessage | undefined, b: MsgCreateGaugeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateGaugeResponse, a, b); - } -} - -/** - * MsgAddToGauge adds coins to a previously created gauge - * - * @generated from message osmosis.incentives.MsgAddToGauge - */ -export class MsgAddToGauge extends Message { - /** - * owner is the gauge owner's address - * - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * gauge_id is the ID of gauge that rewards are getting added to - * - * @generated from field: uint64 gauge_id = 2; - */ - gaugeId = protoInt64.zero; - - /** - * rewards are the coin(s) to add to gauge - * - * @generated from field: repeated cosmos.base.v1beta1.Coin rewards = 3; - */ - rewards: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgAddToGauge"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "rewards", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToGauge { - return new MsgAddToGauge().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToGauge { - return new MsgAddToGauge().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToGauge { - return new MsgAddToGauge().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToGauge | PlainMessage | undefined, b: MsgAddToGauge | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToGauge, a, b); - } -} - -/** - * @generated from message osmosis.incentives.MsgAddToGaugeResponse - */ -export class MsgAddToGaugeResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgAddToGaugeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToGaugeResponse { - return new MsgAddToGaugeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToGaugeResponse { - return new MsgAddToGaugeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToGaugeResponse { - return new MsgAddToGaugeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToGaugeResponse | PlainMessage | undefined, b: MsgAddToGaugeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToGaugeResponse, a, b); - } -} - -/** - * MsgCreateGroup creates a group to distribute rewards to a group of pools - * - * @generated from message osmosis.incentives.MsgCreateGroup - */ -export class MsgCreateGroup extends Message { - /** - * coins are the provided coins that the group will distribute - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - /** - * num_epochs_paid_over is the number of epochs distribution will be completed - * in. 0 means it's perpetual - * - * @generated from field: uint64 num_epochs_paid_over = 2; - */ - numEpochsPaidOver = protoInt64.zero; - - /** - * owner is the group owner's address - * - * @generated from field: string owner = 3; - */ - owner = ""; - - /** - * pool_ids are the IDs of pools that the group is comprised of - * - * @generated from field: repeated uint64 pool_ids = 4; - */ - poolIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgCreateGroup"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "num_epochs_paid_over", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "pool_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateGroup { - return new MsgCreateGroup().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateGroup { - return new MsgCreateGroup().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateGroup { - return new MsgCreateGroup().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateGroup | PlainMessage | undefined, b: MsgCreateGroup | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateGroup, a, b); - } -} - -/** - * @generated from message osmosis.incentives.MsgCreateGroupResponse - */ -export class MsgCreateGroupResponse extends Message { - /** - * group_id is the ID of the group that is created from this msg - * - * @generated from field: uint64 group_id = 1; - */ - groupId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.incentives.MsgCreateGroupResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "group_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateGroupResponse { - return new MsgCreateGroupResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateGroupResponse { - return new MsgCreateGroupResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateGroupResponse { - return new MsgCreateGroupResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateGroupResponse | PlainMessage | undefined, b: MsgCreateGroupResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateGroupResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_cosmes.ts b/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_cosmes.ts deleted file mode 100644 index 993278386..000000000 --- a/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_cosmes.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/ingest/v1beta1/ingest.proto (package osmosis.ingest.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ProcessBlockReply, ProcessBlockRequest } from "./ingest_pb.js"; - -const TYPE_NAME = "osmosis.ingest.v1beta1.SQSIngester"; - -/** - * ProcessBlock processes a block from the Osmosis node. - * - * @generated from rpc osmosis.ingest.v1beta1.SQSIngester.ProcessBlock - */ -export const SQSIngesterProcessBlockService = { - typeName: TYPE_NAME, - method: "ProcessBlock", - Request: ProcessBlockRequest, - Response: ProcessBlockReply, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_pb.ts b/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_pb.ts deleted file mode 100644 index 7320a3cdf..000000000 --- a/packages/es/src/protobufs/osmosis/ingest/v1beta1/ingest_pb.ts +++ /dev/null @@ -1,158 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/ingest/v1beta1/ingest.proto (package osmosis.ingest.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * PoolData represents a structure encapsulating an Osmosis liquidity pool. - * - * @generated from message osmosis.ingest.v1beta1.PoolData - */ -export class PoolData extends Message { - /** - * ChainModel is the chain representation model of the pool. - * - * @generated from field: bytes chain_model = 1; - */ - chainModel = new Uint8Array(0); - - /** - * SqsModel is additional pool data used by the sidecar query server. - * - * @generated from field: bytes sqs_model = 2; - */ - sqsModel = new Uint8Array(0); - - /** - * TickModel is the tick data of a concentrated liquidity pool. - * This field is only valid and set for concentrated pools. It is nil - * otherwise. - * - * @generated from field: bytes tick_model = 3; - */ - tickModel = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ingest.v1beta1.PoolData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "chain_model", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "sqs_model", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "tick_model", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolData { - return new PoolData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolData { - return new PoolData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolData { - return new PoolData().fromJsonString(jsonString, options); - } - - static equals(a: PoolData | PlainMessage | undefined, b: PoolData | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolData, a, b); - } -} - -/** - * The block process request. - * Sends taker fees, block height and pools. - * - * @generated from message osmosis.ingest.v1beta1.ProcessBlockRequest - */ -export class ProcessBlockRequest extends Message { - /** - * block height is the height of the block being processed. - * - * @generated from field: uint64 block_height = 1; - */ - blockHeight = protoInt64.zero; - - /** - * taker_fees_map is the map of taker fees for the block. - * - * @generated from field: bytes taker_fees_map = 2; - */ - takerFeesMap = new Uint8Array(0); - - /** - * pools in the block. - * - * @generated from field: repeated osmosis.ingest.v1beta1.PoolData pools = 3; - */ - pools: PoolData[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ingest.v1beta1.ProcessBlockRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "taker_fees_map", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 3, name: "pools", kind: "message", T: PoolData, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ProcessBlockRequest { - return new ProcessBlockRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ProcessBlockRequest { - return new ProcessBlockRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ProcessBlockRequest { - return new ProcessBlockRequest().fromJsonString(jsonString, options); - } - - static equals(a: ProcessBlockRequest | PlainMessage | undefined, b: ProcessBlockRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ProcessBlockRequest, a, b); - } -} - -/** - * The response after completing the block processing. - * - * @generated from message osmosis.ingest.v1beta1.ProcessBlockReply - */ -export class ProcessBlockReply extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.ingest.v1beta1.ProcessBlockReply"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ProcessBlockReply { - return new ProcessBlockReply().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ProcessBlockReply { - return new ProcessBlockReply().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ProcessBlockReply { - return new ProcessBlockReply().fromJsonString(jsonString, options); - } - - static equals(a: ProcessBlockReply | PlainMessage | undefined, b: ProcessBlockReply | PlainMessage | undefined): boolean { - return proto3.util.equals(ProcessBlockReply, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/lockup/genesis_pb.ts b/packages/es/src/protobufs/osmosis/lockup/genesis_pb.ts deleted file mode 100644 index 52b2630a3..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/genesis_pb.ts +++ /dev/null @@ -1,67 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/lockup/genesis.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { PeriodLock, SyntheticLock } from "./lock_pb.js"; -import { Params } from "./params_pb.js"; - -/** - * GenesisState defines the lockup module's genesis state. - * - * @generated from message osmosis.lockup.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: uint64 last_lock_id = 1; - */ - lastLockId = protoInt64.zero; - - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 2; - */ - locks: PeriodLock[] = []; - - /** - * @generated from field: repeated osmosis.lockup.SyntheticLock synthetic_locks = 3; - */ - syntheticLocks: SyntheticLock[] = []; - - /** - * @generated from field: osmosis.lockup.Params params = 4; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "last_lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - { no: 3, name: "synthetic_locks", kind: "message", T: SyntheticLock, repeated: true }, - { no: 4, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/lockup/lock_pb.ts b/packages/es/src/protobufs/osmosis/lockup/lock_pb.ts deleted file mode 100644 index fcb447e4e..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/lock_pb.ts +++ /dev/null @@ -1,280 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/lockup/lock.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * LockQueryType defines the type of the lock query that can - * either be by duration or start time of the lock. - * - * @generated from enum osmosis.lockup.LockQueryType - */ -export enum LockQueryType { - /** - * @generated from enum value: ByDuration = 0; - */ - ByDuration = 0, - - /** - * @generated from enum value: ByTime = 1; - */ - ByTime = 1, - - /** - * @generated from enum value: NoLock = 2; - */ - NoLock = 2, - - /** - * @generated from enum value: ByGroup = 3; - */ - ByGroup = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(LockQueryType) -proto3.util.setEnumType(LockQueryType, "osmosis.lockup.LockQueryType", [ - { no: 0, name: "ByDuration" }, - { no: 1, name: "ByTime" }, - { no: 2, name: "NoLock" }, - { no: 3, name: "ByGroup" }, -]); - -/** - * PeriodLock is a single lock unit by period defined by the x/lockup module. - * It's a record of a locked coin at a specific time. It stores owner, duration, - * unlock time and the number of coins locked. A state of a period lock is - * created upon lock creation, and deleted once the lock has been matured after - * the `duration` has passed since unbonding started. - * - * @generated from message osmosis.lockup.PeriodLock - */ -export class PeriodLock extends Message { - /** - * ID is the unique id of the lock. - * The ID of the lock is decided upon lock creation, incrementing by 1 for - * every lock. - * - * @generated from field: uint64 ID = 1; - */ - ID = protoInt64.zero; - - /** - * Owner is the account address of the lock owner. - * Only the owner can modify the state of the lock. - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * Duration is the time needed for a lock to mature after unlocking has - * started. - * - * @generated from field: google.protobuf.Duration duration = 3; - */ - duration?: Duration; - - /** - * EndTime refers to the time at which the lock would mature and get deleted. - * This value is first initialized when an unlock has started for the lock, - * end time being block time + duration. - * - * @generated from field: google.protobuf.Timestamp end_time = 4; - */ - endTime?: Timestamp; - - /** - * Coins are the tokens locked within the lock, kept in the module account. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 5; - */ - coins: Coin[] = []; - - /** - * Reward Receiver Address is the address that would be receiving rewards for - * the incentives for the lock. This is set to owner by default and can be - * changed via separate msg. - * - * @generated from field: string reward_receiver_address = 6; - */ - rewardReceiverAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.PeriodLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "duration", kind: "message", T: Duration }, - { no: 4, name: "end_time", kind: "message", T: Timestamp }, - { no: 5, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 6, name: "reward_receiver_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PeriodLock { - return new PeriodLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PeriodLock { - return new PeriodLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PeriodLock { - return new PeriodLock().fromJsonString(jsonString, options); - } - - static equals(a: PeriodLock | PlainMessage | undefined, b: PeriodLock | PlainMessage | undefined): boolean { - return proto3.util.equals(PeriodLock, a, b); - } -} - -/** - * QueryCondition is a struct used for querying locks upon different conditions. - * Duration field and timestamp fields could be optional, depending on the - * LockQueryType. - * - * @generated from message osmosis.lockup.QueryCondition - */ -export class QueryCondition extends Message { - /** - * LockQueryType is a type of lock query, ByLockDuration | ByLockTime - * - * @generated from field: osmosis.lockup.LockQueryType lock_query_type = 1; - */ - lockQueryType = LockQueryType.ByDuration; - - /** - * Denom represents the token denomination we are looking to lock up - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * Duration is used to query locks with longer duration than the specified - * duration. Duration field must not be nil when the lock query type is - * `ByLockDuration`. - * - * @generated from field: google.protobuf.Duration duration = 3; - */ - duration?: Duration; - - /** - * Timestamp is used by locks started before the specified duration. - * Timestamp field must not be nil when the lock query type is `ByLockTime`. - * Querying locks with timestamp is currently not implemented. - * - * @generated from field: google.protobuf.Timestamp timestamp = 4; - */ - timestamp?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.QueryCondition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_query_type", kind: "enum", T: proto3.getEnumType(LockQueryType) }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "duration", kind: "message", T: Duration }, - { no: 4, name: "timestamp", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryCondition { - return new QueryCondition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryCondition { - return new QueryCondition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryCondition { - return new QueryCondition().fromJsonString(jsonString, options); - } - - static equals(a: QueryCondition | PlainMessage | undefined, b: QueryCondition | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryCondition, a, b); - } -} - -/** - * SyntheticLock is creating virtual lockup where new denom is combination of - * original denom and synthetic suffix. At the time of synthetic lockup creation - * and deletion, accumulation store is also being updated and on querier side, - * they can query as freely as native lockup. - * - * @generated from message osmosis.lockup.SyntheticLock - */ -export class SyntheticLock extends Message { - /** - * Underlying Lock ID is the underlying native lock's id for this synthetic - * lockup. A synthetic lock MUST have an underlying lock. - * - * @generated from field: uint64 underlying_lock_id = 1; - */ - underlyingLockId = protoInt64.zero; - - /** - * SynthDenom is the synthetic denom that is a combination of - * gamm share + bonding status + validator address. - * - * @generated from field: string synth_denom = 2; - */ - synthDenom = ""; - - /** - * used for unbonding synthetic lockups, for active synthetic lockups, this - * value is set to uninitialized value - * - * @generated from field: google.protobuf.Timestamp end_time = 3; - */ - endTime?: Timestamp; - - /** - * Duration is the duration for a synthetic lock to mature - * at the point of unbonding has started. - * - * @generated from field: google.protobuf.Duration duration = 4; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.SyntheticLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "underlying_lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "synth_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "end_time", kind: "message", T: Timestamp }, - { no: 4, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SyntheticLock { - return new SyntheticLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SyntheticLock { - return new SyntheticLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SyntheticLock { - return new SyntheticLock().fromJsonString(jsonString, options); - } - - static equals(a: SyntheticLock | PlainMessage | undefined, b: SyntheticLock | PlainMessage | undefined): boolean { - return proto3.util.equals(SyntheticLock, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/lockup/params_pb.ts b/packages/es/src/protobufs/osmosis/lockup/params_pb.ts deleted file mode 100644 index 68e4dad3b..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/params_pb.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/lockup/params.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.lockup.Params - */ -export class Params extends Message { - /** - * @generated from field: repeated string force_unlock_allowed_addresses = 1; - */ - forceUnlockAllowedAddresses: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "force_unlock_allowed_addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/lockup/query_cosmes.ts b/packages/es/src/protobufs/osmosis/lockup/query_cosmes.ts deleted file mode 100644 index 72fa06807..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/query_cosmes.ts +++ /dev/null @@ -1,253 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/lockup/query.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { AccountLockedCoinsRequest, AccountLockedCoinsResponse, AccountLockedDurationRequest, AccountLockedDurationResponse, AccountLockedLongerDurationDenomRequest, AccountLockedLongerDurationDenomResponse, AccountLockedLongerDurationNotUnlockingOnlyRequest, AccountLockedLongerDurationNotUnlockingOnlyResponse, AccountLockedLongerDurationRequest, AccountLockedLongerDurationResponse, AccountLockedPastTimeDenomRequest, AccountLockedPastTimeDenomResponse, AccountLockedPastTimeNotUnlockingOnlyRequest, AccountLockedPastTimeNotUnlockingOnlyResponse, AccountLockedPastTimeRequest, AccountLockedPastTimeResponse, AccountUnlockableCoinsRequest, AccountUnlockableCoinsResponse, AccountUnlockedBeforeTimeRequest, AccountUnlockedBeforeTimeResponse, AccountUnlockingCoinsRequest, AccountUnlockingCoinsResponse, LockedDenomRequest, LockedDenomResponse, LockedRequest, LockedResponse, LockRewardReceiverRequest, LockRewardReceiverResponse, ModuleBalanceRequest, ModuleBalanceResponse, ModuleLockedAmountRequest, ModuleLockedAmountResponse, NextLockIDRequest, NextLockIDResponse, QueryParamsRequest, QueryParamsResponse, SyntheticLockupByLockupIDRequest, SyntheticLockupByLockupIDResponse, SyntheticLockupsByLockupIDRequest, SyntheticLockupsByLockupIDResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.lockup.Query"; - -/** - * Return full balance of the module - * - * @generated from rpc osmosis.lockup.Query.ModuleBalance - */ -export const QueryModuleBalanceService = { - typeName: TYPE_NAME, - method: "ModuleBalance", - Request: ModuleBalanceRequest, - Response: ModuleBalanceResponse, -} as const; - -/** - * Return locked balance of the module - * - * @generated from rpc osmosis.lockup.Query.ModuleLockedAmount - */ -export const QueryModuleLockedAmountService = { - typeName: TYPE_NAME, - method: "ModuleLockedAmount", - Request: ModuleLockedAmountRequest, - Response: ModuleLockedAmountResponse, -} as const; - -/** - * Returns unlockable coins which are not withdrawn yet - * - * @generated from rpc osmosis.lockup.Query.AccountUnlockableCoins - */ -export const QueryAccountUnlockableCoinsService = { - typeName: TYPE_NAME, - method: "AccountUnlockableCoins", - Request: AccountUnlockableCoinsRequest, - Response: AccountUnlockableCoinsResponse, -} as const; - -/** - * Returns unlocking coins - * - * @generated from rpc osmosis.lockup.Query.AccountUnlockingCoins - */ -export const QueryAccountUnlockingCoinsService = { - typeName: TYPE_NAME, - method: "AccountUnlockingCoins", - Request: AccountUnlockingCoinsRequest, - Response: AccountUnlockingCoinsResponse, -} as const; - -/** - * Return a locked coins that can't be withdrawn - * - * @generated from rpc osmosis.lockup.Query.AccountLockedCoins - */ -export const QueryAccountLockedCoinsService = { - typeName: TYPE_NAME, - method: "AccountLockedCoins", - Request: AccountLockedCoinsRequest, - Response: AccountLockedCoinsResponse, -} as const; - -/** - * Returns locked records of an account with unlock time beyond timestamp - * - * @generated from rpc osmosis.lockup.Query.AccountLockedPastTime - */ -export const QueryAccountLockedPastTimeService = { - typeName: TYPE_NAME, - method: "AccountLockedPastTime", - Request: AccountLockedPastTimeRequest, - Response: AccountLockedPastTimeResponse, -} as const; - -/** - * Returns locked records of an account with unlock time beyond timestamp - * excluding tokens started unlocking - * - * @generated from rpc osmosis.lockup.Query.AccountLockedPastTimeNotUnlockingOnly - */ -export const QueryAccountLockedPastTimeNotUnlockingOnlyService = { - typeName: TYPE_NAME, - method: "AccountLockedPastTimeNotUnlockingOnly", - Request: AccountLockedPastTimeNotUnlockingOnlyRequest, - Response: AccountLockedPastTimeNotUnlockingOnlyResponse, -} as const; - -/** - * Returns unlocked records with unlock time before timestamp - * - * @generated from rpc osmosis.lockup.Query.AccountUnlockedBeforeTime - */ -export const QueryAccountUnlockedBeforeTimeService = { - typeName: TYPE_NAME, - method: "AccountUnlockedBeforeTime", - Request: AccountUnlockedBeforeTimeRequest, - Response: AccountUnlockedBeforeTimeResponse, -} as const; - -/** - * Returns lock records by address, timestamp, denom - * - * @generated from rpc osmosis.lockup.Query.AccountLockedPastTimeDenom - */ -export const QueryAccountLockedPastTimeDenomService = { - typeName: TYPE_NAME, - method: "AccountLockedPastTimeDenom", - Request: AccountLockedPastTimeDenomRequest, - Response: AccountLockedPastTimeDenomResponse, -} as const; - -/** - * Returns total locked per denom with longer past given time - * - * @generated from rpc osmosis.lockup.Query.LockedDenom - */ -export const QueryLockedDenomService = { - typeName: TYPE_NAME, - method: "LockedDenom", - Request: LockedDenomRequest, - Response: LockedDenomResponse, -} as const; - -/** - * Returns lock record by id - * - * @generated from rpc osmosis.lockup.Query.LockedByID - */ -export const QueryLockedByIDService = { - typeName: TYPE_NAME, - method: "LockedByID", - Request: LockedRequest, - Response: LockedResponse, -} as const; - -/** - * Returns lock record by id - * - * @generated from rpc osmosis.lockup.Query.LockRewardReceiver - */ -export const QueryLockRewardReceiverService = { - typeName: TYPE_NAME, - method: "LockRewardReceiver", - Request: LockRewardReceiverRequest, - Response: LockRewardReceiverResponse, -} as const; - -/** - * Returns next lock ID - * - * @generated from rpc osmosis.lockup.Query.NextLockID - */ -export const QueryNextLockIDService = { - typeName: TYPE_NAME, - method: "NextLockID", - Request: NextLockIDRequest, - Response: NextLockIDResponse, -} as const; - -/** - * Returns synthetic lockup by native lockup id - * Deprecated: use SyntheticLockupByLockupID instead - * - * @generated from rpc osmosis.lockup.Query.SyntheticLockupsByLockupID - * @deprecated - */ -export const QuerySyntheticLockupsByLockupIDService = { - typeName: TYPE_NAME, - method: "SyntheticLockupsByLockupID", - Request: SyntheticLockupsByLockupIDRequest, - Response: SyntheticLockupsByLockupIDResponse, -} as const; - -/** - * Returns synthetic lockup by native lockup id - * - * @generated from rpc osmosis.lockup.Query.SyntheticLockupByLockupID - */ -export const QuerySyntheticLockupByLockupIDService = { - typeName: TYPE_NAME, - method: "SyntheticLockupByLockupID", - Request: SyntheticLockupByLockupIDRequest, - Response: SyntheticLockupByLockupIDResponse, -} as const; - -/** - * Returns account locked records with longer duration - * - * @generated from rpc osmosis.lockup.Query.AccountLockedLongerDuration - */ -export const QueryAccountLockedLongerDurationService = { - typeName: TYPE_NAME, - method: "AccountLockedLongerDuration", - Request: AccountLockedLongerDurationRequest, - Response: AccountLockedLongerDurationResponse, -} as const; - -/** - * Returns account locked records with a specific duration - * - * @generated from rpc osmosis.lockup.Query.AccountLockedDuration - */ -export const QueryAccountLockedDurationService = { - typeName: TYPE_NAME, - method: "AccountLockedDuration", - Request: AccountLockedDurationRequest, - Response: AccountLockedDurationResponse, -} as const; - -/** - * Returns account locked records with longer duration excluding tokens - * started unlocking - * - * @generated from rpc osmosis.lockup.Query.AccountLockedLongerDurationNotUnlockingOnly - */ -export const QueryAccountLockedLongerDurationNotUnlockingOnlyService = { - typeName: TYPE_NAME, - method: "AccountLockedLongerDurationNotUnlockingOnly", - Request: AccountLockedLongerDurationNotUnlockingOnlyRequest, - Response: AccountLockedLongerDurationNotUnlockingOnlyResponse, -} as const; - -/** - * Returns account's locked records for a denom with longer duration - * - * @generated from rpc osmosis.lockup.Query.AccountLockedLongerDurationDenom - */ -export const QueryAccountLockedLongerDurationDenomService = { - typeName: TYPE_NAME, - method: "AccountLockedLongerDurationDenom", - Request: AccountLockedLongerDurationDenomRequest, - Response: AccountLockedLongerDurationDenomResponse, -} as const; - -/** - * Params returns lockup params. - * - * @generated from rpc osmosis.lockup.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/lockup/query_pb.ts b/packages/es/src/protobufs/osmosis/lockup/query_pb.ts deleted file mode 100644 index 8473752f4..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/query_pb.ts +++ /dev/null @@ -1,1535 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/lockup/query.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; -import { PeriodLock, SyntheticLock } from "./lock_pb.js"; -import { Params } from "./params_pb.js"; - -/** - * @generated from message osmosis.lockup.ModuleBalanceRequest - */ -export class ModuleBalanceRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.ModuleBalanceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleBalanceRequest { - return new ModuleBalanceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleBalanceRequest { - return new ModuleBalanceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleBalanceRequest { - return new ModuleBalanceRequest().fromJsonString(jsonString, options); - } - - static equals(a: ModuleBalanceRequest | PlainMessage | undefined, b: ModuleBalanceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleBalanceRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.ModuleBalanceResponse - */ -export class ModuleBalanceResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.ModuleBalanceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleBalanceResponse { - return new ModuleBalanceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleBalanceResponse { - return new ModuleBalanceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleBalanceResponse { - return new ModuleBalanceResponse().fromJsonString(jsonString, options); - } - - static equals(a: ModuleBalanceResponse | PlainMessage | undefined, b: ModuleBalanceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleBalanceResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.ModuleLockedAmountRequest - */ -export class ModuleLockedAmountRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.ModuleLockedAmountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleLockedAmountRequest { - return new ModuleLockedAmountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleLockedAmountRequest { - return new ModuleLockedAmountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleLockedAmountRequest { - return new ModuleLockedAmountRequest().fromJsonString(jsonString, options); - } - - static equals(a: ModuleLockedAmountRequest | PlainMessage | undefined, b: ModuleLockedAmountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleLockedAmountRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.ModuleLockedAmountResponse - */ -export class ModuleLockedAmountResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.ModuleLockedAmountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleLockedAmountResponse { - return new ModuleLockedAmountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleLockedAmountResponse { - return new ModuleLockedAmountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleLockedAmountResponse { - return new ModuleLockedAmountResponse().fromJsonString(jsonString, options); - } - - static equals(a: ModuleLockedAmountResponse | PlainMessage | undefined, b: ModuleLockedAmountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleLockedAmountResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockableCoinsRequest - */ -export class AccountUnlockableCoinsRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockableCoinsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockableCoinsRequest { - return new AccountUnlockableCoinsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockableCoinsRequest { - return new AccountUnlockableCoinsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockableCoinsRequest { - return new AccountUnlockableCoinsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockableCoinsRequest | PlainMessage | undefined, b: AccountUnlockableCoinsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockableCoinsRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockableCoinsResponse - */ -export class AccountUnlockableCoinsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockableCoinsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockableCoinsResponse { - return new AccountUnlockableCoinsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockableCoinsResponse { - return new AccountUnlockableCoinsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockableCoinsResponse { - return new AccountUnlockableCoinsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockableCoinsResponse | PlainMessage | undefined, b: AccountUnlockableCoinsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockableCoinsResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockingCoinsRequest - */ -export class AccountUnlockingCoinsRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockingCoinsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockingCoinsRequest { - return new AccountUnlockingCoinsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockingCoinsRequest { - return new AccountUnlockingCoinsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockingCoinsRequest { - return new AccountUnlockingCoinsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockingCoinsRequest | PlainMessage | undefined, b: AccountUnlockingCoinsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockingCoinsRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockingCoinsResponse - */ -export class AccountUnlockingCoinsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockingCoinsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockingCoinsResponse { - return new AccountUnlockingCoinsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockingCoinsResponse { - return new AccountUnlockingCoinsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockingCoinsResponse { - return new AccountUnlockingCoinsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockingCoinsResponse | PlainMessage | undefined, b: AccountUnlockingCoinsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockingCoinsResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedCoinsRequest - */ -export class AccountLockedCoinsRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedCoinsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedCoinsRequest { - return new AccountLockedCoinsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedCoinsRequest { - return new AccountLockedCoinsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedCoinsRequest { - return new AccountLockedCoinsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedCoinsRequest | PlainMessage | undefined, b: AccountLockedCoinsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedCoinsRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedCoinsResponse - */ -export class AccountLockedCoinsResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 1; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedCoinsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedCoinsResponse { - return new AccountLockedCoinsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedCoinsResponse { - return new AccountLockedCoinsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedCoinsResponse { - return new AccountLockedCoinsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedCoinsResponse | PlainMessage | undefined, b: AccountLockedCoinsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedCoinsResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeRequest - */ -export class AccountLockedPastTimeRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Timestamp timestamp = 2; - */ - timestamp?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timestamp", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeRequest { - return new AccountLockedPastTimeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeRequest { - return new AccountLockedPastTimeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeRequest { - return new AccountLockedPastTimeRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeRequest | PlainMessage | undefined, b: AccountLockedPastTimeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeResponse - */ -export class AccountLockedPastTimeResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeResponse { - return new AccountLockedPastTimeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeResponse { - return new AccountLockedPastTimeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeResponse { - return new AccountLockedPastTimeResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeResponse | PlainMessage | undefined, b: AccountLockedPastTimeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeNotUnlockingOnlyRequest - */ -export class AccountLockedPastTimeNotUnlockingOnlyRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Timestamp timestamp = 2; - */ - timestamp?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeNotUnlockingOnlyRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timestamp", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyRequest { - return new AccountLockedPastTimeNotUnlockingOnlyRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyRequest { - return new AccountLockedPastTimeNotUnlockingOnlyRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyRequest { - return new AccountLockedPastTimeNotUnlockingOnlyRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeNotUnlockingOnlyRequest | PlainMessage | undefined, b: AccountLockedPastTimeNotUnlockingOnlyRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeNotUnlockingOnlyRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeNotUnlockingOnlyResponse - */ -export class AccountLockedPastTimeNotUnlockingOnlyResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeNotUnlockingOnlyResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyResponse { - return new AccountLockedPastTimeNotUnlockingOnlyResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyResponse { - return new AccountLockedPastTimeNotUnlockingOnlyResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeNotUnlockingOnlyResponse { - return new AccountLockedPastTimeNotUnlockingOnlyResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeNotUnlockingOnlyResponse | PlainMessage | undefined, b: AccountLockedPastTimeNotUnlockingOnlyResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeNotUnlockingOnlyResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockedBeforeTimeRequest - */ -export class AccountUnlockedBeforeTimeRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Timestamp timestamp = 2; - */ - timestamp?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockedBeforeTimeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timestamp", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockedBeforeTimeRequest { - return new AccountUnlockedBeforeTimeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockedBeforeTimeRequest { - return new AccountUnlockedBeforeTimeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockedBeforeTimeRequest { - return new AccountUnlockedBeforeTimeRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockedBeforeTimeRequest | PlainMessage | undefined, b: AccountUnlockedBeforeTimeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockedBeforeTimeRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountUnlockedBeforeTimeResponse - */ -export class AccountUnlockedBeforeTimeResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountUnlockedBeforeTimeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountUnlockedBeforeTimeResponse { - return new AccountUnlockedBeforeTimeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountUnlockedBeforeTimeResponse { - return new AccountUnlockedBeforeTimeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountUnlockedBeforeTimeResponse { - return new AccountUnlockedBeforeTimeResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountUnlockedBeforeTimeResponse | PlainMessage | undefined, b: AccountUnlockedBeforeTimeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountUnlockedBeforeTimeResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeDenomRequest - */ -export class AccountLockedPastTimeDenomRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Timestamp timestamp = 2; - */ - timestamp?: Timestamp; - - /** - * @generated from field: string denom = 3; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "timestamp", kind: "message", T: Timestamp }, - { no: 3, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeDenomRequest { - return new AccountLockedPastTimeDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeDenomRequest { - return new AccountLockedPastTimeDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeDenomRequest { - return new AccountLockedPastTimeDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeDenomRequest | PlainMessage | undefined, b: AccountLockedPastTimeDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedPastTimeDenomResponse - */ -export class AccountLockedPastTimeDenomResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedPastTimeDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedPastTimeDenomResponse { - return new AccountLockedPastTimeDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedPastTimeDenomResponse { - return new AccountLockedPastTimeDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedPastTimeDenomResponse { - return new AccountLockedPastTimeDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedPastTimeDenomResponse | PlainMessage | undefined, b: AccountLockedPastTimeDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedPastTimeDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockedDenomRequest - */ -export class LockedDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockedDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockedDenomRequest { - return new LockedDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockedDenomRequest { - return new LockedDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockedDenomRequest { - return new LockedDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: LockedDenomRequest | PlainMessage | undefined, b: LockedDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(LockedDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockedDenomResponse - */ -export class LockedDenomResponse extends Message { - /** - * @generated from field: string amount = 1; - */ - amount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockedDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockedDenomResponse { - return new LockedDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockedDenomResponse { - return new LockedDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockedDenomResponse { - return new LockedDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: LockedDenomResponse | PlainMessage | undefined, b: LockedDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(LockedDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockedRequest - */ -export class LockedRequest extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockedRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockedRequest { - return new LockedRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockedRequest { - return new LockedRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockedRequest { - return new LockedRequest().fromJsonString(jsonString, options); - } - - static equals(a: LockedRequest | PlainMessage | undefined, b: LockedRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(LockedRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockedResponse - */ -export class LockedResponse extends Message { - /** - * @generated from field: osmosis.lockup.PeriodLock lock = 1; - */ - lock?: PeriodLock; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockedResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock", kind: "message", T: PeriodLock }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockedResponse { - return new LockedResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockedResponse { - return new LockedResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockedResponse { - return new LockedResponse().fromJsonString(jsonString, options); - } - - static equals(a: LockedResponse | PlainMessage | undefined, b: LockedResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(LockedResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockRewardReceiverRequest - */ -export class LockRewardReceiverRequest extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockRewardReceiverRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockRewardReceiverRequest { - return new LockRewardReceiverRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockRewardReceiverRequest { - return new LockRewardReceiverRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockRewardReceiverRequest { - return new LockRewardReceiverRequest().fromJsonString(jsonString, options); - } - - static equals(a: LockRewardReceiverRequest | PlainMessage | undefined, b: LockRewardReceiverRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(LockRewardReceiverRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.LockRewardReceiverResponse - */ -export class LockRewardReceiverResponse extends Message { - /** - * @generated from field: string reward_receiver = 1; - */ - rewardReceiver = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.LockRewardReceiverResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "reward_receiver", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockRewardReceiverResponse { - return new LockRewardReceiverResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockRewardReceiverResponse { - return new LockRewardReceiverResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockRewardReceiverResponse { - return new LockRewardReceiverResponse().fromJsonString(jsonString, options); - } - - static equals(a: LockRewardReceiverResponse | PlainMessage | undefined, b: LockRewardReceiverResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(LockRewardReceiverResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.NextLockIDRequest - */ -export class NextLockIDRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.NextLockIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NextLockIDRequest { - return new NextLockIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NextLockIDRequest { - return new NextLockIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NextLockIDRequest { - return new NextLockIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: NextLockIDRequest | PlainMessage | undefined, b: NextLockIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(NextLockIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.NextLockIDResponse - */ -export class NextLockIDResponse extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.NextLockIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NextLockIDResponse { - return new NextLockIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NextLockIDResponse { - return new NextLockIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NextLockIDResponse { - return new NextLockIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: NextLockIDResponse | PlainMessage | undefined, b: NextLockIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(NextLockIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.SyntheticLockupsByLockupIDRequest - * @deprecated - */ -export class SyntheticLockupsByLockupIDRequest extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.SyntheticLockupsByLockupIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SyntheticLockupsByLockupIDRequest { - return new SyntheticLockupsByLockupIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SyntheticLockupsByLockupIDRequest { - return new SyntheticLockupsByLockupIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SyntheticLockupsByLockupIDRequest { - return new SyntheticLockupsByLockupIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: SyntheticLockupsByLockupIDRequest | PlainMessage | undefined, b: SyntheticLockupsByLockupIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SyntheticLockupsByLockupIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.SyntheticLockupsByLockupIDResponse - * @deprecated - */ -export class SyntheticLockupsByLockupIDResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.SyntheticLock synthetic_locks = 1; - */ - syntheticLocks: SyntheticLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.SyntheticLockupsByLockupIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "synthetic_locks", kind: "message", T: SyntheticLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SyntheticLockupsByLockupIDResponse { - return new SyntheticLockupsByLockupIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SyntheticLockupsByLockupIDResponse { - return new SyntheticLockupsByLockupIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SyntheticLockupsByLockupIDResponse { - return new SyntheticLockupsByLockupIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: SyntheticLockupsByLockupIDResponse | PlainMessage | undefined, b: SyntheticLockupsByLockupIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SyntheticLockupsByLockupIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.SyntheticLockupByLockupIDRequest - */ -export class SyntheticLockupByLockupIDRequest extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.SyntheticLockupByLockupIDRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SyntheticLockupByLockupIDRequest { - return new SyntheticLockupByLockupIDRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SyntheticLockupByLockupIDRequest { - return new SyntheticLockupByLockupIDRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SyntheticLockupByLockupIDRequest { - return new SyntheticLockupByLockupIDRequest().fromJsonString(jsonString, options); - } - - static equals(a: SyntheticLockupByLockupIDRequest | PlainMessage | undefined, b: SyntheticLockupByLockupIDRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SyntheticLockupByLockupIDRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.SyntheticLockupByLockupIDResponse - */ -export class SyntheticLockupByLockupIDResponse extends Message { - /** - * @generated from field: osmosis.lockup.SyntheticLock synthetic_lock = 1; - */ - syntheticLock?: SyntheticLock; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.SyntheticLockupByLockupIDResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "synthetic_lock", kind: "message", T: SyntheticLock }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SyntheticLockupByLockupIDResponse { - return new SyntheticLockupByLockupIDResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SyntheticLockupByLockupIDResponse { - return new SyntheticLockupByLockupIDResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SyntheticLockupByLockupIDResponse { - return new SyntheticLockupByLockupIDResponse().fromJsonString(jsonString, options); - } - - static equals(a: SyntheticLockupByLockupIDResponse | PlainMessage | undefined, b: SyntheticLockupByLockupIDResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SyntheticLockupByLockupIDResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationRequest - */ -export class AccountLockedLongerDurationRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationRequest { - return new AccountLockedLongerDurationRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationRequest { - return new AccountLockedLongerDurationRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationRequest { - return new AccountLockedLongerDurationRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationRequest | PlainMessage | undefined, b: AccountLockedLongerDurationRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationResponse - */ -export class AccountLockedLongerDurationResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationResponse { - return new AccountLockedLongerDurationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationResponse { - return new AccountLockedLongerDurationResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationResponse { - return new AccountLockedLongerDurationResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationResponse | PlainMessage | undefined, b: AccountLockedLongerDurationResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedDurationRequest - */ -export class AccountLockedDurationRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedDurationRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedDurationRequest { - return new AccountLockedDurationRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedDurationRequest { - return new AccountLockedDurationRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedDurationRequest { - return new AccountLockedDurationRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedDurationRequest | PlainMessage | undefined, b: AccountLockedDurationRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedDurationRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedDurationResponse - */ -export class AccountLockedDurationResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedDurationResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedDurationResponse { - return new AccountLockedDurationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedDurationResponse { - return new AccountLockedDurationResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedDurationResponse { - return new AccountLockedDurationResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedDurationResponse | PlainMessage | undefined, b: AccountLockedDurationResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedDurationResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationNotUnlockingOnlyRequest - */ -export class AccountLockedLongerDurationNotUnlockingOnlyRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationNotUnlockingOnlyRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyRequest { - return new AccountLockedLongerDurationNotUnlockingOnlyRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyRequest { - return new AccountLockedLongerDurationNotUnlockingOnlyRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyRequest { - return new AccountLockedLongerDurationNotUnlockingOnlyRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationNotUnlockingOnlyRequest | PlainMessage | undefined, b: AccountLockedLongerDurationNotUnlockingOnlyRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationNotUnlockingOnlyRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationNotUnlockingOnlyResponse - */ -export class AccountLockedLongerDurationNotUnlockingOnlyResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationNotUnlockingOnlyResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyResponse { - return new AccountLockedLongerDurationNotUnlockingOnlyResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyResponse { - return new AccountLockedLongerDurationNotUnlockingOnlyResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationNotUnlockingOnlyResponse { - return new AccountLockedLongerDurationNotUnlockingOnlyResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationNotUnlockingOnlyResponse | PlainMessage | undefined, b: AccountLockedLongerDurationNotUnlockingOnlyResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationNotUnlockingOnlyResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationDenomRequest - */ -export class AccountLockedLongerDurationDenomRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - /** - * @generated from field: string denom = 3; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - { no: 3, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationDenomRequest { - return new AccountLockedLongerDurationDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationDenomRequest { - return new AccountLockedLongerDurationDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationDenomRequest { - return new AccountLockedLongerDurationDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationDenomRequest | PlainMessage | undefined, b: AccountLockedLongerDurationDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.AccountLockedLongerDurationDenomResponse - */ -export class AccountLockedLongerDurationDenomResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock locks = 1; - */ - locks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.AccountLockedLongerDurationDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "locks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountLockedLongerDurationDenomResponse { - return new AccountLockedLongerDurationDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountLockedLongerDurationDenomResponse { - return new AccountLockedLongerDurationDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountLockedLongerDurationDenomResponse { - return new AccountLockedLongerDurationDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: AccountLockedLongerDurationDenomResponse | PlainMessage | undefined, b: AccountLockedLongerDurationDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountLockedLongerDurationDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.lockup.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * @generated from field: osmosis.lockup.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/lockup/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/lockup/tx_cosmes.ts deleted file mode 100644 index da136607b..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/tx_cosmes.ts +++ /dev/null @@ -1,79 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/lockup/tx.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgBeginUnlocking, MsgBeginUnlockingAll, MsgBeginUnlockingAllResponse, MsgBeginUnlockingResponse, MsgExtendLockup, MsgExtendLockupResponse, MsgForceUnlock, MsgForceUnlockResponse, MsgLockTokens, MsgLockTokensResponse, MsgSetRewardReceiverAddress, MsgSetRewardReceiverAddressResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.lockup.Msg"; - -/** - * LockTokens lock tokens - * - * @generated from rpc osmosis.lockup.Msg.LockTokens - */ -export const MsgLockTokensService = { - typeName: TYPE_NAME, - method: "LockTokens", - Request: MsgLockTokens, - Response: MsgLockTokensResponse, -} as const; - -/** - * BeginUnlockingAll begin unlocking all tokens - * - * @generated from rpc osmosis.lockup.Msg.BeginUnlockingAll - */ -export const MsgBeginUnlockingAllService = { - typeName: TYPE_NAME, - method: "BeginUnlockingAll", - Request: MsgBeginUnlockingAll, - Response: MsgBeginUnlockingAllResponse, -} as const; - -/** - * MsgBeginUnlocking begins unlocking tokens by lock ID - * - * @generated from rpc osmosis.lockup.Msg.BeginUnlocking - */ -export const MsgBeginUnlockingService = { - typeName: TYPE_NAME, - method: "BeginUnlocking", - Request: MsgBeginUnlocking, - Response: MsgBeginUnlockingResponse, -} as const; - -/** - * MsgEditLockup edits the existing lockups by lock ID - * - * @generated from rpc osmosis.lockup.Msg.ExtendLockup - */ -export const MsgExtendLockupService = { - typeName: TYPE_NAME, - method: "ExtendLockup", - Request: MsgExtendLockup, - Response: MsgExtendLockupResponse, -} as const; - -/** - * @generated from rpc osmosis.lockup.Msg.ForceUnlock - */ -export const MsgForceUnlockService = { - typeName: TYPE_NAME, - method: "ForceUnlock", - Request: MsgForceUnlock, - Response: MsgForceUnlockResponse, -} as const; - -/** - * SetRewardReceiverAddress edits the reward receiver for the given lock ID - * - * @generated from rpc osmosis.lockup.Msg.SetRewardReceiverAddress - */ -export const MsgSetRewardReceiverAddressService = { - typeName: TYPE_NAME, - method: "SetRewardReceiverAddress", - Request: MsgSetRewardReceiverAddress, - Response: MsgSetRewardReceiverAddressResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/lockup/tx_pb.ts b/packages/es/src/protobufs/osmosis/lockup/tx_pb.ts deleted file mode 100644 index 23856fb5a..000000000 --- a/packages/es/src/protobufs/osmosis/lockup/tx_pb.ts +++ /dev/null @@ -1,616 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/lockup/tx.proto (package osmosis.lockup, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; -import { PeriodLock } from "./lock_pb.js"; - -/** - * @generated from message osmosis.lockup.MsgLockTokens - */ -export class MsgLockTokens extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 3; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgLockTokens"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - { no: 3, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLockTokens { - return new MsgLockTokens().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLockTokens { - return new MsgLockTokens().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLockTokens { - return new MsgLockTokens().fromJsonString(jsonString, options); - } - - static equals(a: MsgLockTokens | PlainMessage | undefined, b: MsgLockTokens | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLockTokens, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgLockTokensResponse - */ -export class MsgLockTokensResponse extends Message { - /** - * @generated from field: uint64 ID = 1; - */ - ID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgLockTokensResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLockTokensResponse { - return new MsgLockTokensResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLockTokensResponse { - return new MsgLockTokensResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLockTokensResponse { - return new MsgLockTokensResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgLockTokensResponse | PlainMessage | undefined, b: MsgLockTokensResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLockTokensResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgBeginUnlockingAll - */ -export class MsgBeginUnlockingAll extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgBeginUnlockingAll"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBeginUnlockingAll { - return new MsgBeginUnlockingAll().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBeginUnlockingAll { - return new MsgBeginUnlockingAll().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBeginUnlockingAll { - return new MsgBeginUnlockingAll().fromJsonString(jsonString, options); - } - - static equals(a: MsgBeginUnlockingAll | PlainMessage | undefined, b: MsgBeginUnlockingAll | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBeginUnlockingAll, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgBeginUnlockingAllResponse - */ -export class MsgBeginUnlockingAllResponse extends Message { - /** - * @generated from field: repeated osmosis.lockup.PeriodLock unlocks = 1; - */ - unlocks: PeriodLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgBeginUnlockingAllResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "unlocks", kind: "message", T: PeriodLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBeginUnlockingAllResponse { - return new MsgBeginUnlockingAllResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBeginUnlockingAllResponse { - return new MsgBeginUnlockingAllResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBeginUnlockingAllResponse { - return new MsgBeginUnlockingAllResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgBeginUnlockingAllResponse | PlainMessage | undefined, b: MsgBeginUnlockingAllResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBeginUnlockingAllResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgBeginUnlocking - */ -export class MsgBeginUnlocking extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: uint64 ID = 2; - */ - ID = protoInt64.zero; - - /** - * Amount of unlocking coins. Unlock all if not set. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 3; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgBeginUnlocking"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBeginUnlocking { - return new MsgBeginUnlocking().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBeginUnlocking { - return new MsgBeginUnlocking().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBeginUnlocking { - return new MsgBeginUnlocking().fromJsonString(jsonString, options); - } - - static equals(a: MsgBeginUnlocking | PlainMessage | undefined, b: MsgBeginUnlocking | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBeginUnlocking, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgBeginUnlockingResponse - */ -export class MsgBeginUnlockingResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - /** - * @generated from field: uint64 unlockingLockID = 2; - */ - unlockingLockID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgBeginUnlockingResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "unlockingLockID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBeginUnlockingResponse { - return new MsgBeginUnlockingResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBeginUnlockingResponse { - return new MsgBeginUnlockingResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBeginUnlockingResponse { - return new MsgBeginUnlockingResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgBeginUnlockingResponse | PlainMessage | undefined, b: MsgBeginUnlockingResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBeginUnlockingResponse, a, b); - } -} - -/** - * MsgExtendLockup extends the existing lockup's duration. - * The new duration is longer than the original. - * - * @generated from message osmosis.lockup.MsgExtendLockup - */ -export class MsgExtendLockup extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: uint64 ID = 2; - */ - ID = protoInt64.zero; - - /** - * duration to be set. fails if lower than the current duration, or is - * unlocking - * - * @generated from field: google.protobuf.Duration duration = 3; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgExtendLockup"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExtendLockup { - return new MsgExtendLockup().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExtendLockup { - return new MsgExtendLockup().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExtendLockup { - return new MsgExtendLockup().fromJsonString(jsonString, options); - } - - static equals(a: MsgExtendLockup | PlainMessage | undefined, b: MsgExtendLockup | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExtendLockup, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgExtendLockupResponse - */ -export class MsgExtendLockupResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgExtendLockupResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgExtendLockupResponse { - return new MsgExtendLockupResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgExtendLockupResponse { - return new MsgExtendLockupResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgExtendLockupResponse { - return new MsgExtendLockupResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgExtendLockupResponse | PlainMessage | undefined, b: MsgExtendLockupResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgExtendLockupResponse, a, b); - } -} - -/** - * MsgForceUnlock unlocks locks immediately for - * addresses registered via governance. - * - * @generated from message osmosis.lockup.MsgForceUnlock - */ -export class MsgForceUnlock extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: uint64 ID = 2; - */ - ID = protoInt64.zero; - - /** - * Amount of unlocking coins. Unlock all if not set. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 3; - */ - coins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgForceUnlock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgForceUnlock { - return new MsgForceUnlock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgForceUnlock { - return new MsgForceUnlock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgForceUnlock { - return new MsgForceUnlock().fromJsonString(jsonString, options); - } - - static equals(a: MsgForceUnlock | PlainMessage | undefined, b: MsgForceUnlock | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgForceUnlock, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgForceUnlockResponse - */ -export class MsgForceUnlockResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgForceUnlockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgForceUnlockResponse { - return new MsgForceUnlockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgForceUnlockResponse { - return new MsgForceUnlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgForceUnlockResponse { - return new MsgForceUnlockResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgForceUnlockResponse | PlainMessage | undefined, b: MsgForceUnlockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgForceUnlockResponse, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgSetRewardReceiverAddress - */ -export class MsgSetRewardReceiverAddress extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: uint64 lockID = 2; - */ - lockID = protoInt64.zero; - - /** - * @generated from field: string reward_receiver = 3; - */ - rewardReceiver = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgSetRewardReceiverAddress"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lockID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "reward_receiver", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetRewardReceiverAddress { - return new MsgSetRewardReceiverAddress().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetRewardReceiverAddress { - return new MsgSetRewardReceiverAddress().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetRewardReceiverAddress { - return new MsgSetRewardReceiverAddress().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetRewardReceiverAddress | PlainMessage | undefined, b: MsgSetRewardReceiverAddress | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetRewardReceiverAddress, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgSetRewardReceiverAddressResponse - */ -export class MsgSetRewardReceiverAddressResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgSetRewardReceiverAddressResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetRewardReceiverAddressResponse { - return new MsgSetRewardReceiverAddressResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetRewardReceiverAddressResponse { - return new MsgSetRewardReceiverAddressResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetRewardReceiverAddressResponse { - return new MsgSetRewardReceiverAddressResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetRewardReceiverAddressResponse | PlainMessage | undefined, b: MsgSetRewardReceiverAddressResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetRewardReceiverAddressResponse, a, b); - } -} - -/** - * DEPRECATED - * Following messages are deprecated but kept to support indexing. - * - * @generated from message osmosis.lockup.MsgUnlockPeriodLock - */ -export class MsgUnlockPeriodLock extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - /** - * @generated from field: uint64 ID = 2; - */ - ID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgUnlockPeriodLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnlockPeriodLock { - return new MsgUnlockPeriodLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnlockPeriodLock { - return new MsgUnlockPeriodLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnlockPeriodLock { - return new MsgUnlockPeriodLock().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnlockPeriodLock | PlainMessage | undefined, b: MsgUnlockPeriodLock | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnlockPeriodLock, a, b); - } -} - -/** - * @generated from message osmosis.lockup.MsgUnlockTokens - */ -export class MsgUnlockTokens extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.lockup.MsgUnlockTokens"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnlockTokens { - return new MsgUnlockTokens().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnlockTokens { - return new MsgUnlockTokens().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnlockTokens { - return new MsgUnlockTokens().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnlockTokens | PlainMessage | undefined, b: MsgUnlockTokens | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnlockTokens, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/mint/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/mint/v1beta1/genesis_pb.ts deleted file mode 100644 index 62e90753a..000000000 --- a/packages/es/src/protobufs/osmosis/mint/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,67 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/mint/v1beta1/genesis.proto (package osmosis.mint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Minter, Params } from "./mint_pb.js"; - -/** - * GenesisState defines the mint module's genesis state. - * - * @generated from message osmosis.mint.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * minter is an abstraction for holding current rewards information. - * - * @generated from field: osmosis.mint.v1beta1.Minter minter = 1; - */ - minter?: Minter; - - /** - * params defines all the parameters of the mint module. - * - * @generated from field: osmosis.mint.v1beta1.Params params = 2; - */ - params?: Params; - - /** - * reduction_started_epoch is the first epoch in which the reduction of mint - * begins. - * - * @generated from field: int64 reduction_started_epoch = 3; - */ - reductionStartedEpoch = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "minter", kind: "message", T: Minter }, - { no: 2, name: "params", kind: "message", T: Params }, - { no: 3, name: "reduction_started_epoch", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/mint/v1beta1/mint_pb.ts b/packages/es/src/protobufs/osmosis/mint/v1beta1/mint_pb.ts deleted file mode 100644 index bb7166edd..000000000 --- a/packages/es/src/protobufs/osmosis/mint/v1beta1/mint_pb.ts +++ /dev/null @@ -1,272 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/mint/v1beta1/mint.proto (package osmosis.mint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Minter represents the minting state. - * - * @generated from message osmosis.mint.v1beta1.Minter - */ -export class Minter extends Message { - /** - * epoch_provisions represent rewards for the current epoch. - * - * @generated from field: string epoch_provisions = 1; - */ - epochProvisions = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.Minter"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epoch_provisions", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Minter { - return new Minter().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Minter { - return new Minter().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Minter { - return new Minter().fromJsonString(jsonString, options); - } - - static equals(a: Minter | PlainMessage | undefined, b: Minter | PlainMessage | undefined): boolean { - return proto3.util.equals(Minter, a, b); - } -} - -/** - * WeightedAddress represents an address with a weight assigned to it. - * The weight is used to determine the proportion of the total minted - * tokens to be minted to the address. - * - * @generated from message osmosis.mint.v1beta1.WeightedAddress - */ -export class WeightedAddress extends Message { - /** - * @generated from field: string address = 1; - */ - address = ""; - - /** - * @generated from field: string weight = 2; - */ - weight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.WeightedAddress"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): WeightedAddress { - return new WeightedAddress().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): WeightedAddress { - return new WeightedAddress().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): WeightedAddress { - return new WeightedAddress().fromJsonString(jsonString, options); - } - - static equals(a: WeightedAddress | PlainMessage | undefined, b: WeightedAddress | PlainMessage | undefined): boolean { - return proto3.util.equals(WeightedAddress, a, b); - } -} - -/** - * DistributionProportions defines the distribution proportions of the minted - * denom. In other words, defines which stakeholders will receive the minted - * denoms and how much. - * - * @generated from message osmosis.mint.v1beta1.DistributionProportions - */ -export class DistributionProportions extends Message { - /** - * staking defines the proportion of the minted mint_denom that is to be - * allocated as staking rewards. - * - * @generated from field: string staking = 1; - */ - staking = ""; - - /** - * pool_incentives defines the proportion of the minted mint_denom that is - * to be allocated as pool incentives. - * - * @generated from field: string pool_incentives = 2; - */ - poolIncentives = ""; - - /** - * developer_rewards defines the proportion of the minted mint_denom that is - * to be allocated to developer rewards address. - * - * @generated from field: string developer_rewards = 3; - */ - developerRewards = ""; - - /** - * community_pool defines the proportion of the minted mint_denom that is - * to be allocated to the community pool. - * - * @generated from field: string community_pool = 4; - */ - communityPool = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.DistributionProportions"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "staking", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_incentives", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "developer_rewards", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "community_pool", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DistributionProportions { - return new DistributionProportions().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DistributionProportions { - return new DistributionProportions().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DistributionProportions { - return new DistributionProportions().fromJsonString(jsonString, options); - } - - static equals(a: DistributionProportions | PlainMessage | undefined, b: DistributionProportions | PlainMessage | undefined): boolean { - return proto3.util.equals(DistributionProportions, a, b); - } -} - -/** - * Params holds parameters for the x/mint module. - * - * @generated from message osmosis.mint.v1beta1.Params - */ -export class Params extends Message { - /** - * mint_denom is the denom of the coin to mint. - * - * @generated from field: string mint_denom = 1; - */ - mintDenom = ""; - - /** - * genesis_epoch_provisions epoch provisions from the first epoch. - * - * @generated from field: string genesis_epoch_provisions = 2; - */ - genesisEpochProvisions = ""; - - /** - * epoch_identifier mint epoch identifier e.g. (day, week). - * - * @generated from field: string epoch_identifier = 3; - */ - epochIdentifier = ""; - - /** - * reduction_period_in_epochs the number of epochs it takes - * to reduce the rewards. - * - * @generated from field: int64 reduction_period_in_epochs = 4; - */ - reductionPeriodInEpochs = protoInt64.zero; - - /** - * reduction_factor is the reduction multiplier to execute - * at the end of each period set by reduction_period_in_epochs. - * - * @generated from field: string reduction_factor = 5; - */ - reductionFactor = ""; - - /** - * distribution_proportions defines the distribution proportions of the minted - * denom. In other words, defines which stakeholders will receive the minted - * denoms and how much. - * - * @generated from field: osmosis.mint.v1beta1.DistributionProportions distribution_proportions = 6; - */ - distributionProportions?: DistributionProportions; - - /** - * weighted_developer_rewards_receivers is the address to receive developer - * rewards with weights assignedt to each address. The final amount that each - * address receives is: epoch_provisions * - * distribution_proportions.developer_rewards * Address's Weight. - * - * @generated from field: repeated osmosis.mint.v1beta1.WeightedAddress weighted_developer_rewards_receivers = 7; - */ - weightedDeveloperRewardsReceivers: WeightedAddress[] = []; - - /** - * minting_rewards_distribution_start_epoch start epoch to distribute minting - * rewards - * - * @generated from field: int64 minting_rewards_distribution_start_epoch = 8; - */ - mintingRewardsDistributionStartEpoch = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "mint_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "genesis_epoch_provisions", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "epoch_identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "reduction_period_in_epochs", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "reduction_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "distribution_proportions", kind: "message", T: DistributionProportions }, - { no: 7, name: "weighted_developer_rewards_receivers", kind: "message", T: WeightedAddress, repeated: true }, - { no: 8, name: "minting_rewards_distribution_start_epoch", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/mint/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/mint/v1beta1/query_cosmes.ts deleted file mode 100644 index a762b8ea0..000000000 --- a/packages/es/src/protobufs/osmosis/mint/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/mint/v1beta1/query.proto (package osmosis.mint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryEpochProvisionsRequest, QueryEpochProvisionsResponse, QueryInflationRequest, QueryInflationResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.mint.v1beta1.Query"; - -/** - * Params returns the total set of minting parameters. - * - * @generated from rpc osmosis.mint.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * EpochProvisions returns the current minting epoch provisions value. - * - * @generated from rpc osmosis.mint.v1beta1.Query.EpochProvisions - */ -export const QueryEpochProvisionsService = { - typeName: TYPE_NAME, - method: "EpochProvisions", - Request: QueryEpochProvisionsRequest, - Response: QueryEpochProvisionsResponse, -} as const; - -/** - * Inflation returns the current minting inflation value. - * - * @generated from rpc osmosis.mint.v1beta1.Query.Inflation - */ -export const QueryInflationService = { - typeName: TYPE_NAME, - method: "Inflation", - Request: QueryInflationRequest, - Response: QueryInflationResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/mint/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/mint/v1beta1/query_pb.ts deleted file mode 100644 index 3ad81cb96..000000000 --- a/packages/es/src/protobufs/osmosis/mint/v1beta1/query_pb.ts +++ /dev/null @@ -1,234 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/mint/v1beta1/query.proto (package osmosis.mint.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./mint_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message osmosis.mint.v1beta1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message osmosis.mint.v1beta1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: osmosis.mint.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryEpochProvisionsRequest is the request type for the - * Query/EpochProvisions RPC method. - * - * @generated from message osmosis.mint.v1beta1.QueryEpochProvisionsRequest - */ -export class QueryEpochProvisionsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryEpochProvisionsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEpochProvisionsRequest { - return new QueryEpochProvisionsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEpochProvisionsRequest { - return new QueryEpochProvisionsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEpochProvisionsRequest { - return new QueryEpochProvisionsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEpochProvisionsRequest | PlainMessage | undefined, b: QueryEpochProvisionsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEpochProvisionsRequest, a, b); - } -} - -/** - * QueryEpochProvisionsResponse is the response type for the - * Query/EpochProvisions RPC method. - * - * @generated from message osmosis.mint.v1beta1.QueryEpochProvisionsResponse - */ -export class QueryEpochProvisionsResponse extends Message { - /** - * epoch_provisions is the current minting per epoch provisions value. - * - * @generated from field: bytes epoch_provisions = 1; - */ - epochProvisions = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryEpochProvisionsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epoch_provisions", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEpochProvisionsResponse { - return new QueryEpochProvisionsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEpochProvisionsResponse { - return new QueryEpochProvisionsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEpochProvisionsResponse { - return new QueryEpochProvisionsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEpochProvisionsResponse | PlainMessage | undefined, b: QueryEpochProvisionsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEpochProvisionsResponse, a, b); - } -} - -/** - * QueryInflationRequest is the request type for the Query/Inflation RPC method. - * - * @generated from message osmosis.mint.v1beta1.QueryInflationRequest - */ -export class QueryInflationRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryInflationRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInflationRequest { - return new QueryInflationRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInflationRequest { - return new QueryInflationRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInflationRequest { - return new QueryInflationRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryInflationRequest | PlainMessage | undefined, b: QueryInflationRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInflationRequest, a, b); - } -} - -/** - * QueryInflationResponse is the response type for the Query/Inflation RPC - * method. - * - * @generated from message osmosis.mint.v1beta1.QueryInflationResponse - */ -export class QueryInflationResponse extends Message { - /** - * inflation is the current minting inflation value. - * - * @generated from field: bytes inflation = 1; - */ - inflation = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.mint.v1beta1.QueryInflationResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "inflation", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryInflationResponse { - return new QueryInflationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryInflationResponse { - return new QueryInflationResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryInflationResponse { - return new QueryInflationResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryInflationResponse | PlainMessage | undefined, b: QueryInflationResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryInflationResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/genesis_pb.ts deleted file mode 100644 index ce00876b6..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/genesis.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3 } from "@bufbuild/protobuf"; -import { AnyPoolToInternalGauges, ConcentratedPoolToNoLockGauges, DistrInfo, Params } from "./incentives_pb.js"; - -/** - * GenesisState defines the pool incentives module's genesis state. - * - * @generated from message osmosis.poolincentives.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params defines all the parameters of the module. - * - * @generated from field: osmosis.poolincentives.v1beta1.Params params = 1; - */ - params?: Params; - - /** - * @generated from field: repeated google.protobuf.Duration lockable_durations = 2; - */ - lockableDurations: Duration[] = []; - - /** - * @generated from field: osmosis.poolincentives.v1beta1.DistrInfo distr_info = 3; - */ - distrInfo?: DistrInfo; - - /** - * any_pool_to_internal_gauges defines the gauges for any pool to internal - * pool. For every pool type (e.g. LP, Concentrated, etc), there is one such - * link - * - * @generated from field: osmosis.poolincentives.v1beta1.AnyPoolToInternalGauges any_pool_to_internal_gauges = 4; - */ - anyPoolToInternalGauges?: AnyPoolToInternalGauges; - - /** - * concentrated_pool_to_no_lock_gauges defines the no lock gauges for - * concentrated pool. This only exists between concentrated pool and no lock - * gauges. Both external and internal gauges are included. - * - * @generated from field: osmosis.poolincentives.v1beta1.ConcentratedPoolToNoLockGauges concentrated_pool_to_no_lock_gauges = 5; - */ - concentratedPoolToNoLockGauges?: ConcentratedPoolToNoLockGauges; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - { no: 3, name: "distr_info", kind: "message", T: DistrInfo }, - { no: 4, name: "any_pool_to_internal_gauges", kind: "message", T: AnyPoolToInternalGauges }, - { no: 5, name: "concentrated_pool_to_no_lock_gauges", kind: "message", T: ConcentratedPoolToNoLockGauges }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/gov_pb.ts deleted file mode 100644 index 9fd9ee3b8..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/gov_pb.ts +++ /dev/null @@ -1,123 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/gov.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { DistrRecord } from "./incentives_pb.js"; - -/** - * ReplacePoolIncentivesProposal is a gov Content type for updating the pool - * incentives. If a ReplacePoolIncentivesProposal passes, the proposal’s records - * override the existing DistrRecords set in the module. Each record has a - * specified gauge id and weight, and the incentives are distributed to each - * gauge according to weight/total_weight. The incentives are put in the fee - * pool and it is allocated to gauges and community pool by the DistrRecords - * configuration. Note that gaugeId=0 represents the community pool. - * - * @generated from message osmosis.poolincentives.v1beta1.ReplacePoolIncentivesProposal - */ -export class ReplacePoolIncentivesProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.DistrRecord records = 3; - */ - records: DistrRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.ReplacePoolIncentivesProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "records", kind: "message", T: DistrRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ReplacePoolIncentivesProposal { - return new ReplacePoolIncentivesProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ReplacePoolIncentivesProposal { - return new ReplacePoolIncentivesProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ReplacePoolIncentivesProposal { - return new ReplacePoolIncentivesProposal().fromJsonString(jsonString, options); - } - - static equals(a: ReplacePoolIncentivesProposal | PlainMessage | undefined, b: ReplacePoolIncentivesProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(ReplacePoolIncentivesProposal, a, b); - } -} - -/** - * For example: if the existing DistrRecords were: - * [(Gauge 0, 5), (Gauge 1, 6), (Gauge 2, 6)] - * An UpdatePoolIncentivesProposal includes - * [(Gauge 1, 0), (Gauge 2, 4), (Gauge 3, 10)] - * This would delete Gauge 1, Edit Gauge 2, and Add Gauge 3 - * The result DistrRecords in state would be: - * [(Gauge 0, 5), (Gauge 2, 4), (Gauge 3, 10)] - * - * @generated from message osmosis.poolincentives.v1beta1.UpdatePoolIncentivesProposal - */ -export class UpdatePoolIncentivesProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.DistrRecord records = 3; - */ - records: DistrRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.UpdatePoolIncentivesProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "records", kind: "message", T: DistrRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdatePoolIncentivesProposal { - return new UpdatePoolIncentivesProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdatePoolIncentivesProposal { - return new UpdatePoolIncentivesProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdatePoolIncentivesProposal { - return new UpdatePoolIncentivesProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdatePoolIncentivesProposal | PlainMessage | undefined, b: UpdatePoolIncentivesProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdatePoolIncentivesProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/incentives_pb.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/incentives_pb.ts deleted file mode 100644 index 4aeabee0b..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/incentives_pb.ts +++ /dev/null @@ -1,296 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/incentives.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.poolincentives.v1beta1.Params - */ -export class Params extends Message { - /** - * minted_denom is the denomination of the coin expected to be minted by the - * minting module. Pool-incentives module doesn’t actually mint the coin - * itself, but rather manages the distribution of coins that matches the - * defined minted_denom. - * - * @generated from field: string minted_denom = 1; - */ - mintedDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "minted_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.LockableDurationsInfo - */ -export class LockableDurationsInfo extends Message { - /** - * @generated from field: repeated google.protobuf.Duration lockable_durations = 1; - */ - lockableDurations: Duration[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.LockableDurationsInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockableDurationsInfo { - return new LockableDurationsInfo().fromJsonString(jsonString, options); - } - - static equals(a: LockableDurationsInfo | PlainMessage | undefined, b: LockableDurationsInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(LockableDurationsInfo, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.DistrInfo - */ -export class DistrInfo extends Message { - /** - * @generated from field: string total_weight = 1; - */ - totalWeight = ""; - - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.DistrRecord records = 2; - */ - records: DistrRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.DistrInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "records", kind: "message", T: DistrRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DistrInfo { - return new DistrInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DistrInfo { - return new DistrInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DistrInfo { - return new DistrInfo().fromJsonString(jsonString, options); - } - - static equals(a: DistrInfo | PlainMessage | undefined, b: DistrInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(DistrInfo, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.DistrRecord - */ -export class DistrRecord extends Message { - /** - * @generated from field: uint64 gauge_id = 1; - */ - gaugeId = protoInt64.zero; - - /** - * @generated from field: string weight = 2; - */ - weight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.DistrRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DistrRecord { - return new DistrRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DistrRecord { - return new DistrRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DistrRecord { - return new DistrRecord().fromJsonString(jsonString, options); - } - - static equals(a: DistrRecord | PlainMessage | undefined, b: DistrRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(DistrRecord, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.PoolToGauge - */ -export class PoolToGauge extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: uint64 gauge_id = 2; - */ - gaugeId = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Duration duration = 3; - */ - duration?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.PoolToGauge"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "duration", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolToGauge { - return new PoolToGauge().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolToGauge { - return new PoolToGauge().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolToGauge { - return new PoolToGauge().fromJsonString(jsonString, options); - } - - static equals(a: PoolToGauge | PlainMessage | undefined, b: PoolToGauge | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolToGauge, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.AnyPoolToInternalGauges - */ -export class AnyPoolToInternalGauges extends Message { - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.PoolToGauge pool_to_gauge = 2; - */ - poolToGauge: PoolToGauge[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.AnyPoolToInternalGauges"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "pool_to_gauge", kind: "message", T: PoolToGauge, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AnyPoolToInternalGauges { - return new AnyPoolToInternalGauges().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AnyPoolToInternalGauges { - return new AnyPoolToInternalGauges().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AnyPoolToInternalGauges { - return new AnyPoolToInternalGauges().fromJsonString(jsonString, options); - } - - static equals(a: AnyPoolToInternalGauges | PlainMessage | undefined, b: AnyPoolToInternalGauges | PlainMessage | undefined): boolean { - return proto3.util.equals(AnyPoolToInternalGauges, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.ConcentratedPoolToNoLockGauges - */ -export class ConcentratedPoolToNoLockGauges extends Message { - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.PoolToGauge pool_to_gauge = 1; - */ - poolToGauge: PoolToGauge[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.ConcentratedPoolToNoLockGauges"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_to_gauge", kind: "message", T: PoolToGauge, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConcentratedPoolToNoLockGauges { - return new ConcentratedPoolToNoLockGauges().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConcentratedPoolToNoLockGauges { - return new ConcentratedPoolToNoLockGauges().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConcentratedPoolToNoLockGauges { - return new ConcentratedPoolToNoLockGauges().fromJsonString(jsonString, options); - } - - static equals(a: ConcentratedPoolToNoLockGauges | PlainMessage | undefined, b: ConcentratedPoolToNoLockGauges | PlainMessage | undefined): boolean { - return proto3.util.equals(ConcentratedPoolToNoLockGauges, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_cosmes.ts deleted file mode 100644 index 7600eab93..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,81 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/query.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryDistrInfoRequest, QueryDistrInfoResponse, QueryExternalIncentiveGaugesRequest, QueryExternalIncentiveGaugesResponse, QueryGaugeIdsRequest, QueryGaugeIdsResponse, QueryIncentivizedPoolsRequest, QueryIncentivizedPoolsResponse, QueryLockableDurationsRequest, QueryLockableDurationsResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.poolincentives.v1beta1.Query"; - -/** - * GaugeIds takes the pool id and returns the matching gauge ids and durations - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.GaugeIds - */ -export const QueryGaugeIdsService = { - typeName: TYPE_NAME, - method: "GaugeIds", - Request: QueryGaugeIdsRequest, - Response: QueryGaugeIdsResponse, -} as const; - -/** - * DistrInfo returns the pool's matching gauge ids and weights. - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.DistrInfo - */ -export const QueryDistrInfoService = { - typeName: TYPE_NAME, - method: "DistrInfo", - Request: QueryDistrInfoRequest, - Response: QueryDistrInfoResponse, -} as const; - -/** - * Params returns pool incentives params. - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * LockableDurations returns lock durations for pools. - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.LockableDurations - */ -export const QueryLockableDurationsService = { - typeName: TYPE_NAME, - method: "LockableDurations", - Request: QueryLockableDurationsRequest, - Response: QueryLockableDurationsResponse, -} as const; - -/** - * IncentivizedPools returns currently incentivized pools - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.IncentivizedPools - */ -export const QueryIncentivizedPoolsService = { - typeName: TYPE_NAME, - method: "IncentivizedPools", - Request: QueryIncentivizedPoolsRequest, - Response: QueryIncentivizedPoolsResponse, -} as const; - -/** - * ExternalIncentiveGauges returns external incentive gauges. - * - * @generated from rpc osmosis.poolincentives.v1beta1.Query.ExternalIncentiveGauges - */ -export const QueryExternalIncentiveGaugesService = { - typeName: TYPE_NAME, - method: "ExternalIncentiveGauges", - Request: QueryExternalIncentiveGaugesRequest, - Response: QueryExternalIncentiveGaugesResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_pb.ts deleted file mode 100644 index 66c601cfa..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/query_pb.ts +++ /dev/null @@ -1,522 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/query.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { DistrInfo, Params } from "./incentives_pb.js"; -import { Gauge } from "../../incentives/gauge_pb.js"; - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryGaugeIdsRequest - */ -export class QueryGaugeIdsRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryGaugeIdsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGaugeIdsRequest { - return new QueryGaugeIdsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGaugeIdsRequest { - return new QueryGaugeIdsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGaugeIdsRequest { - return new QueryGaugeIdsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGaugeIdsRequest | PlainMessage | undefined, b: QueryGaugeIdsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGaugeIdsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryGaugeIdsResponse - */ -export class QueryGaugeIdsResponse extends Message { - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.QueryGaugeIdsResponse.GaugeIdWithDuration gauge_ids_with_duration = 1; - */ - gaugeIdsWithDuration: QueryGaugeIdsResponse_GaugeIdWithDuration[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryGaugeIdsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_ids_with_duration", kind: "message", T: QueryGaugeIdsResponse_GaugeIdWithDuration, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGaugeIdsResponse { - return new QueryGaugeIdsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGaugeIdsResponse { - return new QueryGaugeIdsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGaugeIdsResponse { - return new QueryGaugeIdsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGaugeIdsResponse | PlainMessage | undefined, b: QueryGaugeIdsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGaugeIdsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryGaugeIdsResponse.GaugeIdWithDuration - */ -export class QueryGaugeIdsResponse_GaugeIdWithDuration extends Message { - /** - * @generated from field: uint64 gauge_id = 1; - */ - gaugeId = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Duration duration = 2; - */ - duration?: Duration; - - /** - * @generated from field: string gauge_incentive_percentage = 3; - */ - gaugeIncentivePercentage = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryGaugeIdsResponse.GaugeIdWithDuration"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "duration", kind: "message", T: Duration }, - { no: 3, name: "gauge_incentive_percentage", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGaugeIdsResponse_GaugeIdWithDuration { - return new QueryGaugeIdsResponse_GaugeIdWithDuration().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGaugeIdsResponse_GaugeIdWithDuration { - return new QueryGaugeIdsResponse_GaugeIdWithDuration().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGaugeIdsResponse_GaugeIdWithDuration { - return new QueryGaugeIdsResponse_GaugeIdWithDuration().fromJsonString(jsonString, options); - } - - static equals(a: QueryGaugeIdsResponse_GaugeIdWithDuration | PlainMessage | undefined, b: QueryGaugeIdsResponse_GaugeIdWithDuration | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGaugeIdsResponse_GaugeIdWithDuration, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryDistrInfoRequest - */ -export class QueryDistrInfoRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryDistrInfoRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDistrInfoRequest { - return new QueryDistrInfoRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDistrInfoRequest { - return new QueryDistrInfoRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDistrInfoRequest { - return new QueryDistrInfoRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDistrInfoRequest | PlainMessage | undefined, b: QueryDistrInfoRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDistrInfoRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryDistrInfoResponse - */ -export class QueryDistrInfoResponse extends Message { - /** - * @generated from field: osmosis.poolincentives.v1beta1.DistrInfo distr_info = 1; - */ - distrInfo?: DistrInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryDistrInfoResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "distr_info", kind: "message", T: DistrInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDistrInfoResponse { - return new QueryDistrInfoResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDistrInfoResponse { - return new QueryDistrInfoResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDistrInfoResponse { - return new QueryDistrInfoResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDistrInfoResponse | PlainMessage | undefined, b: QueryDistrInfoResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDistrInfoResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * @generated from field: osmosis.poolincentives.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryLockableDurationsRequest - */ -export class QueryLockableDurationsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryLockableDurationsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLockableDurationsRequest { - return new QueryLockableDurationsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryLockableDurationsRequest | PlainMessage | undefined, b: QueryLockableDurationsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLockableDurationsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryLockableDurationsResponse - */ -export class QueryLockableDurationsResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Duration lockable_durations = 1; - */ - lockableDurations: Duration[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryLockableDurationsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lockable_durations", kind: "message", T: Duration, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryLockableDurationsResponse { - return new QueryLockableDurationsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryLockableDurationsResponse | PlainMessage | undefined, b: QueryLockableDurationsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryLockableDurationsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryIncentivizedPoolsRequest - */ -export class QueryIncentivizedPoolsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryIncentivizedPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryIncentivizedPoolsRequest { - return new QueryIncentivizedPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryIncentivizedPoolsRequest { - return new QueryIncentivizedPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryIncentivizedPoolsRequest { - return new QueryIncentivizedPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryIncentivizedPoolsRequest | PlainMessage | undefined, b: QueryIncentivizedPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryIncentivizedPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.IncentivizedPool - */ -export class IncentivizedPool extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: google.protobuf.Duration lockable_duration = 2; - */ - lockableDuration?: Duration; - - /** - * @generated from field: uint64 gauge_id = 3; - */ - gaugeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.IncentivizedPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "lockable_duration", kind: "message", T: Duration }, - { no: 3, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): IncentivizedPool { - return new IncentivizedPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): IncentivizedPool { - return new IncentivizedPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): IncentivizedPool { - return new IncentivizedPool().fromJsonString(jsonString, options); - } - - static equals(a: IncentivizedPool | PlainMessage | undefined, b: IncentivizedPool | PlainMessage | undefined): boolean { - return proto3.util.equals(IncentivizedPool, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryIncentivizedPoolsResponse - */ -export class QueryIncentivizedPoolsResponse extends Message { - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.IncentivizedPool incentivized_pools = 1; - */ - incentivizedPools: IncentivizedPool[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryIncentivizedPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "incentivized_pools", kind: "message", T: IncentivizedPool, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryIncentivizedPoolsResponse { - return new QueryIncentivizedPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryIncentivizedPoolsResponse { - return new QueryIncentivizedPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryIncentivizedPoolsResponse { - return new QueryIncentivizedPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryIncentivizedPoolsResponse | PlainMessage | undefined, b: QueryIncentivizedPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryIncentivizedPoolsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryExternalIncentiveGaugesRequest - */ -export class QueryExternalIncentiveGaugesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryExternalIncentiveGaugesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryExternalIncentiveGaugesRequest { - return new QueryExternalIncentiveGaugesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryExternalIncentiveGaugesRequest { - return new QueryExternalIncentiveGaugesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryExternalIncentiveGaugesRequest { - return new QueryExternalIncentiveGaugesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryExternalIncentiveGaugesRequest | PlainMessage | undefined, b: QueryExternalIncentiveGaugesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryExternalIncentiveGaugesRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolincentives.v1beta1.QueryExternalIncentiveGaugesResponse - */ -export class QueryExternalIncentiveGaugesResponse extends Message { - /** - * @generated from field: repeated osmosis.incentives.Gauge data = 1; - */ - data: Gauge[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.QueryExternalIncentiveGaugesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "data", kind: "message", T: Gauge, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryExternalIncentiveGaugesResponse { - return new QueryExternalIncentiveGaugesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryExternalIncentiveGaugesResponse { - return new QueryExternalIncentiveGaugesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryExternalIncentiveGaugesResponse { - return new QueryExternalIncentiveGaugesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryExternalIncentiveGaugesResponse | PlainMessage | undefined, b: QueryExternalIncentiveGaugesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryExternalIncentiveGaugesResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/shared_pb.ts b/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/shared_pb.ts deleted file mode 100644 index 1c3815146..000000000 --- a/packages/es/src/protobufs/osmosis/poolincentives/v1beta1/shared_pb.ts +++ /dev/null @@ -1,104 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolincentives/v1beta1/shared.proto (package osmosis.poolincentives.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * MigrationRecords contains all the links between balancer and concentrated - * pools. - * - * This is copied over from the gamm proto file in order to circumnavigate - * the circular dependency between the two modules. - * - * @generated from message osmosis.poolincentives.v1beta1.MigrationRecords - */ -export class MigrationRecords extends Message { - /** - * @generated from field: repeated osmosis.poolincentives.v1beta1.BalancerToConcentratedPoolLink balancer_to_concentrated_pool_links = 1; - */ - balancerToConcentratedPoolLinks: BalancerToConcentratedPoolLink[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.MigrationRecords"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balancer_to_concentrated_pool_links", kind: "message", T: BalancerToConcentratedPoolLink, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MigrationRecords { - return new MigrationRecords().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MigrationRecords { - return new MigrationRecords().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MigrationRecords { - return new MigrationRecords().fromJsonString(jsonString, options); - } - - static equals(a: MigrationRecords | PlainMessage | undefined, b: MigrationRecords | PlainMessage | undefined): boolean { - return proto3.util.equals(MigrationRecords, a, b); - } -} - -/** - * BalancerToConcentratedPoolLink defines a single link between a single - * balancer pool and a single concentrated liquidity pool. This link is used to - * allow a balancer pool to migrate to a single canonical full range - * concentrated liquidity pool position - * A balancer pool can be linked to a maximum of one cl pool, and a cl pool can - * be linked to a maximum of one balancer pool. - * - * This is copied over from the gamm proto file in order to circumnavigate - * the circular dependency between the two modules. - * - * @generated from message osmosis.poolincentives.v1beta1.BalancerToConcentratedPoolLink - */ -export class BalancerToConcentratedPoolLink extends Message { - /** - * @generated from field: uint64 balancer_pool_id = 1; - */ - balancerPoolId = protoInt64.zero; - - /** - * @generated from field: uint64 cl_pool_id = 2; - */ - clPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolincentives.v1beta1.BalancerToConcentratedPoolLink"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "balancer_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "cl_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BalancerToConcentratedPoolLink { - return new BalancerToConcentratedPoolLink().fromJsonString(jsonString, options); - } - - static equals(a: BalancerToConcentratedPoolLink | PlainMessage | undefined, b: BalancerToConcentratedPoolLink | PlainMessage | undefined): boolean { - return proto3.util.equals(BalancerToConcentratedPoolLink, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/genesis_pb.ts deleted file mode 100644 index db3d791be..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,427 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/genesis.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { ModuleRoute } from "./module_route_pb.js"; -import { DenomPairTakerFee } from "./tx_pb.js"; - -/** - * Params holds parameters for the poolmanager module - * - * @generated from message osmosis.poolmanager.v1beta1.Params - */ -export class Params extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin pool_creation_fee = 1; - */ - poolCreationFee: Coin[] = []; - - /** - * taker_fee_params is the container of taker fee parameters. - * - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeeParams taker_fee_params = 2; - */ - takerFeeParams?: TakerFeeParams; - - /** - * authorized_quote_denoms is a list of quote denoms that can be used as - * token1 when creating a concentrated pool. We limit the quote assets to a - * small set for the purposes of having convenient price increments stemming - * from tick to price conversion. These increments are in a human readable - * magnitude only for token1 as a quote. For limit orders in the future, this - * will be a desirable property in terms of UX as to allow users to set limit - * orders at prices in terms of token1 (quote asset) that are easy to reason - * about. - * DEPRECATED: Quote asset whitelisting requirement removed as per Proposal - * 819. Any asset can now be used as a quote asset in concentrated liquidity - * pools. - * - * @generated from field: repeated string authorized_quote_denoms = 3 [deprecated = true]; - * @deprecated - */ - authorizedQuoteDenoms: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_creation_fee", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "taker_fee_params", kind: "message", T: TakerFeeParams }, - { no: 3, name: "authorized_quote_denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * GenesisState defines the poolmanager module's genesis state. - * - * @generated from message osmosis.poolmanager.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * the next_pool_id - * - * @generated from field: uint64 next_pool_id = 1; - */ - nextPoolId = protoInt64.zero; - - /** - * params is the container of poolmanager parameters. - * - * @generated from field: osmosis.poolmanager.v1beta1.Params params = 2; - */ - params?: Params; - - /** - * pool_routes is the container of the mappings from pool id to pool type. - * - * @generated from field: repeated osmosis.poolmanager.v1beta1.ModuleRoute pool_routes = 3; - */ - poolRoutes: ModuleRoute[] = []; - - /** - * KVStore state - * - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeesTracker taker_fees_tracker = 4; - */ - takerFeesTracker?: TakerFeesTracker; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.PoolVolume pool_volumes = 5; - */ - poolVolumes: PoolVolume[] = []; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.DenomPairTakerFee denom_pair_taker_fee_store = 6; - */ - denomPairTakerFeeStore: DenomPairTakerFee[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "next_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "params", kind: "message", T: Params }, - { no: 3, name: "pool_routes", kind: "message", T: ModuleRoute, repeated: true }, - { no: 4, name: "taker_fees_tracker", kind: "message", T: TakerFeesTracker }, - { no: 5, name: "pool_volumes", kind: "message", T: PoolVolume, repeated: true }, - { no: 6, name: "denom_pair_taker_fee_store", kind: "message", T: DenomPairTakerFee, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * TakerFeeParams consolidates the taker fee parameters for the poolmanager. - * - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeParams - */ -export class TakerFeeParams extends Message { - /** - * default_taker_fee is the fee used when creating a new pool that doesn't - * fall under a custom pool taker fee or stableswap taker fee category. - * - * @generated from field: string default_taker_fee = 1; - */ - defaultTakerFee = ""; - - /** - * osmo_taker_fee_distribution defines the distribution of taker fees - * generated in OSMO. As of this writing, it has two categories: - * - staking_rewards: the percent of the taker fee that gets distributed to - * stakers. - * - community_pool: the percent of the taker fee that gets sent to the - * community pool. - * - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeeDistributionPercentage osmo_taker_fee_distribution = 2; - */ - osmoTakerFeeDistribution?: TakerFeeDistributionPercentage; - - /** - * non_osmo_taker_fee_distribution defines the distribution of taker fees - * generated in non-OSMO. As of this writing, it has two categories: - * - staking_rewards: the percent of the taker fee that gets swapped to OSMO - * and then distributed to stakers. - * - community_pool: the percent of the taker fee that gets sent to the - * community pool. Note: If the non-OSMO asset is an authorized_quote_denom, - * that denom is sent directly to the community pool. Otherwise, it is - * swapped to the community_pool_denom_to_swap_non_whitelisted_assets_to and - * then sent to the community pool as that denom. - * - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeeDistributionPercentage non_osmo_taker_fee_distribution = 3; - */ - nonOsmoTakerFeeDistribution?: TakerFeeDistributionPercentage; - - /** - * admin_addresses is a list of addresses that are allowed to set and remove - * custom taker fees for denom pairs. Governance also has the ability to set - * and remove custom taker fees for denom pairs, but with the normal - * governance delay. - * - * @generated from field: repeated string admin_addresses = 4; - */ - adminAddresses: string[] = []; - - /** - * community_pool_denom_to_swap_non_whitelisted_assets_to is the denom that - * non-whitelisted taker fees will be swapped to before being sent to - * the community pool. - * - * @generated from field: string community_pool_denom_to_swap_non_whitelisted_assets_to = 5; - */ - communityPoolDenomToSwapNonWhitelistedAssetsTo = ""; - - /** - * reduced_fee_whitelist is a list of addresses that are - * allowed to pay a reduce taker fee when performing a swap - * (i.e. swap without paying the taker fee). - * It is intended to be used for integrators who meet qualifying factors - * that are approved by governance. - * Initially, the taker fee is allowed to be bypassed completely. However - * In the future, we will charge a reduced taker fee instead of no fee at all. - * - * @generated from field: repeated string reduced_fee_whitelist = 6; - */ - reducedFeeWhitelist: string[] = []; - - /** - * community_pool_denom_whitelist is a list of denoms that should be sent - * directly to the community pool instead of being swapped to the - * `community_pool_denom_to_swap_non_whitelisted_assets_to`. - * - * @generated from field: repeated string community_pool_denom_whitelist = 7; - */ - communityPoolDenomWhitelist: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "default_taker_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "osmo_taker_fee_distribution", kind: "message", T: TakerFeeDistributionPercentage }, - { no: 3, name: "non_osmo_taker_fee_distribution", kind: "message", T: TakerFeeDistributionPercentage }, - { no: 4, name: "admin_addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "community_pool_denom_to_swap_non_whitelisted_assets_to", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "reduced_fee_whitelist", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 7, name: "community_pool_denom_whitelist", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeParams { - return new TakerFeeParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeParams { - return new TakerFeeParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeParams { - return new TakerFeeParams().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeParams | PlainMessage | undefined, b: TakerFeeParams | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeParams, a, b); - } -} - -/** - * TakerFeeDistributionPercentage defines what percent of the taker fee category - * gets distributed to the available categories. - * - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeDistributionPercentage - */ -export class TakerFeeDistributionPercentage extends Message { - /** - * @generated from field: string staking_rewards = 1; - */ - stakingRewards = ""; - - /** - * @generated from field: string community_pool = 2; - */ - communityPool = ""; - - /** - * @generated from field: string burn = 3; - */ - burn = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeDistributionPercentage"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "staking_rewards", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "community_pool", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "burn", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeDistributionPercentage { - return new TakerFeeDistributionPercentage().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeDistributionPercentage { - return new TakerFeeDistributionPercentage().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeDistributionPercentage { - return new TakerFeeDistributionPercentage().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeDistributionPercentage | PlainMessage | undefined, b: TakerFeeDistributionPercentage | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeDistributionPercentage, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TakerFeesTracker - */ -export class TakerFeesTracker extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin taker_fees_to_stakers = 1; - */ - takerFeesToStakers: Coin[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin taker_fees_to_community_pool = 2; - */ - takerFeesToCommunityPool: Coin[] = []; - - /** - * @generated from field: int64 height_accounting_starts_from = 3; - */ - heightAccountingStartsFrom = protoInt64.zero; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin taker_fees_to_burn = 4; - */ - takerFeesToBurn: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeesTracker"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fees_to_stakers", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "taker_fees_to_community_pool", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "height_accounting_starts_from", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 4, name: "taker_fees_to_burn", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeesTracker { - return new TakerFeesTracker().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeesTracker { - return new TakerFeesTracker().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeesTracker { - return new TakerFeesTracker().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeesTracker | PlainMessage | undefined, b: TakerFeesTracker | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeesTracker, a, b); - } -} - -/** - * PoolVolume stores the KVStore entries for each pool's volume, which - * is used in export/import genesis. - * - * @generated from message osmosis.poolmanager.v1beta1.PoolVolume - */ -export class PoolVolume extends Message { - /** - * pool_id is the id of the pool. - * - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * pool_volume is the cumulative volume of the pool. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin pool_volume = 2; - */ - poolVolume: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.PoolVolume"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "pool_volume", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolVolume { - return new PoolVolume().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolVolume { - return new PoolVolume().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolVolume { - return new PoolVolume().fromJsonString(jsonString, options); - } - - static equals(a: PoolVolume | PlainMessage | undefined, b: PoolVolume | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolVolume, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/gov_pb.ts deleted file mode 100644 index f9cbe13cd..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/gov_pb.ts +++ /dev/null @@ -1,61 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/gov.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { DenomPairTakerFee } from "./tx_pb.js"; - -/** - * DenomPairTakerFeeProposal is a type for adding/removing a custom taker fee(s) - * for one or more denom pairs. - * - * @generated from message osmosis.poolmanager.v1beta1.DenomPairTakerFeeProposal - */ -export class DenomPairTakerFeeProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.DenomPairTakerFee denom_pair_taker_fee = 3; - */ - denomPairTakerFee: DenomPairTakerFee[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.DenomPairTakerFeeProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "denom_pair_taker_fee", kind: "message", T: DenomPairTakerFee, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DenomPairTakerFeeProposal { - return new DenomPairTakerFeeProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DenomPairTakerFeeProposal { - return new DenomPairTakerFeeProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DenomPairTakerFeeProposal { - return new DenomPairTakerFeeProposal().fromJsonString(jsonString, options); - } - - static equals(a: DenomPairTakerFeeProposal | PlainMessage | undefined, b: DenomPairTakerFeeProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(DenomPairTakerFeeProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/module_route_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/module_route_pb.ts deleted file mode 100644 index 6c47500e8..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/module_route_pb.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/module_route.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * PoolType is an enumeration of all supported pool types. - * - * @generated from enum osmosis.poolmanager.v1beta1.PoolType - */ -export enum PoolType { - /** - * Balancer is the standard xy=k curve. Its pool model is defined in x/gamm. - * - * @generated from enum value: Balancer = 0; - */ - Balancer = 0, - - /** - * Stableswap is the Solidly cfmm stable swap curve. Its pool model is defined - * in x/gamm. - * - * @generated from enum value: Stableswap = 1; - */ - Stableswap = 1, - - /** - * Concentrated is the pool model specific to concentrated liquidity. It is - * defined in x/concentrated-liquidity. - * - * @generated from enum value: Concentrated = 2; - */ - Concentrated = 2, - - /** - * CosmWasm is the pool model specific to CosmWasm. It is defined in - * x/cosmwasmpool. - * - * @generated from enum value: CosmWasm = 3; - */ - CosmWasm = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(PoolType) -proto3.util.setEnumType(PoolType, "osmosis.poolmanager.v1beta1.PoolType", [ - { no: 0, name: "Balancer" }, - { no: 1, name: "Stableswap" }, - { no: 2, name: "Concentrated" }, - { no: 3, name: "CosmWasm" }, -]); - -/** - * ModuleRouter defines a route encapsulating pool type. - * It is used as the value of a mapping from pool id to the pool type, - * allowing the pool manager to know which module to route swaps to given the - * pool id. - * - * @generated from message osmosis.poolmanager.v1beta1.ModuleRoute - */ -export class ModuleRoute extends Message { - /** - * pool_type specifies the type of the pool - * - * @generated from field: osmosis.poolmanager.v1beta1.PoolType pool_type = 1; - */ - poolType = PoolType.Balancer; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.ModuleRoute"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_type", kind: "enum", T: proto3.getEnumType(PoolType) }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ModuleRoute { - return new ModuleRoute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ModuleRoute { - return new ModuleRoute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ModuleRoute { - return new ModuleRoute().fromJsonString(jsonString, options); - } - - static equals(a: ModuleRoute | PlainMessage | undefined, b: ModuleRoute | PlainMessage | undefined): boolean { - return proto3.util.equals(ModuleRoute, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_cosmes.ts deleted file mode 100644 index 2fc8500fa..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,325 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/query.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { AllPoolsRequest, AllPoolsResponse, AllRegisteredAlloyedPoolsRequest, AllRegisteredAlloyedPoolsResponse, AllTakerFeeShareAccumulatorsRequest, AllTakerFeeShareAccumulatorsResponse, AllTakerFeeShareAgreementsRequest, AllTakerFeeShareAgreementsResponse, EstimateSinglePoolSwapExactAmountInRequest, EstimateSinglePoolSwapExactAmountOutRequest, EstimateSwapExactAmountInRequest, EstimateSwapExactAmountInResponse, EstimateSwapExactAmountInWithPrimitiveTypesRequest, EstimateSwapExactAmountOutRequest, EstimateSwapExactAmountOutResponse, EstimateSwapExactAmountOutWithPrimitiveTypesRequest, EstimateTradeBasedOnPriceImpactRequest, EstimateTradeBasedOnPriceImpactResponse, ListPoolsByDenomRequest, ListPoolsByDenomResponse, NumPoolsRequest, NumPoolsResponse, ParamsRequest, ParamsResponse, PoolRequest, PoolResponse, RegisteredAlloyedPoolFromDenomRequest, RegisteredAlloyedPoolFromDenomResponse, RegisteredAlloyedPoolFromPoolIdRequest, RegisteredAlloyedPoolFromPoolIdResponse, SpotPriceRequest, SpotPriceResponse, TakerFeeShareAgreementFromDenomRequest, TakerFeeShareAgreementFromDenomResponse, TakerFeeShareDenomsToAccruedValueRequest, TakerFeeShareDenomsToAccruedValueResponse, TotalLiquidityRequest, TotalLiquidityResponse, TotalPoolLiquidityRequest, TotalPoolLiquidityResponse, TotalVolumeForPoolRequest, TotalVolumeForPoolResponse, TradingPairTakerFeeRequest, TradingPairTakerFeeResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.poolmanager.v1beta1.Query"; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - -/** - * Estimates swap amount out given in. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSwapExactAmountIn - */ -export const QueryEstimateSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountIn", - Request: EstimateSwapExactAmountInRequest, - Response: EstimateSwapExactAmountInResponse, -} as const; - -/** - * EstimateSwapExactAmountInWithPrimitiveTypes is an alternative query for - * EstimateSwapExactAmountIn. Supports query via GRPC-Gateway by using - * primitive types instead of repeated structs. Each index in the - * routes_pool_id field corresponds to the respective routes_token_out_denom - * value, thus they are required to have the same length and are grouped - * together as pairs. - * example usage: - * http://0.0.0.0:1317/osmosis/poolmanager/v1beta1/1/estimate/ - * swap_exact_amount_in_with_primitive_types?token_in=100000stake&routes_token_out_denom=uatom - * &routes_token_out_denom=uion&routes_pool_id=1&routes_pool_id=2 - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSwapExactAmountInWithPrimitiveTypes - */ -export const QueryEstimateSwapExactAmountInWithPrimitiveTypesService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountInWithPrimitiveTypes", - Request: EstimateSwapExactAmountInWithPrimitiveTypesRequest, - Response: EstimateSwapExactAmountInResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSinglePoolSwapExactAmountIn - */ -export const QueryEstimateSinglePoolSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "EstimateSinglePoolSwapExactAmountIn", - Request: EstimateSinglePoolSwapExactAmountInRequest, - Response: EstimateSwapExactAmountInResponse, -} as const; - -/** - * Estimates swap amount in given out. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSwapExactAmountOut - */ -export const QueryEstimateSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountOut", - Request: EstimateSwapExactAmountOutRequest, - Response: EstimateSwapExactAmountOutResponse, -} as const; - -/** - * Estimates swap amount in given out. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSwapExactAmountOutWithPrimitiveTypes - */ -export const QueryEstimateSwapExactAmountOutWithPrimitiveTypesService = { - typeName: TYPE_NAME, - method: "EstimateSwapExactAmountOutWithPrimitiveTypes", - Request: EstimateSwapExactAmountOutWithPrimitiveTypesRequest, - Response: EstimateSwapExactAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateSinglePoolSwapExactAmountOut - */ -export const QueryEstimateSinglePoolSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "EstimateSinglePoolSwapExactAmountOut", - Request: EstimateSinglePoolSwapExactAmountOutRequest, - Response: EstimateSwapExactAmountOutResponse, -} as const; - -/** - * Returns the total number of pools existing in Osmosis. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.NumPools - */ -export const QueryNumPoolsService = { - typeName: TYPE_NAME, - method: "NumPools", - Request: NumPoolsRequest, - Response: NumPoolsResponse, -} as const; - -/** - * Pool returns the Pool specified by the pool id - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.Pool - */ -export const QueryPoolService = { - typeName: TYPE_NAME, - method: "Pool", - Request: PoolRequest, - Response: PoolResponse, -} as const; - -/** - * AllPools returns all pools on the Osmosis chain sorted by IDs. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.AllPools - */ -export const QueryAllPoolsService = { - typeName: TYPE_NAME, - method: "AllPools", - Request: AllPoolsRequest, - Response: AllPoolsResponse, -} as const; - -/** - * ListPoolsByDenom return all pools by denom - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.ListPoolsByDenom - */ -export const QueryListPoolsByDenomService = { - typeName: TYPE_NAME, - method: "ListPoolsByDenom", - Request: ListPoolsByDenomRequest, - Response: ListPoolsByDenomResponse, -} as const; - -/** - * SpotPrice defines a gRPC query handler that returns the spot price given - * a base denomination and a quote denomination. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.SpotPrice - */ -export const QuerySpotPriceService = { - typeName: TYPE_NAME, - method: "SpotPrice", - Request: SpotPriceRequest, - Response: SpotPriceResponse, -} as const; - -/** - * TotalPoolLiquidity returns the total liquidity of the specified pool. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TotalPoolLiquidity - */ -export const QueryTotalPoolLiquidityService = { - typeName: TYPE_NAME, - method: "TotalPoolLiquidity", - Request: TotalPoolLiquidityRequest, - Response: TotalPoolLiquidityResponse, -} as const; - -/** - * TotalLiquidity returns the total liquidity across all pools. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TotalLiquidity - */ -export const QueryTotalLiquidityService = { - typeName: TYPE_NAME, - method: "TotalLiquidity", - Request: TotalLiquidityRequest, - Response: TotalLiquidityResponse, -} as const; - -/** - * TotalVolumeForPool returns the total volume of the specified pool. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TotalVolumeForPool - */ -export const QueryTotalVolumeForPoolService = { - typeName: TYPE_NAME, - method: "TotalVolumeForPool", - Request: TotalVolumeForPoolRequest, - Response: TotalVolumeForPoolResponse, -} as const; - -/** - * TradingPairTakerFee returns the taker fee for a given set of denoms - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TradingPairTakerFee - */ -export const QueryTradingPairTakerFeeService = { - typeName: TYPE_NAME, - method: "TradingPairTakerFee", - Request: TradingPairTakerFeeRequest, - Response: TradingPairTakerFeeResponse, -} as const; - -/** - * EstimateTradeBasedOnPriceImpact returns an estimated trade based on price - * impact, if a trade cannot be estimated a 0 input and 0 output would be - * returned. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.EstimateTradeBasedOnPriceImpact - */ -export const QueryEstimateTradeBasedOnPriceImpactService = { - typeName: TYPE_NAME, - method: "EstimateTradeBasedOnPriceImpact", - Request: EstimateTradeBasedOnPriceImpactRequest, - Response: EstimateTradeBasedOnPriceImpactResponse, -} as const; - -/** - * AllTakerFeeShareAgreements returns all taker fee share agreements. - * A taker fee share agreement includes the denom of the denom getting the - * taker fees, the percent of the taker fees that the denom gets when it is - * in the route being traded against, and the address that the taker fees are - * sent to at epoch. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.AllTakerFeeShareAgreements - */ -export const QueryAllTakerFeeShareAgreementsService = { - typeName: TYPE_NAME, - method: "AllTakerFeeShareAgreements", - Request: AllTakerFeeShareAgreementsRequest, - Response: AllTakerFeeShareAgreementsResponse, -} as const; - -/** - * TakerFeeShareAgreementFromDenom returns the taker fee share agreement for a - * given denom. A taker fee share agreement includes the denom of the denom - * getting the taker fees, the percent of the taker fees that the denom gets - * when it is in the route being traded against, and the address that the - * taker fees are sent to at epoch. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TakerFeeShareAgreementFromDenom - */ -export const QueryTakerFeeShareAgreementFromDenomService = { - typeName: TYPE_NAME, - method: "TakerFeeShareAgreementFromDenom", - Request: TakerFeeShareAgreementFromDenomRequest, - Response: TakerFeeShareAgreementFromDenomResponse, -} as const; - -/** - * TakerFeeShareDenomsToAccruedValue returns the accrued value (as an Int) of - * the given taker fee denom (the collected fees) for the given fee share - * denom (the denom with the taker fee share agreement) - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.TakerFeeShareDenomsToAccruedValue - */ -export const QueryTakerFeeShareDenomsToAccruedValueService = { - typeName: TYPE_NAME, - method: "TakerFeeShareDenomsToAccruedValue", - Request: TakerFeeShareDenomsToAccruedValueRequest, - Response: TakerFeeShareDenomsToAccruedValueResponse, -} as const; - -/** - * AllTakerFeeShareAccumulators returns all taker fee share accumulators. A - * taker fee share accumulator includes the denom of the denom getting the - * taker fees, and an accumulated value of coins that the denom has accrued - * since the last time it was distributed in the epoch prior. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.AllTakerFeeShareAccumulators - */ -export const QueryAllTakerFeeShareAccumulatorsService = { - typeName: TYPE_NAME, - method: "AllTakerFeeShareAccumulators", - Request: AllTakerFeeShareAccumulatorsRequest, - Response: AllTakerFeeShareAccumulatorsResponse, -} as const; - -/** - * RegisteredAlloyedPoolFromDenom returns the registered alloyed pool state - * from the given denom. The registered alloyed pool contains the pool's - * contract address, along with the current distribution composition of taker - * fee share denoms within the alloyed pool. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.RegisteredAlloyedPoolFromDenom - */ -export const QueryRegisteredAlloyedPoolFromDenomService = { - typeName: TYPE_NAME, - method: "RegisteredAlloyedPoolFromDenom", - Request: RegisteredAlloyedPoolFromDenomRequest, - Response: RegisteredAlloyedPoolFromDenomResponse, -} as const; - -/** - * RegisteredAlloyedPoolFromPoolId returns the registered alloyed pool state - * from the given pool id. The registered alloyed pool contains the pool's - * contract address, along with the current distribution composition of taker - * fee share denoms within the alloyed pool. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.RegisteredAlloyedPoolFromPoolId - */ -export const QueryRegisteredAlloyedPoolFromPoolIdService = { - typeName: TYPE_NAME, - method: "RegisteredAlloyedPoolFromPoolId", - Request: RegisteredAlloyedPoolFromPoolIdRequest, - Response: RegisteredAlloyedPoolFromPoolIdResponse, -} as const; - -/** - * AllRegisteredAlloyedPools returns all registered alloyed pools. The - * registered alloyed pool contains the pool's contract address, along with - * the current distribution composition of taker fee share denoms within the - * alloyed pool. - * - * @generated from rpc osmosis.poolmanager.v1beta1.Query.AllRegisteredAlloyedPools - */ -export const QueryAllRegisteredAlloyedPoolsService = { - typeName: TYPE_NAME, - method: "AllRegisteredAlloyedPools", - Request: AllRegisteredAlloyedPoolsRequest, - Response: AllRegisteredAlloyedPoolsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_pb.ts deleted file mode 100644 index 23c66a643..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/query_pb.ts +++ /dev/null @@ -1,1820 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/query.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Any, Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { SwapAmountInRoute, SwapAmountOutRoute } from "./swap_route_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { AlloyContractTakerFeeShareState, TakerFeeShareAgreement, TakerFeeSkimAccumulator } from "./taker_fee_share_pb.js"; - -/** - * =============================== Params - * - * @generated from message osmosis.poolmanager.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.poolmanager.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - -/** - * =============================== EstimateSwapExactAmountIn - * - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInRequest - */ -export class EstimateSwapExactAmountInRequest extends Message { - /** - * DEPRECATED - * - * @generated from field: string sender = 1 [deprecated = true]; - * @deprecated - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2 [deprecated = true]; - * @deprecated - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in = 3; - */ - tokenIn = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInRoute routes = 4; - */ - routes: SwapAmountInRoute[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "routes", kind: "message", T: SwapAmountInRoute, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountInRequest { - return new EstimateSwapExactAmountInRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountInRequest { - return new EstimateSwapExactAmountInRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountInRequest { - return new EstimateSwapExactAmountInRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountInRequest | PlainMessage | undefined, b: EstimateSwapExactAmountInRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountInRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInWithPrimitiveTypesRequest - */ -export class EstimateSwapExactAmountInWithPrimitiveTypesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1 [deprecated = true]; - * @deprecated - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in = 2; - */ - tokenIn = ""; - - /** - * @generated from field: repeated uint64 routes_pool_id = 3; - */ - routesPoolId: bigint[] = []; - - /** - * @generated from field: repeated string routes_token_out_denom = 4; - */ - routesTokenOutDenom: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInWithPrimitiveTypesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "routes_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 4, name: "routes_token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountInWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountInWithPrimitiveTypesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountInWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountInWithPrimitiveTypesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountInWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountInWithPrimitiveTypesRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountInWithPrimitiveTypesRequest | PlainMessage | undefined, b: EstimateSwapExactAmountInWithPrimitiveTypesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountInWithPrimitiveTypesRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSinglePoolSwapExactAmountInRequest - */ -export class EstimateSinglePoolSwapExactAmountInRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in = 2; - */ - tokenIn = ""; - - /** - * @generated from field: string token_out_denom = 3; - */ - tokenOutDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSinglePoolSwapExactAmountInRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSinglePoolSwapExactAmountInRequest { - return new EstimateSinglePoolSwapExactAmountInRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSinglePoolSwapExactAmountInRequest { - return new EstimateSinglePoolSwapExactAmountInRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSinglePoolSwapExactAmountInRequest { - return new EstimateSinglePoolSwapExactAmountInRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSinglePoolSwapExactAmountInRequest | PlainMessage | undefined, b: EstimateSinglePoolSwapExactAmountInRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSinglePoolSwapExactAmountInRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInResponse - */ -export class EstimateSwapExactAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountInResponse { - return new EstimateSwapExactAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountInResponse { - return new EstimateSwapExactAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountInResponse { - return new EstimateSwapExactAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountInResponse | PlainMessage | undefined, b: EstimateSwapExactAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountInResponse, a, b); - } -} - -/** - * =============================== EstimateSwapExactAmountOut - * - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutRequest - */ -export class EstimateSwapExactAmountOutRequest extends Message { - /** - * DEPRECATED - * - * @generated from field: string sender = 1 [deprecated = true]; - * @deprecated - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2 [deprecated = true]; - * @deprecated - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutRoute routes = 3; - */ - routes: SwapAmountOutRoute[] = []; - - /** - * @generated from field: string token_out = 4; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "routes", kind: "message", T: SwapAmountOutRoute, repeated: true }, - { no: 4, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountOutRequest { - return new EstimateSwapExactAmountOutRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountOutRequest { - return new EstimateSwapExactAmountOutRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountOutRequest { - return new EstimateSwapExactAmountOutRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountOutRequest | PlainMessage | undefined, b: EstimateSwapExactAmountOutRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountOutRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutWithPrimitiveTypesRequest - */ -export class EstimateSwapExactAmountOutWithPrimitiveTypesRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1 [deprecated = true]; - * @deprecated - */ - poolId = protoInt64.zero; - - /** - * @generated from field: repeated uint64 routes_pool_id = 2; - */ - routesPoolId: bigint[] = []; - - /** - * @generated from field: repeated string routes_token_in_denom = 3; - */ - routesTokenInDenom: string[] = []; - - /** - * @generated from field: string token_out = 4; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutWithPrimitiveTypesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "routes_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 3, name: "routes_token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 4, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountOutWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountOutWithPrimitiveTypesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountOutWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountOutWithPrimitiveTypesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountOutWithPrimitiveTypesRequest { - return new EstimateSwapExactAmountOutWithPrimitiveTypesRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountOutWithPrimitiveTypesRequest | PlainMessage | undefined, b: EstimateSwapExactAmountOutWithPrimitiveTypesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountOutWithPrimitiveTypesRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSinglePoolSwapExactAmountOutRequest - */ -export class EstimateSinglePoolSwapExactAmountOutRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in_denom = 2; - */ - tokenInDenom = ""; - - /** - * @generated from field: string token_out = 3; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSinglePoolSwapExactAmountOutRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSinglePoolSwapExactAmountOutRequest { - return new EstimateSinglePoolSwapExactAmountOutRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSinglePoolSwapExactAmountOutRequest { - return new EstimateSinglePoolSwapExactAmountOutRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSinglePoolSwapExactAmountOutRequest { - return new EstimateSinglePoolSwapExactAmountOutRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSinglePoolSwapExactAmountOutRequest | PlainMessage | undefined, b: EstimateSinglePoolSwapExactAmountOutRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSinglePoolSwapExactAmountOutRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutResponse - */ -export class EstimateSwapExactAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateSwapExactAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSwapExactAmountOutResponse { - return new EstimateSwapExactAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSwapExactAmountOutResponse { - return new EstimateSwapExactAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSwapExactAmountOutResponse { - return new EstimateSwapExactAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSwapExactAmountOutResponse | PlainMessage | undefined, b: EstimateSwapExactAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSwapExactAmountOutResponse, a, b); - } -} - -/** - * =============================== NumPools - * - * @generated from message osmosis.poolmanager.v1beta1.NumPoolsRequest - */ -export class NumPoolsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.NumPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumPoolsRequest { - return new NumPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumPoolsRequest { - return new NumPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumPoolsRequest { - return new NumPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: NumPoolsRequest | PlainMessage | undefined, b: NumPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(NumPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.NumPoolsResponse - */ -export class NumPoolsResponse extends Message { - /** - * @generated from field: uint64 num_pools = 1; - */ - numPools = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.NumPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "num_pools", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): NumPoolsResponse { - return new NumPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): NumPoolsResponse { - return new NumPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): NumPoolsResponse { - return new NumPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: NumPoolsResponse | PlainMessage | undefined, b: NumPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(NumPoolsResponse, a, b); - } -} - -/** - * =============================== Pool - * - * @generated from message osmosis.poolmanager.v1beta1.PoolRequest - */ -export class PoolRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.PoolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolRequest { - return new PoolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolRequest { - return new PoolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolRequest { - return new PoolRequest().fromJsonString(jsonString, options); - } - - static equals(a: PoolRequest | PlainMessage | undefined, b: PoolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.PoolResponse - */ -export class PoolResponse extends Message { - /** - * @generated from field: google.protobuf.Any pool = 1; - */ - pool?: Any; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.PoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool", kind: "message", T: Any }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolResponse { - return new PoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolResponse { - return new PoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolResponse { - return new PoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: PoolResponse | PlainMessage | undefined, b: PoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolResponse, a, b); - } -} - -/** - * =============================== AllPools - * - * @generated from message osmosis.poolmanager.v1beta1.AllPoolsRequest - */ -export class AllPoolsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllPoolsRequest { - return new AllPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllPoolsRequest { - return new AllPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllPoolsRequest { - return new AllPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllPoolsRequest | PlainMessage | undefined, b: AllPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllPoolsResponse - */ -export class AllPoolsResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllPoolsResponse { - return new AllPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllPoolsResponse { - return new AllPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllPoolsResponse { - return new AllPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllPoolsResponse | PlainMessage | undefined, b: AllPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllPoolsResponse, a, b); - } -} - -/** - * ======================================================= - * ListPoolsByDenomRequest - * - * @generated from message osmosis.poolmanager.v1beta1.ListPoolsByDenomRequest - */ -export class ListPoolsByDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.ListPoolsByDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ListPoolsByDenomRequest { - return new ListPoolsByDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ListPoolsByDenomRequest { - return new ListPoolsByDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ListPoolsByDenomRequest { - return new ListPoolsByDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: ListPoolsByDenomRequest | PlainMessage | undefined, b: ListPoolsByDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ListPoolsByDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.ListPoolsByDenomResponse - */ -export class ListPoolsByDenomResponse extends Message { - /** - * @generated from field: repeated google.protobuf.Any pools = 1; - */ - pools: Any[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.ListPoolsByDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: Any, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ListPoolsByDenomResponse { - return new ListPoolsByDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ListPoolsByDenomResponse { - return new ListPoolsByDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ListPoolsByDenomResponse { - return new ListPoolsByDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: ListPoolsByDenomResponse | PlainMessage | undefined, b: ListPoolsByDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ListPoolsByDenomResponse, a, b); - } -} - -/** - * ========================================================== - * SpotPriceRequest defines the gRPC request structure for a SpotPrice - * query. - * - * @generated from message osmosis.poolmanager.v1beta1.SpotPriceRequest - */ -export class SpotPriceRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset_denom = 2; - */ - baseAssetDenom = ""; - - /** - * @generated from field: string quote_asset_denom = 3; - */ - quoteAssetDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SpotPriceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceRequest | PlainMessage | undefined, b: SpotPriceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceRequest, a, b); - } -} - -/** - * SpotPriceResponse defines the gRPC response structure for a SpotPrice - * query. - * - * @generated from message osmosis.poolmanager.v1beta1.SpotPriceResponse - */ -export class SpotPriceResponse extends Message { - /** - * String of the Dec. Ex) 10.203uatom - * - * @generated from field: string spot_price = 1; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SpotPriceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceResponse | PlainMessage | undefined, b: SpotPriceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceResponse, a, b); - } -} - -/** - * =============================== TotalPoolLiquidity - * - * @generated from message osmosis.poolmanager.v1beta1.TotalPoolLiquidityRequest - */ -export class TotalPoolLiquidityRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalPoolLiquidityRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalPoolLiquidityRequest { - return new TotalPoolLiquidityRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalPoolLiquidityRequest { - return new TotalPoolLiquidityRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalPoolLiquidityRequest { - return new TotalPoolLiquidityRequest().fromJsonString(jsonString, options); - } - - static equals(a: TotalPoolLiquidityRequest | PlainMessage | undefined, b: TotalPoolLiquidityRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalPoolLiquidityRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TotalPoolLiquidityResponse - */ -export class TotalPoolLiquidityResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin liquidity = 1; - */ - liquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalPoolLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalPoolLiquidityResponse { - return new TotalPoolLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: TotalPoolLiquidityResponse | PlainMessage | undefined, b: TotalPoolLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalPoolLiquidityResponse, a, b); - } -} - -/** - * =============================== TotalLiquidity - * - * @generated from message osmosis.poolmanager.v1beta1.TotalLiquidityRequest - */ -export class TotalLiquidityRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalLiquidityRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalLiquidityRequest { - return new TotalLiquidityRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalLiquidityRequest { - return new TotalLiquidityRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalLiquidityRequest { - return new TotalLiquidityRequest().fromJsonString(jsonString, options); - } - - static equals(a: TotalLiquidityRequest | PlainMessage | undefined, b: TotalLiquidityRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalLiquidityRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TotalLiquidityResponse - */ -export class TotalLiquidityResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin liquidity = 1; - */ - liquidity: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalLiquidityResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "liquidity", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalLiquidityResponse { - return new TotalLiquidityResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalLiquidityResponse { - return new TotalLiquidityResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalLiquidityResponse { - return new TotalLiquidityResponse().fromJsonString(jsonString, options); - } - - static equals(a: TotalLiquidityResponse | PlainMessage | undefined, b: TotalLiquidityResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalLiquidityResponse, a, b); - } -} - -/** - * =============================== TotalVolumeForPool - * - * @generated from message osmosis.poolmanager.v1beta1.TotalVolumeForPoolRequest - */ -export class TotalVolumeForPoolRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalVolumeForPoolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalVolumeForPoolRequest { - return new TotalVolumeForPoolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalVolumeForPoolRequest { - return new TotalVolumeForPoolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalVolumeForPoolRequest { - return new TotalVolumeForPoolRequest().fromJsonString(jsonString, options); - } - - static equals(a: TotalVolumeForPoolRequest | PlainMessage | undefined, b: TotalVolumeForPoolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalVolumeForPoolRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TotalVolumeForPoolResponse - */ -export class TotalVolumeForPoolResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin volume = 1; - */ - volume: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TotalVolumeForPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "volume", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalVolumeForPoolResponse { - return new TotalVolumeForPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalVolumeForPoolResponse { - return new TotalVolumeForPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalVolumeForPoolResponse { - return new TotalVolumeForPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: TotalVolumeForPoolResponse | PlainMessage | undefined, b: TotalVolumeForPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalVolumeForPoolResponse, a, b); - } -} - -/** - * =============================== TradingPairTakerFee - * - * @generated from message osmosis.poolmanager.v1beta1.TradingPairTakerFeeRequest - */ -export class TradingPairTakerFeeRequest extends Message { - /** - * @generated from field: string denom_0 = 1; - */ - denom0 = ""; - - /** - * @generated from field: string denom_1 = 2; - */ - denom1 = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TradingPairTakerFeeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom_0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom_1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TradingPairTakerFeeRequest { - return new TradingPairTakerFeeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TradingPairTakerFeeRequest { - return new TradingPairTakerFeeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TradingPairTakerFeeRequest { - return new TradingPairTakerFeeRequest().fromJsonString(jsonString, options); - } - - static equals(a: TradingPairTakerFeeRequest | PlainMessage | undefined, b: TradingPairTakerFeeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TradingPairTakerFeeRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TradingPairTakerFeeResponse - */ -export class TradingPairTakerFeeResponse extends Message { - /** - * @generated from field: string taker_fee = 1; - */ - takerFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TradingPairTakerFeeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TradingPairTakerFeeResponse { - return new TradingPairTakerFeeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TradingPairTakerFeeResponse { - return new TradingPairTakerFeeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TradingPairTakerFeeResponse { - return new TradingPairTakerFeeResponse().fromJsonString(jsonString, options); - } - - static equals(a: TradingPairTakerFeeResponse | PlainMessage | undefined, b: TradingPairTakerFeeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TradingPairTakerFeeResponse, a, b); - } -} - -/** - * EstimateTradeBasedOnPriceImpactRequest represents a request to estimate a - * trade for Balancer/StableSwap/Concentrated liquidity pool types based on the - * given parameters. - * - * @generated from message osmosis.poolmanager.v1beta1.EstimateTradeBasedOnPriceImpactRequest - */ -export class EstimateTradeBasedOnPriceImpactRequest extends Message { - /** - * from_coin is the total amount of tokens that the user wants to sell. - * - * @generated from field: cosmos.base.v1beta1.Coin from_coin = 1; - */ - fromCoin?: Coin; - - /** - * to_coin_denom is the denom identifier of the token that the user wants to - * buy. - * - * @generated from field: string to_coin_denom = 2; - */ - toCoinDenom = ""; - - /** - * pool_id is the identifier of the liquidity pool that the trade will occur - * on. - * - * @generated from field: uint64 pool_id = 3; - */ - poolId = protoInt64.zero; - - /** - * max_price_impact is the maximum percentage that the user is willing - * to affect the price of the liquidity pool. - * - * @generated from field: string max_price_impact = 4; - */ - maxPriceImpact = ""; - - /** - * external_price is an optional external price that the user can enter. - * It adjusts the MaxPriceImpact as the SpotPrice of a pool can be changed at - * any time. - * - * @generated from field: string external_price = 5; - */ - externalPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateTradeBasedOnPriceImpactRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "from_coin", kind: "message", T: Coin }, - { no: 2, name: "to_coin_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "max_price_impact", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "external_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateTradeBasedOnPriceImpactRequest { - return new EstimateTradeBasedOnPriceImpactRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateTradeBasedOnPriceImpactRequest { - return new EstimateTradeBasedOnPriceImpactRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateTradeBasedOnPriceImpactRequest { - return new EstimateTradeBasedOnPriceImpactRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateTradeBasedOnPriceImpactRequest | PlainMessage | undefined, b: EstimateTradeBasedOnPriceImpactRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateTradeBasedOnPriceImpactRequest, a, b); - } -} - -/** - * EstimateTradeBasedOnPriceImpactResponse represents the response data - * for an estimated trade based on price impact. If a trade fails to be - * estimated the response would be 0,0 for input_coin and output_coin and will - * not error. - * - * @generated from message osmosis.poolmanager.v1beta1.EstimateTradeBasedOnPriceImpactResponse - */ -export class EstimateTradeBasedOnPriceImpactResponse extends Message { - /** - * input_coin is the actual input amount that would be tradeable - * under the specified price impact. - * - * @generated from field: cosmos.base.v1beta1.Coin input_coin = 1; - */ - inputCoin?: Coin; - - /** - * output_coin is the amount of tokens of the ToCoinDenom type - * that will be received for the actual InputCoin trade. - * - * @generated from field: cosmos.base.v1beta1.Coin output_coin = 2; - */ - outputCoin?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.EstimateTradeBasedOnPriceImpactResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "input_coin", kind: "message", T: Coin }, - { no: 2, name: "output_coin", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateTradeBasedOnPriceImpactResponse { - return new EstimateTradeBasedOnPriceImpactResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateTradeBasedOnPriceImpactResponse { - return new EstimateTradeBasedOnPriceImpactResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateTradeBasedOnPriceImpactResponse { - return new EstimateTradeBasedOnPriceImpactResponse().fromJsonString(jsonString, options); - } - - static equals(a: EstimateTradeBasedOnPriceImpactResponse | PlainMessage | undefined, b: EstimateTradeBasedOnPriceImpactResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateTradeBasedOnPriceImpactResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllTakerFeeShareAgreementsRequest - */ -export class AllTakerFeeShareAgreementsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllTakerFeeShareAgreementsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllTakerFeeShareAgreementsRequest { - return new AllTakerFeeShareAgreementsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllTakerFeeShareAgreementsRequest { - return new AllTakerFeeShareAgreementsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllTakerFeeShareAgreementsRequest { - return new AllTakerFeeShareAgreementsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllTakerFeeShareAgreementsRequest | PlainMessage | undefined, b: AllTakerFeeShareAgreementsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllTakerFeeShareAgreementsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllTakerFeeShareAgreementsResponse - */ -export class AllTakerFeeShareAgreementsResponse extends Message { - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.TakerFeeShareAgreement taker_fee_share_agreements = 1; - */ - takerFeeShareAgreements: TakerFeeShareAgreement[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllTakerFeeShareAgreementsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fee_share_agreements", kind: "message", T: TakerFeeShareAgreement, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllTakerFeeShareAgreementsResponse { - return new AllTakerFeeShareAgreementsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllTakerFeeShareAgreementsResponse { - return new AllTakerFeeShareAgreementsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllTakerFeeShareAgreementsResponse { - return new AllTakerFeeShareAgreementsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllTakerFeeShareAgreementsResponse | PlainMessage | undefined, b: AllTakerFeeShareAgreementsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllTakerFeeShareAgreementsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeShareAgreementFromDenomRequest - */ -export class TakerFeeShareAgreementFromDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeShareAgreementFromDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeShareAgreementFromDenomRequest { - return new TakerFeeShareAgreementFromDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeShareAgreementFromDenomRequest { - return new TakerFeeShareAgreementFromDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeShareAgreementFromDenomRequest { - return new TakerFeeShareAgreementFromDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeShareAgreementFromDenomRequest | PlainMessage | undefined, b: TakerFeeShareAgreementFromDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeShareAgreementFromDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeShareAgreementFromDenomResponse - */ -export class TakerFeeShareAgreementFromDenomResponse extends Message { - /** - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeeShareAgreement taker_fee_share_agreement = 1; - */ - takerFeeShareAgreement?: TakerFeeShareAgreement; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeShareAgreementFromDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fee_share_agreement", kind: "message", T: TakerFeeShareAgreement }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeShareAgreementFromDenomResponse { - return new TakerFeeShareAgreementFromDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeShareAgreementFromDenomResponse { - return new TakerFeeShareAgreementFromDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeShareAgreementFromDenomResponse { - return new TakerFeeShareAgreementFromDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeShareAgreementFromDenomResponse | PlainMessage | undefined, b: TakerFeeShareAgreementFromDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeShareAgreementFromDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeShareDenomsToAccruedValueRequest - */ -export class TakerFeeShareDenomsToAccruedValueRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: string takerFeeDenom = 2; - */ - takerFeeDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeShareDenomsToAccruedValueRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "takerFeeDenom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeShareDenomsToAccruedValueRequest { - return new TakerFeeShareDenomsToAccruedValueRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeShareDenomsToAccruedValueRequest { - return new TakerFeeShareDenomsToAccruedValueRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeShareDenomsToAccruedValueRequest { - return new TakerFeeShareDenomsToAccruedValueRequest().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeShareDenomsToAccruedValueRequest | PlainMessage | undefined, b: TakerFeeShareDenomsToAccruedValueRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeShareDenomsToAccruedValueRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeShareDenomsToAccruedValueResponse - */ -export class TakerFeeShareDenomsToAccruedValueResponse extends Message { - /** - * @generated from field: string amount = 1; - */ - amount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeShareDenomsToAccruedValueResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeShareDenomsToAccruedValueResponse { - return new TakerFeeShareDenomsToAccruedValueResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeShareDenomsToAccruedValueResponse { - return new TakerFeeShareDenomsToAccruedValueResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeShareDenomsToAccruedValueResponse { - return new TakerFeeShareDenomsToAccruedValueResponse().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeShareDenomsToAccruedValueResponse | PlainMessage | undefined, b: TakerFeeShareDenomsToAccruedValueResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeShareDenomsToAccruedValueResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllTakerFeeShareAccumulatorsRequest - */ -export class AllTakerFeeShareAccumulatorsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllTakerFeeShareAccumulatorsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllTakerFeeShareAccumulatorsRequest { - return new AllTakerFeeShareAccumulatorsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllTakerFeeShareAccumulatorsRequest { - return new AllTakerFeeShareAccumulatorsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllTakerFeeShareAccumulatorsRequest { - return new AllTakerFeeShareAccumulatorsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllTakerFeeShareAccumulatorsRequest | PlainMessage | undefined, b: AllTakerFeeShareAccumulatorsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllTakerFeeShareAccumulatorsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllTakerFeeShareAccumulatorsResponse - */ -export class AllTakerFeeShareAccumulatorsResponse extends Message { - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.TakerFeeSkimAccumulator taker_fee_skim_accumulators = 1; - */ - takerFeeSkimAccumulators: TakerFeeSkimAccumulator[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllTakerFeeShareAccumulatorsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fee_skim_accumulators", kind: "message", T: TakerFeeSkimAccumulator, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllTakerFeeShareAccumulatorsResponse { - return new AllTakerFeeShareAccumulatorsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllTakerFeeShareAccumulatorsResponse { - return new AllTakerFeeShareAccumulatorsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllTakerFeeShareAccumulatorsResponse { - return new AllTakerFeeShareAccumulatorsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllTakerFeeShareAccumulatorsResponse | PlainMessage | undefined, b: AllTakerFeeShareAccumulatorsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllTakerFeeShareAccumulatorsResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromDenomRequest - */ -export class RegisteredAlloyedPoolFromDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RegisteredAlloyedPoolFromDenomRequest { - return new RegisteredAlloyedPoolFromDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RegisteredAlloyedPoolFromDenomRequest { - return new RegisteredAlloyedPoolFromDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RegisteredAlloyedPoolFromDenomRequest { - return new RegisteredAlloyedPoolFromDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: RegisteredAlloyedPoolFromDenomRequest | PlainMessage | undefined, b: RegisteredAlloyedPoolFromDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(RegisteredAlloyedPoolFromDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromDenomResponse - */ -export class RegisteredAlloyedPoolFromDenomResponse extends Message { - /** - * @generated from field: osmosis.poolmanager.v1beta1.AlloyContractTakerFeeShareState contract_state = 1; - */ - contractState?: AlloyContractTakerFeeShareState; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_state", kind: "message", T: AlloyContractTakerFeeShareState }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RegisteredAlloyedPoolFromDenomResponse { - return new RegisteredAlloyedPoolFromDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RegisteredAlloyedPoolFromDenomResponse { - return new RegisteredAlloyedPoolFromDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RegisteredAlloyedPoolFromDenomResponse { - return new RegisteredAlloyedPoolFromDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: RegisteredAlloyedPoolFromDenomResponse | PlainMessage | undefined, b: RegisteredAlloyedPoolFromDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(RegisteredAlloyedPoolFromDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromPoolIdRequest - */ -export class RegisteredAlloyedPoolFromPoolIdRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromPoolIdRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RegisteredAlloyedPoolFromPoolIdRequest { - return new RegisteredAlloyedPoolFromPoolIdRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RegisteredAlloyedPoolFromPoolIdRequest { - return new RegisteredAlloyedPoolFromPoolIdRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RegisteredAlloyedPoolFromPoolIdRequest { - return new RegisteredAlloyedPoolFromPoolIdRequest().fromJsonString(jsonString, options); - } - - static equals(a: RegisteredAlloyedPoolFromPoolIdRequest | PlainMessage | undefined, b: RegisteredAlloyedPoolFromPoolIdRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(RegisteredAlloyedPoolFromPoolIdRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromPoolIdResponse - */ -export class RegisteredAlloyedPoolFromPoolIdResponse extends Message { - /** - * @generated from field: osmosis.poolmanager.v1beta1.AlloyContractTakerFeeShareState contract_state = 1; - */ - contractState?: AlloyContractTakerFeeShareState; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.RegisteredAlloyedPoolFromPoolIdResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_state", kind: "message", T: AlloyContractTakerFeeShareState }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RegisteredAlloyedPoolFromPoolIdResponse { - return new RegisteredAlloyedPoolFromPoolIdResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RegisteredAlloyedPoolFromPoolIdResponse { - return new RegisteredAlloyedPoolFromPoolIdResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RegisteredAlloyedPoolFromPoolIdResponse { - return new RegisteredAlloyedPoolFromPoolIdResponse().fromJsonString(jsonString, options); - } - - static equals(a: RegisteredAlloyedPoolFromPoolIdResponse | PlainMessage | undefined, b: RegisteredAlloyedPoolFromPoolIdResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(RegisteredAlloyedPoolFromPoolIdResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllRegisteredAlloyedPoolsRequest - */ -export class AllRegisteredAlloyedPoolsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllRegisteredAlloyedPoolsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllRegisteredAlloyedPoolsRequest { - return new AllRegisteredAlloyedPoolsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllRegisteredAlloyedPoolsRequest { - return new AllRegisteredAlloyedPoolsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllRegisteredAlloyedPoolsRequest { - return new AllRegisteredAlloyedPoolsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllRegisteredAlloyedPoolsRequest | PlainMessage | undefined, b: AllRegisteredAlloyedPoolsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllRegisteredAlloyedPoolsRequest, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.AllRegisteredAlloyedPoolsResponse - */ -export class AllRegisteredAlloyedPoolsResponse extends Message { - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.AlloyContractTakerFeeShareState contract_states = 1; - */ - contractStates: AlloyContractTakerFeeShareState[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AllRegisteredAlloyedPoolsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_states", kind: "message", T: AlloyContractTakerFeeShareState, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllRegisteredAlloyedPoolsResponse { - return new AllRegisteredAlloyedPoolsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllRegisteredAlloyedPoolsResponse { - return new AllRegisteredAlloyedPoolsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllRegisteredAlloyedPoolsResponse { - return new AllRegisteredAlloyedPoolsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllRegisteredAlloyedPoolsResponse | PlainMessage | undefined, b: AllRegisteredAlloyedPoolsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllRegisteredAlloyedPoolsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/swap_route_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/swap_route_pb.ts deleted file mode 100644 index cd5223c4b..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/swap_route_pb.ts +++ /dev/null @@ -1,180 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/swap_route.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.poolmanager.v1beta1.SwapAmountInRoute - */ -export class SwapAmountInRoute extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_out_denom = 2; - */ - tokenOutDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SwapAmountInRoute"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapAmountInRoute { - return new SwapAmountInRoute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapAmountInRoute { - return new SwapAmountInRoute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapAmountInRoute { - return new SwapAmountInRoute().fromJsonString(jsonString, options); - } - - static equals(a: SwapAmountInRoute | PlainMessage | undefined, b: SwapAmountInRoute | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapAmountInRoute, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.SwapAmountOutRoute - */ -export class SwapAmountOutRoute extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string token_in_denom = 2; - */ - tokenInDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SwapAmountOutRoute"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapAmountOutRoute { - return new SwapAmountOutRoute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapAmountOutRoute { - return new SwapAmountOutRoute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapAmountOutRoute { - return new SwapAmountOutRoute().fromJsonString(jsonString, options); - } - - static equals(a: SwapAmountOutRoute | PlainMessage | undefined, b: SwapAmountOutRoute | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapAmountOutRoute, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.SwapAmountInSplitRoute - */ -export class SwapAmountInSplitRoute extends Message { - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInRoute pools = 1; - */ - pools: SwapAmountInRoute[] = []; - - /** - * @generated from field: string token_in_amount = 2; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SwapAmountInSplitRoute"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: SwapAmountInRoute, repeated: true }, - { no: 2, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapAmountInSplitRoute { - return new SwapAmountInSplitRoute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapAmountInSplitRoute { - return new SwapAmountInSplitRoute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapAmountInSplitRoute { - return new SwapAmountInSplitRoute().fromJsonString(jsonString, options); - } - - static equals(a: SwapAmountInSplitRoute | PlainMessage | undefined, b: SwapAmountInSplitRoute | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapAmountInSplitRoute, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.SwapAmountOutSplitRoute - */ -export class SwapAmountOutSplitRoute extends Message { - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutRoute pools = 1; - */ - pools: SwapAmountOutRoute[] = []; - - /** - * @generated from field: string token_out_amount = 2; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.SwapAmountOutSplitRoute"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pools", kind: "message", T: SwapAmountOutRoute, repeated: true }, - { no: 2, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SwapAmountOutSplitRoute { - return new SwapAmountOutSplitRoute().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SwapAmountOutSplitRoute { - return new SwapAmountOutSplitRoute().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SwapAmountOutSplitRoute { - return new SwapAmountOutSplitRoute().fromJsonString(jsonString, options); - } - - static equals(a: SwapAmountOutSplitRoute | PlainMessage | undefined, b: SwapAmountOutSplitRoute | PlainMessage | undefined): boolean { - return proto3.util.equals(SwapAmountOutSplitRoute, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/taker_fee_share_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/taker_fee_share_pb.ts deleted file mode 100644 index 5e1167b06..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/taker_fee_share_pb.ts +++ /dev/null @@ -1,182 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/taker_fee_share.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * TakerFeeShareAgreement represents the agreement between the Osmosis protocol - * and a specific denom to share a certain percent of taker fees generated in - * any route that contains said denom. For example, if the agreement specifies a - * 10% skim_percent, this means 10% of the taker fees generated in a swap route - * containing the specified denom will be sent to the address specified - * in the skim_address field at the end of each epoch. These skim_percents are - * additive, so if three taker fee agreements have skim percents of 10%, 20%, - * and 30%, the total skim percent for the route will be 60%. - * - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeShareAgreement - */ -export class TakerFeeShareAgreement extends Message { - /** - * denom is the denom that has the taker fee share agreement. - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * skim_percent is the percentage of taker fees that will be skimmed for the - * denom, in the event that the denom is included in the swap route. - * - * @generated from field: string skim_percent = 2; - */ - skimPercent = ""; - - /** - * skim_address is the address belonging to the respective denom - * that the skimmed taker fees will be sent to at the end of each epoch. - * - * @generated from field: string skim_address = 3; - */ - skimAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeShareAgreement"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "skim_percent", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "skim_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeShareAgreement { - return new TakerFeeShareAgreement().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeShareAgreement { - return new TakerFeeShareAgreement().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeShareAgreement { - return new TakerFeeShareAgreement().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeShareAgreement | PlainMessage | undefined, b: TakerFeeShareAgreement | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeShareAgreement, a, b); - } -} - -/** - * TakerFeeSkimAccumulator accumulates the total skimmed taker fees for each - * denom that has a taker fee share agreement. - * - * @generated from message osmosis.poolmanager.v1beta1.TakerFeeSkimAccumulator - */ -export class TakerFeeSkimAccumulator extends Message { - /** - * denom is the denom that has the taker fee share agreement. - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * skimmed_taker_fees is the total skimmed taker fees for the denom. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin skimmed_taker_fees = 2; - */ - skimmedTakerFees: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TakerFeeSkimAccumulator"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "skimmed_taker_fees", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TakerFeeSkimAccumulator { - return new TakerFeeSkimAccumulator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TakerFeeSkimAccumulator { - return new TakerFeeSkimAccumulator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TakerFeeSkimAccumulator { - return new TakerFeeSkimAccumulator().fromJsonString(jsonString, options); - } - - static equals(a: TakerFeeSkimAccumulator | PlainMessage | undefined, b: TakerFeeSkimAccumulator | PlainMessage | undefined): boolean { - return proto3.util.equals(TakerFeeSkimAccumulator, a, b); - } -} - -/** - * AlloyContractTakerFeeShareState contains the contract address of the alloyed - * asset pool, along with the adjusted taker fee share agreements for any asset - * within the alloyed asset pool that has a taker fee share agreement. If for - * instance there are two denoms, and denomA makes up 50 percent and denomB - * makes up 50 percent, and denom A has a taker fee share agreement with a skim - * percent of 10%, then the adjusted taker fee share agreement for denomA will - * be 5%. - * - * @generated from message osmosis.poolmanager.v1beta1.AlloyContractTakerFeeShareState - */ -export class AlloyContractTakerFeeShareState extends Message { - /** - * contract_address is the address of the alloyed asset pool contract. - * - * @generated from field: string contract_address = 1; - */ - contractAddress = ""; - - /** - * taker_fee_share_agreements is the adjusted taker fee share agreements for - * any asset within the alloyed asset pool that has a taker fee share - * agreement. - * - * @generated from field: repeated osmosis.poolmanager.v1beta1.TakerFeeShareAgreement taker_fee_share_agreements = 2; - */ - takerFeeShareAgreements: TakerFeeShareAgreement[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.AlloyContractTakerFeeShareState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "taker_fee_share_agreements", kind: "message", T: TakerFeeShareAgreement, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AlloyContractTakerFeeShareState { - return new AlloyContractTakerFeeShareState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AlloyContractTakerFeeShareState { - return new AlloyContractTakerFeeShareState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AlloyContractTakerFeeShareState { - return new AlloyContractTakerFeeShareState().fromJsonString(jsonString, options); - } - - static equals(a: AlloyContractTakerFeeShareState | PlainMessage | undefined, b: AlloyContractTakerFeeShareState | PlainMessage | undefined): boolean { - return proto3.util.equals(AlloyContractTakerFeeShareState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tracked_volume_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tracked_volume_pb.ts deleted file mode 100644 index fdefbb989..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tracked_volume_pb.ts +++ /dev/null @@ -1,46 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/tracked_volume.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * @generated from message osmosis.poolmanager.v1beta1.TrackedVolume - */ -export class TrackedVolume extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin amount = 1; - */ - amount: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.TrackedVolume"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TrackedVolume { - return new TrackedVolume().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TrackedVolume { - return new TrackedVolume().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TrackedVolume { - return new TrackedVolume().fromJsonString(jsonString, options); - } - - static equals(a: TrackedVolume | PlainMessage | undefined, b: TrackedVolume | PlainMessage | undefined): boolean { - return proto3.util.equals(TrackedVolume, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_cosmes.ts deleted file mode 100644 index 9c1abf938..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,79 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/tx.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgSetDenomPairTakerFee, MsgSetDenomPairTakerFeeResponse, MsgSetRegisteredAlloyedPool, MsgSetRegisteredAlloyedPoolResponse, MsgSetTakerFeeShareAgreementForDenom, MsgSetTakerFeeShareAgreementForDenomResponse, MsgSplitRouteSwapExactAmountIn, MsgSplitRouteSwapExactAmountInResponse, MsgSplitRouteSwapExactAmountOut, MsgSplitRouteSwapExactAmountOutResponse, MsgSwapExactAmountIn, MsgSwapExactAmountInResponse, MsgSwapExactAmountOut, MsgSwapExactAmountOutResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.poolmanager.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SwapExactAmountIn - */ -export const MsgSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "SwapExactAmountIn", - Request: MsgSwapExactAmountIn, - Response: MsgSwapExactAmountInResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SwapExactAmountOut - */ -export const MsgSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "SwapExactAmountOut", - Request: MsgSwapExactAmountOut, - Response: MsgSwapExactAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SplitRouteSwapExactAmountIn - */ -export const MsgSplitRouteSwapExactAmountInService = { - typeName: TYPE_NAME, - method: "SplitRouteSwapExactAmountIn", - Request: MsgSplitRouteSwapExactAmountIn, - Response: MsgSplitRouteSwapExactAmountInResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SplitRouteSwapExactAmountOut - */ -export const MsgSplitRouteSwapExactAmountOutService = { - typeName: TYPE_NAME, - method: "SplitRouteSwapExactAmountOut", - Request: MsgSplitRouteSwapExactAmountOut, - Response: MsgSplitRouteSwapExactAmountOutResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SetDenomPairTakerFee - */ -export const MsgSetDenomPairTakerFeeService = { - typeName: TYPE_NAME, - method: "SetDenomPairTakerFee", - Request: MsgSetDenomPairTakerFee, - Response: MsgSetDenomPairTakerFeeResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SetTakerFeeShareAgreementForDenom - */ -export const MsgSetTakerFeeShareAgreementForDenomService = { - typeName: TYPE_NAME, - method: "SetTakerFeeShareAgreementForDenom", - Request: MsgSetTakerFeeShareAgreementForDenom, - Response: MsgSetTakerFeeShareAgreementForDenomResponse, -} as const; - -/** - * @generated from rpc osmosis.poolmanager.v1beta1.Msg.SetRegisteredAlloyedPool - */ -export const MsgSetRegisteredAlloyedPoolService = { - typeName: TYPE_NAME, - method: "SetRegisteredAlloyedPool", - Request: MsgSetRegisteredAlloyedPool, - Response: MsgSetRegisteredAlloyedPoolResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_pb.ts deleted file mode 100644 index 586cd5def..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v1beta1/tx_pb.ts +++ /dev/null @@ -1,715 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v1beta1/tx.proto (package osmosis.poolmanager.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { SwapAmountInRoute, SwapAmountInSplitRoute, SwapAmountOutRoute, SwapAmountOutSplitRoute } from "./swap_route_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * ===================== MsgSwapExactAmountIn - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSwapExactAmountIn - */ -export class MsgSwapExactAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInRoute routes = 2; - */ - routes: SwapAmountInRoute[] = []; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_in = 3; - */ - tokenIn?: Coin; - - /** - * @generated from field: string token_out_min_amount = 4; - */ - tokenOutMinAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSwapExactAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountInRoute, repeated: true }, - { no: 3, name: "token_in", kind: "message", T: Coin }, - { no: 4, name: "token_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountIn { - return new MsgSwapExactAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountIn | PlainMessage | undefined, b: MsgSwapExactAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSwapExactAmountInResponse - */ -export class MsgSwapExactAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSwapExactAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountInResponse { - return new MsgSwapExactAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountInResponse | PlainMessage | undefined, b: MsgSwapExactAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountInResponse, a, b); - } -} - -/** - * ===================== MsgSplitRouteSwapExactAmountIn - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountIn - */ -export class MsgSplitRouteSwapExactAmountIn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountInSplitRoute routes = 2; - */ - routes: SwapAmountInSplitRoute[] = []; - - /** - * @generated from field: string token_in_denom = 3; - */ - tokenInDenom = ""; - - /** - * @generated from field: string token_out_min_amount = 4; - */ - tokenOutMinAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountIn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountInSplitRoute, repeated: true }, - { no: 3, name: "token_in_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_out_min_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSplitRouteSwapExactAmountIn { - return new MsgSplitRouteSwapExactAmountIn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSplitRouteSwapExactAmountIn { - return new MsgSplitRouteSwapExactAmountIn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSplitRouteSwapExactAmountIn { - return new MsgSplitRouteSwapExactAmountIn().fromJsonString(jsonString, options); - } - - static equals(a: MsgSplitRouteSwapExactAmountIn | PlainMessage | undefined, b: MsgSplitRouteSwapExactAmountIn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSplitRouteSwapExactAmountIn, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountInResponse - */ -export class MsgSplitRouteSwapExactAmountInResponse extends Message { - /** - * @generated from field: string token_out_amount = 1; - */ - tokenOutAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountInResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_out_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSplitRouteSwapExactAmountInResponse { - return new MsgSplitRouteSwapExactAmountInResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSplitRouteSwapExactAmountInResponse { - return new MsgSplitRouteSwapExactAmountInResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSplitRouteSwapExactAmountInResponse { - return new MsgSplitRouteSwapExactAmountInResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSplitRouteSwapExactAmountInResponse | PlainMessage | undefined, b: MsgSplitRouteSwapExactAmountInResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSplitRouteSwapExactAmountInResponse, a, b); - } -} - -/** - * ===================== MsgSwapExactAmountOut - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSwapExactAmountOut - */ -export class MsgSwapExactAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutRoute routes = 2; - */ - routes: SwapAmountOutRoute[] = []; - - /** - * @generated from field: string token_in_max_amount = 3; - */ - tokenInMaxAmount = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_out = 4; - */ - tokenOut?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSwapExactAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountOutRoute, repeated: true }, - { no: 3, name: "token_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_out", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountOut { - return new MsgSwapExactAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountOut | PlainMessage | undefined, b: MsgSwapExactAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSwapExactAmountOutResponse - */ -export class MsgSwapExactAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSwapExactAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSwapExactAmountOutResponse { - return new MsgSwapExactAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSwapExactAmountOutResponse | PlainMessage | undefined, b: MsgSwapExactAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSwapExactAmountOutResponse, a, b); - } -} - -/** - * ===================== MsgSplitRouteSwapExactAmountOut - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountOut - */ -export class MsgSplitRouteSwapExactAmountOut extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.SwapAmountOutSplitRoute routes = 2; - */ - routes: SwapAmountOutSplitRoute[] = []; - - /** - * @generated from field: string token_out_denom = 3; - */ - tokenOutDenom = ""; - - /** - * @generated from field: string token_in_max_amount = 4; - */ - tokenInMaxAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountOut"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "routes", kind: "message", T: SwapAmountOutSplitRoute, repeated: true }, - { no: 3, name: "token_out_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_in_max_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSplitRouteSwapExactAmountOut { - return new MsgSplitRouteSwapExactAmountOut().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSplitRouteSwapExactAmountOut { - return new MsgSplitRouteSwapExactAmountOut().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSplitRouteSwapExactAmountOut { - return new MsgSplitRouteSwapExactAmountOut().fromJsonString(jsonString, options); - } - - static equals(a: MsgSplitRouteSwapExactAmountOut | PlainMessage | undefined, b: MsgSplitRouteSwapExactAmountOut | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSplitRouteSwapExactAmountOut, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountOutResponse - */ -export class MsgSplitRouteSwapExactAmountOutResponse extends Message { - /** - * @generated from field: string token_in_amount = 1; - */ - tokenInAmount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSplitRouteSwapExactAmountOutResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "token_in_amount", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSplitRouteSwapExactAmountOutResponse { - return new MsgSplitRouteSwapExactAmountOutResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSplitRouteSwapExactAmountOutResponse { - return new MsgSplitRouteSwapExactAmountOutResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSplitRouteSwapExactAmountOutResponse { - return new MsgSplitRouteSwapExactAmountOutResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSplitRouteSwapExactAmountOutResponse | PlainMessage | undefined, b: MsgSplitRouteSwapExactAmountOutResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSplitRouteSwapExactAmountOutResponse, a, b); - } -} - -/** - * ===================== MsgSetDenomPairTakerFee - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSetDenomPairTakerFee - */ -export class MsgSetDenomPairTakerFee extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated osmosis.poolmanager.v1beta1.DenomPairTakerFee denom_pair_taker_fee = 2; - */ - denomPairTakerFee: DenomPairTakerFee[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetDenomPairTakerFee"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom_pair_taker_fee", kind: "message", T: DenomPairTakerFee, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDenomPairTakerFee { - return new MsgSetDenomPairTakerFee().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDenomPairTakerFee { - return new MsgSetDenomPairTakerFee().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDenomPairTakerFee { - return new MsgSetDenomPairTakerFee().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDenomPairTakerFee | PlainMessage | undefined, b: MsgSetDenomPairTakerFee | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDenomPairTakerFee, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSetDenomPairTakerFeeResponse - */ -export class MsgSetDenomPairTakerFeeResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetDenomPairTakerFeeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDenomPairTakerFeeResponse { - return new MsgSetDenomPairTakerFeeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDenomPairTakerFeeResponse { - return new MsgSetDenomPairTakerFeeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDenomPairTakerFeeResponse { - return new MsgSetDenomPairTakerFeeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDenomPairTakerFeeResponse | PlainMessage | undefined, b: MsgSetDenomPairTakerFeeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDenomPairTakerFeeResponse, a, b); - } -} - -/** - * ===================== MsgSetTakerFeeShareAgreementForDenom - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSetTakerFeeShareAgreementForDenom - */ -export class MsgSetTakerFeeShareAgreementForDenom extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * denom is the denom that the taker fee share agreement is being set for. - * Ex. If this is set to "nBTC", then any trade route that includes "nBTC" - * will have the skim_percent skimmed from the taker fees and sent to the - * skim_address. - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * skim_percent is the percentage of taker fees that will be skimmed for the - * bridge provider, in the event that the bridge provider's denom is included - * in the swap route. - * - * @generated from field: string skim_percent = 3; - */ - skimPercent = ""; - - /** - * skim_address is the address belonging to the respective bridge provider - * that the skimmed taker fees will be sent to at the end of each epoch. - * - * @generated from field: string skim_address = 4; - */ - skimAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetTakerFeeShareAgreementForDenom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "skim_percent", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "skim_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetTakerFeeShareAgreementForDenom { - return new MsgSetTakerFeeShareAgreementForDenom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetTakerFeeShareAgreementForDenom { - return new MsgSetTakerFeeShareAgreementForDenom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetTakerFeeShareAgreementForDenom { - return new MsgSetTakerFeeShareAgreementForDenom().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetTakerFeeShareAgreementForDenom | PlainMessage | undefined, b: MsgSetTakerFeeShareAgreementForDenom | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetTakerFeeShareAgreementForDenom, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSetTakerFeeShareAgreementForDenomResponse - */ -export class MsgSetTakerFeeShareAgreementForDenomResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetTakerFeeShareAgreementForDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetTakerFeeShareAgreementForDenomResponse { - return new MsgSetTakerFeeShareAgreementForDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetTakerFeeShareAgreementForDenomResponse { - return new MsgSetTakerFeeShareAgreementForDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetTakerFeeShareAgreementForDenomResponse { - return new MsgSetTakerFeeShareAgreementForDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetTakerFeeShareAgreementForDenomResponse | PlainMessage | undefined, b: MsgSetTakerFeeShareAgreementForDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetTakerFeeShareAgreementForDenomResponse, a, b); - } -} - -/** - * ===================== MsgSetRegisteredAlloyedPool - * - * @generated from message osmosis.poolmanager.v1beta1.MsgSetRegisteredAlloyedPool - */ -export class MsgSetRegisteredAlloyedPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * pool_id is the id of the pool that is being registered as an alloyed pool. - * Only alloyed pools that intend to be used in taker fee revenue sharing - * should be registered. - * - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetRegisteredAlloyedPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetRegisteredAlloyedPool { - return new MsgSetRegisteredAlloyedPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetRegisteredAlloyedPool { - return new MsgSetRegisteredAlloyedPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetRegisteredAlloyedPool { - return new MsgSetRegisteredAlloyedPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetRegisteredAlloyedPool | PlainMessage | undefined, b: MsgSetRegisteredAlloyedPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetRegisteredAlloyedPool, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.MsgSetRegisteredAlloyedPoolResponse - */ -export class MsgSetRegisteredAlloyedPoolResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.MsgSetRegisteredAlloyedPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetRegisteredAlloyedPoolResponse { - return new MsgSetRegisteredAlloyedPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetRegisteredAlloyedPoolResponse { - return new MsgSetRegisteredAlloyedPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetRegisteredAlloyedPoolResponse { - return new MsgSetRegisteredAlloyedPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetRegisteredAlloyedPoolResponse | PlainMessage | undefined, b: MsgSetRegisteredAlloyedPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetRegisteredAlloyedPoolResponse, a, b); - } -} - -/** - * @generated from message osmosis.poolmanager.v1beta1.DenomPairTakerFee - */ -export class DenomPairTakerFee extends Message { - /** - * DEPRECATED: Now that we are using uni-directional trading pairs, we are - * using tokenInDenom and tokenOutDenom instead of denom0 and denom1 to - * prevent confusion. - * - * @generated from field: string denom0 = 1 [deprecated = true]; - * @deprecated - */ - denom0 = ""; - - /** - * @generated from field: string denom1 = 2 [deprecated = true]; - * @deprecated - */ - denom1 = ""; - - /** - * @generated from field: string taker_fee = 3; - */ - takerFee = ""; - - /** - * @generated from field: string tokenInDenom = 4; - */ - tokenInDenom = ""; - - /** - * @generated from field: string tokenOutDenom = 5; - */ - tokenOutDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v1beta1.DenomPairTakerFee"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "taker_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "tokenInDenom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "tokenOutDenom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DenomPairTakerFee { - return new DenomPairTakerFee().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DenomPairTakerFee { - return new DenomPairTakerFee().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DenomPairTakerFee { - return new DenomPairTakerFee().fromJsonString(jsonString, options); - } - - static equals(a: DenomPairTakerFee | PlainMessage | undefined, b: DenomPairTakerFee | PlainMessage | undefined): boolean { - return proto3.util.equals(DenomPairTakerFee, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v2/query_cosmes.ts b/packages/es/src/protobufs/osmosis/poolmanager/v2/query_cosmes.ts deleted file mode 100644 index b82f020dc..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v2/query_cosmes.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v2/query.proto (package osmosis.poolmanager.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { SpotPriceRequest, SpotPriceResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.poolmanager.v2.Query"; - -/** - * SpotPriceV2 defines a gRPC query handler that returns the spot price given - * a base denomination and a quote denomination. - * The returned spot price has 36 decimal places. However, some of - * modules perform sig fig rounding so most of the rightmost decimals can be - * zeroes. - * - * @generated from rpc osmosis.poolmanager.v2.Query.SpotPriceV2 - */ -export const QuerySpotPriceV2Service = { - typeName: TYPE_NAME, - method: "SpotPriceV2", - Request: SpotPriceRequest, - Response: SpotPriceResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/poolmanager/v2/query_pb.ts b/packages/es/src/protobufs/osmosis/poolmanager/v2/query_pb.ts deleted file mode 100644 index ca942e2ee..000000000 --- a/packages/es/src/protobufs/osmosis/poolmanager/v2/query_pb.ts +++ /dev/null @@ -1,102 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/poolmanager/v2/query.proto (package osmosis.poolmanager.v2, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * SpotPriceRequest defines the gRPC request structure for a SpotPrice - * query. - * - * @generated from message osmosis.poolmanager.v2.SpotPriceRequest - */ -export class SpotPriceRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset_denom = 2; - */ - baseAssetDenom = ""; - - /** - * @generated from field: string quote_asset_denom = 3; - */ - quoteAssetDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v2.SpotPriceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceRequest { - return new SpotPriceRequest().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceRequest | PlainMessage | undefined, b: SpotPriceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceRequest, a, b); - } -} - -/** - * SpotPriceResponse defines the gRPC response structure for a SpotPrice - * query. - * - * @generated from message osmosis.poolmanager.v2.SpotPriceResponse - */ -export class SpotPriceResponse extends Message { - /** - * String of the BigDec. Ex) 10.203uatom - * - * @generated from field: string spot_price = 1; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.poolmanager.v2.SpotPriceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SpotPriceResponse { - return new SpotPriceResponse().fromJsonString(jsonString, options); - } - - static equals(a: SpotPriceResponse | PlainMessage | undefined, b: SpotPriceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SpotPriceResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/genesis_pb.ts deleted file mode 100644 index 6e64a705a..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,161 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/genesis.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { BaseDenom, CyclicArbTracker, InfoByPoolType, PoolWeights, TokenPairArbRoutes } from "./protorev_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * GenesisState defines the protorev module's genesis state. - * - * @generated from message osmosis.protorev.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * Parameters for the protorev module. - * - * @generated from field: osmosis.protorev.v1beta1.Params params = 1; - */ - params?: Params; - - /** - * Token pair arb routes for the protorev module (hot routes). - * - * @generated from field: repeated osmosis.protorev.v1beta1.TokenPairArbRoutes token_pair_arb_routes = 2; - */ - tokenPairArbRoutes: TokenPairArbRoutes[] = []; - - /** - * The base denominations being used to create cyclic arbitrage routes via the - * highest liquidity method. - * - * @generated from field: repeated osmosis.protorev.v1beta1.BaseDenom base_denoms = 3; - */ - baseDenoms: BaseDenom[] = []; - - /** - * DEPRECATED: pool_weights are weights that are being used to calculate the - * compute cost of each route. This field is deprecated. - * It is replaced by the `info_by_pool_type` field. - * - * @generated from field: osmosis.protorev.v1beta1.PoolWeights pool_weights = 4 [deprecated = true]; - * @deprecated - */ - poolWeights?: PoolWeights; - - /** - * The number of days since module genesis. - * - * @generated from field: uint64 days_since_module_genesis = 5; - */ - daysSinceModuleGenesis = protoInt64.zero; - - /** - * The fees the developer account has accumulated over time. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin developer_fees = 6; - */ - developerFees: Coin[] = []; - - /** - * The latest block height that the module has processed. - * - * @generated from field: uint64 latest_block_height = 7; - */ - latestBlockHeight = protoInt64.zero; - - /** - * The developer account address of the module. - * - * @generated from field: string developer_address = 8; - */ - developerAddress = ""; - - /** - * Max pool points per block i.e. the maximum compute time (in ms) - * that protorev can use per block. - * - * @generated from field: uint64 max_pool_points_per_block = 9; - */ - maxPoolPointsPerBlock = protoInt64.zero; - - /** - * Max pool points per tx i.e. the maximum compute time (in ms) that - * protorev can use per tx. - * - * @generated from field: uint64 max_pool_points_per_tx = 10; - */ - maxPoolPointsPerTx = protoInt64.zero; - - /** - * The number of pool points that have been consumed in the current block. - * - * @generated from field: uint64 point_count_for_block = 11; - */ - pointCountForBlock = protoInt64.zero; - - /** - * All of the profits that have been accumulated by the module. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin profits = 12; - */ - profits: Coin[] = []; - - /** - * Information that is used to estimate execution time / gas - * consumption of a swap on a given pool type. - * - * @generated from field: osmosis.protorev.v1beta1.InfoByPoolType info_by_pool_type = 13; - */ - infoByPoolType?: InfoByPoolType; - - /** - * @generated from field: osmosis.protorev.v1beta1.CyclicArbTracker cyclic_arb_tracker = 14; - */ - cyclicArbTracker?: CyclicArbTracker; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "token_pair_arb_routes", kind: "message", T: TokenPairArbRoutes, repeated: true }, - { no: 3, name: "base_denoms", kind: "message", T: BaseDenom, repeated: true }, - { no: 4, name: "pool_weights", kind: "message", T: PoolWeights }, - { no: 5, name: "days_since_module_genesis", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 6, name: "developer_fees", kind: "message", T: Coin, repeated: true }, - { no: 7, name: "latest_block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 8, name: "developer_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "max_pool_points_per_block", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 10, name: "max_pool_points_per_tx", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 11, name: "point_count_for_block", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 12, name: "profits", kind: "message", T: Coin, repeated: true }, - { no: 13, name: "info_by_pool_type", kind: "message", T: InfoByPoolType }, - { no: 14, name: "cyclic_arb_tracker", kind: "message", T: CyclicArbTracker }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/gov_pb.ts deleted file mode 100644 index 36a645acf..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/gov_pb.ts +++ /dev/null @@ -1,113 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/gov.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * SetProtoRevEnabledProposal is a gov Content type to update whether the - * protorev module is enabled - * - * @generated from message osmosis.protorev.v1beta1.SetProtoRevEnabledProposal - */ -export class SetProtoRevEnabledProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: bool enabled = 3; - */ - enabled = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.SetProtoRevEnabledProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SetProtoRevEnabledProposal { - return new SetProtoRevEnabledProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SetProtoRevEnabledProposal { - return new SetProtoRevEnabledProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SetProtoRevEnabledProposal { - return new SetProtoRevEnabledProposal().fromJsonString(jsonString, options); - } - - static equals(a: SetProtoRevEnabledProposal | PlainMessage | undefined, b: SetProtoRevEnabledProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(SetProtoRevEnabledProposal, a, b); - } -} - -/** - * SetProtoRevAdminAccountProposal is a gov Content type to set the admin - * account that will receive permissions to alter hot routes and set the - * developer address that will be receiving a share of profits from the module - * - * @generated from message osmosis.protorev.v1beta1.SetProtoRevAdminAccountProposal - */ -export class SetProtoRevAdminAccountProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: string account = 3; - */ - account = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.SetProtoRevAdminAccountProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SetProtoRevAdminAccountProposal { - return new SetProtoRevAdminAccountProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SetProtoRevAdminAccountProposal { - return new SetProtoRevAdminAccountProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SetProtoRevAdminAccountProposal { - return new SetProtoRevAdminAccountProposal().fromJsonString(jsonString, options); - } - - static equals(a: SetProtoRevAdminAccountProposal | PlainMessage | undefined, b: SetProtoRevAdminAccountProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(SetProtoRevAdminAccountProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/params_pb.ts deleted file mode 100644 index 7e5995706..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/params_pb.ts +++ /dev/null @@ -1,57 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/params.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params defines the parameters for the module. - * - * @generated from message osmosis.protorev.v1beta1.Params - */ -export class Params extends Message { - /** - * Boolean whether the protorev module is enabled. - * - * @generated from field: bool enabled = 1; - */ - enabled = false; - - /** - * The admin account (settings manager) of the protorev module. - * - * @generated from field: string admin = 2; - */ - admin = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/protorev_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/protorev_pb.ts deleted file mode 100644 index add6efb18..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/protorev_pb.ts +++ /dev/null @@ -1,786 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/protorev.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { TakerFeesTracker } from "../../poolmanager/v1beta1/genesis_pb.js"; -import { TxFeesTracker } from "../../txfees/v1beta1/genesis_pb.js"; - -/** - * TokenPairArbRoutes tracks all of the hot routes for a given pair of tokens - * - * @generated from message osmosis.protorev.v1beta1.TokenPairArbRoutes - */ -export class TokenPairArbRoutes extends Message { - /** - * Stores all of the possible hot paths for a given pair of tokens - * - * @generated from field: repeated osmosis.protorev.v1beta1.Route arb_routes = 1; - */ - arbRoutes: Route[] = []; - - /** - * Token denomination of the first asset - * - * @generated from field: string token_in = 2; - */ - tokenIn = ""; - - /** - * Token denomination of the second asset - * - * @generated from field: string token_out = 3; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.TokenPairArbRoutes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "arb_routes", kind: "message", T: Route, repeated: true }, - { no: 2, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TokenPairArbRoutes { - return new TokenPairArbRoutes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TokenPairArbRoutes { - return new TokenPairArbRoutes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TokenPairArbRoutes { - return new TokenPairArbRoutes().fromJsonString(jsonString, options); - } - - static equals(a: TokenPairArbRoutes | PlainMessage | undefined, b: TokenPairArbRoutes | PlainMessage | undefined): boolean { - return proto3.util.equals(TokenPairArbRoutes, a, b); - } -} - -/** - * Route is a hot route for a given pair of tokens - * - * @generated from message osmosis.protorev.v1beta1.Route - */ -export class Route extends Message { - /** - * The pool IDs that are traversed in the directed cyclic graph (traversed - * left - * -> right) - * - * @generated from field: repeated osmosis.protorev.v1beta1.Trade trades = 1; - */ - trades: Trade[] = []; - - /** - * The step size that will be used to find the optimal swap amount in the - * binary search - * - * @generated from field: string step_size = 2; - */ - stepSize = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.Route"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "trades", kind: "message", T: Trade, repeated: true }, - { no: 2, name: "step_size", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Route { - return new Route().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Route { - return new Route().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Route { - return new Route().fromJsonString(jsonString, options); - } - - static equals(a: Route | PlainMessage | undefined, b: Route | PlainMessage | undefined): boolean { - return proto3.util.equals(Route, a, b); - } -} - -/** - * Trade is a single trade in a route - * - * @generated from message osmosis.protorev.v1beta1.Trade - */ -export class Trade extends Message { - /** - * The pool id of the pool that is traded on - * - * @generated from field: uint64 pool = 1; - */ - pool = protoInt64.zero; - - /** - * The denom of the token that is traded - * - * @generated from field: string token_in = 2; - */ - tokenIn = ""; - - /** - * The denom of the token that is received - * - * @generated from field: string token_out = 3; - */ - tokenOut = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.Trade"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "token_in", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_out", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Trade { - return new Trade().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Trade { - return new Trade().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Trade { - return new Trade().fromJsonString(jsonString, options); - } - - static equals(a: Trade | PlainMessage | undefined, b: Trade | PlainMessage | undefined): boolean { - return proto3.util.equals(Trade, a, b); - } -} - -/** - * RouteStatistics contains the number of trades the module has executed after a - * swap on a given route and the profits from the trades - * - * @generated from message osmosis.protorev.v1beta1.RouteStatistics - */ -export class RouteStatistics extends Message { - /** - * profits is the total profit from all trades on this route - * - * @generated from field: repeated cosmos.base.v1beta1.Coin profits = 1; - */ - profits: Coin[] = []; - - /** - * number_of_trades is the number of trades the module has executed using this - * route - * - * @generated from field: string number_of_trades = 2; - */ - numberOfTrades = ""; - - /** - * route is the route that was used (pool ids along the arbitrage route) - * - * @generated from field: repeated uint64 route = 3; - */ - route: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.RouteStatistics"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "profits", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "number_of_trades", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "route", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RouteStatistics { - return new RouteStatistics().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RouteStatistics { - return new RouteStatistics().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RouteStatistics { - return new RouteStatistics().fromJsonString(jsonString, options); - } - - static equals(a: RouteStatistics | PlainMessage | undefined, b: RouteStatistics | PlainMessage | undefined): boolean { - return proto3.util.equals(RouteStatistics, a, b); - } -} - -/** - * PoolWeights contains the weights of all of the different pool types. This - * distinction is made and necessary because the execution time ranges - * significantly between the different pool types. Each weight roughly - * corresponds to the amount of time (in ms) it takes to execute a swap on that - * pool type. - * - * DEPRECATED: This field is deprecated and will be removed in the next - * release. It is replaced by the `info_by_pool_type` field. - * - * @generated from message osmosis.protorev.v1beta1.PoolWeights - */ -export class PoolWeights extends Message { - /** - * The weight of a stableswap pool - * - * @generated from field: uint64 stable_weight = 1; - */ - stableWeight = protoInt64.zero; - - /** - * The weight of a balancer pool - * - * @generated from field: uint64 balancer_weight = 2; - */ - balancerWeight = protoInt64.zero; - - /** - * The weight of a concentrated pool - * - * @generated from field: uint64 concentrated_weight = 3; - */ - concentratedWeight = protoInt64.zero; - - /** - * The weight of a cosmwasm pool - * - * @generated from field: uint64 cosmwasm_weight = 4; - */ - cosmwasmWeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.PoolWeights"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "stable_weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "balancer_weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "concentrated_weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "cosmwasm_weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PoolWeights { - return new PoolWeights().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PoolWeights { - return new PoolWeights().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PoolWeights { - return new PoolWeights().fromJsonString(jsonString, options); - } - - static equals(a: PoolWeights | PlainMessage | undefined, b: PoolWeights | PlainMessage | undefined): boolean { - return proto3.util.equals(PoolWeights, a, b); - } -} - -/** - * InfoByPoolType contains information pertaining to how expensive (in terms of - * gas and time) it is to execute a swap on a given pool type. This distinction - * is made and necessary because the execution time ranges significantly between - * the different pool types. - * - * @generated from message osmosis.protorev.v1beta1.InfoByPoolType - */ -export class InfoByPoolType extends Message { - /** - * The stable pool info - * - * @generated from field: osmosis.protorev.v1beta1.StablePoolInfo stable = 1; - */ - stable?: StablePoolInfo; - - /** - * The balancer pool info - * - * @generated from field: osmosis.protorev.v1beta1.BalancerPoolInfo balancer = 2; - */ - balancer?: BalancerPoolInfo; - - /** - * The concentrated pool info - * - * @generated from field: osmosis.protorev.v1beta1.ConcentratedPoolInfo concentrated = 3; - */ - concentrated?: ConcentratedPoolInfo; - - /** - * The cosmwasm pool info - * - * @generated from field: osmosis.protorev.v1beta1.CosmwasmPoolInfo cosmwasm = 4; - */ - cosmwasm?: CosmwasmPoolInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.InfoByPoolType"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "stable", kind: "message", T: StablePoolInfo }, - { no: 2, name: "balancer", kind: "message", T: BalancerPoolInfo }, - { no: 3, name: "concentrated", kind: "message", T: ConcentratedPoolInfo }, - { no: 4, name: "cosmwasm", kind: "message", T: CosmwasmPoolInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): InfoByPoolType { - return new InfoByPoolType().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): InfoByPoolType { - return new InfoByPoolType().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): InfoByPoolType { - return new InfoByPoolType().fromJsonString(jsonString, options); - } - - static equals(a: InfoByPoolType | PlainMessage | undefined, b: InfoByPoolType | PlainMessage | undefined): boolean { - return proto3.util.equals(InfoByPoolType, a, b); - } -} - -/** - * StablePoolInfo contains meta data pertaining to a stableswap pool type. - * - * @generated from message osmosis.protorev.v1beta1.StablePoolInfo - */ -export class StablePoolInfo extends Message { - /** - * The weight of a stableswap pool - * - * @generated from field: uint64 weight = 1; - */ - weight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.StablePoolInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): StablePoolInfo { - return new StablePoolInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): StablePoolInfo { - return new StablePoolInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): StablePoolInfo { - return new StablePoolInfo().fromJsonString(jsonString, options); - } - - static equals(a: StablePoolInfo | PlainMessage | undefined, b: StablePoolInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(StablePoolInfo, a, b); - } -} - -/** - * BalancerPoolInfo contains meta data pertaining to a balancer pool type. - * - * @generated from message osmosis.protorev.v1beta1.BalancerPoolInfo - */ -export class BalancerPoolInfo extends Message { - /** - * The weight of a balancer pool - * - * @generated from field: uint64 weight = 1; - */ - weight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.BalancerPoolInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BalancerPoolInfo { - return new BalancerPoolInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BalancerPoolInfo { - return new BalancerPoolInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BalancerPoolInfo { - return new BalancerPoolInfo().fromJsonString(jsonString, options); - } - - static equals(a: BalancerPoolInfo | PlainMessage | undefined, b: BalancerPoolInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(BalancerPoolInfo, a, b); - } -} - -/** - * ConcentratedPoolInfo contains meta data pertaining to a concentrated pool - * type. - * - * @generated from message osmosis.protorev.v1beta1.ConcentratedPoolInfo - */ -export class ConcentratedPoolInfo extends Message { - /** - * The weight of a concentrated pool - * - * @generated from field: uint64 weight = 1; - */ - weight = protoInt64.zero; - - /** - * The maximum number of ticks we can move when rebalancing - * - * @generated from field: uint64 max_ticks_crossed = 2; - */ - maxTicksCrossed = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.ConcentratedPoolInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "max_ticks_crossed", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConcentratedPoolInfo { - return new ConcentratedPoolInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConcentratedPoolInfo { - return new ConcentratedPoolInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConcentratedPoolInfo { - return new ConcentratedPoolInfo().fromJsonString(jsonString, options); - } - - static equals(a: ConcentratedPoolInfo | PlainMessage | undefined, b: ConcentratedPoolInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(ConcentratedPoolInfo, a, b); - } -} - -/** - * CosmwasmPoolInfo contains meta data pertaining to a cosmwasm pool type. - * - * @generated from message osmosis.protorev.v1beta1.CosmwasmPoolInfo - */ -export class CosmwasmPoolInfo extends Message { - /** - * The weight of a cosmwasm pool (by contract address) - * - * @generated from field: repeated osmosis.protorev.v1beta1.WeightMap weight_maps = 1; - */ - weightMaps: WeightMap[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.CosmwasmPoolInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "weight_maps", kind: "message", T: WeightMap, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CosmwasmPoolInfo { - return new CosmwasmPoolInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CosmwasmPoolInfo { - return new CosmwasmPoolInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CosmwasmPoolInfo { - return new CosmwasmPoolInfo().fromJsonString(jsonString, options); - } - - static equals(a: CosmwasmPoolInfo | PlainMessage | undefined, b: CosmwasmPoolInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(CosmwasmPoolInfo, a, b); - } -} - -/** - * WeightMap maps a contract address to a weight. The weight of an address - * corresponds to the amount of ms required to execute a swap on that contract. - * - * @generated from message osmosis.protorev.v1beta1.WeightMap - */ -export class WeightMap extends Message { - /** - * The weight of a cosmwasm pool (by contract address) - * - * @generated from field: uint64 weight = 1; - */ - weight = protoInt64.zero; - - /** - * The contract address - * - * @generated from field: string contract_address = 2; - */ - contractAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.WeightMap"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "weight", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "contract_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): WeightMap { - return new WeightMap().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): WeightMap { - return new WeightMap().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): WeightMap { - return new WeightMap().fromJsonString(jsonString, options); - } - - static equals(a: WeightMap | PlainMessage | undefined, b: WeightMap | PlainMessage | undefined): boolean { - return proto3.util.equals(WeightMap, a, b); - } -} - -/** - * BaseDenom represents a single base denom that the module uses for its - * arbitrage trades. It contains the denom name alongside the step size of the - * binary search that is used to find the optimal swap amount - * - * @generated from message osmosis.protorev.v1beta1.BaseDenom - */ -export class BaseDenom extends Message { - /** - * The denom i.e. name of the base denom (ex. uosmo) - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * The step size of the binary search that is used to find the optimal swap - * amount - * - * @generated from field: string step_size = 2; - */ - stepSize = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.BaseDenom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "step_size", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BaseDenom { - return new BaseDenom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BaseDenom { - return new BaseDenom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BaseDenom { - return new BaseDenom().fromJsonString(jsonString, options); - } - - static equals(a: BaseDenom | PlainMessage | undefined, b: BaseDenom | PlainMessage | undefined): boolean { - return proto3.util.equals(BaseDenom, a, b); - } -} - -/** - * BaseDenoms represents all of the base denoms that the module uses for its - * arbitrage trades. - * - * @generated from message osmosis.protorev.v1beta1.BaseDenoms - */ -export class BaseDenoms extends Message { - /** - * @generated from field: repeated osmosis.protorev.v1beta1.BaseDenom base_denoms = 1; - */ - baseDenoms: BaseDenom[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.BaseDenoms"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_denoms", kind: "message", T: BaseDenom, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): BaseDenoms { - return new BaseDenoms().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): BaseDenoms { - return new BaseDenoms().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): BaseDenoms { - return new BaseDenoms().fromJsonString(jsonString, options); - } - - static equals(a: BaseDenoms | PlainMessage | undefined, b: BaseDenoms | PlainMessage | undefined): boolean { - return proto3.util.equals(BaseDenoms, a, b); - } -} - -/** - * @generated from message osmosis.protorev.v1beta1.AllProtocolRevenue - */ -export class AllProtocolRevenue extends Message { - /** - * @generated from field: osmosis.poolmanager.v1beta1.TakerFeesTracker taker_fees_tracker = 1; - */ - takerFeesTracker?: TakerFeesTracker; - - /** - * DEPRECATED - * - * @generated from field: osmosis.txfees.v1beta1.TxFeesTracker tx_fees_tracker = 2 [deprecated = true]; - * @deprecated - */ - txFeesTracker?: TxFeesTracker; - - /** - * @generated from field: osmosis.protorev.v1beta1.CyclicArbTracker cyclic_arb_tracker = 3; - */ - cyclicArbTracker?: CyclicArbTracker; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.AllProtocolRevenue"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "taker_fees_tracker", kind: "message", T: TakerFeesTracker }, - { no: 2, name: "tx_fees_tracker", kind: "message", T: TxFeesTracker }, - { no: 3, name: "cyclic_arb_tracker", kind: "message", T: CyclicArbTracker }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllProtocolRevenue { - return new AllProtocolRevenue().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllProtocolRevenue { - return new AllProtocolRevenue().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllProtocolRevenue { - return new AllProtocolRevenue().fromJsonString(jsonString, options); - } - - static equals(a: AllProtocolRevenue | PlainMessage | undefined, b: AllProtocolRevenue | PlainMessage | undefined): boolean { - return proto3.util.equals(AllProtocolRevenue, a, b); - } -} - -/** - * @generated from message osmosis.protorev.v1beta1.CyclicArbTracker - */ -export class CyclicArbTracker extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin cyclic_arb = 1; - */ - cyclicArb: Coin[] = []; - - /** - * @generated from field: int64 height_accounting_starts_from = 2; - */ - heightAccountingStartsFrom = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.CyclicArbTracker"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cyclic_arb", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "height_accounting_starts_from", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): CyclicArbTracker { - return new CyclicArbTracker().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): CyclicArbTracker { - return new CyclicArbTracker().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): CyclicArbTracker { - return new CyclicArbTracker().fromJsonString(jsonString, options); - } - - static equals(a: CyclicArbTracker | PlainMessage | undefined, b: CyclicArbTracker | PlainMessage | undefined): boolean { - return proto3.util.equals(CyclicArbTracker, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_cosmes.ts deleted file mode 100644 index 9083458fc..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,212 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/query.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryGetAllProtocolRevenueRequest, QueryGetAllProtocolRevenueResponse, QueryGetProtoRevAdminAccountRequest, QueryGetProtoRevAdminAccountResponse, QueryGetProtoRevAllProfitsRequest, QueryGetProtoRevAllProfitsResponse, QueryGetProtoRevAllRouteStatisticsRequest, QueryGetProtoRevAllRouteStatisticsResponse, QueryGetProtoRevBaseDenomsRequest, QueryGetProtoRevBaseDenomsResponse, QueryGetProtoRevDeveloperAccountRequest, QueryGetProtoRevDeveloperAccountResponse, QueryGetProtoRevEnabledRequest, QueryGetProtoRevEnabledResponse, QueryGetProtoRevInfoByPoolTypeRequest, QueryGetProtoRevInfoByPoolTypeResponse, QueryGetProtoRevMaxPoolPointsPerBlockRequest, QueryGetProtoRevMaxPoolPointsPerBlockResponse, QueryGetProtoRevMaxPoolPointsPerTxRequest, QueryGetProtoRevMaxPoolPointsPerTxResponse, QueryGetProtoRevNumberOfTradesRequest, QueryGetProtoRevNumberOfTradesResponse, QueryGetProtoRevPoolRequest, QueryGetProtoRevPoolResponse, QueryGetProtoRevProfitsByDenomRequest, QueryGetProtoRevProfitsByDenomResponse, QueryGetProtoRevStatisticsByRouteRequest, QueryGetProtoRevStatisticsByRouteResponse, QueryGetProtoRevTokenPairArbRoutesRequest, QueryGetProtoRevTokenPairArbRoutesResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.protorev.v1beta1.Query"; - -/** - * Params queries the parameters of the module. - * - * @generated from rpc osmosis.protorev.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * GetProtoRevNumberOfTrades queries the number of arbitrage trades the module - * has executed - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevNumberOfTrades - */ -export const QueryGetProtoRevNumberOfTradesService = { - typeName: TYPE_NAME, - method: "GetProtoRevNumberOfTrades", - Request: QueryGetProtoRevNumberOfTradesRequest, - Response: QueryGetProtoRevNumberOfTradesResponse, -} as const; - -/** - * GetProtoRevProfitsByDenom queries the profits of the module by denom - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevProfitsByDenom - */ -export const QueryGetProtoRevProfitsByDenomService = { - typeName: TYPE_NAME, - method: "GetProtoRevProfitsByDenom", - Request: QueryGetProtoRevProfitsByDenomRequest, - Response: QueryGetProtoRevProfitsByDenomResponse, -} as const; - -/** - * GetProtoRevAllProfits queries all of the profits from the module - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevAllProfits - */ -export const QueryGetProtoRevAllProfitsService = { - typeName: TYPE_NAME, - method: "GetProtoRevAllProfits", - Request: QueryGetProtoRevAllProfitsRequest, - Response: QueryGetProtoRevAllProfitsResponse, -} as const; - -/** - * GetProtoRevStatisticsByRoute queries the number of arbitrages and profits - * that have been executed for a given route - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevStatisticsByRoute - */ -export const QueryGetProtoRevStatisticsByRouteService = { - typeName: TYPE_NAME, - method: "GetProtoRevStatisticsByRoute", - Request: QueryGetProtoRevStatisticsByRouteRequest, - Response: QueryGetProtoRevStatisticsByRouteResponse, -} as const; - -/** - * GetProtoRevAllRouteStatistics queries all of routes that the module has - * arbitraged against and the number of trades and profits that have been - * accumulated for each route - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevAllRouteStatistics - */ -export const QueryGetProtoRevAllRouteStatisticsService = { - typeName: TYPE_NAME, - method: "GetProtoRevAllRouteStatistics", - Request: QueryGetProtoRevAllRouteStatisticsRequest, - Response: QueryGetProtoRevAllRouteStatisticsResponse, -} as const; - -/** - * GetProtoRevTokenPairArbRoutes queries all of the hot routes that the module - * is currently arbitraging - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevTokenPairArbRoutes - */ -export const QueryGetProtoRevTokenPairArbRoutesService = { - typeName: TYPE_NAME, - method: "GetProtoRevTokenPairArbRoutes", - Request: QueryGetProtoRevTokenPairArbRoutesRequest, - Response: QueryGetProtoRevTokenPairArbRoutesResponse, -} as const; - -/** - * GetProtoRevAdminAccount queries the admin account of the module - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevAdminAccount - */ -export const QueryGetProtoRevAdminAccountService = { - typeName: TYPE_NAME, - method: "GetProtoRevAdminAccount", - Request: QueryGetProtoRevAdminAccountRequest, - Response: QueryGetProtoRevAdminAccountResponse, -} as const; - -/** - * GetProtoRevDeveloperAccount queries the developer account of the module - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevDeveloperAccount - */ -export const QueryGetProtoRevDeveloperAccountService = { - typeName: TYPE_NAME, - method: "GetProtoRevDeveloperAccount", - Request: QueryGetProtoRevDeveloperAccountRequest, - Response: QueryGetProtoRevDeveloperAccountResponse, -} as const; - -/** - * GetProtoRevInfoByPoolType queries pool type information that is currently - * being utilized by the module - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevInfoByPoolType - */ -export const QueryGetProtoRevInfoByPoolTypeService = { - typeName: TYPE_NAME, - method: "GetProtoRevInfoByPoolType", - Request: QueryGetProtoRevInfoByPoolTypeRequest, - Response: QueryGetProtoRevInfoByPoolTypeResponse, -} as const; - -/** - * GetProtoRevMaxPoolPointsPerTx queries the maximum number of pool points - * that can be consumed per transaction - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevMaxPoolPointsPerTx - */ -export const QueryGetProtoRevMaxPoolPointsPerTxService = { - typeName: TYPE_NAME, - method: "GetProtoRevMaxPoolPointsPerTx", - Request: QueryGetProtoRevMaxPoolPointsPerTxRequest, - Response: QueryGetProtoRevMaxPoolPointsPerTxResponse, -} as const; - -/** - * GetProtoRevMaxPoolPointsPerBlock queries the maximum number of pool points - * that can consumed per block - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevMaxPoolPointsPerBlock - */ -export const QueryGetProtoRevMaxPoolPointsPerBlockService = { - typeName: TYPE_NAME, - method: "GetProtoRevMaxPoolPointsPerBlock", - Request: QueryGetProtoRevMaxPoolPointsPerBlockRequest, - Response: QueryGetProtoRevMaxPoolPointsPerBlockResponse, -} as const; - -/** - * GetProtoRevBaseDenoms queries the base denoms that the module is currently - * utilizing for arbitrage - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevBaseDenoms - */ -export const QueryGetProtoRevBaseDenomsService = { - typeName: TYPE_NAME, - method: "GetProtoRevBaseDenoms", - Request: QueryGetProtoRevBaseDenomsRequest, - Response: QueryGetProtoRevBaseDenomsResponse, -} as const; - -/** - * GetProtoRevEnabled queries whether the module is enabled or not - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevEnabled - */ -export const QueryGetProtoRevEnabledService = { - typeName: TYPE_NAME, - method: "GetProtoRevEnabled", - Request: QueryGetProtoRevEnabledRequest, - Response: QueryGetProtoRevEnabledResponse, -} as const; - -/** - * GetProtoRevPool queries the pool id used via the highest liquidity method - * for arbitrage route building given a pair of denominations - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetProtoRevPool - */ -export const QueryGetProtoRevPoolService = { - typeName: TYPE_NAME, - method: "GetProtoRevPool", - Request: QueryGetProtoRevPoolRequest, - Response: QueryGetProtoRevPoolResponse, -} as const; - -/** - * GetAllProtocolRevenue queries all of the protocol revenue that has been - * accumulated by any module - * - * @generated from rpc osmosis.protorev.v1beta1.Query.GetAllProtocolRevenue - */ -export const QueryGetAllProtocolRevenueService = { - typeName: TYPE_NAME, - method: "GetAllProtocolRevenue", - Request: QueryGetAllProtocolRevenueRequest, - Response: QueryGetAllProtocolRevenueResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_pb.ts deleted file mode 100644 index 0c2af40cd..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/query_pb.ts +++ /dev/null @@ -1,1256 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/query.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { AllProtocolRevenue, BaseDenom, InfoByPoolType, RouteStatistics, TokenPairArbRoutes } from "./protorev_pb.js"; - -/** - * QueryParamsRequest is request type for the Query/Params RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is response type for the Query/Params RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params holds all the parameters of this module. - * - * @generated from field: osmosis.protorev.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryGetProtoRevNumberOfTradesRequest is request type for the - * Query/GetProtoRevNumberOfTrades RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevNumberOfTradesRequest - */ -export class QueryGetProtoRevNumberOfTradesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevNumberOfTradesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevNumberOfTradesRequest { - return new QueryGetProtoRevNumberOfTradesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevNumberOfTradesRequest { - return new QueryGetProtoRevNumberOfTradesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevNumberOfTradesRequest { - return new QueryGetProtoRevNumberOfTradesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevNumberOfTradesRequest | PlainMessage | undefined, b: QueryGetProtoRevNumberOfTradesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevNumberOfTradesRequest, a, b); - } -} - -/** - * QueryGetProtoRevNumberOfTradesResponse is response type for the - * Query/GetProtoRevNumberOfTrades RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevNumberOfTradesResponse - */ -export class QueryGetProtoRevNumberOfTradesResponse extends Message { - /** - * number_of_trades is the number of trades the module has executed - * - * @generated from field: string number_of_trades = 1; - */ - numberOfTrades = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevNumberOfTradesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "number_of_trades", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevNumberOfTradesResponse { - return new QueryGetProtoRevNumberOfTradesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevNumberOfTradesResponse { - return new QueryGetProtoRevNumberOfTradesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevNumberOfTradesResponse { - return new QueryGetProtoRevNumberOfTradesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevNumberOfTradesResponse | PlainMessage | undefined, b: QueryGetProtoRevNumberOfTradesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevNumberOfTradesResponse, a, b); - } -} - -/** - * QueryGetProtoRevProfitsByDenomRequest is request type for the - * Query/GetProtoRevProfitsByDenom RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevProfitsByDenomRequest - */ -export class QueryGetProtoRevProfitsByDenomRequest extends Message { - /** - * denom is the denom to query profits by - * - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevProfitsByDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevProfitsByDenomRequest { - return new QueryGetProtoRevProfitsByDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevProfitsByDenomRequest { - return new QueryGetProtoRevProfitsByDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevProfitsByDenomRequest { - return new QueryGetProtoRevProfitsByDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevProfitsByDenomRequest | PlainMessage | undefined, b: QueryGetProtoRevProfitsByDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevProfitsByDenomRequest, a, b); - } -} - -/** - * QueryGetProtoRevProfitsByDenomResponse is response type for the - * Query/GetProtoRevProfitsByDenom RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevProfitsByDenomResponse - */ -export class QueryGetProtoRevProfitsByDenomResponse extends Message { - /** - * profit is the profits of the module by the selected denom - * - * @generated from field: cosmos.base.v1beta1.Coin profit = 1; - */ - profit?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevProfitsByDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "profit", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevProfitsByDenomResponse { - return new QueryGetProtoRevProfitsByDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevProfitsByDenomResponse { - return new QueryGetProtoRevProfitsByDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevProfitsByDenomResponse { - return new QueryGetProtoRevProfitsByDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevProfitsByDenomResponse | PlainMessage | undefined, b: QueryGetProtoRevProfitsByDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevProfitsByDenomResponse, a, b); - } -} - -/** - * QueryGetProtoRevAllProfitsRequest is request type for the - * Query/GetProtoRevAllProfits RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAllProfitsRequest - */ -export class QueryGetProtoRevAllProfitsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAllProfitsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAllProfitsRequest { - return new QueryGetProtoRevAllProfitsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAllProfitsRequest { - return new QueryGetProtoRevAllProfitsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAllProfitsRequest { - return new QueryGetProtoRevAllProfitsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAllProfitsRequest | PlainMessage | undefined, b: QueryGetProtoRevAllProfitsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAllProfitsRequest, a, b); - } -} - -/** - * QueryGetProtoRevAllProfitsResponse is response type for the - * Query/GetProtoRevAllProfits RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAllProfitsResponse - */ -export class QueryGetProtoRevAllProfitsResponse extends Message { - /** - * profits is a list of all of the profits from the module - * - * @generated from field: repeated cosmos.base.v1beta1.Coin profits = 1; - */ - profits: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAllProfitsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "profits", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAllProfitsResponse { - return new QueryGetProtoRevAllProfitsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAllProfitsResponse { - return new QueryGetProtoRevAllProfitsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAllProfitsResponse { - return new QueryGetProtoRevAllProfitsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAllProfitsResponse | PlainMessage | undefined, b: QueryGetProtoRevAllProfitsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAllProfitsResponse, a, b); - } -} - -/** - * QueryGetProtoRevStatisticsByPoolRequest is request type for the - * Query/GetProtoRevStatisticsByRoute RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevStatisticsByRouteRequest - */ -export class QueryGetProtoRevStatisticsByRouteRequest extends Message { - /** - * route is the set of pool ids to query statistics by i.e. 1,2,3 - * - * @generated from field: repeated uint64 route = 1; - */ - route: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevStatisticsByRouteRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "route", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevStatisticsByRouteRequest { - return new QueryGetProtoRevStatisticsByRouteRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevStatisticsByRouteRequest { - return new QueryGetProtoRevStatisticsByRouteRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevStatisticsByRouteRequest { - return new QueryGetProtoRevStatisticsByRouteRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevStatisticsByRouteRequest | PlainMessage | undefined, b: QueryGetProtoRevStatisticsByRouteRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevStatisticsByRouteRequest, a, b); - } -} - -/** - * QueryGetProtoRevStatisticsByRouteResponse is response type for the - * Query/GetProtoRevStatisticsByRoute RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevStatisticsByRouteResponse - */ -export class QueryGetProtoRevStatisticsByRouteResponse extends Message { - /** - * statistics contains the number of trades the module has executed after a - * swap on a given pool and the profits from the trades - * - * @generated from field: osmosis.protorev.v1beta1.RouteStatistics statistics = 1; - */ - statistics?: RouteStatistics; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevStatisticsByRouteResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "statistics", kind: "message", T: RouteStatistics }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevStatisticsByRouteResponse { - return new QueryGetProtoRevStatisticsByRouteResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevStatisticsByRouteResponse { - return new QueryGetProtoRevStatisticsByRouteResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevStatisticsByRouteResponse { - return new QueryGetProtoRevStatisticsByRouteResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevStatisticsByRouteResponse | PlainMessage | undefined, b: QueryGetProtoRevStatisticsByRouteResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevStatisticsByRouteResponse, a, b); - } -} - -/** - * QueryGetProtoRevAllRouteStatisticsRequest is request type for the - * Query/GetProtoRevAllRouteStatistics RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAllRouteStatisticsRequest - */ -export class QueryGetProtoRevAllRouteStatisticsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAllRouteStatisticsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAllRouteStatisticsRequest { - return new QueryGetProtoRevAllRouteStatisticsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAllRouteStatisticsRequest { - return new QueryGetProtoRevAllRouteStatisticsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAllRouteStatisticsRequest { - return new QueryGetProtoRevAllRouteStatisticsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAllRouteStatisticsRequest | PlainMessage | undefined, b: QueryGetProtoRevAllRouteStatisticsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAllRouteStatisticsRequest, a, b); - } -} - -/** - * QueryGetProtoRevAllRouteStatisticsResponse is response type for the - * Query/GetProtoRevAllRouteStatistics RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAllRouteStatisticsResponse - */ -export class QueryGetProtoRevAllRouteStatisticsResponse extends Message { - /** - * statistics contains the number of trades/profits the module has executed on - * all routes it has successfully executed a trade on - * - * @generated from field: repeated osmosis.protorev.v1beta1.RouteStatistics statistics = 1; - */ - statistics: RouteStatistics[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAllRouteStatisticsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "statistics", kind: "message", T: RouteStatistics, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAllRouteStatisticsResponse { - return new QueryGetProtoRevAllRouteStatisticsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAllRouteStatisticsResponse { - return new QueryGetProtoRevAllRouteStatisticsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAllRouteStatisticsResponse { - return new QueryGetProtoRevAllRouteStatisticsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAllRouteStatisticsResponse | PlainMessage | undefined, b: QueryGetProtoRevAllRouteStatisticsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAllRouteStatisticsResponse, a, b); - } -} - -/** - * QueryGetProtoRevTokenPairArbRoutesRequest is request type for the - * Query/GetProtoRevTokenPairArbRoutes RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevTokenPairArbRoutesRequest - */ -export class QueryGetProtoRevTokenPairArbRoutesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevTokenPairArbRoutesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevTokenPairArbRoutesRequest { - return new QueryGetProtoRevTokenPairArbRoutesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevTokenPairArbRoutesRequest { - return new QueryGetProtoRevTokenPairArbRoutesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevTokenPairArbRoutesRequest { - return new QueryGetProtoRevTokenPairArbRoutesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevTokenPairArbRoutesRequest | PlainMessage | undefined, b: QueryGetProtoRevTokenPairArbRoutesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevTokenPairArbRoutesRequest, a, b); - } -} - -/** - * QueryGetProtoRevTokenPairArbRoutesResponse is response type for the - * Query/GetProtoRevTokenPairArbRoutes RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevTokenPairArbRoutesResponse - */ -export class QueryGetProtoRevTokenPairArbRoutesResponse extends Message { - /** - * routes is a list of all of the hot routes that the module is currently - * arbitraging - * - * @generated from field: repeated osmosis.protorev.v1beta1.TokenPairArbRoutes routes = 1; - */ - routes: TokenPairArbRoutes[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevTokenPairArbRoutesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "routes", kind: "message", T: TokenPairArbRoutes, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevTokenPairArbRoutesResponse { - return new QueryGetProtoRevTokenPairArbRoutesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevTokenPairArbRoutesResponse { - return new QueryGetProtoRevTokenPairArbRoutesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevTokenPairArbRoutesResponse { - return new QueryGetProtoRevTokenPairArbRoutesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevTokenPairArbRoutesResponse | PlainMessage | undefined, b: QueryGetProtoRevTokenPairArbRoutesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevTokenPairArbRoutesResponse, a, b); - } -} - -/** - * QueryGetProtoRevAdminAccountRequest is request type for the - * Query/GetProtoRevAdminAccount RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAdminAccountRequest - */ -export class QueryGetProtoRevAdminAccountRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAdminAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAdminAccountRequest { - return new QueryGetProtoRevAdminAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAdminAccountRequest { - return new QueryGetProtoRevAdminAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAdminAccountRequest { - return new QueryGetProtoRevAdminAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAdminAccountRequest | PlainMessage | undefined, b: QueryGetProtoRevAdminAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAdminAccountRequest, a, b); - } -} - -/** - * QueryGetProtoRevAdminAccountResponse is response type for the - * Query/GetProtoRevAdminAccount RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevAdminAccountResponse - */ -export class QueryGetProtoRevAdminAccountResponse extends Message { - /** - * admin_account is the admin account of the module - * - * @generated from field: string admin_account = 1; - */ - adminAccount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevAdminAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin_account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevAdminAccountResponse { - return new QueryGetProtoRevAdminAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevAdminAccountResponse { - return new QueryGetProtoRevAdminAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevAdminAccountResponse { - return new QueryGetProtoRevAdminAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevAdminAccountResponse | PlainMessage | undefined, b: QueryGetProtoRevAdminAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevAdminAccountResponse, a, b); - } -} - -/** - * QueryGetProtoRevDeveloperAccountRequest is request type for the - * Query/GetProtoRevDeveloperAccount RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevDeveloperAccountRequest - */ -export class QueryGetProtoRevDeveloperAccountRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevDeveloperAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevDeveloperAccountRequest { - return new QueryGetProtoRevDeveloperAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevDeveloperAccountRequest { - return new QueryGetProtoRevDeveloperAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevDeveloperAccountRequest { - return new QueryGetProtoRevDeveloperAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevDeveloperAccountRequest | PlainMessage | undefined, b: QueryGetProtoRevDeveloperAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevDeveloperAccountRequest, a, b); - } -} - -/** - * QueryGetProtoRevDeveloperAccountResponse is response type for the - * Query/GetProtoRevDeveloperAccount RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevDeveloperAccountResponse - */ -export class QueryGetProtoRevDeveloperAccountResponse extends Message { - /** - * developer_account is the developer account of the module - * - * @generated from field: string developer_account = 1; - */ - developerAccount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevDeveloperAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "developer_account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevDeveloperAccountResponse { - return new QueryGetProtoRevDeveloperAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevDeveloperAccountResponse { - return new QueryGetProtoRevDeveloperAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevDeveloperAccountResponse { - return new QueryGetProtoRevDeveloperAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevDeveloperAccountResponse | PlainMessage | undefined, b: QueryGetProtoRevDeveloperAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevDeveloperAccountResponse, a, b); - } -} - -/** - * QueryGetProtoRevInfoByPoolTypeRequest is request type for the - * Query/GetProtoRevInfoByPoolType RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevInfoByPoolTypeRequest - */ -export class QueryGetProtoRevInfoByPoolTypeRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevInfoByPoolTypeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevInfoByPoolTypeRequest { - return new QueryGetProtoRevInfoByPoolTypeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevInfoByPoolTypeRequest { - return new QueryGetProtoRevInfoByPoolTypeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevInfoByPoolTypeRequest { - return new QueryGetProtoRevInfoByPoolTypeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevInfoByPoolTypeRequest | PlainMessage | undefined, b: QueryGetProtoRevInfoByPoolTypeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevInfoByPoolTypeRequest, a, b); - } -} - -/** - * QueryGetProtoRevInfoByPoolTypeResponse is response type for the - * Query/GetProtoRevInfoByPoolType RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevInfoByPoolTypeResponse - */ -export class QueryGetProtoRevInfoByPoolTypeResponse extends Message { - /** - * InfoByPoolType contains all information pertaining to how different - * pool types are handled by the module. - * - * @generated from field: osmosis.protorev.v1beta1.InfoByPoolType info_by_pool_type = 1; - */ - infoByPoolType?: InfoByPoolType; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevInfoByPoolTypeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "info_by_pool_type", kind: "message", T: InfoByPoolType }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevInfoByPoolTypeResponse { - return new QueryGetProtoRevInfoByPoolTypeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevInfoByPoolTypeResponse { - return new QueryGetProtoRevInfoByPoolTypeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevInfoByPoolTypeResponse { - return new QueryGetProtoRevInfoByPoolTypeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevInfoByPoolTypeResponse | PlainMessage | undefined, b: QueryGetProtoRevInfoByPoolTypeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevInfoByPoolTypeResponse, a, b); - } -} - -/** - * QueryGetProtoRevMaxPoolPointsPerBlockRequest is request type for the - * Query/GetProtoRevMaxPoolPointsPerBlock RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerBlockRequest - */ -export class QueryGetProtoRevMaxPoolPointsPerBlockRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerBlockRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockRequest { - return new QueryGetProtoRevMaxPoolPointsPerBlockRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockRequest { - return new QueryGetProtoRevMaxPoolPointsPerBlockRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockRequest { - return new QueryGetProtoRevMaxPoolPointsPerBlockRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevMaxPoolPointsPerBlockRequest | PlainMessage | undefined, b: QueryGetProtoRevMaxPoolPointsPerBlockRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevMaxPoolPointsPerBlockRequest, a, b); - } -} - -/** - * QueryGetProtoRevMaxPoolPointsPerBlockResponse is response type for the - * Query/GetProtoRevMaxPoolPointsPerBlock RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerBlockResponse - */ -export class QueryGetProtoRevMaxPoolPointsPerBlockResponse extends Message { - /** - * max_pool_points_per_block is the maximum number of pool points that can be - * consumed per block - * - * @generated from field: uint64 max_pool_points_per_block = 1; - */ - maxPoolPointsPerBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerBlockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_pool_points_per_block", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockResponse { - return new QueryGetProtoRevMaxPoolPointsPerBlockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockResponse { - return new QueryGetProtoRevMaxPoolPointsPerBlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevMaxPoolPointsPerBlockResponse { - return new QueryGetProtoRevMaxPoolPointsPerBlockResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevMaxPoolPointsPerBlockResponse | PlainMessage | undefined, b: QueryGetProtoRevMaxPoolPointsPerBlockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevMaxPoolPointsPerBlockResponse, a, b); - } -} - -/** - * QueryGetProtoRevMaxPoolPointsPerTxRequest is request type for the - * Query/GetProtoRevMaxPoolPointsPerTx RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerTxRequest - */ -export class QueryGetProtoRevMaxPoolPointsPerTxRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerTxRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxRequest { - return new QueryGetProtoRevMaxPoolPointsPerTxRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxRequest { - return new QueryGetProtoRevMaxPoolPointsPerTxRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxRequest { - return new QueryGetProtoRevMaxPoolPointsPerTxRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevMaxPoolPointsPerTxRequest | PlainMessage | undefined, b: QueryGetProtoRevMaxPoolPointsPerTxRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevMaxPoolPointsPerTxRequest, a, b); - } -} - -/** - * QueryGetProtoRevMaxPoolPointsPerTxResponse is response type for the - * Query/GetProtoRevMaxPoolPointsPerTx RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerTxResponse - */ -export class QueryGetProtoRevMaxPoolPointsPerTxResponse extends Message { - /** - * max_pool_points_per_tx is the maximum number of pool points that can be - * consumed per transaction - * - * @generated from field: uint64 max_pool_points_per_tx = 1; - */ - maxPoolPointsPerTx = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevMaxPoolPointsPerTxResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_pool_points_per_tx", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxResponse { - return new QueryGetProtoRevMaxPoolPointsPerTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxResponse { - return new QueryGetProtoRevMaxPoolPointsPerTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevMaxPoolPointsPerTxResponse { - return new QueryGetProtoRevMaxPoolPointsPerTxResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevMaxPoolPointsPerTxResponse | PlainMessage | undefined, b: QueryGetProtoRevMaxPoolPointsPerTxResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevMaxPoolPointsPerTxResponse, a, b); - } -} - -/** - * QueryGetProtoRevBaseDenomsRequest is request type for the - * Query/GetProtoRevBaseDenoms RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevBaseDenomsRequest - */ -export class QueryGetProtoRevBaseDenomsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevBaseDenomsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevBaseDenomsRequest { - return new QueryGetProtoRevBaseDenomsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevBaseDenomsRequest { - return new QueryGetProtoRevBaseDenomsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevBaseDenomsRequest { - return new QueryGetProtoRevBaseDenomsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevBaseDenomsRequest | PlainMessage | undefined, b: QueryGetProtoRevBaseDenomsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevBaseDenomsRequest, a, b); - } -} - -/** - * QueryGetProtoRevBaseDenomsResponse is response type for the - * Query/GetProtoRevBaseDenoms RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevBaseDenomsResponse - */ -export class QueryGetProtoRevBaseDenomsResponse extends Message { - /** - * base_denoms is a list of all of the base denoms and step sizes - * - * @generated from field: repeated osmosis.protorev.v1beta1.BaseDenom base_denoms = 1; - */ - baseDenoms: BaseDenom[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevBaseDenomsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_denoms", kind: "message", T: BaseDenom, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevBaseDenomsResponse { - return new QueryGetProtoRevBaseDenomsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevBaseDenomsResponse { - return new QueryGetProtoRevBaseDenomsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevBaseDenomsResponse { - return new QueryGetProtoRevBaseDenomsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevBaseDenomsResponse | PlainMessage | undefined, b: QueryGetProtoRevBaseDenomsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevBaseDenomsResponse, a, b); - } -} - -/** - * QueryGetProtoRevEnabledRequest is request type for the - * Query/GetProtoRevEnabled RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevEnabledRequest - */ -export class QueryGetProtoRevEnabledRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevEnabledRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevEnabledRequest { - return new QueryGetProtoRevEnabledRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevEnabledRequest { - return new QueryGetProtoRevEnabledRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevEnabledRequest { - return new QueryGetProtoRevEnabledRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevEnabledRequest | PlainMessage | undefined, b: QueryGetProtoRevEnabledRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevEnabledRequest, a, b); - } -} - -/** - * QueryGetProtoRevEnabledResponse is response type for the - * Query/GetProtoRevEnabled RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevEnabledResponse - */ -export class QueryGetProtoRevEnabledResponse extends Message { - /** - * enabled is whether the module is enabled - * - * @generated from field: bool enabled = 1; - */ - enabled = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevEnabledResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "enabled", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevEnabledResponse { - return new QueryGetProtoRevEnabledResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevEnabledResponse { - return new QueryGetProtoRevEnabledResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevEnabledResponse { - return new QueryGetProtoRevEnabledResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevEnabledResponse | PlainMessage | undefined, b: QueryGetProtoRevEnabledResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevEnabledResponse, a, b); - } -} - -/** - * QueryGetProtoRevPoolRequest is request type for the - * Query/GetProtoRevPool RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevPoolRequest - */ -export class QueryGetProtoRevPoolRequest extends Message { - /** - * base_denom is the base denom set in protorev for the denom pair to pool - * mapping - * - * @generated from field: string base_denom = 1; - */ - baseDenom = ""; - - /** - * other_denom is the other denom for the denom pair to pool mapping - * - * @generated from field: string other_denom = 2; - */ - otherDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevPoolRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "other_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevPoolRequest { - return new QueryGetProtoRevPoolRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevPoolRequest { - return new QueryGetProtoRevPoolRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevPoolRequest { - return new QueryGetProtoRevPoolRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevPoolRequest | PlainMessage | undefined, b: QueryGetProtoRevPoolRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevPoolRequest, a, b); - } -} - -/** - * QueryGetProtoRevPoolResponse is response type for the - * Query/GetProtoRevPool RPC method. - * - * @generated from message osmosis.protorev.v1beta1.QueryGetProtoRevPoolResponse - */ -export class QueryGetProtoRevPoolResponse extends Message { - /** - * pool_id is the pool_id stored for the denom pair - * - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetProtoRevPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetProtoRevPoolResponse { - return new QueryGetProtoRevPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetProtoRevPoolResponse { - return new QueryGetProtoRevPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetProtoRevPoolResponse { - return new QueryGetProtoRevPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetProtoRevPoolResponse | PlainMessage | undefined, b: QueryGetProtoRevPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetProtoRevPoolResponse, a, b); - } -} - -/** - * @generated from message osmosis.protorev.v1beta1.QueryGetAllProtocolRevenueRequest - */ -export class QueryGetAllProtocolRevenueRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetAllProtocolRevenueRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetAllProtocolRevenueRequest { - return new QueryGetAllProtocolRevenueRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetAllProtocolRevenueRequest { - return new QueryGetAllProtocolRevenueRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetAllProtocolRevenueRequest { - return new QueryGetAllProtocolRevenueRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetAllProtocolRevenueRequest | PlainMessage | undefined, b: QueryGetAllProtocolRevenueRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetAllProtocolRevenueRequest, a, b); - } -} - -/** - * @generated from message osmosis.protorev.v1beta1.QueryGetAllProtocolRevenueResponse - */ -export class QueryGetAllProtocolRevenueResponse extends Message { - /** - * @generated from field: osmosis.protorev.v1beta1.AllProtocolRevenue all_protocol_revenue = 1; - */ - allProtocolRevenue?: AllProtocolRevenue; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.QueryGetAllProtocolRevenueResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "all_protocol_revenue", kind: "message", T: AllProtocolRevenue }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryGetAllProtocolRevenueResponse { - return new QueryGetAllProtocolRevenueResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryGetAllProtocolRevenueResponse { - return new QueryGetAllProtocolRevenueResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryGetAllProtocolRevenueResponse { - return new QueryGetAllProtocolRevenueResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryGetAllProtocolRevenueResponse | PlainMessage | undefined, b: QueryGetAllProtocolRevenueResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryGetAllProtocolRevenueResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_cosmes.ts deleted file mode 100644 index ed074757d..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,87 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/tx.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgSetBaseDenoms, MsgSetBaseDenomsResponse, MsgSetDeveloperAccount, MsgSetDeveloperAccountResponse, MsgSetHotRoutes, MsgSetHotRoutesResponse, MsgSetInfoByPoolType, MsgSetInfoByPoolTypeResponse, MsgSetMaxPoolPointsPerBlock, MsgSetMaxPoolPointsPerBlockResponse, MsgSetMaxPoolPointsPerTx, MsgSetMaxPoolPointsPerTxResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.protorev.v1beta1.Msg"; - -/** - * SetHotRoutes sets the hot routes that will be explored when creating - * cyclic arbitrage routes. Can only be called by the admin account. - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetHotRoutes - */ -export const MsgSetHotRoutesService = { - typeName: TYPE_NAME, - method: "SetHotRoutes", - Request: MsgSetHotRoutes, - Response: MsgSetHotRoutesResponse, -} as const; - -/** - * SetDeveloperAccount sets the account that can withdraw a portion of the - * profits from the protorev module. This will be Skip's address. - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetDeveloperAccount - */ -export const MsgSetDeveloperAccountService = { - typeName: TYPE_NAME, - method: "SetDeveloperAccount", - Request: MsgSetDeveloperAccount, - Response: MsgSetDeveloperAccountResponse, -} as const; - -/** - * SetMaxPoolPointsPerTx sets the maximum number of pool points that can be - * consumed per transaction. Can only be called by the admin account. - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetMaxPoolPointsPerTx - */ -export const MsgSetMaxPoolPointsPerTxService = { - typeName: TYPE_NAME, - method: "SetMaxPoolPointsPerTx", - Request: MsgSetMaxPoolPointsPerTx, - Response: MsgSetMaxPoolPointsPerTxResponse, -} as const; - -/** - * SetMaxPoolPointsPerBlock sets the maximum number of pool points that can be - * consumed per block. Can only be called by the admin account. - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetMaxPoolPointsPerBlock - */ -export const MsgSetMaxPoolPointsPerBlockService = { - typeName: TYPE_NAME, - method: "SetMaxPoolPointsPerBlock", - Request: MsgSetMaxPoolPointsPerBlock, - Response: MsgSetMaxPoolPointsPerBlockResponse, -} as const; - -/** - * SetInfoByPoolType sets the pool type information needed to make smart - * assumptions about swapping on different pool types - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetInfoByPoolType - */ -export const MsgSetInfoByPoolTypeService = { - typeName: TYPE_NAME, - method: "SetInfoByPoolType", - Request: MsgSetInfoByPoolType, - Response: MsgSetInfoByPoolTypeResponse, -} as const; - -/** - * SetBaseDenoms sets the base denoms that will be used to create cyclic - * arbitrage routes. Can only be called by the admin account. - * - * @generated from rpc osmosis.protorev.v1beta1.Msg.SetBaseDenoms - */ -export const MsgSetBaseDenomsService = { - typeName: TYPE_NAME, - method: "SetBaseDenoms", - Request: MsgSetBaseDenoms, - Response: MsgSetBaseDenomsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_pb.ts deleted file mode 100644 index 47e8c6fbd..000000000 --- a/packages/es/src/protobufs/osmosis/protorev/v1beta1/tx_pb.ts +++ /dev/null @@ -1,559 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/protorev/v1beta1/tx.proto (package osmosis.protorev.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { BaseDenom, InfoByPoolType, PoolWeights, TokenPairArbRoutes } from "./protorev_pb.js"; - -/** - * MsgSetHotRoutes defines the Msg/SetHotRoutes request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetHotRoutes - */ -export class MsgSetHotRoutes extends Message { - /** - * admin is the account that is authorized to set the hot routes. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * hot_routes is the list of hot routes to set. - * - * @generated from field: repeated osmosis.protorev.v1beta1.TokenPairArbRoutes hot_routes = 2; - */ - hotRoutes: TokenPairArbRoutes[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetHotRoutes"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "hot_routes", kind: "message", T: TokenPairArbRoutes, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetHotRoutes { - return new MsgSetHotRoutes().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetHotRoutes { - return new MsgSetHotRoutes().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetHotRoutes { - return new MsgSetHotRoutes().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetHotRoutes | PlainMessage | undefined, b: MsgSetHotRoutes | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetHotRoutes, a, b); - } -} - -/** - * MsgSetHotRoutesResponse defines the Msg/SetHotRoutes response type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetHotRoutesResponse - */ -export class MsgSetHotRoutesResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetHotRoutesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetHotRoutesResponse { - return new MsgSetHotRoutesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetHotRoutesResponse { - return new MsgSetHotRoutesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetHotRoutesResponse { - return new MsgSetHotRoutesResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetHotRoutesResponse | PlainMessage | undefined, b: MsgSetHotRoutesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetHotRoutesResponse, a, b); - } -} - -/** - * MsgSetDeveloperAccount defines the Msg/SetDeveloperAccount request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetDeveloperAccount - */ -export class MsgSetDeveloperAccount extends Message { - /** - * admin is the account that is authorized to set the developer account. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * developer_account is the account that will receive a portion of the profits - * from the protorev module. - * - * @generated from field: string developer_account = 2; - */ - developerAccount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetDeveloperAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "developer_account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDeveloperAccount { - return new MsgSetDeveloperAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDeveloperAccount { - return new MsgSetDeveloperAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDeveloperAccount { - return new MsgSetDeveloperAccount().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDeveloperAccount | PlainMessage | undefined, b: MsgSetDeveloperAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDeveloperAccount, a, b); - } -} - -/** - * MsgSetDeveloperAccountResponse defines the Msg/SetDeveloperAccount response - * type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetDeveloperAccountResponse - */ -export class MsgSetDeveloperAccountResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetDeveloperAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDeveloperAccountResponse { - return new MsgSetDeveloperAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDeveloperAccountResponse { - return new MsgSetDeveloperAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDeveloperAccountResponse { - return new MsgSetDeveloperAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDeveloperAccountResponse | PlainMessage | undefined, b: MsgSetDeveloperAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDeveloperAccountResponse, a, b); - } -} - -/** - * MsgSetInfoByPoolType defines the Msg/SetInfoByPoolType request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetInfoByPoolType - */ -export class MsgSetInfoByPoolType extends Message { - /** - * admin is the account that is authorized to set the pool weights. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * info_by_pool_type contains information about the pool types. - * - * @generated from field: osmosis.protorev.v1beta1.InfoByPoolType info_by_pool_type = 2; - */ - infoByPoolType?: InfoByPoolType; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetInfoByPoolType"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "info_by_pool_type", kind: "message", T: InfoByPoolType }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetInfoByPoolType { - return new MsgSetInfoByPoolType().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetInfoByPoolType { - return new MsgSetInfoByPoolType().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetInfoByPoolType { - return new MsgSetInfoByPoolType().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetInfoByPoolType | PlainMessage | undefined, b: MsgSetInfoByPoolType | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetInfoByPoolType, a, b); - } -} - -/** - * MsgSetInfoByPoolTypeResponse defines the Msg/SetInfoByPoolType response type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetInfoByPoolTypeResponse - */ -export class MsgSetInfoByPoolTypeResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetInfoByPoolTypeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetInfoByPoolTypeResponse { - return new MsgSetInfoByPoolTypeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetInfoByPoolTypeResponse { - return new MsgSetInfoByPoolTypeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetInfoByPoolTypeResponse { - return new MsgSetInfoByPoolTypeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetInfoByPoolTypeResponse | PlainMessage | undefined, b: MsgSetInfoByPoolTypeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetInfoByPoolTypeResponse, a, b); - } -} - -/** - * MsgSetMaxPoolPointsPerTx defines the Msg/SetMaxPoolPointsPerTx request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerTx - */ -export class MsgSetMaxPoolPointsPerTx extends Message { - /** - * admin is the account that is authorized to set the max pool points per tx. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * max_pool_points_per_tx is the maximum number of pool points that can be - * consumed per transaction. - * - * @generated from field: uint64 max_pool_points_per_tx = 2; - */ - maxPoolPointsPerTx = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerTx"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "max_pool_points_per_tx", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetMaxPoolPointsPerTx { - return new MsgSetMaxPoolPointsPerTx().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetMaxPoolPointsPerTx { - return new MsgSetMaxPoolPointsPerTx().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetMaxPoolPointsPerTx { - return new MsgSetMaxPoolPointsPerTx().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetMaxPoolPointsPerTx | PlainMessage | undefined, b: MsgSetMaxPoolPointsPerTx | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetMaxPoolPointsPerTx, a, b); - } -} - -/** - * MsgSetMaxPoolPointsPerTxResponse defines the Msg/SetMaxPoolPointsPerTx - * response type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerTxResponse - */ -export class MsgSetMaxPoolPointsPerTxResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerTxResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetMaxPoolPointsPerTxResponse { - return new MsgSetMaxPoolPointsPerTxResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetMaxPoolPointsPerTxResponse { - return new MsgSetMaxPoolPointsPerTxResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetMaxPoolPointsPerTxResponse { - return new MsgSetMaxPoolPointsPerTxResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetMaxPoolPointsPerTxResponse | PlainMessage | undefined, b: MsgSetMaxPoolPointsPerTxResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetMaxPoolPointsPerTxResponse, a, b); - } -} - -/** - * MsgSetMaxPoolPointsPerBlock defines the Msg/SetMaxPoolPointsPerBlock request - * type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerBlock - */ -export class MsgSetMaxPoolPointsPerBlock extends Message { - /** - * admin is the account that is authorized to set the max pool points per - * block. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * max_pool_points_per_block is the maximum number of pool points that can be - * consumed per block. - * - * @generated from field: uint64 max_pool_points_per_block = 2; - */ - maxPoolPointsPerBlock = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerBlock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "max_pool_points_per_block", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetMaxPoolPointsPerBlock { - return new MsgSetMaxPoolPointsPerBlock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetMaxPoolPointsPerBlock { - return new MsgSetMaxPoolPointsPerBlock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetMaxPoolPointsPerBlock { - return new MsgSetMaxPoolPointsPerBlock().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetMaxPoolPointsPerBlock | PlainMessage | undefined, b: MsgSetMaxPoolPointsPerBlock | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetMaxPoolPointsPerBlock, a, b); - } -} - -/** - * MsgSetMaxPoolPointsPerBlockResponse defines the - * Msg/SetMaxPoolPointsPerBlock response type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerBlockResponse - */ -export class MsgSetMaxPoolPointsPerBlockResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetMaxPoolPointsPerBlockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetMaxPoolPointsPerBlockResponse { - return new MsgSetMaxPoolPointsPerBlockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetMaxPoolPointsPerBlockResponse { - return new MsgSetMaxPoolPointsPerBlockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetMaxPoolPointsPerBlockResponse { - return new MsgSetMaxPoolPointsPerBlockResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetMaxPoolPointsPerBlockResponse | PlainMessage | undefined, b: MsgSetMaxPoolPointsPerBlockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetMaxPoolPointsPerBlockResponse, a, b); - } -} - -/** - * MsgSetBaseDenoms defines the Msg/SetBaseDenoms request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetBaseDenoms - */ -export class MsgSetBaseDenoms extends Message { - /** - * admin is the account that is authorized to set the base denoms. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * base_denoms is the list of base denoms to set. - * - * @generated from field: repeated osmosis.protorev.v1beta1.BaseDenom base_denoms = 2; - */ - baseDenoms: BaseDenom[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetBaseDenoms"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "base_denoms", kind: "message", T: BaseDenom, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetBaseDenoms { - return new MsgSetBaseDenoms().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetBaseDenoms { - return new MsgSetBaseDenoms().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetBaseDenoms { - return new MsgSetBaseDenoms().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetBaseDenoms | PlainMessage | undefined, b: MsgSetBaseDenoms | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetBaseDenoms, a, b); - } -} - -/** - * Deprecated, but must be retained in the file to allow indexers - * to index blocks since genesis - * - * @generated from message osmosis.protorev.v1beta1.MsgSetBaseDenomsResponse - */ -export class MsgSetBaseDenomsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetBaseDenomsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetBaseDenomsResponse { - return new MsgSetBaseDenomsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetBaseDenomsResponse { - return new MsgSetBaseDenomsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetBaseDenomsResponse { - return new MsgSetBaseDenomsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetBaseDenomsResponse | PlainMessage | undefined, b: MsgSetBaseDenomsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetBaseDenomsResponse, a, b); - } -} - -/** - * MsgSetPoolWeights defines the Msg/SetPoolWeights request type. - * - * @generated from message osmosis.protorev.v1beta1.MsgSetPoolWeights - */ -export class MsgSetPoolWeights extends Message { - /** - * admin is the account that is authorized to set the pool weights. - * - * @generated from field: string admin = 1; - */ - admin = ""; - - /** - * pool_weights is the list of pool weights to set. - * - * @generated from field: osmosis.protorev.v1beta1.PoolWeights pool_weights = 2; - */ - poolWeights?: PoolWeights; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.protorev.v1beta1.MsgSetPoolWeights"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_weights", kind: "message", T: PoolWeights }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetPoolWeights { - return new MsgSetPoolWeights().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetPoolWeights { - return new MsgSetPoolWeights().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetPoolWeights { - return new MsgSetPoolWeights().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetPoolWeights | PlainMessage | undefined, b: MsgSetPoolWeights | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetPoolWeights, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/genesis_pb.ts deleted file mode 100644 index 80eb3568f..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,120 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/genesis.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { AccountAuthenticator } from "./models_pb.js"; -import { Params } from "./params_pb.js"; - -/** - * AuthenticatorData represents a genesis exported account with Authenticators. - * The address is used as the key, and the account authenticators are stored in - * the authenticators field. - * - * @generated from message osmosis.smartaccount.v1beta1.AuthenticatorData - */ -export class AuthenticatorData extends Message { - /** - * address is an account address, one address can have many authenticators - * - * @generated from field: string address = 1; - */ - address = ""; - - /** - * authenticators are the account's authenticators, these can be multiple - * types including SignatureVerification, AllOfs, CosmWasmAuthenticators, etc - * - * @generated from field: repeated osmosis.smartaccount.v1beta1.AccountAuthenticator authenticators = 2; - */ - authenticators: AccountAuthenticator[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.AuthenticatorData"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "authenticators", kind: "message", T: AccountAuthenticator, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AuthenticatorData { - return new AuthenticatorData().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AuthenticatorData { - return new AuthenticatorData().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AuthenticatorData { - return new AuthenticatorData().fromJsonString(jsonString, options); - } - - static equals(a: AuthenticatorData | PlainMessage | undefined, b: AuthenticatorData | PlainMessage | undefined): boolean { - return proto3.util.equals(AuthenticatorData, a, b); - } -} - -/** - * GenesisState defines the authenticator module's genesis state. - * - * @generated from message osmosis.smartaccount.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params define the parameters for the authenticator module. - * - * @generated from field: osmosis.smartaccount.v1beta1.Params params = 1; - */ - params?: Params; - - /** - * next_authenticator_id is the next available authenticator ID. - * - * @generated from field: uint64 next_authenticator_id = 2; - */ - nextAuthenticatorId = protoInt64.zero; - - /** - * authenticator_data contains the data for multiple accounts, each with their - * authenticators. - * - * @generated from field: repeated osmosis.smartaccount.v1beta1.AuthenticatorData authenticator_data = 3; - */ - authenticatorData: AuthenticatorData[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "next_authenticator_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "authenticator_data", kind: "message", T: AuthenticatorData, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/models_pb.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/models_pb.ts deleted file mode 100644 index 5c2aecc38..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/models_pb.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/models.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * AccountAuthenticator represents a foundational model for all authenticators. - * It provides extensibility by allowing concrete types to interpret and - * validate transactions based on the encapsulated data. - * - * @generated from message osmosis.smartaccount.v1beta1.AccountAuthenticator - */ -export class AccountAuthenticator extends Message { - /** - * ID uniquely identifies the authenticator instance. - * - * @generated from field: uint64 id = 1; - */ - id = protoInt64.zero; - - /** - * Type specifies the category of the AccountAuthenticator. - * This type information is essential for differentiating authenticators - * and ensuring precise data retrieval from the storage layer. - * - * @generated from field: string type = 2; - */ - type = ""; - - /** - * Config is a versatile field used in conjunction with the specific type of - * account authenticator to facilitate complex authentication processes. - * The interpretation of this field is overloaded, enabling multiple - * authenticators to utilize it for their respective purposes. - * - * @generated from field: bytes config = 3; - */ - config = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.AccountAuthenticator"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "config", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AccountAuthenticator { - return new AccountAuthenticator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AccountAuthenticator { - return new AccountAuthenticator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AccountAuthenticator { - return new AccountAuthenticator().fromJsonString(jsonString, options); - } - - static equals(a: AccountAuthenticator | PlainMessage | undefined, b: AccountAuthenticator | PlainMessage | undefined): boolean { - return proto3.util.equals(AccountAuthenticator, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/params_pb.ts deleted file mode 100644 index 127b96991..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/params_pb.ts +++ /dev/null @@ -1,70 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/params.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * Params defines the parameters for the module. - * - * @generated from message osmosis.smartaccount.v1beta1.Params - */ -export class Params extends Message { - /** - * MaximumUnauthenticatedGas defines the maximum amount of gas that can be - * used to authenticate a transaction in ante handler without having fee payer - * authenticated. - * - * @generated from field: uint64 maximum_unauthenticated_gas = 1; - */ - maximumUnauthenticatedGas = protoInt64.zero; - - /** - * IsSmartAccountActive defines the state of the authenticator. - * If set to false, the authenticator module will not be used - * and the classic cosmos sdk authentication will be used instead. - * - * @generated from field: bool is_smart_account_active = 2; - */ - isSmartAccountActive = false; - - /** - * CircuitBreakerControllers defines list of addresses that are allowed to - * set is_smart_account_active without going through governance. - * - * @generated from field: repeated string circuit_breaker_controllers = 3; - */ - circuitBreakerControllers: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "maximum_unauthenticated_gas", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "is_smart_account_active", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 3, name: "circuit_breaker_controllers", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_cosmes.ts deleted file mode 100644 index 9df34f97f..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,41 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/query.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { GetAuthenticatorRequest, GetAuthenticatorResponse, GetAuthenticatorsRequest, GetAuthenticatorsResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.smartaccount.v1beta1.Query"; - -/** - * Parameters queries the parameters of the module. - * - * @generated from rpc osmosis.smartaccount.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * @generated from rpc osmosis.smartaccount.v1beta1.Query.GetAuthenticator - */ -export const QueryGetAuthenticatorService = { - typeName: TYPE_NAME, - method: "GetAuthenticator", - Request: GetAuthenticatorRequest, - Response: GetAuthenticatorResponse, -} as const; - -/** - * @generated from rpc osmosis.smartaccount.v1beta1.Query.GetAuthenticators - */ -export const QueryGetAuthenticatorsService = { - typeName: TYPE_NAME, - method: "GetAuthenticators", - Request: GetAuthenticatorsRequest, - Response: GetAuthenticatorsResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_pb.ts deleted file mode 100644 index 32733a4af..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/query_pb.ts +++ /dev/null @@ -1,246 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/query.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { AccountAuthenticator } from "./models_pb.js"; - -/** - * QueryParamsRequest is request type for the Query/Params RPC method. - * - * @generated from message osmosis.smartaccount.v1beta1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is response type for the Query/Params RPC method. - * - * @generated from message osmosis.smartaccount.v1beta1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params holds all the parameters of this module. - * - * @generated from field: osmosis.smartaccount.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * MsgGetAuthenticatorsRequest defines the Msg/GetAuthenticators request type. - * - * @generated from message osmosis.smartaccount.v1beta1.GetAuthenticatorsRequest - */ -export class GetAuthenticatorsRequest extends Message { - /** - * @generated from field: string account = 1; - */ - account = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.GetAuthenticatorsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetAuthenticatorsRequest { - return new GetAuthenticatorsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetAuthenticatorsRequest { - return new GetAuthenticatorsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetAuthenticatorsRequest { - return new GetAuthenticatorsRequest().fromJsonString(jsonString, options); - } - - static equals(a: GetAuthenticatorsRequest | PlainMessage | undefined, b: GetAuthenticatorsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GetAuthenticatorsRequest, a, b); - } -} - -/** - * MsgGetAuthenticatorsResponse defines the Msg/GetAuthenticators response type. - * - * @generated from message osmosis.smartaccount.v1beta1.GetAuthenticatorsResponse - */ -export class GetAuthenticatorsResponse extends Message { - /** - * @generated from field: repeated osmosis.smartaccount.v1beta1.AccountAuthenticator account_authenticators = 1; - */ - accountAuthenticators: AccountAuthenticator[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.GetAuthenticatorsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account_authenticators", kind: "message", T: AccountAuthenticator, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetAuthenticatorsResponse { - return new GetAuthenticatorsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetAuthenticatorsResponse { - return new GetAuthenticatorsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetAuthenticatorsResponse { - return new GetAuthenticatorsResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetAuthenticatorsResponse | PlainMessage | undefined, b: GetAuthenticatorsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetAuthenticatorsResponse, a, b); - } -} - -/** - * MsgGetAuthenticatorRequest defines the Msg/GetAuthenticator request type. - * - * @generated from message osmosis.smartaccount.v1beta1.GetAuthenticatorRequest - */ -export class GetAuthenticatorRequest extends Message { - /** - * @generated from field: string account = 1; - */ - account = ""; - - /** - * @generated from field: uint64 authenticator_id = 2; - */ - authenticatorId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.GetAuthenticatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "authenticator_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetAuthenticatorRequest { - return new GetAuthenticatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetAuthenticatorRequest { - return new GetAuthenticatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetAuthenticatorRequest { - return new GetAuthenticatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: GetAuthenticatorRequest | PlainMessage | undefined, b: GetAuthenticatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GetAuthenticatorRequest, a, b); - } -} - -/** - * MsgGetAuthenticatorResponse defines the Msg/GetAuthenticator response type. - * - * @generated from message osmosis.smartaccount.v1beta1.GetAuthenticatorResponse - */ -export class GetAuthenticatorResponse extends Message { - /** - * @generated from field: osmosis.smartaccount.v1beta1.AccountAuthenticator account_authenticator = 1; - */ - accountAuthenticator?: AccountAuthenticator; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.GetAuthenticatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account_authenticator", kind: "message", T: AccountAuthenticator }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GetAuthenticatorResponse { - return new GetAuthenticatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GetAuthenticatorResponse { - return new GetAuthenticatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GetAuthenticatorResponse { - return new GetAuthenticatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: GetAuthenticatorResponse | PlainMessage | undefined, b: GetAuthenticatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GetAuthenticatorResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_cosmes.ts deleted file mode 100644 index 75dca7562..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/tx.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddAuthenticator, MsgAddAuthenticatorResponse, MsgRemoveAuthenticator, MsgRemoveAuthenticatorResponse, MsgSetActiveState, MsgSetActiveStateResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.smartaccount.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.smartaccount.v1beta1.Msg.AddAuthenticator - */ -export const MsgAddAuthenticatorService = { - typeName: TYPE_NAME, - method: "AddAuthenticator", - Request: MsgAddAuthenticator, - Response: MsgAddAuthenticatorResponse, -} as const; - -/** - * @generated from rpc osmosis.smartaccount.v1beta1.Msg.RemoveAuthenticator - */ -export const MsgRemoveAuthenticatorService = { - typeName: TYPE_NAME, - method: "RemoveAuthenticator", - Request: MsgRemoveAuthenticator, - Response: MsgRemoveAuthenticatorResponse, -} as const; - -/** - * SetActiveState sets the active state of the authenticator. - * Primarily used for circuit breaking. - * - * @generated from rpc osmosis.smartaccount.v1beta1.Msg.SetActiveState - */ -export const MsgSetActiveStateService = { - typeName: TYPE_NAME, - method: "SetActiveState", - Request: MsgSetActiveState, - Response: MsgSetActiveStateResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_pb.ts deleted file mode 100644 index 281fdffa9..000000000 --- a/packages/es/src/protobufs/osmosis/smartaccount/v1beta1/tx_pb.ts +++ /dev/null @@ -1,301 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/smartaccount/v1beta1/tx.proto (package osmosis.smartaccount.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * MsgAddAuthenticatorRequest defines the Msg/AddAuthenticator request type. - * - * @generated from message osmosis.smartaccount.v1beta1.MsgAddAuthenticator - */ -export class MsgAddAuthenticator extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: string authenticator_type = 2; - */ - authenticatorType = ""; - - /** - * @generated from field: bytes data = 3; - */ - data = new Uint8Array(0); - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgAddAuthenticator"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "authenticator_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "data", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddAuthenticator { - return new MsgAddAuthenticator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddAuthenticator { - return new MsgAddAuthenticator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddAuthenticator { - return new MsgAddAuthenticator().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddAuthenticator | PlainMessage | undefined, b: MsgAddAuthenticator | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddAuthenticator, a, b); - } -} - -/** - * MsgAddAuthenticatorResponse defines the Msg/AddAuthenticator response type. - * - * @generated from message osmosis.smartaccount.v1beta1.MsgAddAuthenticatorResponse - */ -export class MsgAddAuthenticatorResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgAddAuthenticatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddAuthenticatorResponse { - return new MsgAddAuthenticatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddAuthenticatorResponse { - return new MsgAddAuthenticatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddAuthenticatorResponse { - return new MsgAddAuthenticatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddAuthenticatorResponse | PlainMessage | undefined, b: MsgAddAuthenticatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddAuthenticatorResponse, a, b); - } -} - -/** - * MsgRemoveAuthenticatorRequest defines the Msg/RemoveAuthenticator request - * type. - * - * @generated from message osmosis.smartaccount.v1beta1.MsgRemoveAuthenticator - */ -export class MsgRemoveAuthenticator extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 id = 2; - */ - id = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgRemoveAuthenticator"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveAuthenticator { - return new MsgRemoveAuthenticator().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveAuthenticator { - return new MsgRemoveAuthenticator().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveAuthenticator { - return new MsgRemoveAuthenticator().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveAuthenticator | PlainMessage | undefined, b: MsgRemoveAuthenticator | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveAuthenticator, a, b); - } -} - -/** - * MsgRemoveAuthenticatorResponse defines the Msg/RemoveAuthenticator response - * type. - * - * @generated from message osmosis.smartaccount.v1beta1.MsgRemoveAuthenticatorResponse - */ -export class MsgRemoveAuthenticatorResponse extends Message { - /** - * @generated from field: bool success = 1; - */ - success = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgRemoveAuthenticatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "success", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRemoveAuthenticatorResponse { - return new MsgRemoveAuthenticatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRemoveAuthenticatorResponse { - return new MsgRemoveAuthenticatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRemoveAuthenticatorResponse { - return new MsgRemoveAuthenticatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRemoveAuthenticatorResponse | PlainMessage | undefined, b: MsgRemoveAuthenticatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRemoveAuthenticatorResponse, a, b); - } -} - -/** - * @generated from message osmosis.smartaccount.v1beta1.MsgSetActiveState - */ -export class MsgSetActiveState extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: bool active = 2; - */ - active = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgSetActiveState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "active", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetActiveState { - return new MsgSetActiveState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetActiveState { - return new MsgSetActiveState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetActiveState { - return new MsgSetActiveState().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetActiveState | PlainMessage | undefined, b: MsgSetActiveState | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetActiveState, a, b); - } -} - -/** - * @generated from message osmosis.smartaccount.v1beta1.MsgSetActiveStateResponse - */ -export class MsgSetActiveStateResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.MsgSetActiveStateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetActiveStateResponse { - return new MsgSetActiveStateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetActiveStateResponse { - return new MsgSetActiveStateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetActiveStateResponse { - return new MsgSetActiveStateResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetActiveStateResponse | PlainMessage | undefined, b: MsgSetActiveStateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetActiveStateResponse, a, b); - } -} - -/** - * TxExtension allows for additional authenticator-specific data in - * transactions. - * - * @generated from message osmosis.smartaccount.v1beta1.TxExtension - */ -export class TxExtension extends Message { - /** - * selected_authenticators holds the authenticator_id for the chosen - * authenticator per message. - * - * @generated from field: repeated uint64 selected_authenticators = 1; - */ - selectedAuthenticators: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.smartaccount.v1beta1.TxExtension"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "selected_authenticators", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxExtension { - return new TxExtension().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxExtension { - return new TxExtension().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxExtension { - return new TxExtension().fromJsonString(jsonString, options); - } - - static equals(a: TxExtension | PlainMessage | undefined, b: TxExtension | PlainMessage | undefined): boolean { - return proto3.util.equals(TxExtension, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/store/v1beta1/tree_pb.ts b/packages/es/src/protobufs/osmosis/store/v1beta1/tree_pb.ts deleted file mode 100644 index aeb9bba98..000000000 --- a/packages/es/src/protobufs/osmosis/store/v1beta1/tree_pb.ts +++ /dev/null @@ -1,125 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/store/v1beta1/tree.proto (package osmosis.store.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * @generated from message osmosis.store.v1beta1.Node - */ -export class Node extends Message { - /** - * @generated from field: repeated osmosis.store.v1beta1.Child children = 1; - */ - children: Child[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.store.v1beta1.Node"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "children", kind: "message", T: Child, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Node { - return new Node().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Node { - return new Node().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Node { - return new Node().fromJsonString(jsonString, options); - } - - static equals(a: Node | PlainMessage | undefined, b: Node | PlainMessage | undefined): boolean { - return proto3.util.equals(Node, a, b); - } -} - -/** - * @generated from message osmosis.store.v1beta1.Child - */ -export class Child extends Message { - /** - * @generated from field: bytes index = 1; - */ - index = new Uint8Array(0); - - /** - * @generated from field: string accumulation = 2; - */ - accumulation = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.store.v1beta1.Child"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "index", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 2, name: "accumulation", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Child { - return new Child().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Child { - return new Child().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Child { - return new Child().fromJsonString(jsonString, options); - } - - static equals(a: Child | PlainMessage | undefined, b: Child | PlainMessage | undefined): boolean { - return proto3.util.equals(Child, a, b); - } -} - -/** - * @generated from message osmosis.store.v1beta1.Leaf - */ -export class Leaf extends Message { - /** - * @generated from field: osmosis.store.v1beta1.Child leaf = 1; - */ - leaf?: Child; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.store.v1beta1.Leaf"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "leaf", kind: "message", T: Child }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Leaf { - return new Leaf().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Leaf { - return new Leaf().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Leaf { - return new Leaf().fromJsonString(jsonString, options); - } - - static equals(a: Leaf | PlainMessage | undefined, b: Leaf | PlainMessage | undefined): boolean { - return proto3.util.equals(Leaf, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/genesis_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/genesis_pb.ts deleted file mode 100644 index bb416de17..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/genesis_pb.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/genesis.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { LockIdIntermediaryAccountConnection, OsmoEquivalentMultiplierRecord, SuperfluidAsset, SuperfluidIntermediaryAccount } from "./superfluid_pb.js"; - -/** - * GenesisState defines the module's genesis state. - * - * @generated from message osmosis.superfluid.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: osmosis.superfluid.Params params = 1; - */ - params?: Params; - - /** - * superfluid_assets defines the registered superfluid assets that have been - * registered via governance. - * - * @generated from field: repeated osmosis.superfluid.SuperfluidAsset superfluid_assets = 2; - */ - superfluidAssets: SuperfluidAsset[] = []; - - /** - * osmo_equivalent_multipliers is the records of osmo equivalent amount of - * each superfluid registered pool, updated every epoch. - * - * @generated from field: repeated osmosis.superfluid.OsmoEquivalentMultiplierRecord osmo_equivalent_multipliers = 3; - */ - osmoEquivalentMultipliers: OsmoEquivalentMultiplierRecord[] = []; - - /** - * intermediary_accounts is a secondary account for superfluid staking that - * plays an intermediary role between validators and the delegators. - * - * @generated from field: repeated osmosis.superfluid.SuperfluidIntermediaryAccount intermediary_accounts = 4; - */ - intermediaryAccounts: SuperfluidIntermediaryAccount[] = []; - - /** - * @generated from field: repeated osmosis.superfluid.LockIdIntermediaryAccountConnection intemediary_account_connections = 5; - */ - intemediaryAccountConnections: LockIdIntermediaryAccountConnection[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "superfluid_assets", kind: "message", T: SuperfluidAsset, repeated: true }, - { no: 3, name: "osmo_equivalent_multipliers", kind: "message", T: OsmoEquivalentMultiplierRecord, repeated: true }, - { no: 4, name: "intermediary_accounts", kind: "message", T: SuperfluidIntermediaryAccount, repeated: true }, - { no: 5, name: "intemediary_account_connections", kind: "message", T: LockIdIntermediaryAccountConnection, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/params_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/params_pb.ts deleted file mode 100644 index 3ca546a58..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/params_pb.ts +++ /dev/null @@ -1,52 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/params.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params holds parameters for the superfluid module - * - * @generated from message osmosis.superfluid.Params - */ -export class Params extends Message { - /** - * minimum_risk_factor is to be cut on OSMO equivalent value of lp tokens for - * superfluid staking, default: 5%. The minimum risk factor works - * to counter-balance the staked amount on chain's exposure to various asset - * volatilities, and have base staking be 'resistant' to volatility. - * - * @generated from field: string minimum_risk_factor = 1; - */ - minimumRiskFactor = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "minimum_risk_factor", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/query_cosmes.ts b/packages/es/src/protobufs/osmosis/superfluid/query_cosmes.ts deleted file mode 100644 index c1a356127..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/query_cosmes.ts +++ /dev/null @@ -1,227 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/superfluid/query.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { AllAssetsRequest, AllAssetsResponse, AllIntermediaryAccountsRequest, AllIntermediaryAccountsResponse, AssetMultiplierRequest, AssetMultiplierResponse, AssetTypeRequest, AssetTypeResponse, ConnectedIntermediaryAccountRequest, ConnectedIntermediaryAccountResponse, EstimateSuperfluidDelegatedAmountByValidatorDenomRequest, EstimateSuperfluidDelegatedAmountByValidatorDenomResponse, QueryParamsRequest, QueryParamsResponse, QueryRestSupplyRequest, QueryRestSupplyResponse, QueryTotalDelegationByDelegatorRequest, QueryTotalDelegationByDelegatorResponse, QueryTotalDelegationByValidatorForDenomRequest, QueryTotalDelegationByValidatorForDenomResponse, QueryUnpoolWhitelistRequest, QueryUnpoolWhitelistResponse, SuperfluidDelegationAmountRequest, SuperfluidDelegationAmountResponse, SuperfluidDelegationsByDelegatorRequest, SuperfluidDelegationsByDelegatorResponse, SuperfluidDelegationsByValidatorDenomRequest, SuperfluidDelegationsByValidatorDenomResponse, SuperfluidUndelegationsByDelegatorRequest, SuperfluidUndelegationsByDelegatorResponse, TotalSuperfluidDelegationsRequest, TotalSuperfluidDelegationsResponse, UserConcentratedSuperfluidPositionsDelegatedRequest, UserConcentratedSuperfluidPositionsDelegatedResponse, UserConcentratedSuperfluidPositionsUndelegatingRequest, UserConcentratedSuperfluidPositionsUndelegatingResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.superfluid.Query"; - -/** - * Params returns the total set of superfluid parameters. - * - * @generated from rpc osmosis.superfluid.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * Returns superfluid asset type, whether if it's a native asset or an lp - * share. - * - * @generated from rpc osmosis.superfluid.Query.AssetType - */ -export const QueryAssetTypeService = { - typeName: TYPE_NAME, - method: "AssetType", - Request: AssetTypeRequest, - Response: AssetTypeResponse, -} as const; - -/** - * Returns all registered superfluid assets. - * - * @generated from rpc osmosis.superfluid.Query.AllAssets - */ -export const QueryAllAssetsService = { - typeName: TYPE_NAME, - method: "AllAssets", - Request: AllAssetsRequest, - Response: AllAssetsResponse, -} as const; - -/** - * Returns the osmo equivalent multiplier used in the most recent epoch. - * - * @generated from rpc osmosis.superfluid.Query.AssetMultiplier - */ -export const QueryAssetMultiplierService = { - typeName: TYPE_NAME, - method: "AssetMultiplier", - Request: AssetMultiplierRequest, - Response: AssetMultiplierResponse, -} as const; - -/** - * Returns all superfluid intermediary accounts. - * - * @generated from rpc osmosis.superfluid.Query.AllIntermediaryAccounts - */ -export const QueryAllIntermediaryAccountsService = { - typeName: TYPE_NAME, - method: "AllIntermediaryAccounts", - Request: AllIntermediaryAccountsRequest, - Response: AllIntermediaryAccountsResponse, -} as const; - -/** - * Returns intermediary account connected to a superfluid staked lock by id - * - * @generated from rpc osmosis.superfluid.Query.ConnectedIntermediaryAccount - */ -export const QueryConnectedIntermediaryAccountService = { - typeName: TYPE_NAME, - method: "ConnectedIntermediaryAccount", - Request: ConnectedIntermediaryAccountRequest, - Response: ConnectedIntermediaryAccountResponse, -} as const; - -/** - * Returns the amount of delegations of specific denom for all validators - * - * @generated from rpc osmosis.superfluid.Query.TotalDelegationByValidatorForDenom - */ -export const QueryTotalDelegationByValidatorForDenomService = { - typeName: TYPE_NAME, - method: "TotalDelegationByValidatorForDenom", - Request: QueryTotalDelegationByValidatorForDenomRequest, - Response: QueryTotalDelegationByValidatorForDenomResponse, -} as const; - -/** - * Returns the total amount of osmo superfluidly staked. - * Response is denominated in uosmo. - * - * @generated from rpc osmosis.superfluid.Query.TotalSuperfluidDelegations - */ -export const QueryTotalSuperfluidDelegationsService = { - typeName: TYPE_NAME, - method: "TotalSuperfluidDelegations", - Request: TotalSuperfluidDelegationsRequest, - Response: TotalSuperfluidDelegationsResponse, -} as const; - -/** - * Returns the coins superfluid delegated for the delegator, validator, denom - * triplet - * - * @generated from rpc osmosis.superfluid.Query.SuperfluidDelegationAmount - */ -export const QuerySuperfluidDelegationAmountService = { - typeName: TYPE_NAME, - method: "SuperfluidDelegationAmount", - Request: SuperfluidDelegationAmountRequest, - Response: SuperfluidDelegationAmountResponse, -} as const; - -/** - * Returns all the delegated superfluid positions for a specific delegator. - * - * @generated from rpc osmosis.superfluid.Query.SuperfluidDelegationsByDelegator - */ -export const QuerySuperfluidDelegationsByDelegatorService = { - typeName: TYPE_NAME, - method: "SuperfluidDelegationsByDelegator", - Request: SuperfluidDelegationsByDelegatorRequest, - Response: SuperfluidDelegationsByDelegatorResponse, -} as const; - -/** - * Returns all the undelegating superfluid positions for a specific delegator. - * - * @generated from rpc osmosis.superfluid.Query.SuperfluidUndelegationsByDelegator - */ -export const QuerySuperfluidUndelegationsByDelegatorService = { - typeName: TYPE_NAME, - method: "SuperfluidUndelegationsByDelegator", - Request: SuperfluidUndelegationsByDelegatorRequest, - Response: SuperfluidUndelegationsByDelegatorResponse, -} as const; - -/** - * Returns all the superfluid positions of a specific denom delegated to one - * validator - * - * @generated from rpc osmosis.superfluid.Query.SuperfluidDelegationsByValidatorDenom - */ -export const QuerySuperfluidDelegationsByValidatorDenomService = { - typeName: TYPE_NAME, - method: "SuperfluidDelegationsByValidatorDenom", - Request: SuperfluidDelegationsByValidatorDenomRequest, - Response: SuperfluidDelegationsByValidatorDenomResponse, -} as const; - -/** - * Returns the amount of a specific denom delegated to a specific validator - * This is labeled an estimate, because the way it calculates the amount can - * lead rounding errors from the true delegated amount - * - * @generated from rpc osmosis.superfluid.Query.EstimateSuperfluidDelegatedAmountByValidatorDenom - */ -export const QueryEstimateSuperfluidDelegatedAmountByValidatorDenomService = { - typeName: TYPE_NAME, - method: "EstimateSuperfluidDelegatedAmountByValidatorDenom", - Request: EstimateSuperfluidDelegatedAmountByValidatorDenomRequest, - Response: EstimateSuperfluidDelegatedAmountByValidatorDenomResponse, -} as const; - -/** - * Returns the specified delegations for a specific delegator - * - * @generated from rpc osmosis.superfluid.Query.TotalDelegationByDelegator - */ -export const QueryTotalDelegationByDelegatorService = { - typeName: TYPE_NAME, - method: "TotalDelegationByDelegator", - Request: QueryTotalDelegationByDelegatorRequest, - Response: QueryTotalDelegationByDelegatorResponse, -} as const; - -/** - * Returns a list of whitelisted pool ids to unpool. - * - * @generated from rpc osmosis.superfluid.Query.UnpoolWhitelist - */ -export const QueryUnpoolWhitelistService = { - typeName: TYPE_NAME, - method: "UnpoolWhitelist", - Request: QueryUnpoolWhitelistRequest, - Response: QueryUnpoolWhitelistResponse, -} as const; - -/** - * Returns all of a user's full range CL positions that are superfluid staked. - * - * @generated from rpc osmosis.superfluid.Query.UserConcentratedSuperfluidPositionsDelegated - */ -export const QueryUserConcentratedSuperfluidPositionsDelegatedService = { - typeName: TYPE_NAME, - method: "UserConcentratedSuperfluidPositionsDelegated", - Request: UserConcentratedSuperfluidPositionsDelegatedRequest, - Response: UserConcentratedSuperfluidPositionsDelegatedResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Query.UserConcentratedSuperfluidPositionsUndelegating - */ -export const QueryUserConcentratedSuperfluidPositionsUndelegatingService = { - typeName: TYPE_NAME, - method: "UserConcentratedSuperfluidPositionsUndelegating", - Request: UserConcentratedSuperfluidPositionsUndelegatingRequest, - Response: UserConcentratedSuperfluidPositionsUndelegatingResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Query.RestSupply - */ -export const QueryRestSupplyService = { - typeName: TYPE_NAME, - method: "RestSupply", - Request: QueryRestSupplyRequest, - Response: QueryRestSupplyResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/superfluid/query_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/query_pb.ts deleted file mode 100644 index cdc41deac..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/query_pb.ts +++ /dev/null @@ -1,1510 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/query.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { ConcentratedPoolUserPositionRecord, OsmoEquivalentMultiplierRecord, SuperfluidAsset, SuperfluidAssetType, SuperfluidDelegationRecord } from "./superfluid_pb.js"; -import { PageRequest, PageResponse } from "../../cosmos/base/query/v1beta1/pagination_pb.js"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; -import { SyntheticLock } from "../lockup/lock_pb.js"; -import { DelegationResponse } from "../../cosmos/staking/v1beta1/staking_pb.js"; - -/** - * @generated from message osmosis.superfluid.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: osmosis.superfluid.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AssetTypeRequest - */ -export class AssetTypeRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AssetTypeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AssetTypeRequest { - return new AssetTypeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AssetTypeRequest { - return new AssetTypeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AssetTypeRequest { - return new AssetTypeRequest().fromJsonString(jsonString, options); - } - - static equals(a: AssetTypeRequest | PlainMessage | undefined, b: AssetTypeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AssetTypeRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AssetTypeResponse - */ -export class AssetTypeResponse extends Message { - /** - * @generated from field: osmosis.superfluid.SuperfluidAssetType asset_type = 1; - */ - assetType = SuperfluidAssetType.SuperfluidAssetTypeNative; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AssetTypeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "asset_type", kind: "enum", T: proto3.getEnumType(SuperfluidAssetType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AssetTypeResponse { - return new AssetTypeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AssetTypeResponse { - return new AssetTypeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AssetTypeResponse { - return new AssetTypeResponse().fromJsonString(jsonString, options); - } - - static equals(a: AssetTypeResponse | PlainMessage | undefined, b: AssetTypeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AssetTypeResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AllAssetsRequest - */ -export class AllAssetsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AllAssetsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllAssetsRequest { - return new AllAssetsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllAssetsRequest { - return new AllAssetsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllAssetsRequest { - return new AllAssetsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllAssetsRequest | PlainMessage | undefined, b: AllAssetsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllAssetsRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AllAssetsResponse - */ -export class AllAssetsResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidAsset assets = 1; - */ - assets: SuperfluidAsset[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AllAssetsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "assets", kind: "message", T: SuperfluidAsset, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllAssetsResponse { - return new AllAssetsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllAssetsResponse { - return new AllAssetsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllAssetsResponse { - return new AllAssetsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllAssetsResponse | PlainMessage | undefined, b: AllAssetsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllAssetsResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AssetMultiplierRequest - */ -export class AssetMultiplierRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AssetMultiplierRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AssetMultiplierRequest { - return new AssetMultiplierRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AssetMultiplierRequest { - return new AssetMultiplierRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AssetMultiplierRequest { - return new AssetMultiplierRequest().fromJsonString(jsonString, options); - } - - static equals(a: AssetMultiplierRequest | PlainMessage | undefined, b: AssetMultiplierRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AssetMultiplierRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AssetMultiplierResponse - */ -export class AssetMultiplierResponse extends Message { - /** - * @generated from field: osmosis.superfluid.OsmoEquivalentMultiplierRecord osmo_equivalent_multiplier = 1; - */ - osmoEquivalentMultiplier?: OsmoEquivalentMultiplierRecord; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AssetMultiplierResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "osmo_equivalent_multiplier", kind: "message", T: OsmoEquivalentMultiplierRecord }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AssetMultiplierResponse { - return new AssetMultiplierResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AssetMultiplierResponse { - return new AssetMultiplierResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AssetMultiplierResponse { - return new AssetMultiplierResponse().fromJsonString(jsonString, options); - } - - static equals(a: AssetMultiplierResponse | PlainMessage | undefined, b: AssetMultiplierResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AssetMultiplierResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidIntermediaryAccountInfo - */ -export class SuperfluidIntermediaryAccountInfo extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: string val_addr = 2; - */ - valAddr = ""; - - /** - * @generated from field: uint64 gauge_id = 3; - */ - gaugeId = protoInt64.zero; - - /** - * @generated from field: string address = 4; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidIntermediaryAccountInfo"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidIntermediaryAccountInfo { - return new SuperfluidIntermediaryAccountInfo().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidIntermediaryAccountInfo { - return new SuperfluidIntermediaryAccountInfo().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidIntermediaryAccountInfo { - return new SuperfluidIntermediaryAccountInfo().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidIntermediaryAccountInfo | PlainMessage | undefined, b: SuperfluidIntermediaryAccountInfo | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidIntermediaryAccountInfo, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AllIntermediaryAccountsRequest - */ -export class AllIntermediaryAccountsRequest extends Message { - /** - * @generated from field: cosmos.base.query.v1beta1.PageRequest pagination = 1; - */ - pagination?: PageRequest; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AllIntermediaryAccountsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pagination", kind: "message", T: PageRequest }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllIntermediaryAccountsRequest { - return new AllIntermediaryAccountsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllIntermediaryAccountsRequest { - return new AllIntermediaryAccountsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllIntermediaryAccountsRequest { - return new AllIntermediaryAccountsRequest().fromJsonString(jsonString, options); - } - - static equals(a: AllIntermediaryAccountsRequest | PlainMessage | undefined, b: AllIntermediaryAccountsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(AllIntermediaryAccountsRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.AllIntermediaryAccountsResponse - */ -export class AllIntermediaryAccountsResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidIntermediaryAccountInfo accounts = 1; - */ - accounts: SuperfluidIntermediaryAccountInfo[] = []; - - /** - * @generated from field: cosmos.base.query.v1beta1.PageResponse pagination = 2; - */ - pagination?: PageResponse; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.AllIntermediaryAccountsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "accounts", kind: "message", T: SuperfluidIntermediaryAccountInfo, repeated: true }, - { no: 2, name: "pagination", kind: "message", T: PageResponse }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): AllIntermediaryAccountsResponse { - return new AllIntermediaryAccountsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): AllIntermediaryAccountsResponse { - return new AllIntermediaryAccountsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): AllIntermediaryAccountsResponse { - return new AllIntermediaryAccountsResponse().fromJsonString(jsonString, options); - } - - static equals(a: AllIntermediaryAccountsResponse | PlainMessage | undefined, b: AllIntermediaryAccountsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(AllIntermediaryAccountsResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.ConnectedIntermediaryAccountRequest - */ -export class ConnectedIntermediaryAccountRequest extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.ConnectedIntermediaryAccountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConnectedIntermediaryAccountRequest { - return new ConnectedIntermediaryAccountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConnectedIntermediaryAccountRequest { - return new ConnectedIntermediaryAccountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConnectedIntermediaryAccountRequest { - return new ConnectedIntermediaryAccountRequest().fromJsonString(jsonString, options); - } - - static equals(a: ConnectedIntermediaryAccountRequest | PlainMessage | undefined, b: ConnectedIntermediaryAccountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ConnectedIntermediaryAccountRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.ConnectedIntermediaryAccountResponse - */ -export class ConnectedIntermediaryAccountResponse extends Message { - /** - * @generated from field: osmosis.superfluid.SuperfluidIntermediaryAccountInfo account = 1; - */ - account?: SuperfluidIntermediaryAccountInfo; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.ConnectedIntermediaryAccountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "account", kind: "message", T: SuperfluidIntermediaryAccountInfo }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConnectedIntermediaryAccountResponse { - return new ConnectedIntermediaryAccountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConnectedIntermediaryAccountResponse { - return new ConnectedIntermediaryAccountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConnectedIntermediaryAccountResponse { - return new ConnectedIntermediaryAccountResponse().fromJsonString(jsonString, options); - } - - static equals(a: ConnectedIntermediaryAccountResponse | PlainMessage | undefined, b: ConnectedIntermediaryAccountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ConnectedIntermediaryAccountResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryTotalDelegationByValidatorForDenomRequest - */ -export class QueryTotalDelegationByValidatorForDenomRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryTotalDelegationByValidatorForDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalDelegationByValidatorForDenomRequest { - return new QueryTotalDelegationByValidatorForDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalDelegationByValidatorForDenomRequest { - return new QueryTotalDelegationByValidatorForDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalDelegationByValidatorForDenomRequest { - return new QueryTotalDelegationByValidatorForDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalDelegationByValidatorForDenomRequest | PlainMessage | undefined, b: QueryTotalDelegationByValidatorForDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalDelegationByValidatorForDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryTotalDelegationByValidatorForDenomResponse - */ -export class QueryTotalDelegationByValidatorForDenomResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.Delegations assets = 1; - */ - assets: Delegations[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryTotalDelegationByValidatorForDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "assets", kind: "message", T: Delegations, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalDelegationByValidatorForDenomResponse { - return new QueryTotalDelegationByValidatorForDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalDelegationByValidatorForDenomResponse { - return new QueryTotalDelegationByValidatorForDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalDelegationByValidatorForDenomResponse { - return new QueryTotalDelegationByValidatorForDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalDelegationByValidatorForDenomResponse | PlainMessage | undefined, b: QueryTotalDelegationByValidatorForDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalDelegationByValidatorForDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.Delegations - */ -export class Delegations extends Message { - /** - * @generated from field: string val_addr = 1; - */ - valAddr = ""; - - /** - * @generated from field: string amount_sfsd = 2; - */ - amountSfsd = ""; - - /** - * @generated from field: string osmo_equivalent = 3; - */ - osmoEquivalent = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.Delegations"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount_sfsd", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "osmo_equivalent", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Delegations { - return new Delegations().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Delegations { - return new Delegations().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Delegations { - return new Delegations().fromJsonString(jsonString, options); - } - - static equals(a: Delegations | PlainMessage | undefined, b: Delegations | PlainMessage | undefined): boolean { - return proto3.util.equals(Delegations, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.TotalSuperfluidDelegationsRequest - */ -export class TotalSuperfluidDelegationsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.TotalSuperfluidDelegationsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalSuperfluidDelegationsRequest { - return new TotalSuperfluidDelegationsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalSuperfluidDelegationsRequest { - return new TotalSuperfluidDelegationsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalSuperfluidDelegationsRequest { - return new TotalSuperfluidDelegationsRequest().fromJsonString(jsonString, options); - } - - static equals(a: TotalSuperfluidDelegationsRequest | PlainMessage | undefined, b: TotalSuperfluidDelegationsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalSuperfluidDelegationsRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.TotalSuperfluidDelegationsResponse - */ -export class TotalSuperfluidDelegationsResponse extends Message { - /** - * @generated from field: string total_delegations = 1; - */ - totalDelegations = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.TotalSuperfluidDelegationsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_delegations", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TotalSuperfluidDelegationsResponse { - return new TotalSuperfluidDelegationsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TotalSuperfluidDelegationsResponse { - return new TotalSuperfluidDelegationsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TotalSuperfluidDelegationsResponse { - return new TotalSuperfluidDelegationsResponse().fromJsonString(jsonString, options); - } - - static equals(a: TotalSuperfluidDelegationsResponse | PlainMessage | undefined, b: TotalSuperfluidDelegationsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(TotalSuperfluidDelegationsResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationAmountRequest - */ -export class SuperfluidDelegationAmountRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - /** - * @generated from field: string validator_address = 2; - */ - validatorAddress = ""; - - /** - * @generated from field: string denom = 3; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationAmountRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationAmountRequest { - return new SuperfluidDelegationAmountRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationAmountRequest { - return new SuperfluidDelegationAmountRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationAmountRequest { - return new SuperfluidDelegationAmountRequest().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationAmountRequest | PlainMessage | undefined, b: SuperfluidDelegationAmountRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationAmountRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationAmountResponse - */ -export class SuperfluidDelegationAmountResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin amount = 1; - */ - amount: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationAmountResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationAmountResponse { - return new SuperfluidDelegationAmountResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationAmountResponse { - return new SuperfluidDelegationAmountResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationAmountResponse { - return new SuperfluidDelegationAmountResponse().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationAmountResponse | PlainMessage | undefined, b: SuperfluidDelegationAmountResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationAmountResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationsByDelegatorRequest - */ -export class SuperfluidDelegationsByDelegatorRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationsByDelegatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationsByDelegatorRequest { - return new SuperfluidDelegationsByDelegatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationsByDelegatorRequest { - return new SuperfluidDelegationsByDelegatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationsByDelegatorRequest { - return new SuperfluidDelegationsByDelegatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationsByDelegatorRequest | PlainMessage | undefined, b: SuperfluidDelegationsByDelegatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationsByDelegatorRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationsByDelegatorResponse - */ -export class SuperfluidDelegationsByDelegatorResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidDelegationRecord superfluid_delegation_records = 1; - */ - superfluidDelegationRecords: SuperfluidDelegationRecord[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin total_delegated_coins = 2; - */ - totalDelegatedCoins: Coin[] = []; - - /** - * @generated from field: cosmos.base.v1beta1.Coin total_equivalent_staked_amount = 3; - */ - totalEquivalentStakedAmount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationsByDelegatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "superfluid_delegation_records", kind: "message", T: SuperfluidDelegationRecord, repeated: true }, - { no: 2, name: "total_delegated_coins", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "total_equivalent_staked_amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationsByDelegatorResponse { - return new SuperfluidDelegationsByDelegatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationsByDelegatorResponse { - return new SuperfluidDelegationsByDelegatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationsByDelegatorResponse { - return new SuperfluidDelegationsByDelegatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationsByDelegatorResponse | PlainMessage | undefined, b: SuperfluidDelegationsByDelegatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationsByDelegatorResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidUndelegationsByDelegatorRequest - */ -export class SuperfluidUndelegationsByDelegatorRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - /** - * @generated from field: string denom = 2; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidUndelegationsByDelegatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidUndelegationsByDelegatorRequest { - return new SuperfluidUndelegationsByDelegatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidUndelegationsByDelegatorRequest { - return new SuperfluidUndelegationsByDelegatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidUndelegationsByDelegatorRequest { - return new SuperfluidUndelegationsByDelegatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidUndelegationsByDelegatorRequest | PlainMessage | undefined, b: SuperfluidUndelegationsByDelegatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidUndelegationsByDelegatorRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidUndelegationsByDelegatorResponse - */ -export class SuperfluidUndelegationsByDelegatorResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidDelegationRecord superfluid_delegation_records = 1; - */ - superfluidDelegationRecords: SuperfluidDelegationRecord[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin total_undelegated_coins = 2; - */ - totalUndelegatedCoins: Coin[] = []; - - /** - * @generated from field: repeated osmosis.lockup.SyntheticLock synthetic_locks = 3; - */ - syntheticLocks: SyntheticLock[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidUndelegationsByDelegatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "superfluid_delegation_records", kind: "message", T: SuperfluidDelegationRecord, repeated: true }, - { no: 2, name: "total_undelegated_coins", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "synthetic_locks", kind: "message", T: SyntheticLock, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidUndelegationsByDelegatorResponse { - return new SuperfluidUndelegationsByDelegatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidUndelegationsByDelegatorResponse { - return new SuperfluidUndelegationsByDelegatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidUndelegationsByDelegatorResponse { - return new SuperfluidUndelegationsByDelegatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidUndelegationsByDelegatorResponse | PlainMessage | undefined, b: SuperfluidUndelegationsByDelegatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidUndelegationsByDelegatorResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationsByValidatorDenomRequest - */ -export class SuperfluidDelegationsByValidatorDenomRequest extends Message { - /** - * @generated from field: string validator_address = 1; - */ - validatorAddress = ""; - - /** - * @generated from field: string denom = 2; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationsByValidatorDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationsByValidatorDenomRequest { - return new SuperfluidDelegationsByValidatorDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationsByValidatorDenomRequest { - return new SuperfluidDelegationsByValidatorDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationsByValidatorDenomRequest { - return new SuperfluidDelegationsByValidatorDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationsByValidatorDenomRequest | PlainMessage | undefined, b: SuperfluidDelegationsByValidatorDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationsByValidatorDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.SuperfluidDelegationsByValidatorDenomResponse - */ -export class SuperfluidDelegationsByValidatorDenomResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidDelegationRecord superfluid_delegation_records = 1; - */ - superfluidDelegationRecords: SuperfluidDelegationRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationsByValidatorDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "superfluid_delegation_records", kind: "message", T: SuperfluidDelegationRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationsByValidatorDenomResponse { - return new SuperfluidDelegationsByValidatorDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationsByValidatorDenomResponse { - return new SuperfluidDelegationsByValidatorDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationsByValidatorDenomResponse { - return new SuperfluidDelegationsByValidatorDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationsByValidatorDenomResponse | PlainMessage | undefined, b: SuperfluidDelegationsByValidatorDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationsByValidatorDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.EstimateSuperfluidDelegatedAmountByValidatorDenomRequest - */ -export class EstimateSuperfluidDelegatedAmountByValidatorDenomRequest extends Message { - /** - * @generated from field: string validator_address = 1; - */ - validatorAddress = ""; - - /** - * @generated from field: string denom = 2; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.EstimateSuperfluidDelegatedAmountByValidatorDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomRequest { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomRequest { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomRequest { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSuperfluidDelegatedAmountByValidatorDenomRequest | PlainMessage | undefined, b: EstimateSuperfluidDelegatedAmountByValidatorDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSuperfluidDelegatedAmountByValidatorDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.EstimateSuperfluidDelegatedAmountByValidatorDenomResponse - */ -export class EstimateSuperfluidDelegatedAmountByValidatorDenomResponse extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin total_delegated_coins = 1; - */ - totalDelegatedCoins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.EstimateSuperfluidDelegatedAmountByValidatorDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_delegated_coins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomResponse { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomResponse { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EstimateSuperfluidDelegatedAmountByValidatorDenomResponse { - return new EstimateSuperfluidDelegatedAmountByValidatorDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: EstimateSuperfluidDelegatedAmountByValidatorDenomResponse | PlainMessage | undefined, b: EstimateSuperfluidDelegatedAmountByValidatorDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(EstimateSuperfluidDelegatedAmountByValidatorDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryTotalDelegationByDelegatorRequest - */ -export class QueryTotalDelegationByDelegatorRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryTotalDelegationByDelegatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalDelegationByDelegatorRequest { - return new QueryTotalDelegationByDelegatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalDelegationByDelegatorRequest { - return new QueryTotalDelegationByDelegatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalDelegationByDelegatorRequest { - return new QueryTotalDelegationByDelegatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalDelegationByDelegatorRequest | PlainMessage | undefined, b: QueryTotalDelegationByDelegatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalDelegationByDelegatorRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryTotalDelegationByDelegatorResponse - */ -export class QueryTotalDelegationByDelegatorResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidDelegationRecord superfluid_delegation_records = 1; - */ - superfluidDelegationRecords: SuperfluidDelegationRecord[] = []; - - /** - * @generated from field: repeated cosmos.staking.v1beta1.DelegationResponse delegation_response = 2; - */ - delegationResponse: DelegationResponse[] = []; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin total_delegated_coins = 3; - */ - totalDelegatedCoins: Coin[] = []; - - /** - * @generated from field: cosmos.base.v1beta1.Coin total_equivalent_staked_amount = 4; - */ - totalEquivalentStakedAmount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryTotalDelegationByDelegatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "superfluid_delegation_records", kind: "message", T: SuperfluidDelegationRecord, repeated: true }, - { no: 2, name: "delegation_response", kind: "message", T: DelegationResponse, repeated: true }, - { no: 3, name: "total_delegated_coins", kind: "message", T: Coin, repeated: true }, - { no: 4, name: "total_equivalent_staked_amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryTotalDelegationByDelegatorResponse { - return new QueryTotalDelegationByDelegatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryTotalDelegationByDelegatorResponse { - return new QueryTotalDelegationByDelegatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryTotalDelegationByDelegatorResponse { - return new QueryTotalDelegationByDelegatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryTotalDelegationByDelegatorResponse | PlainMessage | undefined, b: QueryTotalDelegationByDelegatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryTotalDelegationByDelegatorResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryUnpoolWhitelistRequest - */ -export class QueryUnpoolWhitelistRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryUnpoolWhitelistRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnpoolWhitelistRequest { - return new QueryUnpoolWhitelistRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnpoolWhitelistRequest { - return new QueryUnpoolWhitelistRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnpoolWhitelistRequest { - return new QueryUnpoolWhitelistRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnpoolWhitelistRequest | PlainMessage | undefined, b: QueryUnpoolWhitelistRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnpoolWhitelistRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryUnpoolWhitelistResponse - */ -export class QueryUnpoolWhitelistResponse extends Message { - /** - * @generated from field: repeated uint64 pool_ids = 1; - */ - poolIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryUnpoolWhitelistResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryUnpoolWhitelistResponse { - return new QueryUnpoolWhitelistResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryUnpoolWhitelistResponse { - return new QueryUnpoolWhitelistResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryUnpoolWhitelistResponse { - return new QueryUnpoolWhitelistResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryUnpoolWhitelistResponse | PlainMessage | undefined, b: QueryUnpoolWhitelistResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryUnpoolWhitelistResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.UserConcentratedSuperfluidPositionsDelegatedRequest - */ -export class UserConcentratedSuperfluidPositionsDelegatedRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.UserConcentratedSuperfluidPositionsDelegatedRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedRequest { - return new UserConcentratedSuperfluidPositionsDelegatedRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedRequest { - return new UserConcentratedSuperfluidPositionsDelegatedRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedRequest { - return new UserConcentratedSuperfluidPositionsDelegatedRequest().fromJsonString(jsonString, options); - } - - static equals(a: UserConcentratedSuperfluidPositionsDelegatedRequest | PlainMessage | undefined, b: UserConcentratedSuperfluidPositionsDelegatedRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UserConcentratedSuperfluidPositionsDelegatedRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.UserConcentratedSuperfluidPositionsDelegatedResponse - */ -export class UserConcentratedSuperfluidPositionsDelegatedResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.ConcentratedPoolUserPositionRecord cl_pool_user_position_records = 1; - */ - clPoolUserPositionRecords: ConcentratedPoolUserPositionRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.UserConcentratedSuperfluidPositionsDelegatedResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cl_pool_user_position_records", kind: "message", T: ConcentratedPoolUserPositionRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedResponse { - return new UserConcentratedSuperfluidPositionsDelegatedResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedResponse { - return new UserConcentratedSuperfluidPositionsDelegatedResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserConcentratedSuperfluidPositionsDelegatedResponse { - return new UserConcentratedSuperfluidPositionsDelegatedResponse().fromJsonString(jsonString, options); - } - - static equals(a: UserConcentratedSuperfluidPositionsDelegatedResponse | PlainMessage | undefined, b: UserConcentratedSuperfluidPositionsDelegatedResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UserConcentratedSuperfluidPositionsDelegatedResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.UserConcentratedSuperfluidPositionsUndelegatingRequest - */ -export class UserConcentratedSuperfluidPositionsUndelegatingRequest extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.UserConcentratedSuperfluidPositionsUndelegatingRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingRequest { - return new UserConcentratedSuperfluidPositionsUndelegatingRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingRequest { - return new UserConcentratedSuperfluidPositionsUndelegatingRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingRequest { - return new UserConcentratedSuperfluidPositionsUndelegatingRequest().fromJsonString(jsonString, options); - } - - static equals(a: UserConcentratedSuperfluidPositionsUndelegatingRequest | PlainMessage | undefined, b: UserConcentratedSuperfluidPositionsUndelegatingRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UserConcentratedSuperfluidPositionsUndelegatingRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.UserConcentratedSuperfluidPositionsUndelegatingResponse - */ -export class UserConcentratedSuperfluidPositionsUndelegatingResponse extends Message { - /** - * @generated from field: repeated osmosis.superfluid.ConcentratedPoolUserPositionRecord cl_pool_user_position_records = 1; - */ - clPoolUserPositionRecords: ConcentratedPoolUserPositionRecord[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.UserConcentratedSuperfluidPositionsUndelegatingResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cl_pool_user_position_records", kind: "message", T: ConcentratedPoolUserPositionRecord, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingResponse { - return new UserConcentratedSuperfluidPositionsUndelegatingResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingResponse { - return new UserConcentratedSuperfluidPositionsUndelegatingResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserConcentratedSuperfluidPositionsUndelegatingResponse { - return new UserConcentratedSuperfluidPositionsUndelegatingResponse().fromJsonString(jsonString, options); - } - - static equals(a: UserConcentratedSuperfluidPositionsUndelegatingResponse | PlainMessage | undefined, b: UserConcentratedSuperfluidPositionsUndelegatingResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UserConcentratedSuperfluidPositionsUndelegatingResponse, a, b); - } -} - -/** - * THIS QUERY IS TEMPORARY - * - * @generated from message osmosis.superfluid.QueryRestSupplyRequest - */ -export class QueryRestSupplyRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryRestSupplyRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRestSupplyRequest { - return new QueryRestSupplyRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRestSupplyRequest { - return new QueryRestSupplyRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRestSupplyRequest { - return new QueryRestSupplyRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryRestSupplyRequest | PlainMessage | undefined, b: QueryRestSupplyRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRestSupplyRequest, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.QueryRestSupplyResponse - */ -export class QueryRestSupplyResponse extends Message { - /** - * amount is the supply of the coin. - * - * @generated from field: cosmos.base.v1beta1.Coin amount = 1; - */ - amount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.QueryRestSupplyResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryRestSupplyResponse { - return new QueryRestSupplyResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryRestSupplyResponse { - return new QueryRestSupplyResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryRestSupplyResponse { - return new QueryRestSupplyResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryRestSupplyResponse | PlainMessage | undefined, b: QueryRestSupplyResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryRestSupplyResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/superfluid_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/superfluid_pb.ts deleted file mode 100644 index b547ca4ab..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/superfluid_pb.ts +++ /dev/null @@ -1,414 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/superfluid.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; -import { SyntheticLock } from "../lockup/lock_pb.js"; - -/** - * SuperfluidAssetType indicates whether the superfluid asset is - * a native token, lp share of a pool, or concentrated share of a pool - * - * @generated from enum osmosis.superfluid.SuperfluidAssetType - */ -export enum SuperfluidAssetType { - /** - * @generated from enum value: SuperfluidAssetTypeNative = 0; - */ - SuperfluidAssetTypeNative = 0, - - /** - * @generated from enum value: SuperfluidAssetTypeLPShare = 1; - */ - SuperfluidAssetTypeLPShare = 1, - - /** - * SuperfluidAssetTypeLendingShare = 3; // for now not exist - * - * @generated from enum value: SuperfluidAssetTypeConcentratedShare = 2; - */ - SuperfluidAssetTypeConcentratedShare = 2, -} -// Retrieve enum metadata with: proto3.getEnumType(SuperfluidAssetType) -proto3.util.setEnumType(SuperfluidAssetType, "osmosis.superfluid.SuperfluidAssetType", [ - { no: 0, name: "SuperfluidAssetTypeNative" }, - { no: 1, name: "SuperfluidAssetTypeLPShare" }, - { no: 2, name: "SuperfluidAssetTypeConcentratedShare" }, -]); - -/** - * SuperfluidAsset stores the pair of superfluid asset type and denom pair - * - * @generated from message osmosis.superfluid.SuperfluidAsset - */ -export class SuperfluidAsset extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * AssetType indicates whether the superfluid asset is a native token or an lp - * share - * - * @generated from field: osmosis.superfluid.SuperfluidAssetType asset_type = 2; - */ - assetType = SuperfluidAssetType.SuperfluidAssetTypeNative; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidAsset"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "asset_type", kind: "enum", T: proto3.getEnumType(SuperfluidAssetType) }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidAsset { - return new SuperfluidAsset().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidAsset { - return new SuperfluidAsset().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidAsset { - return new SuperfluidAsset().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidAsset | PlainMessage | undefined, b: SuperfluidAsset | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidAsset, a, b); - } -} - -/** - * SuperfluidIntermediaryAccount takes the role of intermediary between LP token - * and OSMO tokens for superfluid staking. The intermediary account is the - * actual account responsible for delegation, not the validator account itself. - * - * @generated from message osmosis.superfluid.SuperfluidIntermediaryAccount - */ -export class SuperfluidIntermediaryAccount extends Message { - /** - * Denom indicates the denom of the superfluid asset. - * - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: string val_addr = 2; - */ - valAddr = ""; - - /** - * perpetual gauge for rewards distribution - * - * @generated from field: uint64 gauge_id = 3; - */ - gaugeId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidIntermediaryAccount"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "gauge_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidIntermediaryAccount { - return new SuperfluidIntermediaryAccount().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidIntermediaryAccount { - return new SuperfluidIntermediaryAccount().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidIntermediaryAccount { - return new SuperfluidIntermediaryAccount().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidIntermediaryAccount | PlainMessage | undefined, b: SuperfluidIntermediaryAccount | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidIntermediaryAccount, a, b); - } -} - -/** - * The Osmo-Equivalent-Multiplier Record for epoch N refers to the osmo worth we - * treat an LP share as having, for all of epoch N. Eventually this is intended - * to be set as the Time-weighted-average-osmo-backing for the entire duration - * of epoch N-1. (Thereby locking what's in use for epoch N as based on the - * prior epochs rewards) However for now, this is not the TWAP but instead the - * spot price at the boundary. For different types of assets in the future, it - * could change. - * - * @generated from message osmosis.superfluid.OsmoEquivalentMultiplierRecord - */ -export class OsmoEquivalentMultiplierRecord extends Message { - /** - * @generated from field: int64 epoch_number = 1; - */ - epochNumber = protoInt64.zero; - - /** - * superfluid asset denom, can be LP token or native token - * - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * @generated from field: string multiplier = 3; - */ - multiplier = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.OsmoEquivalentMultiplierRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "epoch_number", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "multiplier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): OsmoEquivalentMultiplierRecord { - return new OsmoEquivalentMultiplierRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): OsmoEquivalentMultiplierRecord { - return new OsmoEquivalentMultiplierRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): OsmoEquivalentMultiplierRecord { - return new OsmoEquivalentMultiplierRecord().fromJsonString(jsonString, options); - } - - static equals(a: OsmoEquivalentMultiplierRecord | PlainMessage | undefined, b: OsmoEquivalentMultiplierRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(OsmoEquivalentMultiplierRecord, a, b); - } -} - -/** - * SuperfluidDelegationRecord is a struct used to indicate superfluid - * delegations of an account in the state machine in a user friendly form. - * - * @generated from message osmosis.superfluid.SuperfluidDelegationRecord - */ -export class SuperfluidDelegationRecord extends Message { - /** - * @generated from field: string delegator_address = 1; - */ - delegatorAddress = ""; - - /** - * @generated from field: string validator_address = 2; - */ - validatorAddress = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin delegation_amount = 3; - */ - delegationAmount?: Coin; - - /** - * @generated from field: cosmos.base.v1beta1.Coin equivalent_staked_amount = 4; - */ - equivalentStakedAmount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.SuperfluidDelegationRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "delegation_amount", kind: "message", T: Coin }, - { no: 4, name: "equivalent_staked_amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SuperfluidDelegationRecord { - return new SuperfluidDelegationRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SuperfluidDelegationRecord { - return new SuperfluidDelegationRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SuperfluidDelegationRecord { - return new SuperfluidDelegationRecord().fromJsonString(jsonString, options); - } - - static equals(a: SuperfluidDelegationRecord | PlainMessage | undefined, b: SuperfluidDelegationRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(SuperfluidDelegationRecord, a, b); - } -} - -/** - * LockIdIntermediaryAccountConnection is a struct used to indicate the - * relationship between the underlying lock id and superfluid delegation done - * via lp shares. - * - * @generated from message osmosis.superfluid.LockIdIntermediaryAccountConnection - */ -export class LockIdIntermediaryAccountConnection extends Message { - /** - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: string intermediary_account = 2; - */ - intermediaryAccount = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.LockIdIntermediaryAccountConnection"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "intermediary_account", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): LockIdIntermediaryAccountConnection { - return new LockIdIntermediaryAccountConnection().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): LockIdIntermediaryAccountConnection { - return new LockIdIntermediaryAccountConnection().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): LockIdIntermediaryAccountConnection { - return new LockIdIntermediaryAccountConnection().fromJsonString(jsonString, options); - } - - static equals(a: LockIdIntermediaryAccountConnection | PlainMessage | undefined, b: LockIdIntermediaryAccountConnection | PlainMessage | undefined): boolean { - return proto3.util.equals(LockIdIntermediaryAccountConnection, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.UnpoolWhitelistedPools - */ -export class UnpoolWhitelistedPools extends Message { - /** - * @generated from field: repeated uint64 ids = 1; - */ - ids: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.UnpoolWhitelistedPools"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UnpoolWhitelistedPools { - return new UnpoolWhitelistedPools().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UnpoolWhitelistedPools { - return new UnpoolWhitelistedPools().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UnpoolWhitelistedPools { - return new UnpoolWhitelistedPools().fromJsonString(jsonString, options); - } - - static equals(a: UnpoolWhitelistedPools | PlainMessage | undefined, b: UnpoolWhitelistedPools | PlainMessage | undefined): boolean { - return proto3.util.equals(UnpoolWhitelistedPools, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.ConcentratedPoolUserPositionRecord - */ -export class ConcentratedPoolUserPositionRecord extends Message { - /** - * @generated from field: string validator_address = 1; - */ - validatorAddress = ""; - - /** - * @generated from field: uint64 position_id = 2; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: uint64 lock_id = 3; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: osmosis.lockup.SyntheticLock synthetic_lock = 4; - */ - syntheticLock?: SyntheticLock; - - /** - * @generated from field: cosmos.base.v1beta1.Coin delegation_amount = 5; - */ - delegationAmount?: Coin; - - /** - * @generated from field: cosmos.base.v1beta1.Coin equivalent_staked_amount = 6; - */ - equivalentStakedAmount?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.ConcentratedPoolUserPositionRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "validator_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 4, name: "synthetic_lock", kind: "message", T: SyntheticLock }, - { no: 5, name: "delegation_amount", kind: "message", T: Coin }, - { no: 6, name: "equivalent_staked_amount", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ConcentratedPoolUserPositionRecord { - return new ConcentratedPoolUserPositionRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ConcentratedPoolUserPositionRecord { - return new ConcentratedPoolUserPositionRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ConcentratedPoolUserPositionRecord { - return new ConcentratedPoolUserPositionRecord().fromJsonString(jsonString, options); - } - - static equals(a: ConcentratedPoolUserPositionRecord | PlainMessage | undefined, b: ConcentratedPoolUserPositionRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(ConcentratedPoolUserPositionRecord, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/superfluid/tx_cosmes.ts deleted file mode 100644 index 4796087c5..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/tx_cosmes.ts +++ /dev/null @@ -1,123 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/superfluid/tx.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgAddToConcentratedLiquiditySuperfluidPosition, MsgAddToConcentratedLiquiditySuperfluidPositionResponse, MsgCreateFullRangePositionAndSuperfluidDelegate, MsgCreateFullRangePositionAndSuperfluidDelegateResponse, MsgLockAndSuperfluidDelegate, MsgLockAndSuperfluidDelegateResponse, MsgSuperfluidDelegate, MsgSuperfluidDelegateResponse, MsgSuperfluidUnbondLock, MsgSuperfluidUnbondLockResponse, MsgSuperfluidUndelegate, MsgSuperfluidUndelegateAndUnbondLock, MsgSuperfluidUndelegateAndUnbondLockResponse, MsgSuperfluidUndelegateResponse, MsgUnbondConvertAndStake, MsgUnbondConvertAndStakeResponse, MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition, MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse, MsgUnPoolWhitelistedPool, MsgUnPoolWhitelistedPoolResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.superfluid.Msg"; - -/** - * Execute superfluid delegation for a lockup - * - * @generated from rpc osmosis.superfluid.Msg.SuperfluidDelegate - */ -export const MsgSuperfluidDelegateService = { - typeName: TYPE_NAME, - method: "SuperfluidDelegate", - Request: MsgSuperfluidDelegate, - Response: MsgSuperfluidDelegateResponse, -} as const; - -/** - * Execute superfluid undelegation for a lockup - * - * @generated from rpc osmosis.superfluid.Msg.SuperfluidUndelegate - */ -export const MsgSuperfluidUndelegateService = { - typeName: TYPE_NAME, - method: "SuperfluidUndelegate", - Request: MsgSuperfluidUndelegate, - Response: MsgSuperfluidUndelegateResponse, -} as const; - -/** - * For a given lock that is being superfluidly undelegated, - * also unbond the underlying lock. - * - * @generated from rpc osmosis.superfluid.Msg.SuperfluidUnbondLock - */ -export const MsgSuperfluidUnbondLockService = { - typeName: TYPE_NAME, - method: "SuperfluidUnbondLock", - Request: MsgSuperfluidUnbondLock, - Response: MsgSuperfluidUnbondLockResponse, -} as const; - -/** - * Superfluid undelegate and unbond partial amount of the underlying lock. - * - * @generated from rpc osmosis.superfluid.Msg.SuperfluidUndelegateAndUnbondLock - */ -export const MsgSuperfluidUndelegateAndUnbondLockService = { - typeName: TYPE_NAME, - method: "SuperfluidUndelegateAndUnbondLock", - Request: MsgSuperfluidUndelegateAndUnbondLock, - Response: MsgSuperfluidUndelegateAndUnbondLockResponse, -} as const; - -/** - * Execute lockup lock and superfluid delegation in a single msg - * - * @generated from rpc osmosis.superfluid.Msg.LockAndSuperfluidDelegate - */ -export const MsgLockAndSuperfluidDelegateService = { - typeName: TYPE_NAME, - method: "LockAndSuperfluidDelegate", - Request: MsgLockAndSuperfluidDelegate, - Response: MsgLockAndSuperfluidDelegateResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Msg.CreateFullRangePositionAndSuperfluidDelegate - */ -export const MsgCreateFullRangePositionAndSuperfluidDelegateService = { - typeName: TYPE_NAME, - method: "CreateFullRangePositionAndSuperfluidDelegate", - Request: MsgCreateFullRangePositionAndSuperfluidDelegate, - Response: MsgCreateFullRangePositionAndSuperfluidDelegateResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Msg.UnPoolWhitelistedPool - */ -export const MsgUnPoolWhitelistedPoolService = { - typeName: TYPE_NAME, - method: "UnPoolWhitelistedPool", - Request: MsgUnPoolWhitelistedPool, - Response: MsgUnPoolWhitelistedPoolResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Msg.UnlockAndMigrateSharesToFullRangeConcentratedPosition - */ -export const MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionService = { - typeName: TYPE_NAME, - method: "UnlockAndMigrateSharesToFullRangeConcentratedPosition", - Request: MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition, - Response: MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse, -} as const; - -/** - * @generated from rpc osmosis.superfluid.Msg.AddToConcentratedLiquiditySuperfluidPosition - */ -export const MsgAddToConcentratedLiquiditySuperfluidPositionService = { - typeName: TYPE_NAME, - method: "AddToConcentratedLiquiditySuperfluidPosition", - Request: MsgAddToConcentratedLiquiditySuperfluidPosition, - Response: MsgAddToConcentratedLiquiditySuperfluidPositionResponse, -} as const; - -/** - * UnbondConvertAndStake breaks all locks / superfluid staked assets, - * converts them to osmo then stakes the osmo to the designated validator. - * - * @generated from rpc osmosis.superfluid.Msg.UnbondConvertAndStake - */ -export const MsgUnbondConvertAndStakeService = { - typeName: TYPE_NAME, - method: "UnbondConvertAndStake", - Request: MsgUnbondConvertAndStake, - Response: MsgUnbondConvertAndStakeResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/superfluid/tx_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/tx_pb.ts deleted file mode 100644 index c31e93231..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/tx_pb.ts +++ /dev/null @@ -1,959 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/tx.proto (package osmosis.superfluid, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidDelegate - */ -export class MsgSuperfluidDelegate extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 lock_id = 2; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: string val_addr = 3; - */ - valAddr = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidDelegate"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidDelegate { - return new MsgSuperfluidDelegate().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidDelegate { - return new MsgSuperfluidDelegate().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidDelegate { - return new MsgSuperfluidDelegate().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidDelegate | PlainMessage | undefined, b: MsgSuperfluidDelegate | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidDelegate, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidDelegateResponse - */ -export class MsgSuperfluidDelegateResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidDelegateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidDelegateResponse { - return new MsgSuperfluidDelegateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidDelegateResponse { - return new MsgSuperfluidDelegateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidDelegateResponse { - return new MsgSuperfluidDelegateResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidDelegateResponse | PlainMessage | undefined, b: MsgSuperfluidDelegateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidDelegateResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUndelegate - */ -export class MsgSuperfluidUndelegate extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 lock_id = 2; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUndelegate"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUndelegate { - return new MsgSuperfluidUndelegate().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUndelegate { - return new MsgSuperfluidUndelegate().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUndelegate { - return new MsgSuperfluidUndelegate().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUndelegate | PlainMessage | undefined, b: MsgSuperfluidUndelegate | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUndelegate, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUndelegateResponse - */ -export class MsgSuperfluidUndelegateResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUndelegateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUndelegateResponse { - return new MsgSuperfluidUndelegateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUndelegateResponse { - return new MsgSuperfluidUndelegateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUndelegateResponse { - return new MsgSuperfluidUndelegateResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUndelegateResponse | PlainMessage | undefined, b: MsgSuperfluidUndelegateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUndelegateResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUnbondLock - */ -export class MsgSuperfluidUnbondLock extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 lock_id = 2; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUnbondLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUnbondLock { - return new MsgSuperfluidUnbondLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUnbondLock { - return new MsgSuperfluidUnbondLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUnbondLock { - return new MsgSuperfluidUnbondLock().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUnbondLock | PlainMessage | undefined, b: MsgSuperfluidUnbondLock | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUnbondLock, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUnbondLockResponse - */ -export class MsgSuperfluidUnbondLockResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUnbondLockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUnbondLockResponse { - return new MsgSuperfluidUnbondLockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUnbondLockResponse { - return new MsgSuperfluidUnbondLockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUnbondLockResponse { - return new MsgSuperfluidUnbondLockResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUnbondLockResponse | PlainMessage | undefined, b: MsgSuperfluidUnbondLockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUnbondLockResponse, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUndelegateAndUnbondLock - */ -export class MsgSuperfluidUndelegateAndUnbondLock extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 lock_id = 2; - */ - lockId = protoInt64.zero; - - /** - * Amount of unlocking coin. - * - * @generated from field: cosmos.base.v1beta1.Coin coin = 3; - */ - coin?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUndelegateAndUnbondLock"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 3, name: "coin", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUndelegateAndUnbondLock { - return new MsgSuperfluidUndelegateAndUnbondLock().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUndelegateAndUnbondLock { - return new MsgSuperfluidUndelegateAndUnbondLock().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUndelegateAndUnbondLock { - return new MsgSuperfluidUndelegateAndUnbondLock().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUndelegateAndUnbondLock | PlainMessage | undefined, b: MsgSuperfluidUndelegateAndUnbondLock | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUndelegateAndUnbondLock, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgSuperfluidUndelegateAndUnbondLockResponse - */ -export class MsgSuperfluidUndelegateAndUnbondLockResponse extends Message { - /** - * lock id of the new lock created for the remaining amount. - * returns the original lockid if the unlocked amount is equal to the - * original lock's amount. - * - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgSuperfluidUndelegateAndUnbondLockResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSuperfluidUndelegateAndUnbondLockResponse { - return new MsgSuperfluidUndelegateAndUnbondLockResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSuperfluidUndelegateAndUnbondLockResponse { - return new MsgSuperfluidUndelegateAndUnbondLockResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSuperfluidUndelegateAndUnbondLockResponse { - return new MsgSuperfluidUndelegateAndUnbondLockResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSuperfluidUndelegateAndUnbondLockResponse | PlainMessage | undefined, b: MsgSuperfluidUndelegateAndUnbondLockResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSuperfluidUndelegateAndUnbondLockResponse, a, b); - } -} - -/** - * MsgLockAndSuperfluidDelegate locks coins with the unbonding period duration, - * and then does a superfluid lock from the newly created lockup, to the - * specified validator addr. - * - * @generated from message osmosis.superfluid.MsgLockAndSuperfluidDelegate - */ -export class MsgLockAndSuperfluidDelegate extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 2; - */ - coins: Coin[] = []; - - /** - * @generated from field: string val_addr = 3; - */ - valAddr = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgLockAndSuperfluidDelegate"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLockAndSuperfluidDelegate { - return new MsgLockAndSuperfluidDelegate().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLockAndSuperfluidDelegate { - return new MsgLockAndSuperfluidDelegate().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLockAndSuperfluidDelegate { - return new MsgLockAndSuperfluidDelegate().fromJsonString(jsonString, options); - } - - static equals(a: MsgLockAndSuperfluidDelegate | PlainMessage | undefined, b: MsgLockAndSuperfluidDelegate | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLockAndSuperfluidDelegate, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgLockAndSuperfluidDelegateResponse - */ -export class MsgLockAndSuperfluidDelegateResponse extends Message { - /** - * @generated from field: uint64 ID = 1; - */ - ID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgLockAndSuperfluidDelegateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "ID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgLockAndSuperfluidDelegateResponse { - return new MsgLockAndSuperfluidDelegateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgLockAndSuperfluidDelegateResponse { - return new MsgLockAndSuperfluidDelegateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgLockAndSuperfluidDelegateResponse { - return new MsgLockAndSuperfluidDelegateResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgLockAndSuperfluidDelegateResponse | PlainMessage | undefined, b: MsgLockAndSuperfluidDelegateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgLockAndSuperfluidDelegateResponse, a, b); - } -} - -/** - * MsgCreateFullRangePositionAndSuperfluidDelegate creates a full range position - * in a concentrated liquidity pool, then superfluid delegates. - * - * @generated from message osmosis.superfluid.MsgCreateFullRangePositionAndSuperfluidDelegate - */ -export class MsgCreateFullRangePositionAndSuperfluidDelegate extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin coins = 2; - */ - coins: Coin[] = []; - - /** - * @generated from field: string val_addr = 3; - */ - valAddr = ""; - - /** - * @generated from field: uint64 pool_id = 4; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgCreateFullRangePositionAndSuperfluidDelegate"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "coins", kind: "message", T: Coin, repeated: true }, - { no: 3, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegate { - return new MsgCreateFullRangePositionAndSuperfluidDelegate().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegate { - return new MsgCreateFullRangePositionAndSuperfluidDelegate().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegate { - return new MsgCreateFullRangePositionAndSuperfluidDelegate().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateFullRangePositionAndSuperfluidDelegate | PlainMessage | undefined, b: MsgCreateFullRangePositionAndSuperfluidDelegate | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateFullRangePositionAndSuperfluidDelegate, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgCreateFullRangePositionAndSuperfluidDelegateResponse - */ -export class MsgCreateFullRangePositionAndSuperfluidDelegateResponse extends Message { - /** - * @generated from field: uint64 lockID = 1; - */ - lockID = protoInt64.zero; - - /** - * @generated from field: uint64 positionID = 2; - */ - positionID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgCreateFullRangePositionAndSuperfluidDelegateResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lockID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "positionID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegateResponse { - return new MsgCreateFullRangePositionAndSuperfluidDelegateResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegateResponse { - return new MsgCreateFullRangePositionAndSuperfluidDelegateResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateFullRangePositionAndSuperfluidDelegateResponse { - return new MsgCreateFullRangePositionAndSuperfluidDelegateResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateFullRangePositionAndSuperfluidDelegateResponse | PlainMessage | undefined, b: MsgCreateFullRangePositionAndSuperfluidDelegateResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateFullRangePositionAndSuperfluidDelegateResponse, a, b); - } -} - -/** - * MsgUnPoolWhitelistedPool Unpools every lock the sender has, that is - * associated with pool pool_id. If pool_id is not approved for unpooling by - * governance, this is a no-op. Unpooling takes the locked gamm shares, and runs - * "ExitPool" on it, to get the constituent tokens. e.g. z gamm/pool/1 tokens - * ExitPools into constituent tokens x uatom, y uosmo. Then it creates a new - * lock for every constituent token, with the duration associated with the lock. - * If the lock was unbonding, the new lockup durations should be the time left - * until unbond completion. - * - * @generated from message osmosis.superfluid.MsgUnPoolWhitelistedPool - */ -export class MsgUnPoolWhitelistedPool extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: uint64 pool_id = 2; - */ - poolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnPoolWhitelistedPool"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnPoolWhitelistedPool { - return new MsgUnPoolWhitelistedPool().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnPoolWhitelistedPool { - return new MsgUnPoolWhitelistedPool().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnPoolWhitelistedPool { - return new MsgUnPoolWhitelistedPool().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnPoolWhitelistedPool | PlainMessage | undefined, b: MsgUnPoolWhitelistedPool | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnPoolWhitelistedPool, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgUnPoolWhitelistedPoolResponse - */ -export class MsgUnPoolWhitelistedPoolResponse extends Message { - /** - * @generated from field: repeated uint64 exited_lock_ids = 1; - */ - exitedLockIds: bigint[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnPoolWhitelistedPoolResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "exited_lock_ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnPoolWhitelistedPoolResponse { - return new MsgUnPoolWhitelistedPoolResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnPoolWhitelistedPoolResponse { - return new MsgUnPoolWhitelistedPoolResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnPoolWhitelistedPoolResponse { - return new MsgUnPoolWhitelistedPoolResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnPoolWhitelistedPoolResponse | PlainMessage | undefined, b: MsgUnPoolWhitelistedPoolResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnPoolWhitelistedPoolResponse, a, b); - } -} - -/** - * ===================== - * MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition - * - * @generated from message osmosis.superfluid.MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition - */ -export class MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: int64 lock_id = 2; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: cosmos.base.v1beta1.Coin shares_to_migrate = 3; - */ - sharesToMigrate?: Coin; - - /** - * token_out_mins indicates minimum token to exit Balancer pool with. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin token_out_mins = 4; - */ - tokenOutMins: Coin[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lock_id", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 3, name: "shares_to_migrate", kind: "message", T: Coin }, - { no: 4, name: "token_out_mins", kind: "message", T: Coin, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition | PlainMessage | undefined, b: MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse - */ -export class MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse extends Message { - /** - * @generated from field: string amount0 = 1; - */ - amount0 = ""; - - /** - * @generated from field: string amount1 = 2; - */ - amount1 = ""; - - /** - * @generated from field: string liquidity_created = 3; - */ - liquidityCreated = ""; - - /** - * @generated from field: google.protobuf.Timestamp join_time = 4; - */ - joinTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "liquidity_created", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "join_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse { - return new MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse | PlainMessage | undefined, b: MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnlockAndMigrateSharesToFullRangeConcentratedPositionResponse, a, b); - } -} - -/** - * ===================== MsgAddToConcentratedLiquiditySuperfluidPosition - * - * @generated from message osmosis.superfluid.MsgAddToConcentratedLiquiditySuperfluidPosition - */ -export class MsgAddToConcentratedLiquiditySuperfluidPosition extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_desired0 = 3; - */ - tokenDesired0?: Coin; - - /** - * @generated from field: cosmos.base.v1beta1.Coin token_desired1 = 4; - */ - tokenDesired1?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgAddToConcentratedLiquiditySuperfluidPosition"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_desired0", kind: "message", T: Coin }, - { no: 4, name: "token_desired1", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPosition { - return new MsgAddToConcentratedLiquiditySuperfluidPosition().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPosition { - return new MsgAddToConcentratedLiquiditySuperfluidPosition().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPosition { - return new MsgAddToConcentratedLiquiditySuperfluidPosition().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToConcentratedLiquiditySuperfluidPosition | PlainMessage | undefined, b: MsgAddToConcentratedLiquiditySuperfluidPosition | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToConcentratedLiquiditySuperfluidPosition, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgAddToConcentratedLiquiditySuperfluidPositionResponse - */ -export class MsgAddToConcentratedLiquiditySuperfluidPositionResponse extends Message { - /** - * @generated from field: uint64 position_id = 1; - */ - positionId = protoInt64.zero; - - /** - * @generated from field: string amount0 = 2; - */ - amount0 = ""; - - /** - * @generated from field: string amount1 = 3; - */ - amount1 = ""; - - /** - * new_liquidity is the final liquidity after the add. - * It includes the liquidity that existed before in the position - * and the new liquidity that was added to the position. - * - * @generated from field: string new_liquidity = 5; - */ - newLiquidity = ""; - - /** - * @generated from field: uint64 lock_id = 4; - */ - lockId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgAddToConcentratedLiquiditySuperfluidPositionResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "position_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "amount0", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "amount1", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "new_liquidity", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPositionResponse { - return new MsgAddToConcentratedLiquiditySuperfluidPositionResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPositionResponse { - return new MsgAddToConcentratedLiquiditySuperfluidPositionResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgAddToConcentratedLiquiditySuperfluidPositionResponse { - return new MsgAddToConcentratedLiquiditySuperfluidPositionResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgAddToConcentratedLiquiditySuperfluidPositionResponse | PlainMessage | undefined, b: MsgAddToConcentratedLiquiditySuperfluidPositionResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgAddToConcentratedLiquiditySuperfluidPositionResponse, a, b); - } -} - -/** - * ===================== MsgUnbondConvertAndStake - * - * @generated from message osmosis.superfluid.MsgUnbondConvertAndStake - */ -export class MsgUnbondConvertAndStake extends Message { - /** - * lock ID to convert and stake. - * lock id with 0 should be provided if converting liquid gamm shares to stake - * - * @generated from field: uint64 lock_id = 1; - */ - lockId = protoInt64.zero; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - /** - * validator address to delegate to. - * If provided empty string, we use the validators returned from - * valset-preference module. - * - * @generated from field: string val_addr = 3; - */ - valAddr = ""; - - /** - * min_amt_to_stake indicates the minimum amount to stake after conversion - * - * @generated from field: string min_amt_to_stake = 4; - */ - minAmtToStake = ""; - - /** - * shares_to_convert indicates shares wanted to stake. - * Note that this field is only used for liquid(unlocked) gamm shares. - * For all other cases, this field would be disregarded. - * - * @generated from field: cosmos.base.v1beta1.Coin shares_to_convert = 5; - */ - sharesToConvert?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnbondConvertAndStake"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "lock_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "val_addr", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "min_amt_to_stake", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "shares_to_convert", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnbondConvertAndStake { - return new MsgUnbondConvertAndStake().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnbondConvertAndStake { - return new MsgUnbondConvertAndStake().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnbondConvertAndStake { - return new MsgUnbondConvertAndStake().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnbondConvertAndStake | PlainMessage | undefined, b: MsgUnbondConvertAndStake | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnbondConvertAndStake, a, b); - } -} - -/** - * @generated from message osmosis.superfluid.MsgUnbondConvertAndStakeResponse - */ -export class MsgUnbondConvertAndStakeResponse extends Message { - /** - * @generated from field: string total_amt_staked = 1; - */ - totalAmtStaked = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.MsgUnbondConvertAndStakeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "total_amt_staked", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUnbondConvertAndStakeResponse { - return new MsgUnbondConvertAndStakeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUnbondConvertAndStakeResponse { - return new MsgUnbondConvertAndStakeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUnbondConvertAndStakeResponse { - return new MsgUnbondConvertAndStakeResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUnbondConvertAndStakeResponse | PlainMessage | undefined, b: MsgUnbondConvertAndStakeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUnbondConvertAndStakeResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/superfluid/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/superfluid/v1beta1/gov_pb.ts deleted file mode 100644 index 32fe4ad65..000000000 --- a/packages/es/src/protobufs/osmosis/superfluid/v1beta1/gov_pb.ts +++ /dev/null @@ -1,171 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/superfluid/v1beta1/gov.proto (package osmosis.superfluid.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { SuperfluidAsset } from "../superfluid_pb.js"; - -/** - * SetSuperfluidAssetsProposal is a gov Content type to update the superfluid - * assets - * - * @generated from message osmosis.superfluid.v1beta1.SetSuperfluidAssetsProposal - */ -export class SetSuperfluidAssetsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.superfluid.SuperfluidAsset assets = 3; - */ - assets: SuperfluidAsset[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.v1beta1.SetSuperfluidAssetsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "assets", kind: "message", T: SuperfluidAsset, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): SetSuperfluidAssetsProposal { - return new SetSuperfluidAssetsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): SetSuperfluidAssetsProposal { - return new SetSuperfluidAssetsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): SetSuperfluidAssetsProposal { - return new SetSuperfluidAssetsProposal().fromJsonString(jsonString, options); - } - - static equals(a: SetSuperfluidAssetsProposal | PlainMessage | undefined, b: SetSuperfluidAssetsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(SetSuperfluidAssetsProposal, a, b); - } -} - -/** - * RemoveSuperfluidAssetsProposal is a gov Content type to remove the superfluid - * assets by denom - * - * @generated from message osmosis.superfluid.v1beta1.RemoveSuperfluidAssetsProposal - */ -export class RemoveSuperfluidAssetsProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated string superfluid_asset_denoms = 3; - */ - superfluidAssetDenoms: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.v1beta1.RemoveSuperfluidAssetsProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "superfluid_asset_denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): RemoveSuperfluidAssetsProposal { - return new RemoveSuperfluidAssetsProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): RemoveSuperfluidAssetsProposal { - return new RemoveSuperfluidAssetsProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): RemoveSuperfluidAssetsProposal { - return new RemoveSuperfluidAssetsProposal().fromJsonString(jsonString, options); - } - - static equals(a: RemoveSuperfluidAssetsProposal | PlainMessage | undefined, b: RemoveSuperfluidAssetsProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(RemoveSuperfluidAssetsProposal, a, b); - } -} - -/** - * UpdateUnpoolWhiteListProposal is a gov Content type to update the - * allowed list of pool ids. - * - * @generated from message osmosis.superfluid.v1beta1.UpdateUnpoolWhiteListProposal - */ -export class UpdateUnpoolWhiteListProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated uint64 ids = 3; - */ - ids: bigint[] = []; - - /** - * @generated from field: bool is_overwrite = 4; - */ - isOverwrite = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.superfluid.v1beta1.UpdateUnpoolWhiteListProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "ids", kind: "scalar", T: 4 /* ScalarType.UINT64 */, repeated: true }, - { no: 4, name: "is_overwrite", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdateUnpoolWhiteListProposal { - return new UpdateUnpoolWhiteListProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdateUnpoolWhiteListProposal { - return new UpdateUnpoolWhiteListProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdateUnpoolWhiteListProposal { - return new UpdateUnpoolWhiteListProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdateUnpoolWhiteListProposal | PlainMessage | undefined, b: UpdateUnpoolWhiteListProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdateUnpoolWhiteListProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/authorityMetadata_pb.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/authorityMetadata_pb.ts deleted file mode 100644 index 6c380500b..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/authorityMetadata_pb.ts +++ /dev/null @@ -1,51 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/authorityMetadata.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * DenomAuthorityMetadata specifies metadata for addresses that have specific - * capabilities over a token factory denom. Right now there is only one Admin - * permission, but is planned to be extended to the future. - * - * @generated from message osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata - */ -export class DenomAuthorityMetadata extends Message { - /** - * Can be empty for no admin, or a valid osmosis address - * - * @generated from field: string admin = 1; - */ - admin = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DenomAuthorityMetadata { - return new DenomAuthorityMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DenomAuthorityMetadata { - return new DenomAuthorityMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DenomAuthorityMetadata { - return new DenomAuthorityMetadata().fromJsonString(jsonString, options); - } - - static equals(a: DenomAuthorityMetadata | PlainMessage | undefined, b: DenomAuthorityMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(DenomAuthorityMetadata, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/genesis_pb.ts deleted file mode 100644 index 3d8d7b413..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,104 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/genesis.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { DenomAuthorityMetadata } from "./authorityMetadata_pb.js"; - -/** - * GenesisState defines the tokenfactory module's genesis state. - * - * @generated from message osmosis.tokenfactory.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: osmosis.tokenfactory.v1beta1.Params params = 1; - */ - params?: Params; - - /** - * @generated from field: repeated osmosis.tokenfactory.v1beta1.GenesisDenom factory_denoms = 2; - */ - factoryDenoms: GenesisDenom[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "factory_denoms", kind: "message", T: GenesisDenom, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * GenesisDenom defines a tokenfactory denom that is defined within genesis - * state. The structure contains DenomAuthorityMetadata which defines the - * denom's admin. - * - * @generated from message osmosis.tokenfactory.v1beta1.GenesisDenom - */ -export class GenesisDenom extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata authority_metadata = 2; - */ - authorityMetadata?: DenomAuthorityMetadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.GenesisDenom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "authority_metadata", kind: "message", T: DenomAuthorityMetadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisDenom { - return new GenesisDenom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisDenom { - return new GenesisDenom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisDenom { - return new GenesisDenom().fromJsonString(jsonString, options); - } - - static equals(a: GenesisDenom | PlainMessage | undefined, b: GenesisDenom | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisDenom, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/params_pb.ts deleted file mode 100644 index 9e5ba728a..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/params_pb.ts +++ /dev/null @@ -1,63 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/params.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * Params defines the parameters for the tokenfactory module. - * - * @generated from message osmosis.tokenfactory.v1beta1.Params - */ -export class Params extends Message { - /** - * DenomCreationFee defines the fee to be charged on the creation of a new - * denom. The fee is drawn from the MsgCreateDenom's sender account, and - * transferred to the community pool. - * - * @generated from field: repeated cosmos.base.v1beta1.Coin denom_creation_fee = 1; - */ - denomCreationFee: Coin[] = []; - - /** - * DenomCreationGasConsume defines the gas cost for creating a new denom. - * This is intended as a spam deterrence mechanism. - * - * See: https://github.com/CosmWasm/token-factory/issues/11 - * - * @generated from field: uint64 denom_creation_gas_consume = 2; - */ - denomCreationGasConsume = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom_creation_fee", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "denom_creation_gas_consume", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_cosmes.ts deleted file mode 100644 index cba79557f..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,77 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/query.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryAllBeforeSendHooksAddressesRequest, QueryAllBeforeSendHooksAddressesResponse, QueryBeforeSendHookAddressRequest, QueryBeforeSendHookAddressResponse, QueryDenomAuthorityMetadataRequest, QueryDenomAuthorityMetadataResponse, QueryDenomsFromCreatorRequest, QueryDenomsFromCreatorResponse, QueryParamsRequest, QueryParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.tokenfactory.v1beta1.Query"; - -/** - * Params defines a gRPC query method that returns the tokenfactory module's - * parameters. - * - * @generated from rpc osmosis.tokenfactory.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * DenomAuthorityMetadata defines a gRPC query method for fetching - * DenomAuthorityMetadata for a particular denom. - * - * @generated from rpc osmosis.tokenfactory.v1beta1.Query.DenomAuthorityMetadata - */ -export const QueryDenomAuthorityMetadataService = { - typeName: TYPE_NAME, - method: "DenomAuthorityMetadata", - Request: QueryDenomAuthorityMetadataRequest, - Response: QueryDenomAuthorityMetadataResponse, -} as const; - -/** - * DenomsFromCreator defines a gRPC query method for fetching all - * denominations created by a specific admin/creator. - * - * @generated from rpc osmosis.tokenfactory.v1beta1.Query.DenomsFromCreator - */ -export const QueryDenomsFromCreatorService = { - typeName: TYPE_NAME, - method: "DenomsFromCreator", - Request: QueryDenomsFromCreatorRequest, - Response: QueryDenomsFromCreatorResponse, -} as const; - -/** - * BeforeSendHookAddress defines a gRPC query method for - * getting the address registered for the before send hook. - * - * @generated from rpc osmosis.tokenfactory.v1beta1.Query.BeforeSendHookAddress - */ -export const QueryBeforeSendHookAddressService = { - typeName: TYPE_NAME, - method: "BeforeSendHookAddress", - Request: QueryBeforeSendHookAddressRequest, - Response: QueryBeforeSendHookAddressResponse, -} as const; - -/** - * AllBeforeSendHooksAddresses defines a gRPC query method for - * getting all addresses with before send hook registered. - * The response returns two arrays, an array with a list of denom and an array - * of before send hook addresses. The idx of denom corresponds to before send - * hook addresse's idx. - * - * @generated from rpc osmosis.tokenfactory.v1beta1.Query.AllBeforeSendHooksAddresses - */ -export const QueryAllBeforeSendHooksAddressesService = { - typeName: TYPE_NAME, - method: "AllBeforeSendHooksAddresses", - Request: QueryAllBeforeSendHooksAddressesRequest, - Response: QueryAllBeforeSendHooksAddressesResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_pb.ts deleted file mode 100644 index b5270c249..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/query_pb.ts +++ /dev/null @@ -1,398 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/query.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./params_pb.js"; -import { DenomAuthorityMetadata } from "./authorityMetadata_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: osmosis.tokenfactory.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryDenomAuthorityMetadataRequest defines the request structure for the - * DenomAuthorityMetadata gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest - */ -export class QueryDenomAuthorityMetadataRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomAuthorityMetadataRequest { - return new QueryDenomAuthorityMetadataRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomAuthorityMetadataRequest { - return new QueryDenomAuthorityMetadataRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomAuthorityMetadataRequest { - return new QueryDenomAuthorityMetadataRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomAuthorityMetadataRequest | PlainMessage | undefined, b: QueryDenomAuthorityMetadataRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomAuthorityMetadataRequest, a, b); - } -} - -/** - * QueryDenomAuthorityMetadataResponse defines the response structure for the - * DenomAuthorityMetadata gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse - */ -export class QueryDenomAuthorityMetadataResponse extends Message { - /** - * @generated from field: osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata authority_metadata = 1; - */ - authorityMetadata?: DenomAuthorityMetadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority_metadata", kind: "message", T: DenomAuthorityMetadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomAuthorityMetadataResponse { - return new QueryDenomAuthorityMetadataResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomAuthorityMetadataResponse { - return new QueryDenomAuthorityMetadataResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomAuthorityMetadataResponse { - return new QueryDenomAuthorityMetadataResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomAuthorityMetadataResponse | PlainMessage | undefined, b: QueryDenomAuthorityMetadataResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomAuthorityMetadataResponse, a, b); - } -} - -/** - * QueryDenomsFromCreatorRequest defines the request structure for the - * DenomsFromCreator gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest - */ -export class QueryDenomsFromCreatorRequest extends Message { - /** - * @generated from field: string creator = 1; - */ - creator = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomsFromCreatorRequest { - return new QueryDenomsFromCreatorRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomsFromCreatorRequest { - return new QueryDenomsFromCreatorRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomsFromCreatorRequest { - return new QueryDenomsFromCreatorRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomsFromCreatorRequest | PlainMessage | undefined, b: QueryDenomsFromCreatorRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomsFromCreatorRequest, a, b); - } -} - -/** - * QueryDenomsFromCreatorRequest defines the response structure for the - * DenomsFromCreator gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse - */ -export class QueryDenomsFromCreatorResponse extends Message { - /** - * @generated from field: repeated string denoms = 1; - */ - denoms: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomsFromCreatorResponse { - return new QueryDenomsFromCreatorResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomsFromCreatorResponse { - return new QueryDenomsFromCreatorResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomsFromCreatorResponse { - return new QueryDenomsFromCreatorResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomsFromCreatorResponse | PlainMessage | undefined, b: QueryDenomsFromCreatorResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomsFromCreatorResponse, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.QueryBeforeSendHookAddressRequest - */ -export class QueryBeforeSendHookAddressRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryBeforeSendHookAddressRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBeforeSendHookAddressRequest { - return new QueryBeforeSendHookAddressRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBeforeSendHookAddressRequest { - return new QueryBeforeSendHookAddressRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBeforeSendHookAddressRequest { - return new QueryBeforeSendHookAddressRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBeforeSendHookAddressRequest | PlainMessage | undefined, b: QueryBeforeSendHookAddressRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBeforeSendHookAddressRequest, a, b); - } -} - -/** - * QueryBeforeSendHookAddressResponse defines the response structure for the - * DenomBeforeSendHook gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryBeforeSendHookAddressResponse - */ -export class QueryBeforeSendHookAddressResponse extends Message { - /** - * @generated from field: string cosmwasm_address = 1; - */ - cosmwasmAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryBeforeSendHookAddressResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "cosmwasm_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBeforeSendHookAddressResponse { - return new QueryBeforeSendHookAddressResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBeforeSendHookAddressResponse { - return new QueryBeforeSendHookAddressResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBeforeSendHookAddressResponse { - return new QueryBeforeSendHookAddressResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBeforeSendHookAddressResponse | PlainMessage | undefined, b: QueryBeforeSendHookAddressResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBeforeSendHookAddressResponse, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.QueryAllBeforeSendHooksAddressesRequest - */ -export class QueryAllBeforeSendHooksAddressesRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryAllBeforeSendHooksAddressesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllBeforeSendHooksAddressesRequest { - return new QueryAllBeforeSendHooksAddressesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllBeforeSendHooksAddressesRequest { - return new QueryAllBeforeSendHooksAddressesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllBeforeSendHooksAddressesRequest { - return new QueryAllBeforeSendHooksAddressesRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllBeforeSendHooksAddressesRequest | PlainMessage | undefined, b: QueryAllBeforeSendHooksAddressesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllBeforeSendHooksAddressesRequest, a, b); - } -} - -/** - * QueryAllBeforeSendHooksAddressesResponse defines the response structure for - * the AllBeforeSendHooksAddresses gRPC query. - * - * @generated from message osmosis.tokenfactory.v1beta1.QueryAllBeforeSendHooksAddressesResponse - */ -export class QueryAllBeforeSendHooksAddressesResponse extends Message { - /** - * @generated from field: repeated string denoms = 1; - */ - denoms: string[] = []; - - /** - * @generated from field: repeated string before_send_hook_addresses = 2; - */ - beforeSendHookAddresses: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.QueryAllBeforeSendHooksAddressesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denoms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 2, name: "before_send_hook_addresses", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryAllBeforeSendHooksAddressesResponse { - return new QueryAllBeforeSendHooksAddressesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryAllBeforeSendHooksAddressesResponse { - return new QueryAllBeforeSendHooksAddressesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryAllBeforeSendHooksAddressesResponse { - return new QueryAllBeforeSendHooksAddressesResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryAllBeforeSendHooksAddressesResponse | PlainMessage | undefined, b: QueryAllBeforeSendHooksAddressesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryAllBeforeSendHooksAddressesResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_cosmes.ts deleted file mode 100644 index 662fc8e77..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,79 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/tx.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgBurn, MsgBurnResponse, MsgChangeAdmin, MsgChangeAdminResponse, MsgCreateDenom, MsgCreateDenomResponse, MsgForceTransfer, MsgForceTransferResponse, MsgMint, MsgMintResponse, MsgSetBeforeSendHook, MsgSetBeforeSendHookResponse, MsgSetDenomMetadata, MsgSetDenomMetadataResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.tokenfactory.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.CreateDenom - */ -export const MsgCreateDenomService = { - typeName: TYPE_NAME, - method: "CreateDenom", - Request: MsgCreateDenom, - Response: MsgCreateDenomResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.Mint - */ -export const MsgMintService = { - typeName: TYPE_NAME, - method: "Mint", - Request: MsgMint, - Response: MsgMintResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.Burn - */ -export const MsgBurnService = { - typeName: TYPE_NAME, - method: "Burn", - Request: MsgBurn, - Response: MsgBurnResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.ChangeAdmin - */ -export const MsgChangeAdminService = { - typeName: TYPE_NAME, - method: "ChangeAdmin", - Request: MsgChangeAdmin, - Response: MsgChangeAdminResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.SetDenomMetadata - */ -export const MsgSetDenomMetadataService = { - typeName: TYPE_NAME, - method: "SetDenomMetadata", - Request: MsgSetDenomMetadata, - Response: MsgSetDenomMetadataResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.SetBeforeSendHook - */ -export const MsgSetBeforeSendHookService = { - typeName: TYPE_NAME, - method: "SetBeforeSendHook", - Request: MsgSetBeforeSendHook, - Response: MsgSetBeforeSendHookResponse, -} as const; - -/** - * @generated from rpc osmosis.tokenfactory.v1beta1.Msg.ForceTransfer - */ -export const MsgForceTransferService = { - typeName: TYPE_NAME, - method: "ForceTransfer", - Request: MsgForceTransfer, - Response: MsgForceTransferResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_pb.ts deleted file mode 100644 index 288df3112..000000000 --- a/packages/es/src/protobufs/osmosis/tokenfactory/v1beta1/tx_pb.ts +++ /dev/null @@ -1,613 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/tokenfactory/v1beta1/tx.proto (package osmosis.tokenfactory.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; -import { Metadata } from "../../../cosmos/bank/v1beta1/bank_pb.js"; - -/** - * MsgCreateDenom defines the message structure for the CreateDenom gRPC service - * method. It allows an account to create a new denom. It requires a sender - * address and a sub denomination. The (sender_address, sub_denomination) tuple - * must be unique and cannot be reused. - * - * The resulting denom created is defined as - * . The resulting denom's admin is - * originally set to be the creator, but this can be changed later. The token - * denom does not indicate the current admin. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgCreateDenom - */ -export class MsgCreateDenom extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * subdenom can be up to 44 "alphanumeric" characters long. - * - * @generated from field: string subdenom = 2; - */ - subdenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgCreateDenom"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "subdenom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateDenom { - return new MsgCreateDenom().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateDenom { - return new MsgCreateDenom().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateDenom { - return new MsgCreateDenom().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateDenom | PlainMessage | undefined, b: MsgCreateDenom | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateDenom, a, b); - } -} - -/** - * MsgCreateDenomResponse is the return value of MsgCreateDenom - * It returns the full string of the newly created denom - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse - */ -export class MsgCreateDenomResponse extends Message { - /** - * @generated from field: string new_token_denom = 1; - */ - newTokenDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "new_token_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgCreateDenomResponse { - return new MsgCreateDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgCreateDenomResponse { - return new MsgCreateDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgCreateDenomResponse { - return new MsgCreateDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgCreateDenomResponse | PlainMessage | undefined, b: MsgCreateDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgCreateDenomResponse, a, b); - } -} - -/** - * MsgMint is the sdk.Msg type for allowing an admin account to mint - * more of a token. - * Only the admin of the token factory denom has permission to mint unless - * the denom does not have any admin. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgMint - */ -export class MsgMint extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin amount = 2; - */ - amount?: Coin; - - /** - * @generated from field: string mintToAddress = 3; - */ - mintToAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgMint"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount", kind: "message", T: Coin }, - { no: 3, name: "mintToAddress", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMint { - return new MsgMint().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMint { - return new MsgMint().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMint { - return new MsgMint().fromJsonString(jsonString, options); - } - - static equals(a: MsgMint | PlainMessage | undefined, b: MsgMint | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMint, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.MsgMintResponse - */ -export class MsgMintResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgMintResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgMintResponse { - return new MsgMintResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgMintResponse { - return new MsgMintResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgMintResponse { - return new MsgMintResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgMintResponse | PlainMessage | undefined, b: MsgMintResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgMintResponse, a, b); - } -} - -/** - * MsgBurn is the sdk.Msg type for allowing an admin account to burn - * a token. - * Only the admin of the token factory denom has permission to burn unless - * the denom does not have any admin. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgBurn - */ -export class MsgBurn extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin amount = 2; - */ - amount?: Coin; - - /** - * @generated from field: string burnFromAddress = 3; - */ - burnFromAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgBurn"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount", kind: "message", T: Coin }, - { no: 3, name: "burnFromAddress", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBurn { - return new MsgBurn().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBurn { - return new MsgBurn().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBurn { - return new MsgBurn().fromJsonString(jsonString, options); - } - - static equals(a: MsgBurn | PlainMessage | undefined, b: MsgBurn | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBurn, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.MsgBurnResponse - */ -export class MsgBurnResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgBurnResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgBurnResponse { - return new MsgBurnResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgBurnResponse { - return new MsgBurnResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgBurnResponse { - return new MsgBurnResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgBurnResponse | PlainMessage | undefined, b: MsgBurnResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgBurnResponse, a, b); - } -} - -/** - * MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign - * adminship of a denom to a new account - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgChangeAdmin - */ -export class MsgChangeAdmin extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * @generated from field: string new_admin = 3; - */ - newAdmin = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgChangeAdmin"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "new_admin", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChangeAdmin { - return new MsgChangeAdmin().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChangeAdmin { - return new MsgChangeAdmin().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChangeAdmin { - return new MsgChangeAdmin().fromJsonString(jsonString, options); - } - - static equals(a: MsgChangeAdmin | PlainMessage | undefined, b: MsgChangeAdmin | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChangeAdmin, a, b); - } -} - -/** - * MsgChangeAdminResponse defines the response structure for an executed - * MsgChangeAdmin message. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse - */ -export class MsgChangeAdminResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgChangeAdminResponse { - return new MsgChangeAdminResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgChangeAdminResponse { - return new MsgChangeAdminResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgChangeAdminResponse { - return new MsgChangeAdminResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgChangeAdminResponse | PlainMessage | undefined, b: MsgChangeAdminResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgChangeAdminResponse, a, b); - } -} - -/** - * MsgSetBeforeSendHook is the sdk.Msg type for allowing an admin account to - * assign a CosmWasm contract to call with a BeforeSend hook - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgSetBeforeSendHook - */ -export class MsgSetBeforeSendHook extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: string denom = 2; - */ - denom = ""; - - /** - * @generated from field: string cosmwasm_address = 3; - */ - cosmwasmAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgSetBeforeSendHook"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "cosmwasm_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetBeforeSendHook { - return new MsgSetBeforeSendHook().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetBeforeSendHook { - return new MsgSetBeforeSendHook().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetBeforeSendHook { - return new MsgSetBeforeSendHook().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetBeforeSendHook | PlainMessage | undefined, b: MsgSetBeforeSendHook | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetBeforeSendHook, a, b); - } -} - -/** - * MsgSetBeforeSendHookResponse defines the response structure for an executed - * MsgSetBeforeSendHook message. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgSetBeforeSendHookResponse - */ -export class MsgSetBeforeSendHookResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgSetBeforeSendHookResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetBeforeSendHookResponse { - return new MsgSetBeforeSendHookResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetBeforeSendHookResponse { - return new MsgSetBeforeSendHookResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetBeforeSendHookResponse { - return new MsgSetBeforeSendHookResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetBeforeSendHookResponse | PlainMessage | undefined, b: MsgSetBeforeSendHookResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetBeforeSendHookResponse, a, b); - } -} - -/** - * MsgSetDenomMetadata is the sdk.Msg type for allowing an admin account to set - * the denom's bank metadata - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata - */ -export class MsgSetDenomMetadata extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: cosmos.bank.v1beta1.Metadata metadata = 2; - */ - metadata?: Metadata; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "metadata", kind: "message", T: Metadata }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDenomMetadata { - return new MsgSetDenomMetadata().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDenomMetadata { - return new MsgSetDenomMetadata().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDenomMetadata { - return new MsgSetDenomMetadata().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDenomMetadata | PlainMessage | undefined, b: MsgSetDenomMetadata | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDenomMetadata, a, b); - } -} - -/** - * MsgSetDenomMetadataResponse defines the response structure for an executed - * MsgSetDenomMetadata message. - * - * @generated from message osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse - */ -export class MsgSetDenomMetadataResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetDenomMetadataResponse { - return new MsgSetDenomMetadataResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetDenomMetadataResponse { - return new MsgSetDenomMetadataResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetDenomMetadataResponse { - return new MsgSetDenomMetadataResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetDenomMetadataResponse | PlainMessage | undefined, b: MsgSetDenomMetadataResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetDenomMetadataResponse, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.MsgForceTransfer - */ -export class MsgForceTransfer extends Message { - /** - * @generated from field: string sender = 1; - */ - sender = ""; - - /** - * @generated from field: cosmos.base.v1beta1.Coin amount = 2; - */ - amount?: Coin; - - /** - * @generated from field: string transferFromAddress = 3; - */ - transferFromAddress = ""; - - /** - * @generated from field: string transferToAddress = 4; - */ - transferToAddress = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgForceTransfer"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "amount", kind: "message", T: Coin }, - { no: 3, name: "transferFromAddress", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "transferToAddress", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgForceTransfer { - return new MsgForceTransfer().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgForceTransfer { - return new MsgForceTransfer().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgForceTransfer { - return new MsgForceTransfer().fromJsonString(jsonString, options); - } - - static equals(a: MsgForceTransfer | PlainMessage | undefined, b: MsgForceTransfer | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgForceTransfer, a, b); - } -} - -/** - * @generated from message osmosis.tokenfactory.v1beta1.MsgForceTransferResponse - */ -export class MsgForceTransferResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.tokenfactory.v1beta1.MsgForceTransferResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgForceTransferResponse { - return new MsgForceTransferResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgForceTransferResponse { - return new MsgForceTransferResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgForceTransferResponse { - return new MsgForceTransferResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgForceTransferResponse | PlainMessage | undefined, b: MsgForceTransferResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgForceTransferResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/twap/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/twap/v1beta1/genesis_pb.ts deleted file mode 100644 index 6c1b1e7c5..000000000 --- a/packages/es/src/protobufs/osmosis/twap/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/twap/v1beta1/genesis.proto (package osmosis.twap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Duration, Message, proto3 } from "@bufbuild/protobuf"; -import { TwapRecord } from "./twap_record_pb.js"; - -/** - * Params holds parameters for the twap module - * - * @generated from message osmosis.twap.v1beta1.Params - */ -export class Params extends Message { - /** - * @generated from field: string prune_epoch_identifier = 1; - */ - pruneEpochIdentifier = ""; - - /** - * @generated from field: google.protobuf.Duration record_history_keep_period = 2; - */ - recordHistoryKeepPeriod?: Duration; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "prune_epoch_identifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "record_history_keep_period", kind: "message", T: Duration }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - -/** - * GenesisState defines the twap module's genesis state. - * - * @generated from message osmosis.twap.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * twaps is the collection of all twap records. - * - * @generated from field: repeated osmosis.twap.v1beta1.TwapRecord twaps = 1; - */ - twaps: TwapRecord[] = []; - - /** - * params is the container of twap parameters. - * - * @generated from field: osmosis.twap.v1beta1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "twaps", kind: "message", T: TwapRecord, repeated: true }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/twap/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/twap/v1beta1/query_cosmes.ts deleted file mode 100644 index 933b73f69..000000000 --- a/packages/es/src/protobufs/osmosis/twap/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,59 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/twap/v1beta1/query.proto (package osmosis.twap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { ArithmeticTwapRequest, ArithmeticTwapResponse, ArithmeticTwapToNowRequest, ArithmeticTwapToNowResponse, GeometricTwapRequest, GeometricTwapResponse, GeometricTwapToNowRequest, GeometricTwapToNowResponse, ParamsRequest, ParamsResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.twap.v1beta1.Query"; - -/** - * @generated from rpc osmosis.twap.v1beta1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: ParamsRequest, - Response: ParamsResponse, -} as const; - -/** - * @generated from rpc osmosis.twap.v1beta1.Query.ArithmeticTwap - */ -export const QueryArithmeticTwapService = { - typeName: TYPE_NAME, - method: "ArithmeticTwap", - Request: ArithmeticTwapRequest, - Response: ArithmeticTwapResponse, -} as const; - -/** - * @generated from rpc osmosis.twap.v1beta1.Query.ArithmeticTwapToNow - */ -export const QueryArithmeticTwapToNowService = { - typeName: TYPE_NAME, - method: "ArithmeticTwapToNow", - Request: ArithmeticTwapToNowRequest, - Response: ArithmeticTwapToNowResponse, -} as const; - -/** - * @generated from rpc osmosis.twap.v1beta1.Query.GeometricTwap - */ -export const QueryGeometricTwapService = { - typeName: TYPE_NAME, - method: "GeometricTwap", - Request: GeometricTwapRequest, - Response: GeometricTwapResponse, -} as const; - -/** - * @generated from rpc osmosis.twap.v1beta1.Query.GeometricTwapToNow - */ -export const QueryGeometricTwapToNowService = { - typeName: TYPE_NAME, - method: "GeometricTwapToNow", - Request: GeometricTwapToNowRequest, - Response: GeometricTwapToNowResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/twap/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/twap/v1beta1/query_pb.ts deleted file mode 100644 index c95096294..000000000 --- a/packages/es/src/protobufs/osmosis/twap/v1beta1/query_pb.ts +++ /dev/null @@ -1,457 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/twap/v1beta1/query.proto (package osmosis.twap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; - -/** - * @generated from message osmosis.twap.v1beta1.ArithmeticTwapRequest - */ -export class ArithmeticTwapRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset = 2; - */ - baseAsset = ""; - - /** - * @generated from field: string quote_asset = 3; - */ - quoteAsset = ""; - - /** - * @generated from field: google.protobuf.Timestamp start_time = 4; - */ - startTime?: Timestamp; - - /** - * @generated from field: google.protobuf.Timestamp end_time = 5; - */ - endTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ArithmeticTwapRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "start_time", kind: "message", T: Timestamp }, - { no: 5, name: "end_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ArithmeticTwapRequest { - return new ArithmeticTwapRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ArithmeticTwapRequest { - return new ArithmeticTwapRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ArithmeticTwapRequest { - return new ArithmeticTwapRequest().fromJsonString(jsonString, options); - } - - static equals(a: ArithmeticTwapRequest | PlainMessage | undefined, b: ArithmeticTwapRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ArithmeticTwapRequest, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.ArithmeticTwapResponse - */ -export class ArithmeticTwapResponse extends Message { - /** - * @generated from field: string arithmetic_twap = 1; - */ - arithmeticTwap = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ArithmeticTwapResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "arithmetic_twap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ArithmeticTwapResponse { - return new ArithmeticTwapResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ArithmeticTwapResponse { - return new ArithmeticTwapResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ArithmeticTwapResponse { - return new ArithmeticTwapResponse().fromJsonString(jsonString, options); - } - - static equals(a: ArithmeticTwapResponse | PlainMessage | undefined, b: ArithmeticTwapResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ArithmeticTwapResponse, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.ArithmeticTwapToNowRequest - */ -export class ArithmeticTwapToNowRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset = 2; - */ - baseAsset = ""; - - /** - * @generated from field: string quote_asset = 3; - */ - quoteAsset = ""; - - /** - * @generated from field: google.protobuf.Timestamp start_time = 4; - */ - startTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ArithmeticTwapToNowRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "start_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ArithmeticTwapToNowRequest { - return new ArithmeticTwapToNowRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ArithmeticTwapToNowRequest { - return new ArithmeticTwapToNowRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ArithmeticTwapToNowRequest { - return new ArithmeticTwapToNowRequest().fromJsonString(jsonString, options); - } - - static equals(a: ArithmeticTwapToNowRequest | PlainMessage | undefined, b: ArithmeticTwapToNowRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ArithmeticTwapToNowRequest, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.ArithmeticTwapToNowResponse - */ -export class ArithmeticTwapToNowResponse extends Message { - /** - * @generated from field: string arithmetic_twap = 1; - */ - arithmeticTwap = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ArithmeticTwapToNowResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "arithmetic_twap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ArithmeticTwapToNowResponse { - return new ArithmeticTwapToNowResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ArithmeticTwapToNowResponse { - return new ArithmeticTwapToNowResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ArithmeticTwapToNowResponse { - return new ArithmeticTwapToNowResponse().fromJsonString(jsonString, options); - } - - static equals(a: ArithmeticTwapToNowResponse | PlainMessage | undefined, b: ArithmeticTwapToNowResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ArithmeticTwapToNowResponse, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.GeometricTwapRequest - */ -export class GeometricTwapRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset = 2; - */ - baseAsset = ""; - - /** - * @generated from field: string quote_asset = 3; - */ - quoteAsset = ""; - - /** - * @generated from field: google.protobuf.Timestamp start_time = 4; - */ - startTime?: Timestamp; - - /** - * @generated from field: google.protobuf.Timestamp end_time = 5; - */ - endTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.GeometricTwapRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "start_time", kind: "message", T: Timestamp }, - { no: 5, name: "end_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GeometricTwapRequest { - return new GeometricTwapRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GeometricTwapRequest { - return new GeometricTwapRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GeometricTwapRequest { - return new GeometricTwapRequest().fromJsonString(jsonString, options); - } - - static equals(a: GeometricTwapRequest | PlainMessage | undefined, b: GeometricTwapRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GeometricTwapRequest, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.GeometricTwapResponse - */ -export class GeometricTwapResponse extends Message { - /** - * @generated from field: string geometric_twap = 1; - */ - geometricTwap = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.GeometricTwapResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "geometric_twap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GeometricTwapResponse { - return new GeometricTwapResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GeometricTwapResponse { - return new GeometricTwapResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GeometricTwapResponse { - return new GeometricTwapResponse().fromJsonString(jsonString, options); - } - - static equals(a: GeometricTwapResponse | PlainMessage | undefined, b: GeometricTwapResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GeometricTwapResponse, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.GeometricTwapToNowRequest - */ -export class GeometricTwapToNowRequest extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * @generated from field: string base_asset = 2; - */ - baseAsset = ""; - - /** - * @generated from field: string quote_asset = 3; - */ - quoteAsset = ""; - - /** - * @generated from field: google.protobuf.Timestamp start_time = 4; - */ - startTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.GeometricTwapToNowRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "base_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "quote_asset", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "start_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GeometricTwapToNowRequest { - return new GeometricTwapToNowRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GeometricTwapToNowRequest { - return new GeometricTwapToNowRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GeometricTwapToNowRequest { - return new GeometricTwapToNowRequest().fromJsonString(jsonString, options); - } - - static equals(a: GeometricTwapToNowRequest | PlainMessage | undefined, b: GeometricTwapToNowRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(GeometricTwapToNowRequest, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.GeometricTwapToNowResponse - */ -export class GeometricTwapToNowResponse extends Message { - /** - * @generated from field: string geometric_twap = 1; - */ - geometricTwap = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.GeometricTwapToNowResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "geometric_twap", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GeometricTwapToNowResponse { - return new GeometricTwapToNowResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GeometricTwapToNowResponse { - return new GeometricTwapToNowResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GeometricTwapToNowResponse { - return new GeometricTwapToNowResponse().fromJsonString(jsonString, options); - } - - static equals(a: GeometricTwapToNowResponse | PlainMessage | undefined, b: GeometricTwapToNowResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(GeometricTwapToNowResponse, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.ParamsRequest - */ -export class ParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsRequest { - return new ParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsRequest { - return new ParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: ParamsRequest | PlainMessage | undefined, b: ParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsRequest, a, b); - } -} - -/** - * @generated from message osmosis.twap.v1beta1.ParamsResponse - */ -export class ParamsResponse extends Message { - /** - * @generated from field: osmosis.twap.v1beta1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.ParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ParamsResponse { - return new ParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ParamsResponse { - return new ParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: ParamsResponse | PlainMessage | undefined, b: ParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(ParamsResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/twap/v1beta1/twap_record_pb.ts b/packages/es/src/protobufs/osmosis/twap/v1beta1/twap_record_pb.ts deleted file mode 100644 index de6a1fc57..000000000 --- a/packages/es/src/protobufs/osmosis/twap/v1beta1/twap_record_pb.ts +++ /dev/null @@ -1,203 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/twap/v1beta1/twap_record.proto (package osmosis.twap.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * A TWAP record should be indexed in state by pool_id, (asset pair), timestamp - * The asset pair assets should be lexicographically sorted. - * Technically (pool_id, asset_0_denom, asset_1_denom, height) do not need to - * appear in the struct however we view this as the wrong performance tradeoff - * given SDK today. Would rather we optimize for readability and correctness, - * than an optimal state storage format. The system bottleneck is elsewhere for - * now. - * - * @generated from message osmosis.twap.v1beta1.TwapRecord - */ -export class TwapRecord extends Message { - /** - * @generated from field: uint64 pool_id = 1; - */ - poolId = protoInt64.zero; - - /** - * Lexicographically smaller denom of the pair - * - * @generated from field: string asset0_denom = 2; - */ - asset0Denom = ""; - - /** - * Lexicographically larger denom of the pair - * - * @generated from field: string asset1_denom = 3; - */ - asset1Denom = ""; - - /** - * height this record corresponds to, for debugging purposes - * - * @generated from field: int64 height = 4; - */ - height = protoInt64.zero; - - /** - * This field should only exist until we have a global registry in the state - * machine, mapping prior block heights within {TIME RANGE} to times. - * - * @generated from field: google.protobuf.Timestamp time = 5; - */ - time?: Timestamp; - - /** - * We store the last spot prices in the struct, so that we can interpolate - * accumulator values for times between when accumulator records are stored. - * - * @generated from field: string p0_last_spot_price = 6; - */ - p0LastSpotPrice = ""; - - /** - * @generated from field: string p1_last_spot_price = 7; - */ - p1LastSpotPrice = ""; - - /** - * @generated from field: string p0_arithmetic_twap_accumulator = 8; - */ - p0ArithmeticTwapAccumulator = ""; - - /** - * @generated from field: string p1_arithmetic_twap_accumulator = 9; - */ - p1ArithmeticTwapAccumulator = ""; - - /** - * @generated from field: string geometric_twap_accumulator = 10; - */ - geometricTwapAccumulator = ""; - - /** - * This field contains the time in which the last spot price error occurred. - * It is used to alert the caller if they are getting a potentially erroneous - * TWAP, due to an unforeseen underlying error. - * - * @generated from field: google.protobuf.Timestamp last_error_time = 11; - */ - lastErrorTime?: Timestamp; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.TwapRecord"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "asset0_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "asset1_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "height", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "time", kind: "message", T: Timestamp }, - { no: 6, name: "p0_last_spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "p1_last_spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "p0_arithmetic_twap_accumulator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "p1_arithmetic_twap_accumulator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 10, name: "geometric_twap_accumulator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 11, name: "last_error_time", kind: "message", T: Timestamp }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TwapRecord { - return new TwapRecord().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TwapRecord { - return new TwapRecord().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TwapRecord { - return new TwapRecord().fromJsonString(jsonString, options); - } - - static equals(a: TwapRecord | PlainMessage | undefined, b: TwapRecord | PlainMessage | undefined): boolean { - return proto3.util.equals(TwapRecord, a, b); - } -} - -/** - * PruningState allows us to spread out the pruning of TWAP records over time, - * instead of pruning all at once at the end of the epoch. - * - * @generated from message osmosis.twap.v1beta1.PruningState - */ -export class PruningState extends Message { - /** - * is_pruning is true if the pruning process is ongoing. - * This tells the module to continue pruning the TWAP records - * at the EndBlock. - * - * @generated from field: bool is_pruning = 1; - */ - isPruning = false; - - /** - * last_kept_time is the time of the last kept TWAP record. - * This is used to determine all TWAP records that are older than - * last_kept_time and should be pruned. - * - * @generated from field: google.protobuf.Timestamp last_kept_time = 2; - */ - lastKeptTime?: Timestamp; - - /** - * Deprecated: This field is deprecated. - * - * @generated from field: bytes last_key_seen = 3 [deprecated = true]; - * @deprecated - */ - lastKeySeen = new Uint8Array(0); - - /** - * last_seen_pool_id is the pool_id that we will begin pruning in the next - * block. This value starts at the highest pool_id at time of epoch, and - * decreases until it reaches 1. When it reaches 1, the pruning - * process is complete. - * - * @generated from field: uint64 last_seen_pool_id = 4; - */ - lastSeenPoolId = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.twap.v1beta1.PruningState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "is_pruning", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "last_kept_time", kind: "message", T: Timestamp }, - { no: 3, name: "last_key_seen", kind: "scalar", T: 12 /* ScalarType.BYTES */ }, - { no: 4, name: "last_seen_pool_id", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): PruningState { - return new PruningState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): PruningState { - return new PruningState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): PruningState { - return new PruningState().fromJsonString(jsonString, options); - } - - static equals(a: PruningState | PlainMessage | undefined, b: PruningState | PlainMessage | undefined): boolean { - return proto3.util.equals(PruningState, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/feetoken_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/feetoken_pb.ts deleted file mode 100644 index 7c25c04c6..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/feetoken_pb.ts +++ /dev/null @@ -1,56 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/feetoken.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * FeeToken is a struct that specifies a coin denom, and pool ID pair. - * This marks the token as eligible for use as a tx fee asset in Osmosis. - * Its price in osmo is derived through looking at the provided pool ID. - * The pool ID must have osmo as one of its assets. - * - * @generated from message osmosis.txfees.v1beta1.FeeToken - */ -export class FeeToken extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - /** - * @generated from field: uint64 poolID = 2; - */ - poolID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.FeeToken"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "poolID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): FeeToken { - return new FeeToken().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): FeeToken { - return new FeeToken().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): FeeToken { - return new FeeToken().fromJsonString(jsonString, options); - } - - static equals(a: FeeToken | PlainMessage | undefined, b: FeeToken | PlainMessage | undefined): boolean { - return proto3.util.equals(FeeToken, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/genesis_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/genesis_pb.ts deleted file mode 100644 index a84ee0479..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/genesis_pb.ts +++ /dev/null @@ -1,116 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/genesis.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { FeeToken } from "./feetoken_pb.js"; -import { Params } from "./params_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * GenesisState defines the txfees module's genesis state. - * - * @generated from message osmosis.txfees.v1beta1.GenesisState - */ -export class GenesisState extends Message { - /** - * @generated from field: string basedenom = 1; - */ - basedenom = ""; - - /** - * @generated from field: repeated osmosis.txfees.v1beta1.FeeToken feetokens = 2; - */ - feetokens: FeeToken[] = []; - - /** - * DEPRECATED - * - * @generated from field: osmosis.txfees.v1beta1.TxFeesTracker txFeesTracker = 3 [deprecated = true]; - * @deprecated - */ - txFeesTracker?: TxFeesTracker; - - /** - * params is the container of txfees parameters. - * - * @generated from field: osmosis.txfees.v1beta1.Params params = 4; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "basedenom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "feetokens", kind: "message", T: FeeToken, repeated: true }, - { no: 3, name: "txFeesTracker", kind: "message", T: TxFeesTracker }, - { no: 4, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.TxFeesTracker - */ -export class TxFeesTracker extends Message { - /** - * @generated from field: repeated cosmos.base.v1beta1.Coin tx_fees = 1; - */ - txFees: Coin[] = []; - - /** - * @generated from field: int64 height_accounting_starts_from = 2; - */ - heightAccountingStartsFrom = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.TxFeesTracker"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "tx_fees", kind: "message", T: Coin, repeated: true }, - { no: 2, name: "height_accounting_starts_from", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): TxFeesTracker { - return new TxFeesTracker().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): TxFeesTracker { - return new TxFeesTracker().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): TxFeesTracker { - return new TxFeesTracker().fromJsonString(jsonString, options); - } - - static equals(a: TxFeesTracker | PlainMessage | undefined, b: TxFeesTracker | PlainMessage | undefined): boolean { - return proto3.util.equals(TxFeesTracker, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/gov_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/gov_pb.ts deleted file mode 100644 index e3f445cdf..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/gov_pb.ts +++ /dev/null @@ -1,64 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/gov.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { FeeToken } from "./feetoken_pb.js"; - -/** - * UpdateFeeTokenProposal is a gov Content type for adding new whitelisted fee - * token(s). It must specify a denom along with gamm pool ID to use as a spot - * price calculator. It can be used to add new denoms to the whitelist. It can - * also be used to update the Pool to associate with the denom. If Pool ID is - * set to 0, it will remove the denom from the whitelisted set. - * - * @generated from message osmosis.txfees.v1beta1.UpdateFeeTokenProposal - */ -export class UpdateFeeTokenProposal extends Message { - /** - * @generated from field: string title = 1; - */ - title = ""; - - /** - * @generated from field: string description = 2; - */ - description = ""; - - /** - * @generated from field: repeated osmosis.txfees.v1beta1.FeeToken feetokens = 3; - */ - feetokens: FeeToken[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.UpdateFeeTokenProposal"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "title", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "description", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "feetokens", kind: "message", T: FeeToken, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UpdateFeeTokenProposal { - return new UpdateFeeTokenProposal().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UpdateFeeTokenProposal { - return new UpdateFeeTokenProposal().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UpdateFeeTokenProposal { - return new UpdateFeeTokenProposal().fromJsonString(jsonString, options); - } - - static equals(a: UpdateFeeTokenProposal | PlainMessage | undefined, b: UpdateFeeTokenProposal | PlainMessage | undefined): boolean { - return proto3.util.equals(UpdateFeeTokenProposal, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/params_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/params_pb.ts deleted file mode 100644 index 9c5892e92..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/params_pb.ts +++ /dev/null @@ -1,47 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/params.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Params holds parameters for the txfees module - * - * @generated from message osmosis.txfees.v1beta1.Params - */ -export class Params extends Message { - /** - * @generated from field: repeated string whitelisted_fee_token_setters = 1; - */ - whitelistedFeeTokenSetters: string[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "whitelisted_fee_token_setters", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_cosmes.ts deleted file mode 100644 index 1d9ad8003..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,71 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/query.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryBaseDenomRequest, QueryBaseDenomResponse, QueryDenomPoolIdRequest, QueryDenomPoolIdResponse, QueryDenomSpotPriceRequest, QueryDenomSpotPriceResponse, QueryEipBaseFeeRequest, QueryEipBaseFeeResponse, QueryFeeTokensRequest, QueryFeeTokensResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.txfees.v1beta1.Query"; - -/** - * FeeTokens returns a list of all the whitelisted fee tokens and their - * corresponding pools. It does not include the BaseDenom, which has its own - * query endpoint - * - * @generated from rpc osmosis.txfees.v1beta1.Query.FeeTokens - */ -export const QueryFeeTokensService = { - typeName: TYPE_NAME, - method: "FeeTokens", - Request: QueryFeeTokensRequest, - Response: QueryFeeTokensResponse, -} as const; - -/** - * DenomSpotPrice returns all spot prices by each registered token denom. - * - * @generated from rpc osmosis.txfees.v1beta1.Query.DenomSpotPrice - */ -export const QueryDenomSpotPriceService = { - typeName: TYPE_NAME, - method: "DenomSpotPrice", - Request: QueryDenomSpotPriceRequest, - Response: QueryDenomSpotPriceResponse, -} as const; - -/** - * Returns the poolID for a specified denom input. - * - * @generated from rpc osmosis.txfees.v1beta1.Query.DenomPoolId - */ -export const QueryDenomPoolIdService = { - typeName: TYPE_NAME, - method: "DenomPoolId", - Request: QueryDenomPoolIdRequest, - Response: QueryDenomPoolIdResponse, -} as const; - -/** - * Returns a list of all base denom tokens and their corresponding pools. - * - * @generated from rpc osmosis.txfees.v1beta1.Query.BaseDenom - */ -export const QueryBaseDenomService = { - typeName: TYPE_NAME, - method: "BaseDenom", - Request: QueryBaseDenomRequest, - Response: QueryBaseDenomResponse, -} as const; - -/** - * Returns a list of all base denom tokens and their corresponding pools. - * - * @generated from rpc osmosis.txfees.v1beta1.Query.GetEipBaseFee - */ -export const QueryGetEipBaseFeeService = { - typeName: TYPE_NAME, - method: "GetEipBaseFee", - Request: QueryEipBaseFeeRequest, - Response: QueryEipBaseFeeResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_pb.ts deleted file mode 100644 index 0bd46e6c1..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/query_pb.ts +++ /dev/null @@ -1,373 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/query.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { FeeToken } from "./feetoken_pb.js"; - -/** - * @generated from message osmosis.txfees.v1beta1.QueryFeeTokensRequest - */ -export class QueryFeeTokensRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryFeeTokensRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryFeeTokensRequest { - return new QueryFeeTokensRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryFeeTokensRequest { - return new QueryFeeTokensRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryFeeTokensRequest { - return new QueryFeeTokensRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryFeeTokensRequest | PlainMessage | undefined, b: QueryFeeTokensRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryFeeTokensRequest, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryFeeTokensResponse - */ -export class QueryFeeTokensResponse extends Message { - /** - * @generated from field: repeated osmosis.txfees.v1beta1.FeeToken fee_tokens = 1; - */ - feeTokens: FeeToken[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryFeeTokensResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "fee_tokens", kind: "message", T: FeeToken, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryFeeTokensResponse { - return new QueryFeeTokensResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryFeeTokensResponse { - return new QueryFeeTokensResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryFeeTokensResponse { - return new QueryFeeTokensResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryFeeTokensResponse | PlainMessage | undefined, b: QueryFeeTokensResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryFeeTokensResponse, a, b); - } -} - -/** - * QueryDenomSpotPriceRequest defines grpc request structure for querying spot - * price for the specified tx fee denom - * - * @generated from message osmosis.txfees.v1beta1.QueryDenomSpotPriceRequest - */ -export class QueryDenomSpotPriceRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryDenomSpotPriceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomSpotPriceRequest { - return new QueryDenomSpotPriceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomSpotPriceRequest { - return new QueryDenomSpotPriceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomSpotPriceRequest { - return new QueryDenomSpotPriceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomSpotPriceRequest | PlainMessage | undefined, b: QueryDenomSpotPriceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomSpotPriceRequest, a, b); - } -} - -/** - * QueryDenomSpotPriceRequest defines grpc response structure for querying spot - * price for the specified tx fee denom - * - * @generated from message osmosis.txfees.v1beta1.QueryDenomSpotPriceResponse - */ -export class QueryDenomSpotPriceResponse extends Message { - /** - * @generated from field: uint64 poolID = 1; - */ - poolID = protoInt64.zero; - - /** - * @generated from field: string spot_price = 2; - */ - spotPrice = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryDenomSpotPriceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "poolID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - { no: 2, name: "spot_price", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomSpotPriceResponse { - return new QueryDenomSpotPriceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomSpotPriceResponse { - return new QueryDenomSpotPriceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomSpotPriceResponse { - return new QueryDenomSpotPriceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomSpotPriceResponse | PlainMessage | undefined, b: QueryDenomSpotPriceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomSpotPriceResponse, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryDenomPoolIdRequest - */ -export class QueryDenomPoolIdRequest extends Message { - /** - * @generated from field: string denom = 1; - */ - denom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryDenomPoolIdRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomPoolIdRequest { - return new QueryDenomPoolIdRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomPoolIdRequest { - return new QueryDenomPoolIdRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomPoolIdRequest { - return new QueryDenomPoolIdRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomPoolIdRequest | PlainMessage | undefined, b: QueryDenomPoolIdRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomPoolIdRequest, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryDenomPoolIdResponse - */ -export class QueryDenomPoolIdResponse extends Message { - /** - * @generated from field: uint64 poolID = 1; - */ - poolID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryDenomPoolIdResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "poolID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDenomPoolIdResponse { - return new QueryDenomPoolIdResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDenomPoolIdResponse { - return new QueryDenomPoolIdResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDenomPoolIdResponse { - return new QueryDenomPoolIdResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDenomPoolIdResponse | PlainMessage | undefined, b: QueryDenomPoolIdResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDenomPoolIdResponse, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryBaseDenomRequest - */ -export class QueryBaseDenomRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryBaseDenomRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseDenomRequest { - return new QueryBaseDenomRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseDenomRequest { - return new QueryBaseDenomRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseDenomRequest { - return new QueryBaseDenomRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseDenomRequest | PlainMessage | undefined, b: QueryBaseDenomRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseDenomRequest, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryBaseDenomResponse - */ -export class QueryBaseDenomResponse extends Message { - /** - * @generated from field: string base_denom = 1; - */ - baseDenom = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryBaseDenomResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_denom", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryBaseDenomResponse { - return new QueryBaseDenomResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryBaseDenomResponse { - return new QueryBaseDenomResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryBaseDenomResponse { - return new QueryBaseDenomResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryBaseDenomResponse | PlainMessage | undefined, b: QueryBaseDenomResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryBaseDenomResponse, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryEipBaseFeeRequest - */ -export class QueryEipBaseFeeRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryEipBaseFeeRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEipBaseFeeRequest { - return new QueryEipBaseFeeRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEipBaseFeeRequest { - return new QueryEipBaseFeeRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEipBaseFeeRequest { - return new QueryEipBaseFeeRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryEipBaseFeeRequest | PlainMessage | undefined, b: QueryEipBaseFeeRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEipBaseFeeRequest, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.QueryEipBaseFeeResponse - */ -export class QueryEipBaseFeeResponse extends Message { - /** - * @generated from field: string base_fee = 1; - */ - baseFee = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.QueryEipBaseFeeResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "base_fee", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryEipBaseFeeResponse { - return new QueryEipBaseFeeResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryEipBaseFeeResponse { - return new QueryEipBaseFeeResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryEipBaseFeeResponse { - return new QueryEipBaseFeeResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryEipBaseFeeResponse | PlainMessage | undefined, b: QueryEipBaseFeeResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryEipBaseFeeResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_cosmes.ts deleted file mode 100644 index 0d2735cb4..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/tx.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgSetFeeTokens, MsgSetFeeTokensResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.txfees.v1beta1.Msg"; - -/** - * @generated from rpc osmosis.txfees.v1beta1.Msg.SetFeeTokens - */ -export const MsgSetFeeTokensService = { - typeName: TYPE_NAME, - method: "SetFeeTokens", - Request: MsgSetFeeTokens, - Response: MsgSetFeeTokensResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_pb.ts deleted file mode 100644 index a90e448a7..000000000 --- a/packages/es/src/protobufs/osmosis/txfees/v1beta1/tx_pb.ts +++ /dev/null @@ -1,85 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/txfees/v1beta1/tx.proto (package osmosis.txfees.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { FeeToken } from "./feetoken_pb.js"; - -/** - * ===================== MsgSetFeeTokens - * - * @generated from message osmosis.txfees.v1beta1.MsgSetFeeTokens - */ -export class MsgSetFeeTokens extends Message { - /** - * @generated from field: repeated osmosis.txfees.v1beta1.FeeToken fee_tokens = 1; - */ - feeTokens: FeeToken[] = []; - - /** - * @generated from field: string sender = 2; - */ - sender = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.MsgSetFeeTokens"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "fee_tokens", kind: "message", T: FeeToken, repeated: true }, - { no: 2, name: "sender", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetFeeTokens { - return new MsgSetFeeTokens().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetFeeTokens { - return new MsgSetFeeTokens().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetFeeTokens { - return new MsgSetFeeTokens().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetFeeTokens | PlainMessage | undefined, b: MsgSetFeeTokens | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetFeeTokens, a, b); - } -} - -/** - * @generated from message osmosis.txfees.v1beta1.MsgSetFeeTokensResponse - */ -export class MsgSetFeeTokensResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.txfees.v1beta1.MsgSetFeeTokensResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetFeeTokensResponse { - return new MsgSetFeeTokensResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetFeeTokensResponse { - return new MsgSetFeeTokensResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetFeeTokensResponse { - return new MsgSetFeeTokensResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetFeeTokensResponse | PlainMessage | undefined, b: MsgSetFeeTokensResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetFeeTokensResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_cosmes.ts b/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_cosmes.ts deleted file mode 100644 index 7746b7f6e..000000000 --- a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_cosmes.ts +++ /dev/null @@ -1,21 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/valsetpref/v1beta1/query.proto (package osmosis.valsetpref.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { UserValidatorPreferencesRequest, UserValidatorPreferencesResponse } from "./query_pb.js"; - -const TYPE_NAME = "osmosis.valsetpref.v1beta1.Query"; - -/** - * Returns the list of ValidatorPreferences for the user. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Query.UserValidatorPreferences - */ -export const QueryUserValidatorPreferencesService = { - typeName: TYPE_NAME, - method: "UserValidatorPreferences", - Request: UserValidatorPreferencesRequest, - Response: UserValidatorPreferencesResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_pb.ts b/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_pb.ts deleted file mode 100644 index 8b7427c21..000000000 --- a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/query_pb.ts +++ /dev/null @@ -1,89 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/valsetpref/v1beta1/query.proto (package osmosis.valsetpref.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { ValidatorPreference } from "./state_pb.js"; - -/** - * Request type for UserValidatorPreferences. - * - * @generated from message osmosis.valsetpref.v1beta1.UserValidatorPreferencesRequest - */ -export class UserValidatorPreferencesRequest extends Message { - /** - * user account address - * - * @generated from field: string address = 1; - */ - address = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.UserValidatorPreferencesRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserValidatorPreferencesRequest { - return new UserValidatorPreferencesRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserValidatorPreferencesRequest { - return new UserValidatorPreferencesRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserValidatorPreferencesRequest { - return new UserValidatorPreferencesRequest().fromJsonString(jsonString, options); - } - - static equals(a: UserValidatorPreferencesRequest | PlainMessage | undefined, b: UserValidatorPreferencesRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(UserValidatorPreferencesRequest, a, b); - } -} - -/** - * Response type the QueryUserValidatorPreferences query request - * - * @generated from message osmosis.valsetpref.v1beta1.UserValidatorPreferencesResponse - */ -export class UserValidatorPreferencesResponse extends Message { - /** - * @generated from field: repeated osmosis.valsetpref.v1beta1.ValidatorPreference preferences = 1; - */ - preferences: ValidatorPreference[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.UserValidatorPreferencesResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "preferences", kind: "message", T: ValidatorPreference, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): UserValidatorPreferencesResponse { - return new UserValidatorPreferencesResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): UserValidatorPreferencesResponse { - return new UserValidatorPreferencesResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): UserValidatorPreferencesResponse { - return new UserValidatorPreferencesResponse().fromJsonString(jsonString, options); - } - - static equals(a: UserValidatorPreferencesResponse | PlainMessage | undefined, b: UserValidatorPreferencesResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(UserValidatorPreferencesResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/state_pb.ts b/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/state_pb.ts deleted file mode 100644 index eded5cce5..000000000 --- a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/state_pb.ts +++ /dev/null @@ -1,106 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/valsetpref/v1beta1/state.proto (package osmosis.valsetpref.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * ValidatorPreference defines the message structure for - * CreateValidatorSetPreference. It allows a user to set {val_addr, weight} in - * state. If a user does not have a validator set preference list set, and has - * staked, make their preference list default to their current staking - * distribution. - * - * @generated from message osmosis.valsetpref.v1beta1.ValidatorPreference - */ -export class ValidatorPreference extends Message { - /** - * val_oper_address holds the validator address the user wants to delegate - * funds to. - * - * @generated from field: string val_oper_address = 1; - */ - valOperAddress = ""; - - /** - * weight is decimal between 0 and 1, and they all sum to 1. - * - * @generated from field: string weight = 2; - */ - weight = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.ValidatorPreference"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "val_oper_address", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "weight", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ValidatorPreference { - return new ValidatorPreference().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ValidatorPreference { - return new ValidatorPreference().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ValidatorPreference { - return new ValidatorPreference().fromJsonString(jsonString, options); - } - - static equals(a: ValidatorPreference | PlainMessage | undefined, b: ValidatorPreference | PlainMessage | undefined): boolean { - return proto3.util.equals(ValidatorPreference, a, b); - } -} - -/** - * ValidatorSetPreferences defines a delegator's validator set preference. - * It contains a list of (validator, percent_allocation) pairs. - * The percent allocation are arranged in decimal notation from 0 to 1 and must - * add up to 1. - * - * @generated from message osmosis.valsetpref.v1beta1.ValidatorSetPreferences - */ -export class ValidatorSetPreferences extends Message { - /** - * preference holds {valAddr, weight} for the user who created it. - * - * @generated from field: repeated osmosis.valsetpref.v1beta1.ValidatorPreference preferences = 2; - */ - preferences: ValidatorPreference[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.ValidatorSetPreferences"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 2, name: "preferences", kind: "message", T: ValidatorPreference, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ValidatorSetPreferences { - return new ValidatorSetPreferences().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ValidatorSetPreferences { - return new ValidatorSetPreferences().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ValidatorSetPreferences { - return new ValidatorSetPreferences().fromJsonString(jsonString, options); - } - - static equals(a: ValidatorSetPreferences | PlainMessage | undefined, b: ValidatorSetPreferences | PlainMessage | undefined): boolean { - return proto3.util.equals(ValidatorSetPreferences, a, b); - } -} - diff --git a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_cosmes.ts b/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_cosmes.ts deleted file mode 100644 index 2eaf1a998..000000000 --- a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_cosmes.ts +++ /dev/null @@ -1,102 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file osmosis/valsetpref/v1beta1/tx.proto (package osmosis.valsetpref.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgDelegateBondedTokens, MsgDelegateBondedTokensResponse, MsgDelegateToValidatorSet, MsgDelegateToValidatorSetResponse, MsgRedelegateValidatorSet, MsgRedelegateValidatorSetResponse, MsgSetValidatorSetPreference, MsgSetValidatorSetPreferenceResponse, MsgUndelegateFromRebalancedValidatorSet, MsgUndelegateFromRebalancedValidatorSetResponse, MsgUndelegateFromValidatorSet, MsgUndelegateFromValidatorSetResponse, MsgWithdrawDelegationRewards, MsgWithdrawDelegationRewardsResponse } from "./tx_pb.js"; - -const TYPE_NAME = "osmosis.valsetpref.v1beta1.Msg"; - -/** - * SetValidatorSetPreference creates a set of validator preference. - * This message will process both create + update request. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.SetValidatorSetPreference - */ -export const MsgSetValidatorSetPreferenceService = { - typeName: TYPE_NAME, - method: "SetValidatorSetPreference", - Request: MsgSetValidatorSetPreference, - Response: MsgSetValidatorSetPreferenceResponse, -} as const; - -/** - * DelegateToValidatorSet gets the owner, coins and delegates to a - * validator-set. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.DelegateToValidatorSet - */ -export const MsgDelegateToValidatorSetService = { - typeName: TYPE_NAME, - method: "DelegateToValidatorSet", - Request: MsgDelegateToValidatorSet, - Response: MsgDelegateToValidatorSetResponse, -} as const; - -/** - * UndelegateFromValidatorSet gets the owner and coins and undelegates from - * validator-set. The unbonding logic will follow the `Undelegate` logic from - * the sdk. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.UndelegateFromValidatorSet - */ -export const MsgUndelegateFromValidatorSetService = { - typeName: TYPE_NAME, - method: "UndelegateFromValidatorSet", - Request: MsgUndelegateFromValidatorSet, - Response: MsgUndelegateFromValidatorSetResponse, -} as const; - -/** - * UndelegateFromRebalancedValidatorSet undelegates the proivded amount from - * the validator set, but takes into consideration the current delegations - * to the user's validator set to determine the weights assigned to each. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.UndelegateFromRebalancedValidatorSet - */ -export const MsgUndelegateFromRebalancedValidatorSetService = { - typeName: TYPE_NAME, - method: "UndelegateFromRebalancedValidatorSet", - Request: MsgUndelegateFromRebalancedValidatorSet, - Response: MsgUndelegateFromRebalancedValidatorSetResponse, -} as const; - -/** - * RedelegateValidatorSet takes the existing validator set and redelegates to - * a new set. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.RedelegateValidatorSet - */ -export const MsgRedelegateValidatorSetService = { - typeName: TYPE_NAME, - method: "RedelegateValidatorSet", - Request: MsgRedelegateValidatorSet, - Response: MsgRedelegateValidatorSetResponse, -} as const; - -/** - * WithdrawDelegationRewards allows users to claim rewards from the - * validator-set. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.WithdrawDelegationRewards - */ -export const MsgWithdrawDelegationRewardsService = { - typeName: TYPE_NAME, - method: "WithdrawDelegationRewards", - Request: MsgWithdrawDelegationRewards, - Response: MsgWithdrawDelegationRewardsResponse, -} as const; - -/** - * DelegateBondedTokens allows users to break the lockup bond and delegate - * osmo tokens to a predefined validator-set. - * - * @generated from rpc osmosis.valsetpref.v1beta1.Msg.DelegateBondedTokens - */ -export const MsgDelegateBondedTokensService = { - typeName: TYPE_NAME, - method: "DelegateBondedTokens", - Request: MsgDelegateBondedTokens, - Response: MsgDelegateBondedTokensResponse, -} as const; - diff --git a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_pb.ts b/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_pb.ts deleted file mode 100644 index 4fc9ceccb..000000000 --- a/packages/es/src/protobufs/osmosis/valsetpref/v1beta1/tx_pb.ts +++ /dev/null @@ -1,573 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file osmosis/valsetpref/v1beta1/tx.proto (package osmosis.valsetpref.v1beta1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ValidatorPreference } from "./state_pb.js"; -import { Coin } from "../../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * MsgCreateValidatorSetPreference is a list that holds validator-set. - * - * @generated from message osmosis.valsetpref.v1beta1.MsgSetValidatorSetPreference - */ -export class MsgSetValidatorSetPreference extends Message { - /** - * delegator is the user who is trying to create a validator-set. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * list of {valAddr, weight} to delegate to - * - * @generated from field: repeated osmosis.valsetpref.v1beta1.ValidatorPreference preferences = 2; - */ - preferences: ValidatorPreference[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgSetValidatorSetPreference"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "preferences", kind: "message", T: ValidatorPreference, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetValidatorSetPreference { - return new MsgSetValidatorSetPreference().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetValidatorSetPreference { - return new MsgSetValidatorSetPreference().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetValidatorSetPreference { - return new MsgSetValidatorSetPreference().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetValidatorSetPreference | PlainMessage | undefined, b: MsgSetValidatorSetPreference | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetValidatorSetPreference, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgSetValidatorSetPreferenceResponse - */ -export class MsgSetValidatorSetPreferenceResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgSetValidatorSetPreferenceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgSetValidatorSetPreferenceResponse { - return new MsgSetValidatorSetPreferenceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgSetValidatorSetPreferenceResponse { - return new MsgSetValidatorSetPreferenceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgSetValidatorSetPreferenceResponse { - return new MsgSetValidatorSetPreferenceResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgSetValidatorSetPreferenceResponse | PlainMessage | undefined, b: MsgSetValidatorSetPreferenceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgSetValidatorSetPreferenceResponse, a, b); - } -} - -/** - * MsgDelegateToValidatorSet allows users to delegate to an existing - * validator-set - * - * @generated from message osmosis.valsetpref.v1beta1.MsgDelegateToValidatorSet - */ -export class MsgDelegateToValidatorSet extends Message { - /** - * delegator is the user who is trying to delegate. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * the amount of tokens the user is trying to delegate. - * For ex: delegate 10osmo with validator-set {ValA -> 0.5, ValB -> 0.3, ValC - * -> 0.2} our staking logic would attempt to delegate 5osmo to A , 3osmo to - * B, 2osmo to C. - * - * @generated from field: cosmos.base.v1beta1.Coin coin = 2; - */ - coin?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgDelegateToValidatorSet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "coin", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDelegateToValidatorSet { - return new MsgDelegateToValidatorSet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDelegateToValidatorSet { - return new MsgDelegateToValidatorSet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDelegateToValidatorSet { - return new MsgDelegateToValidatorSet().fromJsonString(jsonString, options); - } - - static equals(a: MsgDelegateToValidatorSet | PlainMessage | undefined, b: MsgDelegateToValidatorSet | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDelegateToValidatorSet, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgDelegateToValidatorSetResponse - */ -export class MsgDelegateToValidatorSetResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgDelegateToValidatorSetResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDelegateToValidatorSetResponse { - return new MsgDelegateToValidatorSetResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDelegateToValidatorSetResponse { - return new MsgDelegateToValidatorSetResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDelegateToValidatorSetResponse { - return new MsgDelegateToValidatorSetResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgDelegateToValidatorSetResponse | PlainMessage | undefined, b: MsgDelegateToValidatorSetResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDelegateToValidatorSetResponse, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSet - */ -export class MsgUndelegateFromValidatorSet extends Message { - /** - * delegator is the user who is trying to undelegate. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * the amount the user wants to undelegate - * For ex: Undelegate 10osmo with validator-set {ValA -> 0.5, ValB -> 0.3, - * ValC - * -> 0.2} our undelegate logic would attempt to undelegate 5osmo from A , - * 3osmo from B, 2osmo from C - * - * @generated from field: cosmos.base.v1beta1.Coin coin = 3; - */ - coin?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "coin", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUndelegateFromValidatorSet { - return new MsgUndelegateFromValidatorSet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUndelegateFromValidatorSet { - return new MsgUndelegateFromValidatorSet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUndelegateFromValidatorSet { - return new MsgUndelegateFromValidatorSet().fromJsonString(jsonString, options); - } - - static equals(a: MsgUndelegateFromValidatorSet | PlainMessage | undefined, b: MsgUndelegateFromValidatorSet | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUndelegateFromValidatorSet, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSetResponse - */ -export class MsgUndelegateFromValidatorSetResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSetResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUndelegateFromValidatorSetResponse { - return new MsgUndelegateFromValidatorSetResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUndelegateFromValidatorSetResponse { - return new MsgUndelegateFromValidatorSetResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUndelegateFromValidatorSetResponse { - return new MsgUndelegateFromValidatorSetResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUndelegateFromValidatorSetResponse | PlainMessage | undefined, b: MsgUndelegateFromValidatorSetResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUndelegateFromValidatorSetResponse, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSet - */ -export class MsgUndelegateFromRebalancedValidatorSet extends Message { - /** - * delegator is the user who is trying to undelegate. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * the amount the user wants to undelegate - * For ex: Undelegate 50 osmo with validator-set {ValA -> 0.5, ValB -> 0.5} - * Our undelegate logic would first check the current delegation balance. - * If the user has 90 osmo delegated to ValA and 10 osmo delegated to ValB, - * the rebalanced validator set would be {ValA -> 0.9, ValB -> 0.1} - * So now the 45 osmo would be undelegated from ValA and 5 osmo would be - * undelegated from ValB. - * - * @generated from field: cosmos.base.v1beta1.Coin coin = 2; - */ - coin?: Coin; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "coin", kind: "message", T: Coin }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUndelegateFromRebalancedValidatorSet { - return new MsgUndelegateFromRebalancedValidatorSet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUndelegateFromRebalancedValidatorSet { - return new MsgUndelegateFromRebalancedValidatorSet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUndelegateFromRebalancedValidatorSet { - return new MsgUndelegateFromRebalancedValidatorSet().fromJsonString(jsonString, options); - } - - static equals(a: MsgUndelegateFromRebalancedValidatorSet | PlainMessage | undefined, b: MsgUndelegateFromRebalancedValidatorSet | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUndelegateFromRebalancedValidatorSet, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSetResponse - */ -export class MsgUndelegateFromRebalancedValidatorSetResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSetResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUndelegateFromRebalancedValidatorSetResponse { - return new MsgUndelegateFromRebalancedValidatorSetResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUndelegateFromRebalancedValidatorSetResponse { - return new MsgUndelegateFromRebalancedValidatorSetResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUndelegateFromRebalancedValidatorSetResponse { - return new MsgUndelegateFromRebalancedValidatorSetResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUndelegateFromRebalancedValidatorSetResponse | PlainMessage | undefined, b: MsgUndelegateFromRebalancedValidatorSetResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUndelegateFromRebalancedValidatorSetResponse, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSet - */ -export class MsgRedelegateValidatorSet extends Message { - /** - * delegator is the user who is trying to create a validator-set. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * list of {valAddr, weight} to delegate to - * - * @generated from field: repeated osmosis.valsetpref.v1beta1.ValidatorPreference preferences = 2; - */ - preferences: ValidatorPreference[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSet"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "preferences", kind: "message", T: ValidatorPreference, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRedelegateValidatorSet { - return new MsgRedelegateValidatorSet().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRedelegateValidatorSet { - return new MsgRedelegateValidatorSet().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRedelegateValidatorSet { - return new MsgRedelegateValidatorSet().fromJsonString(jsonString, options); - } - - static equals(a: MsgRedelegateValidatorSet | PlainMessage | undefined, b: MsgRedelegateValidatorSet | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRedelegateValidatorSet, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSetResponse - */ -export class MsgRedelegateValidatorSetResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSetResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRedelegateValidatorSetResponse { - return new MsgRedelegateValidatorSetResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRedelegateValidatorSetResponse { - return new MsgRedelegateValidatorSetResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRedelegateValidatorSetResponse { - return new MsgRedelegateValidatorSetResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRedelegateValidatorSetResponse | PlainMessage | undefined, b: MsgRedelegateValidatorSetResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRedelegateValidatorSetResponse, a, b); - } -} - -/** - * MsgWithdrawDelegationRewards allows user to claim staking rewards from the - * validator set. - * - * @generated from message osmosis.valsetpref.v1beta1.MsgWithdrawDelegationRewards - */ -export class MsgWithdrawDelegationRewards extends Message { - /** - * delegator is the user who is trying to claim staking rewards. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgWithdrawDelegationRewards"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgWithdrawDelegationRewards { - return new MsgWithdrawDelegationRewards().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgWithdrawDelegationRewards { - return new MsgWithdrawDelegationRewards().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgWithdrawDelegationRewards { - return new MsgWithdrawDelegationRewards().fromJsonString(jsonString, options); - } - - static equals(a: MsgWithdrawDelegationRewards | PlainMessage | undefined, b: MsgWithdrawDelegationRewards | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgWithdrawDelegationRewards, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgWithdrawDelegationRewardsResponse - */ -export class MsgWithdrawDelegationRewardsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgWithdrawDelegationRewardsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgWithdrawDelegationRewardsResponse { - return new MsgWithdrawDelegationRewardsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgWithdrawDelegationRewardsResponse { - return new MsgWithdrawDelegationRewardsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgWithdrawDelegationRewardsResponse { - return new MsgWithdrawDelegationRewardsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgWithdrawDelegationRewardsResponse | PlainMessage | undefined, b: MsgWithdrawDelegationRewardsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgWithdrawDelegationRewardsResponse, a, b); - } -} - -/** - * MsgDelegateBondedTokens breaks bonded lockup (by ID) of osmo, of - * length <= 2 weeks and takes all that osmo and delegates according to - * delegator's current validator set preference. - * - * @generated from message osmosis.valsetpref.v1beta1.MsgDelegateBondedTokens - */ -export class MsgDelegateBondedTokens extends Message { - /** - * delegator is the user who is trying to force unbond osmo and delegate. - * - * @generated from field: string delegator = 1; - */ - delegator = ""; - - /** - * lockup id of osmo in the pool - * - * @generated from field: uint64 lockID = 2; - */ - lockID = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgDelegateBondedTokens"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "delegator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "lockID", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDelegateBondedTokens { - return new MsgDelegateBondedTokens().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDelegateBondedTokens { - return new MsgDelegateBondedTokens().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDelegateBondedTokens { - return new MsgDelegateBondedTokens().fromJsonString(jsonString, options); - } - - static equals(a: MsgDelegateBondedTokens | PlainMessage | undefined, b: MsgDelegateBondedTokens | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDelegateBondedTokens, a, b); - } -} - -/** - * @generated from message osmosis.valsetpref.v1beta1.MsgDelegateBondedTokensResponse - */ -export class MsgDelegateBondedTokensResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "osmosis.valsetpref.v1beta1.MsgDelegateBondedTokensResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgDelegateBondedTokensResponse { - return new MsgDelegateBondedTokensResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgDelegateBondedTokensResponse { - return new MsgDelegateBondedTokensResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgDelegateBondedTokensResponse { - return new MsgDelegateBondedTokensResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgDelegateBondedTokensResponse | PlainMessage | undefined, b: MsgDelegateBondedTokensResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgDelegateBondedTokensResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/module/v1/module_pb.ts b/packages/es/src/protobufs/svc/module/v1/module_pb.ts deleted file mode 100644 index df8abc4e9..000000000 --- a/packages/es/src/protobufs/svc/module/v1/module_pb.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/module/v1/module.proto (package svc.module.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; - -/** - * Module is the app config object of the module. - * Learn more: https://docs.cosmos.network/main/building-modules/depinject - * - * @generated from message svc.module.v1.Module - */ -export class Module extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.module.v1.Module"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Module { - return new Module().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Module { - return new Module().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Module { - return new Module().fromJsonString(jsonString, options); - } - - static equals(a: Module | PlainMessage | undefined, b: Module | PlainMessage | undefined): boolean { - return proto3.util.equals(Module, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/v1/events_pb.ts b/packages/es/src/protobufs/svc/v1/events_pb.ts deleted file mode 100644 index 3b24ef15a..000000000 --- a/packages/es/src/protobufs/svc/v1/events_pb.ts +++ /dev/null @@ -1,235 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/v1/events.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64, Timestamp } from "@bufbuild/protobuf"; - -/** - * EventDomainVerificationInitiated is emitted when domain verification is initiated - * - * @generated from message svc.v1.EventDomainVerificationInitiated - */ -export class EventDomainVerificationInitiated extends Message { - /** - * Domain being verified - * - * @generated from field: string domain = 1; - */ - domain = ""; - - /** - * Verification ID - * - * @generated from field: string verification_id = 2; - */ - verificationId = ""; - - /** - * Verification challenge - * - * @generated from field: string challenge = 3; - */ - challenge = ""; - - /** - * Initiator address - * - * @generated from field: string initiator = 4; - */ - initiator = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.EventDomainVerificationInitiated"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "verification_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "challenge", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "initiator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDomainVerificationInitiated { - return new EventDomainVerificationInitiated().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDomainVerificationInitiated { - return new EventDomainVerificationInitiated().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDomainVerificationInitiated { - return new EventDomainVerificationInitiated().fromJsonString(jsonString, options); - } - - static equals(a: EventDomainVerificationInitiated | PlainMessage | undefined, b: EventDomainVerificationInitiated | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDomainVerificationInitiated, a, b); - } -} - -/** - * EventDomainVerified is emitted when a domain is successfully verified - * - * @generated from message svc.v1.EventDomainVerified - */ -export class EventDomainVerified extends Message { - /** - * Domain that was verified - * - * @generated from field: string domain = 1; - */ - domain = ""; - - /** - * Verification ID - * - * @generated from field: string verification_id = 2; - */ - verificationId = ""; - - /** - * Verifier address - * - * @generated from field: string verifier = 3; - */ - verifier = ""; - - /** - * Verification timestamp - * - * @generated from field: google.protobuf.Timestamp verified_at = 4; - */ - verifiedAt?: Timestamp; - - /** - * Block height - * - * @generated from field: uint64 block_height = 5; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.EventDomainVerified"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "verification_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "verifier", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "verified_at", kind: "message", T: Timestamp }, - { no: 5, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventDomainVerified { - return new EventDomainVerified().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventDomainVerified { - return new EventDomainVerified().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventDomainVerified { - return new EventDomainVerified().fromJsonString(jsonString, options); - } - - static equals(a: EventDomainVerified | PlainMessage | undefined, b: EventDomainVerified | PlainMessage | undefined): boolean { - return proto3.util.equals(EventDomainVerified, a, b); - } -} - -/** - * EventServiceRegistered is emitted when a service is registered - * - * @generated from message svc.v1.EventServiceRegistered - */ -export class EventServiceRegistered extends Message { - /** - * Service ID - * - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - /** - * Associated domain - * - * @generated from field: string domain = 2; - */ - domain = ""; - - /** - * Owner DID - * - * @generated from field: string owner = 3; - */ - owner = ""; - - /** - * Service endpoints - * - * @generated from field: repeated string endpoints = 4; - */ - endpoints: string[] = []; - - /** - * Service metadata (JSON string) - * - * @generated from field: string metadata = 5; - */ - metadata = ""; - - /** - * Block height - * - * @generated from field: uint64 block_height = 6; - */ - blockHeight = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.EventServiceRegistered"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "endpoints", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "metadata", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "block_height", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): EventServiceRegistered { - return new EventServiceRegistered().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): EventServiceRegistered { - return new EventServiceRegistered().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): EventServiceRegistered { - return new EventServiceRegistered().fromJsonString(jsonString, options); - } - - static equals(a: EventServiceRegistered | PlainMessage | undefined, b: EventServiceRegistered | PlainMessage | undefined): boolean { - return proto3.util.equals(EventServiceRegistered, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/v1/genesis_pb.ts b/packages/es/src/protobufs/svc/v1/genesis_pb.ts deleted file mode 100644 index d485ae178..000000000 --- a/packages/es/src/protobufs/svc/v1/genesis_pb.ts +++ /dev/null @@ -1,258 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/v1/genesis.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; -import { ServiceCapability } from "./state_pb.js"; -import { Coin } from "../../cosmos/base/v1beta1/coin_pb.js"; - -/** - * GenesisState defines the module genesis state - * - * @generated from message svc.v1.GenesisState - */ -export class GenesisState extends Message { - /** - * Params defines all the parameters of the module. - * - * @generated from field: svc.v1.Params params = 1; - */ - params?: Params; - - /** - * Service capabilities stored in the module - * - * @generated from field: repeated svc.v1.ServiceCapability capabilities = 2; - */ - capabilities: ServiceCapability[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.GenesisState"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - { no: 2, name: "capabilities", kind: "message", T: ServiceCapability, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): GenesisState { - return new GenesisState().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): GenesisState { - return new GenesisState().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): GenesisState { - return new GenesisState().fromJsonString(jsonString, options); - } - - static equals(a: GenesisState | PlainMessage | undefined, b: GenesisState | PlainMessage | undefined): boolean { - return proto3.util.equals(GenesisState, a, b); - } -} - -/** - * Params defines the set of module parameters. - * - * @generated from message svc.v1.Params - */ -export class Params extends Message { - /** - * Service Limits - * Maximum number of services that can be registered per account - * - * @generated from field: uint32 max_services_per_account = 1; - */ - maxServicesPerAccount = 0; - - /** - * Maximum number of domains that can be bound to a single service - * - * @generated from field: uint32 max_domains_per_service = 2; - */ - maxDomainsPerService = 0; - - /** - * Maximum number of endpoints that can be registered per service - * - * @generated from field: uint32 max_endpoints_per_service = 3; - */ - maxEndpointsPerService = 0; - - /** - * Timeouts and Intervals (in seconds) - * Time allowed for domain ownership verification before expiry - * - * @generated from field: int64 domain_verification_timeout = 4; - */ - domainVerificationTimeout = protoInt64.zero; - - /** - * Interval between service health checks - * - * @generated from field: int64 service_health_check_interval = 5; - */ - serviceHealthCheckInterval = protoInt64.zero; - - /** - * Default expiration time for capabilities if not specified - * - * @generated from field: int64 capability_default_expiration = 6; - */ - capabilityDefaultExpiration = protoInt64.zero; - - /** - * Economic Parameters - * Fee required to register a new service - * - * @generated from field: cosmos.base.v1beta1.Coin service_registration_fee = 7; - */ - serviceRegistrationFee?: Coin; - - /** - * Fee required to verify domain ownership - * - * @generated from field: cosmos.base.v1beta1.Coin domain_verification_fee = 8; - */ - domainVerificationFee?: Coin; - - /** - * Minimum stake required to keep a service active - * - * @generated from field: cosmos.base.v1beta1.Coin min_service_stake = 9; - */ - minServiceStake?: Coin; - - /** - * UCAN and Capability Settings - * Maximum depth of delegation chains for capabilities - * - * @generated from field: uint32 max_delegation_chain_depth = 10; - */ - maxDelegationChainDepth = 0; - - /** - * Maximum lifetime for UCAN tokens (in seconds) - * - * @generated from field: int64 ucan_max_lifetime = 11; - */ - ucanMaxLifetime = protoInt64.zero; - - /** - * Minimum lifetime for UCAN tokens (in seconds) - * - * @generated from field: int64 ucan_min_lifetime = 12; - */ - ucanMinLifetime = protoInt64.zero; - - /** - * List of supported signature algorithms for UCAN - * - * @generated from field: repeated string supported_signature_algorithms = 13; - */ - supportedSignatureAlgorithms: string[] = []; - - /** - * Validation Rules - * Whether to require cryptographic proof of domain ownership - * - * @generated from field: bool require_domain_ownership_proof = 14; - */ - requireDomainOwnershipProof = false; - - /** - * Whether to require HTTPS for service endpoints - * - * @generated from field: bool require_https = 15; - */ - requireHttps = false; - - /** - * Whether to allow localhost domains for development - * - * @generated from field: bool allow_localhost = 16; - */ - allowLocalhost = false; - - /** - * Maximum length for service description text - * - * @generated from field: uint32 max_service_description_length = 17; - */ - maxServiceDescriptionLength = 0; - - /** - * Rate Limiting - * Maximum number of service registrations allowed per block - * - * @generated from field: uint32 max_registrations_per_block = 18; - */ - maxRegistrationsPerBlock = 0; - - /** - * Maximum number of service updates allowed per block - * - * @generated from field: uint32 max_updates_per_block = 19; - */ - maxUpdatesPerBlock = 0; - - /** - * Maximum number of capability grants allowed per block - * - * @generated from field: uint32 max_capability_grants_per_block = 20; - */ - maxCapabilityGrantsPerBlock = 0; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.Params"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "max_services_per_account", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 2, name: "max_domains_per_service", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 3, name: "max_endpoints_per_service", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 4, name: "domain_verification_timeout", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 5, name: "service_health_check_interval", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "capability_default_expiration", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "service_registration_fee", kind: "message", T: Coin }, - { no: 8, name: "domain_verification_fee", kind: "message", T: Coin }, - { no: 9, name: "min_service_stake", kind: "message", T: Coin }, - { no: 10, name: "max_delegation_chain_depth", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 11, name: "ucan_max_lifetime", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 12, name: "ucan_min_lifetime", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 13, name: "supported_signature_algorithms", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 14, name: "require_domain_ownership_proof", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 15, name: "require_https", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 16, name: "allow_localhost", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 17, name: "max_service_description_length", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 18, name: "max_registrations_per_block", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 19, name: "max_updates_per_block", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - { no: 20, name: "max_capability_grants_per_block", kind: "scalar", T: 13 /* ScalarType.UINT32 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Params { - return new Params().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Params { - return new Params().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Params { - return new Params().fromJsonString(jsonString, options); - } - - static equals(a: Params | PlainMessage | undefined, b: Params | PlainMessage | undefined): boolean { - return proto3.util.equals(Params, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/v1/query_cosmes.ts b/packages/es/src/protobufs/svc/v1/query_cosmes.ts deleted file mode 100644 index a87c496b6..000000000 --- a/packages/es/src/protobufs/svc/v1/query_cosmes.ts +++ /dev/null @@ -1,110 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file svc/v1/query.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { QueryDomainVerificationRequest, QueryDomainVerificationResponse, QueryParamsRequest, QueryParamsResponse, QueryServiceOIDCDiscoveryRequest, QueryServiceOIDCDiscoveryResponse, QueryServiceOIDCJWKSRequest, QueryServiceOIDCJWKSResponse, QueryServiceOIDCMetadataRequest, QueryServiceOIDCMetadataResponse, QueryServiceRequest, QueryServiceResponse, QueryServicesByDomainRequest, QueryServicesByDomainResponse, QueryServicesByOwnerRequest, QueryServicesByOwnerResponse } from "./query_pb.js"; - -const TYPE_NAME = "svc.v1.Query"; - -/** - * Params queries all parameters of the module. - * - * @generated from rpc svc.v1.Query.Params - */ -export const QueryParamsService = { - typeName: TYPE_NAME, - method: "Params", - Request: QueryParamsRequest, - Response: QueryParamsResponse, -} as const; - -/** - * DomainVerification queries domain verification status by domain name. - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "svc_docs.md"}} - * - * @generated from rpc svc.v1.Query.DomainVerification - */ -export const QueryDomainVerificationService = { - typeName: TYPE_NAME, - method: "DomainVerification", - Request: QueryDomainVerificationRequest, - Response: QueryDomainVerificationResponse, -} as const; - -/** - * Service queries service information by service ID. - * - * @generated from rpc svc.v1.Query.Service - */ -export const QueryServiceService = { - typeName: TYPE_NAME, - method: "Service", - Request: QueryServiceRequest, - Response: QueryServiceResponse, -} as const; - -/** - * ServicesByOwner queries all services owned by a specific address. - * - * @generated from rpc svc.v1.Query.ServicesByOwner - */ -export const QueryServicesByOwnerService = { - typeName: TYPE_NAME, - method: "ServicesByOwner", - Request: QueryServicesByOwnerRequest, - Response: QueryServicesByOwnerResponse, -} as const; - -/** - * ServicesByDomain queries services bound to a specific domain. - * - * @generated from rpc svc.v1.Query.ServicesByDomain - */ -export const QueryServicesByDomainService = { - typeName: TYPE_NAME, - method: "ServicesByDomain", - Request: QueryServicesByDomainRequest, - Response: QueryServicesByDomainResponse, -} as const; - -/** - * ServiceOIDCDiscovery queries OIDC discovery configuration for a service - * - * @generated from rpc svc.v1.Query.ServiceOIDCDiscovery - */ -export const QueryServiceOIDCDiscoveryService = { - typeName: TYPE_NAME, - method: "ServiceOIDCDiscovery", - Request: QueryServiceOIDCDiscoveryRequest, - Response: QueryServiceOIDCDiscoveryResponse, -} as const; - -/** - * ServiceOIDCJWKS queries OIDC JWKS for a service - * - * @generated from rpc svc.v1.Query.ServiceOIDCJWKS - */ -export const QueryServiceOIDCJWKSService = { - typeName: TYPE_NAME, - method: "ServiceOIDCJWKS", - Request: QueryServiceOIDCJWKSRequest, - Response: QueryServiceOIDCJWKSResponse, -} as const; - -/** - * ServiceOIDCMetadata queries OIDC metadata for a service - * - * @generated from rpc svc.v1.Query.ServiceOIDCMetadata - */ -export const QueryServiceOIDCMetadataService = { - typeName: TYPE_NAME, - method: "ServiceOIDCMetadata", - Request: QueryServiceOIDCMetadataRequest, - Response: QueryServiceOIDCMetadataResponse, -} as const; - diff --git a/packages/es/src/protobufs/svc/v1/query_pb.ts b/packages/es/src/protobufs/svc/v1/query_pb.ts deleted file mode 100644 index 20344637c..000000000 --- a/packages/es/src/protobufs/svc/v1/query_pb.ts +++ /dev/null @@ -1,842 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/v1/query.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; -import { DomainVerification, JWK, Service, ServiceOIDCConfig, ServiceStatus } from "./state_pb.js"; - -/** - * QueryParamsRequest is the request type for the Query/Params RPC method. - * - * @generated from message svc.v1.QueryParamsRequest - */ -export class QueryParamsRequest extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryParamsRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsRequest { - return new QueryParamsRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsRequest | PlainMessage | undefined, b: QueryParamsRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsRequest, a, b); - } -} - -/** - * QueryParamsResponse is the response type for the Query/Params RPC method. - * - * @generated from message svc.v1.QueryParamsResponse - */ -export class QueryParamsResponse extends Message { - /** - * params defines the parameters of the module. - * - * @generated from field: svc.v1.Params params = 1; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryParamsResponse { - return new QueryParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryParamsResponse | PlainMessage | undefined, b: QueryParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryParamsResponse, a, b); - } -} - -/** - * QueryDomainVerificationRequest is the request type for the - * Query/DomainVerification RPC method. - * - * @generated from message svc.v1.QueryDomainVerificationRequest - */ -export class QueryDomainVerificationRequest extends Message { - /** - * @generated from field: string domain = 1; - */ - domain = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryDomainVerificationRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDomainVerificationRequest { - return new QueryDomainVerificationRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDomainVerificationRequest { - return new QueryDomainVerificationRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDomainVerificationRequest { - return new QueryDomainVerificationRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryDomainVerificationRequest | PlainMessage | undefined, b: QueryDomainVerificationRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDomainVerificationRequest, a, b); - } -} - -/** - * QueryDomainVerificationResponse is the response type for the - * Query/DomainVerification RPC method. - * - * @generated from message svc.v1.QueryDomainVerificationResponse - */ -export class QueryDomainVerificationResponse extends Message { - /** - * @generated from field: svc.v1.DomainVerification domain_verification = 1; - */ - domainVerification?: DomainVerification; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryDomainVerificationResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain_verification", kind: "message", T: DomainVerification }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryDomainVerificationResponse { - return new QueryDomainVerificationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryDomainVerificationResponse { - return new QueryDomainVerificationResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryDomainVerificationResponse { - return new QueryDomainVerificationResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryDomainVerificationResponse | PlainMessage | undefined, b: QueryDomainVerificationResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryDomainVerificationResponse, a, b); - } -} - -/** - * QueryServiceRequest is the request type for the Query/Service RPC method. - * - * @generated from message svc.v1.QueryServiceRequest - */ -export class QueryServiceRequest extends Message { - /** - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceRequest { - return new QueryServiceRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceRequest { - return new QueryServiceRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceRequest { - return new QueryServiceRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceRequest | PlainMessage | undefined, b: QueryServiceRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceRequest, a, b); - } -} - -/** - * QueryServiceResponse is the response type for the Query/Service RPC method. - * - * @generated from message svc.v1.QueryServiceResponse - */ -export class QueryServiceResponse extends Message { - /** - * @generated from field: svc.v1.Service service = 1; - */ - service?: Service; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service", kind: "message", T: Service }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceResponse { - return new QueryServiceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceResponse { - return new QueryServiceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceResponse { - return new QueryServiceResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceResponse | PlainMessage | undefined, b: QueryServiceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceResponse, a, b); - } -} - -/** - * QueryServicesByOwnerRequest is the request type for the Query/ServicesByOwner - * RPC method. - * - * @generated from message svc.v1.QueryServicesByOwnerRequest - */ -export class QueryServicesByOwnerRequest extends Message { - /** - * @generated from field: string owner = 1; - */ - owner = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServicesByOwnerRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServicesByOwnerRequest { - return new QueryServicesByOwnerRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServicesByOwnerRequest { - return new QueryServicesByOwnerRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServicesByOwnerRequest { - return new QueryServicesByOwnerRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServicesByOwnerRequest | PlainMessage | undefined, b: QueryServicesByOwnerRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServicesByOwnerRequest, a, b); - } -} - -/** - * QueryServicesByOwnerResponse is the response type for the - * Query/ServicesByOwner RPC method. - * - * @generated from message svc.v1.QueryServicesByOwnerResponse - */ -export class QueryServicesByOwnerResponse extends Message { - /** - * @generated from field: repeated svc.v1.Service services = 1; - */ - services: Service[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServicesByOwnerResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "services", kind: "message", T: Service, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServicesByOwnerResponse { - return new QueryServicesByOwnerResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServicesByOwnerResponse { - return new QueryServicesByOwnerResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServicesByOwnerResponse { - return new QueryServicesByOwnerResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServicesByOwnerResponse | PlainMessage | undefined, b: QueryServicesByOwnerResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServicesByOwnerResponse, a, b); - } -} - -/** - * QueryServicesByDomainRequest is the request type for the - * Query/ServicesByDomain RPC method. - * - * @generated from message svc.v1.QueryServicesByDomainRequest - */ -export class QueryServicesByDomainRequest extends Message { - /** - * @generated from field: string domain = 1; - */ - domain = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServicesByDomainRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServicesByDomainRequest { - return new QueryServicesByDomainRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServicesByDomainRequest { - return new QueryServicesByDomainRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServicesByDomainRequest { - return new QueryServicesByDomainRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServicesByDomainRequest | PlainMessage | undefined, b: QueryServicesByDomainRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServicesByDomainRequest, a, b); - } -} - -/** - * QueryServicesByDomainResponse is the response type for the - * Query/ServicesByDomain RPC method. - * - * @generated from message svc.v1.QueryServicesByDomainResponse - */ -export class QueryServicesByDomainResponse extends Message { - /** - * @generated from field: repeated svc.v1.Service services = 1; - */ - services: Service[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServicesByDomainResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "services", kind: "message", T: Service, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServicesByDomainResponse { - return new QueryServicesByDomainResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServicesByDomainResponse { - return new QueryServicesByDomainResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServicesByDomainResponse { - return new QueryServicesByDomainResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServicesByDomainResponse | PlainMessage | undefined, b: QueryServicesByDomainResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServicesByDomainResponse, a, b); - } -} - -/** - * QueryServiceOIDCDiscoveryRequest is the request type for the - * Query/ServiceOIDCDiscovery RPC method. - * - * @generated from message svc.v1.QueryServiceOIDCDiscoveryRequest - */ -export class QueryServiceOIDCDiscoveryRequest extends Message { - /** - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCDiscoveryRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCDiscoveryRequest { - return new QueryServiceOIDCDiscoveryRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCDiscoveryRequest { - return new QueryServiceOIDCDiscoveryRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCDiscoveryRequest { - return new QueryServiceOIDCDiscoveryRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCDiscoveryRequest | PlainMessage | undefined, b: QueryServiceOIDCDiscoveryRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCDiscoveryRequest, a, b); - } -} - -/** - * QueryServiceOIDCDiscoveryResponse is the response type for the - * Query/ServiceOIDCDiscovery RPC method. - * This response follows the OpenID Connect Discovery 1.0 specification - * - * @generated from message svc.v1.QueryServiceOIDCDiscoveryResponse - */ -export class QueryServiceOIDCDiscoveryResponse extends Message { - /** - * The issuer identifier - * - * @generated from field: string issuer = 1; - */ - issuer = ""; - - /** - * URL of the authorization endpoint - * - * @generated from field: string authorization_endpoint = 2; - */ - authorizationEndpoint = ""; - - /** - * URL of the token endpoint - * - * @generated from field: string token_endpoint = 3; - */ - tokenEndpoint = ""; - - /** - * URL of the JSON Web Key Set - * - * @generated from field: string jwks_uri = 4; - */ - jwksUri = ""; - - /** - * URL of the UserInfo endpoint - * - * @generated from field: string userinfo_endpoint = 5; - */ - userinfoEndpoint = ""; - - /** - * URL for the registration endpoint - * - * @generated from field: string registration_endpoint = 6; - */ - registrationEndpoint = ""; - - /** - * JSON array containing a list of the OAuth 2.0 scope values - * - * @generated from field: repeated string scopes_supported = 7; - */ - scopesSupported: string[] = []; - - /** - * JSON array containing a list of the OAuth 2.0 response_type values - * - * @generated from field: repeated string response_types_supported = 8; - */ - responseTypesSupported: string[] = []; - - /** - * JSON array containing a list of the OAuth 2.0 grant_type values - * - * @generated from field: repeated string grant_types_supported = 9; - */ - grantTypesSupported: string[] = []; - - /** - * JSON array containing a list of the JWS signing algorithms - * - * @generated from field: repeated string id_token_signing_alg_values_supported = 10; - */ - idTokenSigningAlgValuesSupported: string[] = []; - - /** - * JSON array containing a list of the Subject Identifier types - * - * @generated from field: repeated string subject_types_supported = 11; - */ - subjectTypesSupported: string[] = []; - - /** - * JSON array containing a list of client authentication methods - * - * @generated from field: repeated string token_endpoint_auth_methods_supported = 12; - */ - tokenEndpointAuthMethodsSupported: string[] = []; - - /** - * JSON array containing a list of the Claim Names - * - * @generated from field: repeated string claims_supported = 13; - */ - claimsSupported: string[] = []; - - /** - * JSON array containing a list of the OAuth 2.0 response_mode values - * - * @generated from field: repeated string response_modes_supported = 14; - */ - responseModesSupported: string[] = []; - - /** - * Service URL for documentation - * - * @generated from field: string service_documentation = 15; - */ - serviceDocumentation = ""; - - /** - * Languages supported for the UI - * - * @generated from field: repeated string ui_locales_supported = 16; - */ - uiLocalesSupported: string[] = []; - - /** - * Languages supported for claims - * - * @generated from field: repeated string claims_locales_supported = 17; - */ - claimsLocalesSupported: string[] = []; - - /** - * Boolean value specifying whether the OP supports use of the request parameter - * - * @generated from field: bool request_parameter_supported = 18; - */ - requestParameterSupported = false; - - /** - * Boolean value specifying whether the OP supports use of the request_uri parameter - * - * @generated from field: bool request_uri_parameter_supported = 19; - */ - requestUriParameterSupported = false; - - /** - * Boolean value specifying whether the OP requires any request_uri values - * - * @generated from field: bool require_request_uri_registration = 20; - */ - requireRequestUriRegistration = false; - - /** - * URL that the OP provides to the person registering the Client - * - * @generated from field: string op_policy_uri = 21; - */ - opPolicyUri = ""; - - /** - * URL that the OP provides to the person registering the Client - * - * @generated from field: string op_tos_uri = 22; - */ - opTosUri = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCDiscoveryResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "authorization_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "token_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "jwks_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "userinfo_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "registration_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "scopes_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 8, name: "response_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 9, name: "grant_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "id_token_signing_alg_values_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 11, name: "subject_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 12, name: "token_endpoint_auth_methods_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 13, name: "claims_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 14, name: "response_modes_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 15, name: "service_documentation", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 16, name: "ui_locales_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 17, name: "claims_locales_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 18, name: "request_parameter_supported", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 19, name: "request_uri_parameter_supported", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 20, name: "require_request_uri_registration", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 21, name: "op_policy_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 22, name: "op_tos_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCDiscoveryResponse { - return new QueryServiceOIDCDiscoveryResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCDiscoveryResponse { - return new QueryServiceOIDCDiscoveryResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCDiscoveryResponse { - return new QueryServiceOIDCDiscoveryResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCDiscoveryResponse | PlainMessage | undefined, b: QueryServiceOIDCDiscoveryResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCDiscoveryResponse, a, b); - } -} - -/** - * QueryServiceOIDCJWKSRequest is the request type for the - * Query/ServiceOIDCJWKS RPC method. - * - * @generated from message svc.v1.QueryServiceOIDCJWKSRequest - */ -export class QueryServiceOIDCJWKSRequest extends Message { - /** - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCJWKSRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCJWKSRequest { - return new QueryServiceOIDCJWKSRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCJWKSRequest { - return new QueryServiceOIDCJWKSRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCJWKSRequest { - return new QueryServiceOIDCJWKSRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCJWKSRequest | PlainMessage | undefined, b: QueryServiceOIDCJWKSRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCJWKSRequest, a, b); - } -} - -/** - * QueryServiceOIDCJWKSResponse is the response type for the - * Query/ServiceOIDCJWKS RPC method. - * This response follows the JSON Web Key Set specification - * - * @generated from message svc.v1.QueryServiceOIDCJWKSResponse - */ -export class QueryServiceOIDCJWKSResponse extends Message { - /** - * Array of JWK values - * - * @generated from field: repeated svc.v1.JWK keys = 1; - */ - keys: JWK[] = []; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCJWKSResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "keys", kind: "message", T: JWK, repeated: true }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCJWKSResponse { - return new QueryServiceOIDCJWKSResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCJWKSResponse { - return new QueryServiceOIDCJWKSResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCJWKSResponse { - return new QueryServiceOIDCJWKSResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCJWKSResponse | PlainMessage | undefined, b: QueryServiceOIDCJWKSResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCJWKSResponse, a, b); - } -} - -/** - * QueryServiceOIDCMetadataRequest is the request type for the - * Query/ServiceOIDCMetadata RPC method. - * - * @generated from message svc.v1.QueryServiceOIDCMetadataRequest - */ -export class QueryServiceOIDCMetadataRequest extends Message { - /** - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCMetadataRequest"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCMetadataRequest { - return new QueryServiceOIDCMetadataRequest().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCMetadataRequest { - return new QueryServiceOIDCMetadataRequest().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCMetadataRequest { - return new QueryServiceOIDCMetadataRequest().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCMetadataRequest | PlainMessage | undefined, b: QueryServiceOIDCMetadataRequest | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCMetadataRequest, a, b); - } -} - -/** - * QueryServiceOIDCMetadataResponse is the response type for the - * Query/ServiceOIDCMetadata RPC method. - * - * @generated from message svc.v1.QueryServiceOIDCMetadataResponse - */ -export class QueryServiceOIDCMetadataResponse extends Message { - /** - * Service-specific OIDC metadata - * - * @generated from field: svc.v1.ServiceOIDCConfig config = 1; - */ - config?: ServiceOIDCConfig; - - /** - * The verified domain of the service - * - * @generated from field: string verified_domain = 2; - */ - verifiedDomain = ""; - - /** - * Service status - * - * @generated from field: svc.v1.ServiceStatus service_status = 3; - */ - serviceStatus = ServiceStatus.ACTIVE; - - /** - * Additional metadata as key-value pairs - * - * @generated from field: map metadata = 4; - */ - metadata: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.QueryServiceOIDCMetadataResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "config", kind: "message", T: ServiceOIDCConfig }, - { no: 2, name: "verified_domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "service_status", kind: "enum", T: proto3.getEnumType(ServiceStatus) }, - { no: 4, name: "metadata", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): QueryServiceOIDCMetadataResponse { - return new QueryServiceOIDCMetadataResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): QueryServiceOIDCMetadataResponse { - return new QueryServiceOIDCMetadataResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): QueryServiceOIDCMetadataResponse { - return new QueryServiceOIDCMetadataResponse().fromJsonString(jsonString, options); - } - - static equals(a: QueryServiceOIDCMetadataResponse | PlainMessage | undefined, b: QueryServiceOIDCMetadataResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(QueryServiceOIDCMetadataResponse, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/v1/state_pb.ts b/packages/es/src/protobufs/svc/v1/state_pb.ts deleted file mode 100644 index fdfd34e4d..000000000 --- a/packages/es/src/protobufs/svc/v1/state_pb.ts +++ /dev/null @@ -1,764 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/v1/state.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3, protoInt64 } from "@bufbuild/protobuf"; - -/** - * DomainVerificationStatus represents the current state of domain verification - * - * @generated from enum svc.v1.DomainVerificationStatus - */ -export enum DomainVerificationStatus { - /** - * Pending verification - DNS TXT record not yet confirmed - * - * @generated from enum value: DOMAIN_VERIFICATION_STATUS_PENDING = 0; - */ - PENDING = 0, - - /** - * Successfully verified - DNS TXT record confirmed - * - * @generated from enum value: DOMAIN_VERIFICATION_STATUS_VERIFIED = 1; - */ - VERIFIED = 1, - - /** - * Verification expired - exceeded time limit - * - * @generated from enum value: DOMAIN_VERIFICATION_STATUS_EXPIRED = 2; - */ - EXPIRED = 2, - - /** - * Verification failed - DNS lookup failed or record mismatch - * - * @generated from enum value: DOMAIN_VERIFICATION_STATUS_FAILED = 3; - */ - FAILED = 3, -} -// Retrieve enum metadata with: proto3.getEnumType(DomainVerificationStatus) -proto3.util.setEnumType(DomainVerificationStatus, "svc.v1.DomainVerificationStatus", [ - { no: 0, name: "DOMAIN_VERIFICATION_STATUS_PENDING" }, - { no: 1, name: "DOMAIN_VERIFICATION_STATUS_VERIFIED" }, - { no: 2, name: "DOMAIN_VERIFICATION_STATUS_EXPIRED" }, - { no: 3, name: "DOMAIN_VERIFICATION_STATUS_FAILED" }, -]); - -/** - * ServiceStatus represents the operational state of a service - * - * @generated from enum svc.v1.ServiceStatus - */ -export enum ServiceStatus { - /** - * Service is active and operational - * - * @generated from enum value: SERVICE_STATUS_ACTIVE = 0; - */ - ACTIVE = 0, - - /** - * Service is temporarily suspended - * - * @generated from enum value: SERVICE_STATUS_SUSPENDED = 1; - */ - SUSPENDED = 1, - - /** - * Service has been permanently revoked - * - * @generated from enum value: SERVICE_STATUS_REVOKED = 2; - */ - REVOKED = 2, -} -// Retrieve enum metadata with: proto3.getEnumType(ServiceStatus) -proto3.util.setEnumType(ServiceStatus, "svc.v1.ServiceStatus", [ - { no: 0, name: "SERVICE_STATUS_ACTIVE" }, - { no: 1, name: "SERVICE_STATUS_SUSPENDED" }, - { no: 2, name: "SERVICE_STATUS_REVOKED" }, -]); - -/** - * Service represents a registered service with domain binding and UCAN - * capabilities - * - * @generated from message svc.v1.Service - */ -export class Service extends Message { - /** - * Unique identifier for the service - * - * @generated from field: string id = 1; - */ - id = ""; - - /** - * DNS-verified domain bound to this service - * - * @generated from field: string domain = 2; - */ - domain = ""; - - /** - * Owner address who registered the service - * - * @generated from field: string owner = 3; - */ - owner = ""; - - /** - * IPFS CID of the UCAN root capability for this service - * - * @generated from field: string root_capability_cid = 4; - */ - rootCapabilityCid = ""; - - /** - * List of permissions granted to this service - * - * @generated from field: repeated string permissions = 5; - */ - permissions: string[] = []; - - /** - * Current status of the service - * - * @generated from field: svc.v1.ServiceStatus status = 6; - */ - status = ServiceStatus.ACTIVE; - - /** - * Unix timestamp when the service was registered - * - * @generated from field: int64 created_at = 7; - */ - createdAt = protoInt64.zero; - - /** - * Unix timestamp of last update - * - * @generated from field: int64 updated_at = 8; - */ - updatedAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.Service"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "root_capability_cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "permissions", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 6, name: "status", kind: "enum", T: proto3.getEnumType(ServiceStatus) }, - { no: 7, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 8, name: "updated_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): Service { - return new Service().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): Service { - return new Service().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): Service { - return new Service().fromJsonString(jsonString, options); - } - - static equals(a: Service | PlainMessage | undefined, b: Service | PlainMessage | undefined): boolean { - return proto3.util.equals(Service, a, b); - } -} - -/** - * DomainVerification represents a domain ownership verification record - * - * @generated from message svc.v1.DomainVerification - */ -export class DomainVerification extends Message { - /** - * The domain being verified (e.g., "example.com") - * - * @generated from field: string domain = 1; - */ - domain = ""; - - /** - * The owner's address who initiated the verification - * - * @generated from field: string owner = 2; - */ - owner = ""; - - /** - * Unique verification token to be placed in DNS TXT record - * - * @generated from field: string verification_token = 3; - */ - verificationToken = ""; - - /** - * Current status of domain verification - * - * @generated from field: svc.v1.DomainVerificationStatus status = 4; - */ - status = DomainVerificationStatus.PENDING; - - /** - * Unix timestamp when the verification expires if not completed - * - * @generated from field: int64 expires_at = 5; - */ - expiresAt = protoInt64.zero; - - /** - * Unix timestamp when the domain was verified (if applicable) - * - * @generated from field: int64 verified_at = 6; - */ - verifiedAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.DomainVerification"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "verification_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "status", kind: "enum", T: proto3.getEnumType(DomainVerificationStatus) }, - { no: 5, name: "expires_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 6, name: "verified_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): DomainVerification { - return new DomainVerification().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): DomainVerification { - return new DomainVerification().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): DomainVerification { - return new DomainVerification().fromJsonString(jsonString, options); - } - - static equals(a: DomainVerification | PlainMessage | undefined, b: DomainVerification | PlainMessage | undefined): boolean { - return proto3.util.equals(DomainVerification, a, b); - } -} - -/** - * ServiceCapability represents a service-specific capability with permissions - * - * @generated from message svc.v1.ServiceCapability - */ -export class ServiceCapability extends Message { - /** - * Unique identifier for the capability - * - * @generated from field: string capability_id = 1; - */ - capabilityId = ""; - - /** - * Service ID this capability belongs to - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - /** - * DNS domain associated with the capability - * - * @generated from field: string domain = 3; - */ - domain = ""; - - /** - * List of abilities/actions granted by this capability - * - * @generated from field: repeated string abilities = 4; - */ - abilities: string[] = []; - - /** - * Owner address who holds this capability - * - * @generated from field: string owner = 5; - */ - owner = ""; - - /** - * Unix timestamp when the capability was created - * - * @generated from field: int64 created_at = 6; - */ - createdAt = protoInt64.zero; - - /** - * Unix timestamp when the capability expires (0 for no expiration) - * - * @generated from field: int64 expires_at = 7; - */ - expiresAt = protoInt64.zero; - - /** - * Whether this capability has been revoked - * - * @generated from field: bool revoked = 8; - */ - revoked = false; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.ServiceCapability"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "capability_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "abilities", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "owner", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 7, name: "expires_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 8, name: "revoked", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ServiceCapability { - return new ServiceCapability().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ServiceCapability { - return new ServiceCapability().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ServiceCapability { - return new ServiceCapability().fromJsonString(jsonString, options); - } - - static equals(a: ServiceCapability | PlainMessage | undefined, b: ServiceCapability | PlainMessage | undefined): boolean { - return proto3.util.equals(ServiceCapability, a, b); - } -} - -/** - * ServiceResource represents a resource that can be accessed with capabilities - * - * @generated from message svc.v1.ServiceResource - */ -export class ServiceResource extends Message { - /** - * Unique identifier for the resource - * - * @generated from field: string resource_id = 1; - */ - resourceId = ""; - - /** - * Service ID this resource belongs to - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - /** - * Type of resource (e.g., "api", "data", "file") - * - * @generated from field: string resource_type = 3; - */ - resourceType = ""; - - /** - * List of abilities that can be performed on this resource - * - * @generated from field: repeated string allowed_abilities = 4; - */ - allowedAbilities: string[] = []; - - /** - * Additional metadata for the resource - * - * @generated from field: map metadata = 5; - */ - metadata: { [key: string]: string } = {}; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.ServiceResource"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "resource_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "resource_type", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "allowed_abilities", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "metadata", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ServiceResource { - return new ServiceResource().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ServiceResource { - return new ServiceResource().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ServiceResource { - return new ServiceResource().fromJsonString(jsonString, options); - } - - static equals(a: ServiceResource | PlainMessage | undefined, b: ServiceResource | PlainMessage | undefined): boolean { - return proto3.util.equals(ServiceResource, a, b); - } -} - -/** - * ServiceOIDCConfig represents OpenID Connect configuration for a service - * - * @generated from message svc.v1.ServiceOIDCConfig - */ -export class ServiceOIDCConfig extends Message { - /** - * Service ID this OIDC config belongs to - * - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - /** - * OIDC issuer URL (must match the service's verified domain) - * - * @generated from field: string issuer = 2; - */ - issuer = ""; - - /** - * Authorization endpoint URL - * - * @generated from field: string authorization_endpoint = 3; - */ - authorizationEndpoint = ""; - - /** - * Token endpoint URL - * - * @generated from field: string token_endpoint = 4; - */ - tokenEndpoint = ""; - - /** - * JWKS URI for public key retrieval - * - * @generated from field: string jwks_uri = 5; - */ - jwksUri = ""; - - /** - * UserInfo endpoint URL - * - * @generated from field: string userinfo_endpoint = 6; - */ - userinfoEndpoint = ""; - - /** - * Supported OIDC scopes for this service - * - * @generated from field: repeated string scopes_supported = 7; - */ - scopesSupported: string[] = []; - - /** - * Supported response types - * - * @generated from field: repeated string response_types_supported = 8; - */ - responseTypesSupported: string[] = []; - - /** - * Supported grant types - * - * @generated from field: repeated string grant_types_supported = 9; - */ - grantTypesSupported: string[] = []; - - /** - * ID token signing algorithm values supported - * - * @generated from field: repeated string id_token_signing_alg_values_supported = 10; - */ - idTokenSigningAlgValuesSupported: string[] = []; - - /** - * Subject types supported - * - * @generated from field: repeated string subject_types_supported = 11; - */ - subjectTypesSupported: string[] = []; - - /** - * Token endpoint auth methods supported - * - * @generated from field: repeated string token_endpoint_auth_methods_supported = 12; - */ - tokenEndpointAuthMethodsSupported: string[] = []; - - /** - * Claims supported in ID tokens - * - * @generated from field: repeated string claims_supported = 13; - */ - claimsSupported: string[] = []; - - /** - * Response modes supported - * - * @generated from field: repeated string response_modes_supported = 14; - */ - responseModesSupported: string[] = []; - - /** - * Additional OIDC metadata as key-value pairs - * - * @generated from field: map metadata = 15; - */ - metadata: { [key: string]: string } = {}; - - /** - * Unix timestamp when this config was created - * - * @generated from field: int64 created_at = 16; - */ - createdAt = protoInt64.zero; - - /** - * Unix timestamp when this config was last updated - * - * @generated from field: int64 updated_at = 17; - */ - updatedAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.ServiceOIDCConfig"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "issuer", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "authorization_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "token_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "jwks_uri", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "userinfo_endpoint", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "scopes_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 8, name: "response_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 9, name: "grant_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 10, name: "id_token_signing_alg_values_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 11, name: "subject_types_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 12, name: "token_endpoint_auth_methods_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 13, name: "claims_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 14, name: "response_modes_supported", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 15, name: "metadata", kind: "map", K: 9 /* ScalarType.STRING */, V: {kind: "scalar", T: 9 /* ScalarType.STRING */} }, - { no: 16, name: "created_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - { no: 17, name: "updated_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ServiceOIDCConfig { - return new ServiceOIDCConfig().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ServiceOIDCConfig { - return new ServiceOIDCConfig().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ServiceOIDCConfig { - return new ServiceOIDCConfig().fromJsonString(jsonString, options); - } - - static equals(a: ServiceOIDCConfig | PlainMessage | undefined, b: ServiceOIDCConfig | PlainMessage | undefined): boolean { - return proto3.util.equals(ServiceOIDCConfig, a, b); - } -} - -/** - * JWK represents a JSON Web Key for OIDC - * - * @generated from message svc.v1.JWK - */ -export class JWK extends Message { - /** - * Key type (e.g., "RSA", "EC") - * - * @generated from field: string kty = 1; - */ - kty = ""; - - /** - * Key use (e.g., "sig", "enc") - * - * @generated from field: string use = 2; - */ - use = ""; - - /** - * Key ID - * - * @generated from field: string kid = 3; - */ - kid = ""; - - /** - * Algorithm (e.g., "RS256", "ES256") - * - * @generated from field: string alg = 4; - */ - alg = ""; - - /** - * RSA modulus (for RSA keys) - * - * @generated from field: string n = 5; - */ - n = ""; - - /** - * RSA exponent (for RSA keys) - * - * @generated from field: string e = 6; - */ - e = ""; - - /** - * Elliptic curve (for EC keys) - * - * @generated from field: string crv = 7; - */ - crv = ""; - - /** - * X coordinate (for EC keys) - * - * @generated from field: string x = 8; - */ - x = ""; - - /** - * Y coordinate (for EC keys) - * - * @generated from field: string y = 9; - */ - y = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.JWK"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "kty", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "use", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "kid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "alg", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 5, name: "n", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 6, name: "e", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 7, name: "crv", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 8, name: "x", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 9, name: "y", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): JWK { - return new JWK().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): JWK { - return new JWK().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): JWK { - return new JWK().fromJsonString(jsonString, options); - } - - static equals(a: JWK | PlainMessage | undefined, b: JWK | PlainMessage | undefined): boolean { - return proto3.util.equals(JWK, a, b); - } -} - -/** - * ServiceJWKS represents the JSON Web Key Set for a service - * - * @generated from message svc.v1.ServiceJWKS - */ -export class ServiceJWKS extends Message { - /** - * Service ID this JWKS belongs to - * - * @generated from field: string service_id = 1; - */ - serviceId = ""; - - /** - * List of public keys - * - * @generated from field: repeated svc.v1.JWK keys = 2; - */ - keys: JWK[] = []; - - /** - * Unix timestamp when this JWKS was last rotated - * - * @generated from field: int64 rotated_at = 3; - */ - rotatedAt = protoInt64.zero; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.ServiceJWKS"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "keys", kind: "message", T: JWK, repeated: true }, - { no: 3, name: "rotated_at", kind: "scalar", T: 3 /* ScalarType.INT64 */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): ServiceJWKS { - return new ServiceJWKS().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): ServiceJWKS { - return new ServiceJWKS().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): ServiceJWKS { - return new ServiceJWKS().fromJsonString(jsonString, options); - } - - static equals(a: ServiceJWKS | PlainMessage | undefined, b: ServiceJWKS | PlainMessage | undefined): boolean { - return proto3.util.equals(ServiceJWKS, a, b); - } -} - diff --git a/packages/es/src/protobufs/svc/v1/tx_cosmes.ts b/packages/es/src/protobufs/svc/v1/tx_cosmes.ts deleted file mode 100644 index e548acc2b..000000000 --- a/packages/es/src/protobufs/svc/v1/tx_cosmes.ts +++ /dev/null @@ -1,64 +0,0 @@ -// @generated by protoc-gen-cosmes v0.0.1 with parameter "target=ts" -// @generated from file svc/v1/tx.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import { MsgInitiateDomainVerification, MsgInitiateDomainVerificationResponse, MsgRegisterService, MsgRegisterServiceResponse, MsgUpdateParams, MsgUpdateParamsResponse, MsgVerifyDomain, MsgVerifyDomainResponse } from "./tx_pb.js"; - -const TYPE_NAME = "svc.v1.Msg"; - -/** - * UpdateParams defines a governance operation for updating the parameters. - * - * Since: cosmos-sdk 0.47 - * - * @generated from rpc svc.v1.Msg.UpdateParams - */ -export const MsgUpdateParamsService = { - typeName: TYPE_NAME, - method: "UpdateParams", - Request: MsgUpdateParams, - Response: MsgUpdateParamsResponse, -} as const; - -/** - * InitiateDomainVerification starts the domain verification process - * - * {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service. - * It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}". - * - * {{import "svc_docs.md"}} - * - * @generated from rpc svc.v1.Msg.InitiateDomainVerification - */ -export const MsgInitiateDomainVerificationService = { - typeName: TYPE_NAME, - method: "InitiateDomainVerification", - Request: MsgInitiateDomainVerification, - Response: MsgInitiateDomainVerificationResponse, -} as const; - -/** - * VerifyDomain completes domain verification by checking DNS TXT records - * - * @generated from rpc svc.v1.Msg.VerifyDomain - */ -export const MsgVerifyDomainService = { - typeName: TYPE_NAME, - method: "VerifyDomain", - Request: MsgVerifyDomain, - Response: MsgVerifyDomainResponse, -} as const; - -/** - * RegisterService registers a new service with verified domain binding - * - * @generated from rpc svc.v1.Msg.RegisterService - */ -export const MsgRegisterServiceService = { - typeName: TYPE_NAME, - method: "RegisterService", - Request: MsgRegisterService, - Response: MsgRegisterServiceResponse, -} as const; - diff --git a/packages/es/src/protobufs/svc/v1/tx_pb.ts b/packages/es/src/protobufs/svc/v1/tx_pb.ts deleted file mode 100644 index 88b63edb2..000000000 --- a/packages/es/src/protobufs/svc/v1/tx_pb.ts +++ /dev/null @@ -1,417 +0,0 @@ -// @generated by protoc-gen-es v1.2.0 with parameter "target=ts" -// @generated from file svc/v1/tx.proto (package svc.v1, syntax proto3) -/* eslint-disable */ -// @ts-nocheck - -import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; -import { Message, proto3 } from "@bufbuild/protobuf"; -import { Params } from "./genesis_pb.js"; - -/** - * MsgUpdateParams is the Msg/UpdateParams request type. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message svc.v1.MsgUpdateParams - */ -export class MsgUpdateParams extends Message { - /** - * authority is the address of the governance account. - * - * @generated from field: string authority = 1; - */ - authority = ""; - - /** - * params defines the parameters to update. - * - * NOTE: All parameters must be supplied. - * - * @generated from field: svc.v1.Params params = 2; - */ - params?: Params; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgUpdateParams"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "authority", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "params", kind: "message", T: Params }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParams { - return new MsgUpdateParams().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParams | PlainMessage | undefined, b: MsgUpdateParams | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParams, a, b); - } -} - -/** - * MsgUpdateParamsResponse defines the response structure for executing a - * MsgUpdateParams message. - * - * Since: cosmos-sdk 0.47 - * - * @generated from message svc.v1.MsgUpdateParamsResponse - */ -export class MsgUpdateParamsResponse extends Message { - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgUpdateParamsResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgUpdateParamsResponse { - return new MsgUpdateParamsResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgUpdateParamsResponse | PlainMessage | undefined, b: MsgUpdateParamsResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgUpdateParamsResponse, a, b); - } -} - -/** - * MsgInitiateDomainVerification initiates domain ownership verification - * - * @generated from message svc.v1.MsgInitiateDomainVerification - */ -export class MsgInitiateDomainVerification extends Message { - /** - * Address of the user initiating domain verification - * - * @generated from field: string creator = 1; - */ - creator = ""; - - /** - * Domain to be verified (e.g., "example.com") - * - * @generated from field: string domain = 2; - */ - domain = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgInitiateDomainVerification"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInitiateDomainVerification { - return new MsgInitiateDomainVerification().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInitiateDomainVerification { - return new MsgInitiateDomainVerification().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInitiateDomainVerification { - return new MsgInitiateDomainVerification().fromJsonString(jsonString, options); - } - - static equals(a: MsgInitiateDomainVerification | PlainMessage | undefined, b: MsgInitiateDomainVerification | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInitiateDomainVerification, a, b); - } -} - -/** - * MsgInitiateDomainVerificationResponse defines the response for domain - * verification initiation - * - * @generated from message svc.v1.MsgInitiateDomainVerificationResponse - */ -export class MsgInitiateDomainVerificationResponse extends Message { - /** - * Verification token to be placed in DNS TXT record - * - * @generated from field: string verification_token = 1; - */ - verificationToken = ""; - - /** - * Instructions for DNS TXT record setup - * - * @generated from field: string dns_instruction = 2; - */ - dnsInstruction = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgInitiateDomainVerificationResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verification_token", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "dns_instruction", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgInitiateDomainVerificationResponse { - return new MsgInitiateDomainVerificationResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgInitiateDomainVerificationResponse { - return new MsgInitiateDomainVerificationResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgInitiateDomainVerificationResponse { - return new MsgInitiateDomainVerificationResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgInitiateDomainVerificationResponse | PlainMessage | undefined, b: MsgInitiateDomainVerificationResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgInitiateDomainVerificationResponse, a, b); - } -} - -/** - * MsgVerifyDomain verifies domain ownership by checking DNS TXT records - * - * @generated from message svc.v1.MsgVerifyDomain - */ -export class MsgVerifyDomain extends Message { - /** - * Address of the user verifying domain ownership - * - * @generated from field: string creator = 1; - */ - creator = ""; - - /** - * Domain to be verified - * - * @generated from field: string domain = 2; - */ - domain = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgVerifyDomain"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgVerifyDomain { - return new MsgVerifyDomain().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgVerifyDomain { - return new MsgVerifyDomain().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgVerifyDomain { - return new MsgVerifyDomain().fromJsonString(jsonString, options); - } - - static equals(a: MsgVerifyDomain | PlainMessage | undefined, b: MsgVerifyDomain | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgVerifyDomain, a, b); - } -} - -/** - * MsgVerifyDomainResponse defines the response for domain verification - * - * @generated from message svc.v1.MsgVerifyDomainResponse - */ -export class MsgVerifyDomainResponse extends Message { - /** - * Whether verification was successful - * - * @generated from field: bool verified = 1; - */ - verified = false; - - /** - * Message describing verification result - * - * @generated from field: string message = 2; - */ - message = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgVerifyDomainResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "verified", kind: "scalar", T: 8 /* ScalarType.BOOL */ }, - { no: 2, name: "message", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgVerifyDomainResponse { - return new MsgVerifyDomainResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgVerifyDomainResponse { - return new MsgVerifyDomainResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgVerifyDomainResponse { - return new MsgVerifyDomainResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgVerifyDomainResponse | PlainMessage | undefined, b: MsgVerifyDomainResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgVerifyDomainResponse, a, b); - } -} - -/** - * MsgRegisterService registers a new service with verified domain binding - * - * @generated from message svc.v1.MsgRegisterService - */ -export class MsgRegisterService extends Message { - /** - * Address of the service owner - * - * @generated from field: string creator = 1; - */ - creator = ""; - - /** - * Unique identifier for the service - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - /** - * Verified domain to bind to this service - * - * @generated from field: string domain = 3; - */ - domain = ""; - - /** - * List of permissions requested for this service - * - * @generated from field: repeated string requested_permissions = 4; - */ - requestedPermissions: string[] = []; - - /** - * UCAN delegation chain for authorization (JWT-encoded) - * - * @generated from field: string ucan_delegation_chain = 5; - */ - ucanDelegationChain = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgRegisterService"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "creator", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 3, name: "domain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 4, name: "requested_permissions", kind: "scalar", T: 9 /* ScalarType.STRING */, repeated: true }, - { no: 5, name: "ucan_delegation_chain", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterService { - return new MsgRegisterService().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterService { - return new MsgRegisterService().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterService { - return new MsgRegisterService().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterService | PlainMessage | undefined, b: MsgRegisterService | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterService, a, b); - } -} - -/** - * MsgRegisterServiceResponse defines the response for service registration - * - * @generated from message svc.v1.MsgRegisterServiceResponse - */ -export class MsgRegisterServiceResponse extends Message { - /** - * IPFS CID of the generated root capability - * - * @generated from field: string root_capability_cid = 1; - */ - rootCapabilityCid = ""; - - /** - * Service registration details - * - * @generated from field: string service_id = 2; - */ - serviceId = ""; - - constructor(data?: PartialMessage) { - super(); - proto3.util.initPartial(data, this); - } - - static readonly runtime: typeof proto3 = proto3; - static readonly typeName = "svc.v1.MsgRegisterServiceResponse"; - static readonly fields: FieldList = proto3.util.newFieldList(() => [ - { no: 1, name: "root_capability_cid", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - { no: 2, name: "service_id", kind: "scalar", T: 9 /* ScalarType.STRING */ }, - ]); - - static fromBinary(bytes: Uint8Array, options?: Partial): MsgRegisterServiceResponse { - return new MsgRegisterServiceResponse().fromBinary(bytes, options); - } - - static fromJson(jsonValue: JsonValue, options?: Partial): MsgRegisterServiceResponse { - return new MsgRegisterServiceResponse().fromJson(jsonValue, options); - } - - static fromJsonString(jsonString: string, options?: Partial): MsgRegisterServiceResponse { - return new MsgRegisterServiceResponse().fromJsonString(jsonString, options); - } - - static equals(a: MsgRegisterServiceResponse | PlainMessage | undefined, b: MsgRegisterServiceResponse | PlainMessage | undefined): boolean { - return proto3.util.equals(MsgRegisterServiceResponse, a, b); - } -} - diff --git a/packages/es/src/registry/apis/getChainRegistryAssetList.ts b/packages/es/src/registry/apis/getChainRegistryAssetList.ts deleted file mode 100644 index ac46fdd73..000000000 --- a/packages/es/src/registry/apis/getChainRegistryAssetList.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { ChainRegistryAssetList } from '../types/ChainRegistryAssetList'; - -export async function getChainRegistryAssetList(chain: string): Promise { - const res = await fetch( - `https://raw.githubusercontent.com/cosmos/chain-registry/master/${chain}/assetlist.json` - ); - return res.json(); -} diff --git a/packages/es/src/registry/apis/getChainRegistryChainInfo.ts b/packages/es/src/registry/apis/getChainRegistryChainInfo.ts deleted file mode 100644 index e33620305..000000000 --- a/packages/es/src/registry/apis/getChainRegistryChainInfo.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { ChainRegistryChainInfo } from '../types/ChainRegistryChainInfo'; - -export async function getChainRegistryChainInfo(chain: string): Promise { - const res = await fetch( - `https://raw.githubusercontent.com/cosmos/chain-registry/master/${chain}/chain.json` - ); - return res.json(); -} diff --git a/packages/es/src/registry/index.ts b/packages/es/src/registry/index.ts deleted file mode 100644 index 09a57e074..000000000 --- a/packages/es/src/registry/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type * from '@keplr-wallet/types'; -export { getChainRegistryAssetList } from './apis/getChainRegistryAssetList'; -export { getChainRegistryChainInfo } from './apis/getChainRegistryChainInfo'; -export type { ChainRegistryAssetList } from './types/ChainRegistryAssetList'; -export type { ChainRegistryChainInfo } from './types/ChainRegistryChainInfo'; diff --git a/packages/es/src/registry/types/ChainRegistryAssetList.ts b/packages/es/src/registry/types/ChainRegistryAssetList.ts deleted file mode 100644 index 797a19501..000000000 --- a/packages/es/src/registry/types/ChainRegistryAssetList.ts +++ /dev/null @@ -1,270 +0,0 @@ -/* eslint-disable */ -/** - * This file was automatically generated by json-schema-to-typescript. - * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, - * and run json-schema-to-typescript to regenerate this file. - */ - -/** - * Asset lists are a similar mechanism to allow frontends and other UIs to fetch metadata associated with Cosmos SDK denoms, especially for assets sent over IBC. - */ -export interface ChainRegistryAssetList { - $schema?: string; - chain_name: string; - assets: Asset[]; -} -export interface Asset { - /** - * [OPTIONAL] Whether the asset has been deprecated for use. For readability, it is best to omit this property unless TRUE. - */ - deprecated?: boolean; - /** - * [OPTIONAL] A short description of the asset - */ - description?: string; - /** - * [OPTIONAL] A long description of the asset - */ - extended_description?: string; - denom_units: DenomUnit[]; - /** - * [OPTIONAL] The potential options for type of asset. By default, assumes sdk.coin - */ - type_asset: - | 'sdk.coin' - | 'cw20' - | 'erc20' - | 'ics20' - | 'snip20' - | 'snip25' - | 'bitcoin-like' - | 'evm-base' - | 'svm-base' - | 'substrate' - | 'unknown'; - /** - * [OPTIONAL] The address of the asset. Only required for type_asset : cw20, snip20 - */ - address?: string; - /** - * The base unit of the asset. Must be in denom_units. - */ - base: string; - /** - * The project name of the asset. For example Bitcoin. - */ - name: string; - /** - * The human friendly unit of the asset. Must be in denom_units. - */ - display: string; - /** - * The symbol of an asset. For example BTC. - */ - symbol: string; - /** - * The origin of the asset, starting with the index, and capturing all transitions in form and location. - */ - traces?: (IbcTransition | IbcCw20Transition | IbcBridgeTransition | NonIbcTransition)[]; - /** - * [OPTIONAL] IBC Channel between src and dst between chain - */ - ibc?: { - source_channel: string; - dst_channel: string; - source_denom: string; - }; - logo_URIs?: { - png?: string; - svg?: string; - }; - /** - * @minItems 1 - */ - images?: [ - { - image_sync?: Pointer; - png?: string; - svg?: string; - theme?: { - circle?: boolean; - dark_mode?: boolean; - monochrome?: boolean; - }; - }, - ...{ - image_sync?: Pointer; - png?: string; - svg?: string; - theme?: { - circle?: boolean; - dark_mode?: boolean; - monochrome?: boolean; - }; - }[], - ]; - /** - * [OPTIONAL] The coingecko id to fetch asset data from coingecko v3 api. See https://api.coingecko.com/api/v3/coins/list - */ - coingecko_id?: string; - keywords?: string[]; - socials?: { - website?: string; - twitter?: string; - telegram?: string; - discord?: string; - github?: string; - medium?: string; - reddit?: string; - }; -} -export interface DenomUnit { - denom: string; - exponent: number; - aliases?: string[]; -} -export interface IbcTransition { - type: 'ibc'; - counterparty: { - /** - * The name of the counterparty chain. (must match exactly the chain name used in the Chain Registry) - */ - chain_name: string; - /** - * The base unit of the asset on its source platform. E.g., when describing ATOM from Cosmos Hub, specify 'uatom', NOT 'atom' nor 'ATOM'; base units are unique per platform. - */ - base_denom: string; - /** - * The counterparty IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - }; - chain: { - /** - * The chain's IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - /** - * The port/channel/denom input string that generates the 'ibc/...' denom. - */ - path: string; - }; -} -export interface IbcCw20Transition { - type: 'ibc-cw20'; - counterparty: { - /** - * The name of the counterparty chain. (must match exactly the chain name used in the Chain Registry) - */ - chain_name: string; - /** - * The base unit of the asset on its source platform. E.g., when describing ATOM from Cosmos Hub, specify 'uatom', NOT 'atom' nor 'ATOM'; base units are unique per platform. - */ - base_denom: string; - /** - * The port used to transfer IBC assets; often 'transfer', but sometimes varies, e.g., for outgoing cw20 transfers. - */ - port: string; - /** - * The counterparty IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - }; - chain: { - /** - * The port used to transfer IBC assets; often 'transfer', but sometimes varies, e.g., for outgoing cw20 transfers. - */ - port: string; - /** - * The chain's IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - /** - * The port/channel/denom input string that generates the 'ibc/...' denom. - */ - path: string; - }; -} -export interface IbcBridgeTransition { - type: 'ibc-bridge'; - counterparty: { - /** - * The name of the counterparty chain. (must match exactly the chain name used in the Chain Registry) - */ - chain_name: string; - /** - * The base unit of the asset on its source platform. E.g., when describing ATOM from Cosmos Hub, specify 'uatom', NOT 'atom' nor 'ATOM'; base units are unique per platform. - */ - base_denom: string; - /** - * The port used to transfer IBC assets; often 'transfer', but sometimes varies, e.g., for outgoing cw20 transfers. - */ - port?: string; - /** - * The counterparty IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - }; - chain: { - /** - * The port used to transfer IBC assets; often 'transfer', but sometimes varies, e.g., for outgoing cw20 transfers. - */ - port?: string; - /** - * The chain's IBC transfer channel(, e.g., 'channel-1'). - */ - channel_id: string; - /** - * The port/channel/denom input string that generates the 'ibc/...' denom. - */ - path: string; - }; - /** - * The entity offering the service. E.g., 'Gravity Bridge' [Network] or 'Tether' [Company]. - */ - provider: string; -} -export interface NonIbcTransition { - type: - | 'bridge' - | 'liquid-stake' - | 'synthetic' - | 'wrapped' - | 'additional-mintage' - | 'test-mintage' - | 'legacy-mintage'; - counterparty: { - /** - * The chain or platform from which the asset originates. E.g., 'cosmoshub', 'ethereum', 'forex', or 'nasdaq' - */ - chain_name: string; - base_denom: string; - /** - * The contract address where the transition takes place, where applicable. E.g., The Ethereum contract that locks up the asset while it's minted on another chain. - */ - contract?: string; - }; - chain?: { - /** - * The contract address where the transition takes place, where applicable. E.g., The Ethereum contract that locks up the asset while it's minted on another chain. - */ - contract: string; - }; - /** - * The entity offering the service. E.g., 'Gravity Bridge' [Network] or 'Tether' [Company]. - */ - provider: string; -} -/** - * The (primary) key used to identify an object within the Chain Registry. - */ -export interface Pointer { - /** - * The chain name or platform from which the object resides. E.g., 'cosmoshub', 'ethereum', 'forex', or 'nasdaq' - */ - chain_name: string; - /** - * The base denom of the asset from which the object originates. E.g., when describing ATOM from Cosmos Hub, specify 'uatom', NOT 'atom' nor 'ATOM'; base units are unique per platform. - */ - base_denom?: string; -} diff --git a/packages/es/src/registry/types/ChainRegistryChainInfo.ts b/packages/es/src/registry/types/ChainRegistryChainInfo.ts deleted file mode 100644 index 0cbf6d2ed..000000000 --- a/packages/es/src/registry/types/ChainRegistryChainInfo.ts +++ /dev/null @@ -1,239 +0,0 @@ -/* eslint-disable */ -/** - * This file was automatically generated by json-schema-to-typescript. - * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, - * and run json-schema-to-typescript to regenerate this file. - */ - -/** - * Chain.json is a metadata file that contains information about a blockchain. - */ -export type ChainRegistryChainInfo = ChainRegistryChainInfo1 & ChainRegistryChainInfo2; -export type ChainRegistryChainInfo1 = { - [k: string]: unknown | undefined; -}; -/** - * Detailed version identifier (e.g., 'v1.0.0-a1s2f43g'). - */ -export type Tag = string; -/** - * Simple version string (e.g., 'v1.0.0'). - */ -export type Version = string; -/** - * URL of the code repository. - */ -export type Repo = string; - -export interface ChainRegistryChainInfo2 { - $schema?: string; - chain_name: string; - /** - * The 'type' of chain as the corresponding CAIP-2 Namespace value. E.G., 'cosmos' or 'eip155'. Namespaces cna be found here: https://github.com/ChainAgnostic/namespaces/tree/main. - */ - chain_type: - | 'cosmos' - | 'eip155' - | 'bip122' - | 'polkadot' - | 'solana' - | 'algorand' - | 'arweave' - | 'ergo' - | 'fil' - | 'hedera' - | 'monero' - | 'reef' - | 'stacks' - | 'starknet' - | 'stellar' - | 'tezos' - | 'vechain' - | 'waves' - | 'xrpl' - | 'unknown'; - chain_id?: string; - pre_fork_chain_name?: string; - pretty_name?: string; - website?: string; - status?: 'live' | 'upcoming' | 'killed'; - network_type?: 'mainnet' | 'testnet' | 'devnet'; - /** - * The default prefix for the human-readable part of addresses that identifies the coin type. Must be registered with SLIP-0173. E.g., 'cosmos' - */ - bech32_prefix?: string; - /** - * Used to override the bech32_prefix for specific uses. - */ - bech32_config?: { - /** - * e.g., 'cosmos' - */ - bech32PrefixAccAddr?: string; - /** - * e.g., 'cosmospub' - */ - bech32PrefixAccPub?: string; - /** - * e.g., 'cosmosvaloper' - */ - bech32PrefixValAddr?: string; - /** - * e.g., 'cosmosvaloperpub' - */ - bech32PrefixValPub?: string; - /** - * e.g., 'cosmosvalcons' - */ - bech32PrefixConsAddr?: string; - /** - * e.g., 'cosmosvalconspub' - */ - bech32PrefixConsPub?: string; - }; - daemon_name?: string; - node_home?: string; - key_algos?: ('secp256k1' | 'ethsecp256k1' | 'ed25519' | 'sr25519' | 'bn254')[]; - slip44?: number; - alternative_slip44s?: number[]; - fees?: { - fee_tokens: FeeToken[]; - }; - staking?: { - staking_tokens: StakingToken[]; - lock_duration?: { - /** - * The number of blocks for which the staked tokens are locked. - */ - blocks?: number; - /** - * The approximate time for which the staked tokens are locked. - */ - time?: string; - }; - }; - codebase?: { - git_repo?: string; - recommended_version?: string; - compatible_versions?: string[]; - tag?: Tag; - language?: Language; - binaries?: Binaries; - sdk?: Sdk; - consensus?: Consensus; - cosmwasm?: Cosmwasm; - ibc?: Ibc; - genesis?: { - name?: string; - genesis_url: string; - ics_ccv_url?: string; - }; - }; - images?: ( - | { - [k: string]: unknown | undefined; - } - | { - [k: string]: unknown | undefined; - } - )[]; - logo_URIs?: { - png?: string; - svg?: string; - }; - description?: string; - peers?: { - seeds?: Peer[]; - persistent_peers?: Peer[]; - }; - apis?: { - rpc?: Endpoint[]; - rest?: Endpoint[]; - grpc?: Endpoint[]; - wss?: Endpoint[]; - 'grpc-web'?: Endpoint[]; - 'evm-http-jsonrpc'?: Endpoint[]; - }; - explorers?: Explorer[]; - keywords?: string[]; - extra_codecs?: ('ethermint' | 'injective')[]; -} -export interface FeeToken { - denom: string; - fixed_min_gas_price?: number; - low_gas_price?: number; - average_gas_price?: number; - high_gas_price?: number; - gas_costs?: { - cosmos_send?: number; - ibc_transfer?: number; - }; -} -export interface StakingToken { - denom: string; -} -export interface Language { - type: 'go' | 'rust' | 'solidity' | 'other'; - version?: Version; - repo?: Repo; - tag?: Tag; -} -export interface Binaries { - 'linux/amd64'?: string; - 'linux/arm64'?: string; - 'darwin/amd64'?: string; - 'darwin/arm64'?: string; - 'windows/amd64'?: string; - 'windows/arm64'?: string; -} -export interface Sdk { - type: 'cosmos' | 'penumbra' | 'other'; - version?: Version; - repo?: Repo; - tag?: Tag; -} -export interface Consensus { - type: 'tendermint' | 'cometbft' | 'sei-tendermint'; - version?: Version; - repo?: Repo; - tag?: Tag; -} -export interface Cosmwasm { - version?: Version; - repo?: Repo; - tag?: Tag; - enabled?: boolean; - /** - * Relative path to the cosmwasm directory. ex. $HOME/.juno/data/wasm - */ - path?: string; -} -export interface Ibc { - type: 'go' | 'rust' | 'other'; - version?: Version; - repo?: Repo; - tag?: Tag; - /** - * List of IBC apps (usually corresponding to a ICS standard) which have been enabled on the network. - */ - ics_enabled?: ('ics20-1' | 'ics27-1' | 'mauth')[]; -} -export interface Peer { - id: string; - address: string; - provider?: string; -} -export interface Endpoint { - address: string; - provider?: string; - archive?: boolean; -} -export interface Explorer { - kind?: string; - url?: string; - tx_page?: string; - account_page?: string; - validator_page?: string; - proposal_page?: string; - block_page?: string; -} diff --git a/packages/es/src/typeutils/prettify.ts b/packages/es/src/typeutils/prettify.ts deleted file mode 100644 index 87de58fac..000000000 --- a/packages/es/src/typeutils/prettify.ts +++ /dev/null @@ -1,18 +0,0 @@ -type Decr = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - -/** - * Helper type to prettify type intersections. - * @see https://twitter.com/mattpocockuk/status/1622730181453533185 - */ -export type Prettify = { - [P in keyof T]: T[P]; -} & unknown; - -/** - * Helper type to prettify deeply nested types. - */ -export type DeepPrettify = N extends 0 - ? T - : T extends Record | unknown[] - ? { [P in keyof T]: DeepPrettify } - : T; diff --git a/packages/es/src/wallet/constants/WalletName.ts b/packages/es/src/wallet/constants/WalletName.ts deleted file mode 100644 index de46a3b5d..000000000 --- a/packages/es/src/wallet/constants/WalletName.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * The unique identifier of the wallet. - */ -export const WalletName = { - STATION: 'station', - KEPLR: 'keplr', - LEAP: 'leap', - COMPASS: 'compass', - COSMOSTATION: 'cosmostation', - METAMASK_INJECTIVE: 'metamask-injective', - NINJI: 'ninji', - OWALLET: 'owallet', -} as const; -export type WalletName = (typeof WalletName)[keyof typeof WalletName]; diff --git a/packages/es/src/wallet/constants/WalletType.ts b/packages/es/src/wallet/constants/WalletType.ts deleted file mode 100644 index 7fd567b11..000000000 --- a/packages/es/src/wallet/constants/WalletType.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * The type of connection to the wallet. - */ -export const WalletType = { - EXTENSION: 'extension', - WALLETCONNECT: 'walletconnect', -} as const; -export type WalletType = (typeof WalletType)[keyof typeof WalletType]; diff --git a/packages/es/src/wallet/index.ts b/packages/es/src/wallet/index.ts deleted file mode 100644 index 63e036442..000000000 --- a/packages/es/src/wallet/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { WalletName } from './constants/WalletName'; -export { WalletType } from './constants/WalletType'; -export { isAndroid, isIOS, isMobile } from './utils/os'; -export { verifyArbitrary } from './utils/verify'; -export { - ConnectedWallet, - type PollTxOptions, - type SignArbitraryResponse, - type UnsignedTx, -} from './wallets/ConnectedWallet'; -export { MnemonicWallet } from './wallets/mnemonic/MnemonicWallet'; -export { - type ChainInfo, - type EventCallback, - WalletController, -} from './wallets/WalletController'; -export { WalletError } from './wallets/WalletError'; diff --git a/packages/es/src/wallet/utils/os.ts b/packages/es/src/wallet/utils/os.ts deleted file mode 100644 index ed61165d2..000000000 --- a/packages/es/src/wallet/utils/os.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function isAndroid() { - return navigator && /Android/i.test(navigator.userAgent); -} - -/** - * @see https://stackoverflow.com/a/58065241 - */ -export function isIOS() { - return ( - navigator && - (/iPhone|iPad|iPod/i.test(navigator.userAgent) || - (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) - ); -} - -export function isMobile() { - return isAndroid() || isIOS(); -} diff --git a/packages/es/src/wallet/utils/sequence.test.ts b/packages/es/src/wallet/utils/sequence.test.ts deleted file mode 100644 index 0f283ff46..000000000 --- a/packages/es/src/wallet/utils/sequence.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { extractExpectedAccountSequence } from './sequence'; - -describe('extractExpectedAccountSequence', () => { - it('should extract expected account sequence numbers from valid errors', () => { - // Older cosmos sdk chains - const err1 = new Error( - 'account sequence mismatch, expected 10, got 11: incorrect account sequence: invalid request' - ); - expect(extractExpectedAccountSequence(err1)).toBe(10n); - - // Newer cosmos sdk chains (0.45+) - const err2 = new Error( - 'rpc error: code = Unknown desc = account sequence mismatch, expected 10, got 11: ......' - ); - expect(extractExpectedAccountSequence(err2)).toBe(10n); - - // Injective - const err3 = new Error( - `[reason]:"incorrect account sequence" metadata:{key:"ABCICode" value:"32"} ...... rpc error: code = Unknown desc = account sequence mismatch, expected 10, got 11: ......` - ); - expect(extractExpectedAccountSequence(err3)).toBe(10n); - }); -}); diff --git a/packages/es/src/wallet/utils/sequence.ts b/packages/es/src/wallet/utils/sequence.ts deleted file mode 100644 index 0e5777a80..000000000 --- a/packages/es/src/wallet/utils/sequence.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Extracts and returns the expected account sequence number from an error. If - * the error is not related to an account sequence mismatch, `null` is returned. - */ -export function extractExpectedAccountSequence(err: Error): bigint | null { - const matches = err.message.match( - // This regex is intentionally kept as strict as possible - /account sequence mismatch, expected (\d+), got (\d+):/ - ); - if (!matches || matches.length < 3) { - return null; - } - return BigInt(matches[1]); -} diff --git a/packages/es/src/wallet/utils/verify.ts b/packages/es/src/wallet/utils/verify.ts deleted file mode 100644 index 9d8b82206..000000000 --- a/packages/es/src/wallet/utils/verify.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { base64, utf8, verifyADR36, verifyECDSA, verifyEIP191 } from '@sonr.io/es/codec'; - -import { WalletName } from '../constants/WalletName'; - -type VerifyArbitraryParams = { - /** The identifier of the wallet which created the signature */ - wallet: WalletName; - /** The base64 encoded public key which created the signature */ - pubKey: string; - /** The bech32 account address prefix of the signer */ - bech32Prefix: string; - /** The utf-8 encoded arbitrary string that was signed */ - data: string; - /** The base64 encoded string of the signature */ - signature: string; - /** The type of the signature */ - type?: 'secp256k1' | 'ethsecp256k1'; -}; - -/** - * Verifies the signature output of a valid call to `ConnectedWallet.signArbitrary`. - * Returns `true` if and only if the signature is valid. - * - * @param wallet The identifier of the wallet which created the signature - * @param pubKey The base64 encoded public key which created the signature - * @param bech32Prefix The bech32 account address prefix of the signer - * @param data The utf-8 encoded arbitrary string that was signed - * @param signature The base64 encoded string of the signature - * @param type The type of the signature (default: `secp256k1`) - */ -export function verifyArbitrary({ - wallet, - pubKey, - bech32Prefix, - data, - signature, - type = 'secp256k1', -}: VerifyArbitraryParams): boolean { - const params = { - pubKey: base64.decode(pubKey), - bech32Prefix, - data: utf8.decode(data), - signature: base64.decode(signature), - type, - }; - try { - switch (wallet) { - case WalletName.METAMASK_INJECTIVE: - return verifyEIP191(params); - default: - // Station mobile uses `verifyECDSA`, all other wallets uses `verifyADR36`. - // We can remove `verifyECDSA` once Station mobile uses `verifyECDSA`. - return verifyADR36(params) || verifyECDSA(params); - } - } catch (_err) { - return false; - } -} diff --git a/packages/es/src/wallet/utils/window.ts b/packages/es/src/wallet/utils/window.ts deleted file mode 100644 index 5c0ae6190..000000000 --- a/packages/es/src/wallet/utils/window.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Similar to `window.addEventListener`, but safe for nodejs/SSR environments, - * and which returns an `unsubscribe` function that when called, removes the - * event listener via `window.removeEventListener`. - */ -export function onWindowEvent( - event: string, - cb: EventListenerOrEventListenerObject, - opts?: AddEventListenerOptions | undefined -): () => void { - if (typeof window === 'undefined') { - // eslint-disable-next-line @typescript-eslint/no-empty-function - return () => {}; - } - window.addEventListener(event, cb, opts); - return () => window.removeEventListener(event, cb); -} diff --git a/packages/es/src/wallet/walletconnect/QRCodeModal.ts b/packages/es/src/wallet/walletconnect/QRCodeModal.ts deleted file mode 100644 index a4710233d..000000000 --- a/packages/es/src/wallet/walletconnect/QRCodeModal.ts +++ /dev/null @@ -1,145 +0,0 @@ -import type { IQRCodeModal } from '@walletconnect/legacy-types'; - -import { isAndroid, isMobile } from '../utils/os'; -import { qrcodegen } from './qrcodegen'; - -export type MobileAppDetails = { - name: string; - android: string; - ios: string; - isStation?: boolean | undefined; -}; - -export class QRCodeModal implements IQRCodeModal { - private readonly id = `wc-modal-${Date.now()}`; - private readonly details: MobileAppDetails; - - constructor(details: MobileAppDetails) { - this.details = details; - } - - public open(uri: string): void { - const overlay = document.createElement('div'); - overlay.style.cssText = [ - 'background-color: rgba(0, 0, 0, 0.5)', - 'backdrop-filter: blur(4px)', - 'z-index: 10000', - 'height: 100vh', - 'width: 100vw', - 'position: fixed', - 'top: 0', - 'left: 0', - 'display: flex', - 'align-items: center', - 'justify-content: center', - 'pointer-events: auto', - ].join(';'); - overlay.onclick = (e): void => { - e.stopPropagation(); - if (e.target === overlay) { - this.close(); - } - }; - - const modal = document.createElement('div'); - modal.style.cssText = [ - 'background-color: #f4f4f5', - 'padding: 1rem', - 'border-radius: 0.5rem', - ].join(';'); - - const schemeUri = this.details.isStation - ? `https://terrastation.page.link/?link=https://terra.money?${encodeURIComponent( - `action=wallet_connect&payload=${encodeURIComponent(uri)}` - )}&apn=money.terra.station&ibi=money.terra.station&isi=1548434735` - : uri; - const qr = qrcodegen.QrCode.encodeText(schemeUri, qrcodegen.QrCode.Ecc.MEDIUM); - const canvas = document.createElement('canvas'); - const scale = this.details.isStation ? 3.7 : 5; - canvas.width = qr.size * scale; - canvas.height = canvas.width; - const ctx = canvas.getContext('2d'); - if (!ctx) { - console.error('Failed to get canvas context'); - return; - } - for (let y = 0; y < qr.size; y++) { - for (let x = 0; x < qr.size; x++) { - ctx.fillStyle = qr.getModule(x, y) ? '#18181b' : '#f4f4f5'; - ctx.fillRect(x * scale, y * scale, scale, scale); - } - } - - if (isMobile()) { - // On mobile, render button to open mobile app and QR code as fallback - const openAppButton = document.createElement('button'); - openAppButton.textContent = `Open ${this.details.name}`; - openAppButton.style.cssText = [ - 'background-color: #3b82f6', - 'color: white', - 'padding: 0.75rem 1.5rem', - 'border: none', - 'border-radius: 0.375rem', - 'font-size: 1rem', - 'font-weight: 600', - 'cursor: pointer', - 'margin-bottom: 1rem', - 'width: 100%', - ].join(';'); - openAppButton.onclick = () => { - window.location.href = this.details.isStation - ? schemeUri - : isAndroid() - ? this.generateAndroidIntent(uri) - : this.generateIosIntent(uri); - }; - modal.appendChild(openAppButton); - - const orText = document.createElement('div'); - orText.textContent = 'or scan QR code'; - orText.style.cssText = [ - 'text-align: center', - 'margin-bottom: 0.5rem', - 'color: #6b7280', - 'font-size: 0.875rem', - ].join(';'); - modal.appendChild(orText); - } else { - // On desktop, show help message to scan the QR code - const msg = document.createElement('div'); - msg.textContent = `Scan via ${this.details.name} mobile app`; - msg.style.cssText = [ - 'margin-bottom: 0.5rem', - 'font-size: 1rem', - 'text-align: center', - 'color: #18181b', - ].join(';'); - modal.appendChild(msg); - } - - const rootDiv = document.createElement('div'); - rootDiv.id = this.id; - const shadowRoot = rootDiv.attachShadow({ mode: 'open' }); - - modal.appendChild(canvas); - overlay.appendChild(modal); - shadowRoot.appendChild(overlay); - document.body.appendChild(rootDiv); - } - - public close(): void { - const rootDiv = document.getElementById(this.id); - if (rootDiv) { - document.body.removeChild(rootDiv); - } - } - - private generateAndroidIntent(uri: string): string { - const hashIndex = this.details.android.indexOf('#'); - return `${this.details.android.slice(0, hashIndex)}?${encodeURIComponent(uri)}${this.details.android.slice(hashIndex)}`; - } - - private generateIosIntent(uri: string): string { - return `${this.details.ios}?${encodeURIComponent(uri)}`; - } -} diff --git a/packages/es/src/wallet/walletconnect/WalletConnectV1.ts b/packages/es/src/wallet/walletconnect/WalletConnectV1.ts deleted file mode 100644 index 2fbb5c7d0..000000000 --- a/packages/es/src/wallet/walletconnect/WalletConnectV1.ts +++ /dev/null @@ -1,85 +0,0 @@ -import WalletConnect from '@walletconnect/legacy-client'; -import type { IWalletConnectSession } from '@walletconnect/legacy-types'; - -import { type MobileAppDetails, QRCodeModal } from './QRCodeModal'; - -type ConnectOptions = Required< - Pick[0], 'bridge' | 'signingMethods'> ->; - -export class WalletConnectV1 { - private readonly sessionStorageKey: string; - private readonly mobileAppDetails: MobileAppDetails; - private readonly connectOpts: ConnectOptions; - private readonly onDisconnectCbs: Set<() => unknown>; - - constructor( - sessionStorageKey: string, - mobileAppDetails: MobileAppDetails, - connectOpts: ConnectOptions - ) { - this.sessionStorageKey = sessionStorageKey; - this.mobileAppDetails = mobileAppDetails; - this.connectOpts = connectOpts; - this.onDisconnectCbs = new Set(); - } - - /** - * Returns the current session if it exists, else, creates a new session. - */ - public async connect(): Promise { - // Get cached session in local storage - const cachedSession = localStorage.getItem(this.sessionStorageKey); - const session = cachedSession - ? (JSON.parse(cachedSession) as IWalletConnectSession) - : undefined; - - // Create a new WalletConnect instance - const wc = new WalletConnect({ - ...this.connectOpts, - qrcodeModal: new QRCodeModal(this.mobileAppDetails), - session, - }); - wc.on('disconnect', () => { - localStorage.removeItem(this.sessionStorageKey); - for (const cb of this.onDisconnectCbs) { - cb(); - } - }); - - // If a previous session exists, return the WalletConnect instance - if (session && wc.connected) { - return wc; - } - - // Else, if no previous session exists, create a new session - if (wc.connected) { - await wc.killSession(); - } - await wc.createSession(); - - // Return the WalletConnect instance once connected - return new Promise((resolve, reject) => { - wc.on('connect', (error, _payload) => { - // Do NOT cache the session here as the user may not have approved the connection - error ? reject(error) : resolve(wc); - }); - }); - } - - public onDisconnect(cb: () => unknown): () => void { - this.onDisconnectCbs.add(cb); - return () => this.onDisconnectCbs.delete(cb); - } - - /** - * Saves the session to local storage. Should only be called once the user actually - * approves the connection to the chain. - */ - public cacheSession(wc: WalletConnect) { - if (!wc.connected) { - return; - } - localStorage.setItem(this.sessionStorageKey, JSON.stringify(wc.session)); - } -} diff --git a/packages/es/src/wallet/walletconnect/WalletConnectV2.ts b/packages/es/src/wallet/walletconnect/WalletConnectV2.ts deleted file mode 100644 index 4498f0696..000000000 --- a/packages/es/src/wallet/walletconnect/WalletConnectV2.ts +++ /dev/null @@ -1,289 +0,0 @@ -import type { SignDoc, StdSignDoc } from '@sonr.io/es/registry'; -import SignClient from '@walletconnect/sign-client'; -import { debounce } from 'lodash-es'; - -import { isAndroid, isMobile } from '../utils/os'; -import { type MobileAppDetails, QRCodeModal } from './QRCodeModal'; - -/** The JSON data stored in `localStorage` to recover previous sessions. */ -type StorageSession = { - /** The WalletConnect V2 topic. */ - topic: string; - /** Non-namespaced chain IDs (eg. `osmosis-1`). */ - chainIds: string[]; -}; - -type GetAccountResponse = { - name?: string | undefined; - address: string; - algo: string; - pubkey: string; -}; - -/** - * The data returned by the `cosmos_signAmino` method. `signed` is optional - * because some wallets (like Cosmostation) may not return it. - */ -type WcSignAminoResponse = { - signature: { - signature: string; - }; - signed?: StdSignDoc | undefined; -}; -type SignAminoResponse = Required; - -/** - * The data returned by the `cosmos_signDirect` method. `signed` is optional - * because some wallets (like Cosmostation) may not return it. - */ -type WcSignDirectResponse = { - signature: { - signature: string; - }; - signed?: SignDoc | undefined; -}; -type SignDirectResponse = Required; - -const Method = { - GET_ACCOUNTS: 'cosmos_getAccounts', - SIGN_AMINO: 'cosmos_signAmino', - SIGN_DIRECT: 'cosmos_signDirect', -} as const; -type Method = (typeof Method)[keyof typeof Method]; - -const Event = { - CHAIN_CHANGED: 'chainChanged', - ACCOUNTS_CHANGED: 'accountsChanged', -} as const; -type Event = (typeof Event)[keyof typeof Event]; - -const DEFAULT_SIGN_OPTIONS = { - preferNoSetFee: true, - preferNoSetMemo: true, -}; - -export class WalletConnectV2 { - private readonly projectId: string; - private readonly mobileAppDetails: MobileAppDetails; - private readonly sessionStorageKey: string; - private readonly onDisconnectCbs: Set<() => unknown>; - private readonly onAccountChangeCbs: Set<() => unknown>; - private signClient: SignClient | null; - - constructor(projectId: string, mobileAppDetails: MobileAppDetails) { - this.projectId = projectId; - this.mobileAppDetails = mobileAppDetails; - this.sessionStorageKey = `@sonr.io/es.wallet.${mobileAppDetails.name.toLowerCase()}.wcSession`; - this.onDisconnectCbs = new Set(); - this.onAccountChangeCbs = new Set(); - this.signClient = null; - } - - public async connect(chainIds: string[]): Promise { - // Initialise the sign client and event listeners if they don't already exist - if (!this.signClient) { - this.signClient = await SignClient.init({ - projectId: this.projectId, - }); - // Disconnect if the session is disconnected or expired - this.signClient.on('session_delete', ({ topic }) => this.disconnect(topic)); - this.signClient.on('session_expire', ({ topic }) => this.disconnect(topic)); - // Handle the `accountsChanged` event - const handleAccountChange = debounce( - // Handler is debounced as the `accountsChanged` event is fired once for - // each connected chain, but we only want to trigger the callback once. - () => this.onAccountChangeCbs.forEach((cb) => cb()), - 300, - { leading: true, trailing: false } - ); - this.signClient.on('session_event', ({ params }) => { - if (params.event.name === Event.ACCOUNTS_CHANGED) { - handleAccountChange(); - } - }); - } - - // Check if a valid session already exists - const oldSession = localStorage.getItem(this.sessionStorageKey); - const chainIdsSet = new Set(chainIds); - if (oldSession) { - const { topic, chainIds: storedIds } = JSON.parse(oldSession) as StorageSession; - const storedIdsSet = new Set(storedIds); - if (chainIds.every((id) => storedIdsSet.has(id))) { - // If the requested chain IDs are a subset of the stored chain IDs, we can - // proceed to check if the session is still working and connected - if (await this.isConnected(this.signClient, topic, 4)) { - // If the current session is properly connected, we can return early - return; - } - // Otherwise, assume the session is stale and disconnect - this.disconnect(topic); - } else { - // Otherwise, we need to merge the stored IDs with the requested IDs - for (const id of storedIds) { - chainIdsSet.add(id); - } - } - } - - // Initialise a new session - const { uri, approval } = await this.signClient.connect({ - requiredNamespaces: { - cosmos: { - chains: [...chainIdsSet].map((id) => this.toCosmosNamespace(id)), - methods: Object.values(Method), - events: Object.values(Event), - }, - }, - }); - if (uri) { - // Open the QR code modal and wait for the user to approve the connection - const modal = new QRCodeModal(this.mobileAppDetails); - modal.open(uri); - const { topic } = await approval(); - modal.close(); - // Save this new session to local storage - const newSession: StorageSession = { - topic, - chainIds: [...chainIdsSet], - }; - localStorage.setItem(this.sessionStorageKey, JSON.stringify(newSession)); - // Disconnect the older session if it exists - if (oldSession) { - const { topic } = JSON.parse(oldSession) as StorageSession; - this.signClient.disconnect({ - topic, - reason: { code: 6000, message: 'User rejected connection' }, - }); - } - } - } - - public onDisconnect(cb: () => unknown): () => void { - this.onDisconnectCbs.add(cb); - return () => this.onDisconnectCbs.delete(cb); - } - - public onAccountChange(cb: () => unknown): () => void { - this.onAccountChangeCbs.add(cb); - return () => this.onAccountChangeCbs.delete(cb); - } - - public async getAccount(chainId: string): Promise { - const [res] = await this.request(chainId, Method.GET_ACCOUNTS, {}); - return res || { address: '', algo: '', pubkey: '' }; - } - - public async signAmino( - chainId: string, - signerAddress: string, - stdSignDoc: StdSignDoc - ): Promise { - const { signature, signed } = await this.request( - chainId, - Method.SIGN_AMINO, - { - signerAddress, - signDoc: stdSignDoc, - signOptions: DEFAULT_SIGN_OPTIONS, - } - ); - return { - signature: signature, - signed: signed ?? stdSignDoc, // simply return the original sign doc if `signed` is not returned - }; - } - - public async signDirect( - chainId: string, - signerAddress: string, - signDoc: SignDoc - ): Promise { - const { signature, signed } = await this.request( - chainId, - Method.SIGN_DIRECT, - { - signerAddress, - signDoc, - signOptions: DEFAULT_SIGN_OPTIONS, - } - ); - return { - signature: signature, - signed: signed ?? signDoc, // simply return the original sign doc if `signed` is not returned - }; - } - - /** - * Checks if the current session is **really connected**. The `ping` method may - * never return a response if the session is already disconnected. Thus, we - * listen to the `session_delete` and `session_expire` events to detect if the - * session is disconnected. If all else fails, we timeout after `timeoutSeconds` - * and assume the session is not connected. - */ - private isConnected( - signClient: SignClient, - topic: string, - timeoutSeconds: number - ): Promise { - const tryPing = async (): Promise => - signClient - .ping({ topic }) - .then(() => true) // we only return `true` if the ping succeeds - .catch(() => false); - const waitDisconnect = async (): Promise => - new Promise((resolve) => { - signClient.on('session_delete', (res) => { - if (topic === res.topic) { - resolve(false); - } - }); - signClient.on('session_expire', (res) => { - if (topic === res.topic) { - resolve(false); - } - }); - }); - const timeout = async (): Promise => - new Promise((resolve) => setTimeout(() => resolve(false), timeoutSeconds * 1_000)); - return Promise.race([tryPing(), waitDisconnect(), timeout()]); - } - - private disconnect(topic: string) { - const session = localStorage.getItem(this.sessionStorageKey); - if (!session || session.includes(topic)) { - // Ignore stale disconnects; clean up only if the topic matches - localStorage.removeItem(this.sessionStorageKey); - this.onDisconnectCbs.forEach((cb) => cb()); - } - } - - private async request(chainId: string, method: Method, params: unknown) { - const session = localStorage.getItem(this.sessionStorageKey); - if (!session || !this.signClient) { - throw new Error(`Session not found for ${chainId}`); - } - const { topic } = JSON.parse(session) as StorageSession; - if ( - isMobile() && - // GET_ACCOUNTS does not require the user to authorise - method !== Method.GET_ACCOUNTS - ) { - window.location.href = isAndroid() - ? this.mobileAppDetails.android - : this.mobileAppDetails.ios; - } - return this.signClient.request({ - topic, - chainId: this.toCosmosNamespace(chainId), - request: { - method, - params, - }, - }); - } - - private toCosmosNamespace(chainId: string): string { - return `cosmos:${chainId}`; - } -} diff --git a/packages/es/src/wallet/walletconnect/qrcodegen.ts b/packages/es/src/wallet/walletconnect/qrcodegen.ts deleted file mode 100644 index 93ebf2d01..000000000 --- a/packages/es/src/wallet/walletconnect/qrcodegen.ts +++ /dev/null @@ -1,956 +0,0 @@ -export namespace qrcodegen { - type bit = number; - type byte = number; - type int = number; - - /*---- QR Code symbol class ----*/ - - /* - * A QR Code symbol, which is a type of two-dimension barcode. - * Invented by Denso Wave and described in the ISO/IEC 18004 standard. - * Instances of this class represent an immutable square grid of dark and light cells. - * The class provides static factory functions to create a QR Code from text or binary data. - * The class covers the QR Code Model 2 specification, supporting all versions (sizes) - * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. - * - * Ways to create a QR Code object: - * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary(). - * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments(). - * - Low level: Custom-make the array of data codeword bytes (including - * segment headers and final padding, excluding error correction codewords), - * supply the appropriate version number, and call the QrCode() constructor. - * (Note that all ways require supplying the desired error correction level.) - */ - export class QrCode { - /*-- Static factory functions (high level) --*/ - - // Returns a QR Code representing the given Unicode text string at the given error correction level. - // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer - // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible - // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the - // ecl argument if it can be done without increasing the version. - public static encodeText(text: string, ecl: QrCode.Ecc): QrCode { - const segs: Array = qrcodegen.QrSegment.makeSegments(text); - return QrCode.encodeSegments(segs, ecl); - } - - // Returns a QR Code representing the given binary data at the given error correction level. - // This function always encodes using the binary segment mode, not any text mode. The maximum number of - // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. - // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. - public static encodeBinary(data: Readonly>, ecl: QrCode.Ecc): QrCode { - const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data); - return QrCode.encodeSegments([seg], ecl); - } - - /*-- Static factory functions (mid level) --*/ - - // Returns a QR Code representing the given segments with the given encoding parameters. - // The smallest possible QR Code version within the given range is automatically - // chosen for the output. Iff boostEcl is true, then the ECC level of the result - // may be higher than the ecl argument if it can be done without increasing the - // version. The mask number is either between 0 to 7 (inclusive) to force that - // mask, or -1 to automatically choose an appropriate mask (which may be slow). - // This function allows the user to create a custom sequence of segments that switches - // between modes (such as alphanumeric and byte) to encode text in less space. - // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). - public static encodeSegments( - segs: Readonly>, - ecl: QrCode.Ecc, - minVersion: int = 1, - maxVersion: int = 40, - mask: int = -1, - boostEcl = true - ): QrCode { - if ( - !( - QrCode.MIN_VERSION <= minVersion && - minVersion <= maxVersion && - maxVersion <= QrCode.MAX_VERSION - ) || - mask < -1 || - mask > 7 - ) - throw new RangeError('Invalid value'); - - // Find the minimal version number to use - let version: int; - let dataUsedBits: int; - for (version = minVersion; ; version++) { - const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available - const usedBits: number = QrSegment.getTotalBits(segs, version); - if (usedBits <= dataCapacityBits) { - dataUsedBits = usedBits; - break; // This version number is found to be suitable - } - if (version >= maxVersion) - // All versions in the range could not fit the given data - throw new RangeError('Data too long'); - } - - // Increase the error correction level while the data still fits in the current version number - for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { - // From low to high - if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) - ecl = newEcl; - } - - // Concatenate all segments to create the data bit string - const bb: Array = []; - for (const seg of segs) { - appendBits(seg.mode.modeBits, 4, bb); - appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb); - for (const b of seg.getData()) bb.push(b); - } - assert(bb.length === dataUsedBits); - - // Add terminator and pad up to a byte if applicable - const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; - assert(bb.length <= dataCapacityBits); - appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); - appendBits(0, (8 - (bb.length % 8)) % 8, bb); - assert(bb.length % 8 === 0); - - // Pad with alternating bytes until data capacity is reached - for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11) - appendBits(padByte, 8, bb); - - // Pack bits into bytes in big endian - const dataCodewords: Array = []; - while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0); - bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3] |= b << (7 - (i & 7)))); - - // Create the QR Code object - return new QrCode(version, ecl, dataCodewords, mask); - } - - /*-- Fields --*/ - - // The width and height of this QR Code, measured in modules, between - // 21 and 177 (inclusive). This is equal to version * 4 + 17. - public readonly size: int; - - // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). - // Even if a QR Code is created with automatic masking requested (mask = -1), - // the resulting object still has a mask value between 0 and 7. - public readonly mask: int; - - // The modules of this QR Code (false = light, true = dark). - // Immutable after constructor finishes. Accessed through getModule(). - private readonly modules: Array> = []; - - // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. - private readonly isFunction: Array> = []; - - /*-- Constructor (low level) and fields --*/ - - // Creates a new QR Code with the given version number, - // error correction level, data codeword bytes, and mask number. - // This is a low-level API that most users should not use directly. - // A mid-level API is the encodeSegments() function. - public constructor( - // The version number of this QR Code, which is between 1 and 40 (inclusive). - // This determines the size of this barcode. - public readonly version: int, - - // The error correction level used in this QR Code. - public readonly errorCorrectionLevel: QrCode.Ecc, - - dataCodewords: Readonly>, - - msk: int - ) { - // Check scalar arguments - if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) - throw new RangeError('Version value out of range'); - if (msk < -1 || msk > 7) throw new RangeError('Mask value out of range'); - this.size = version * 4 + 17; - - // Initialize both grids to be size*size arrays of Boolean false - const row: Array = []; - for (let i = 0; i < this.size; i++) row.push(false); - for (let i = 0; i < this.size; i++) { - this.modules.push(row.slice()); // Initially all light - this.isFunction.push(row.slice()); - } - - // Compute ECC, draw modules - this.drawFunctionPatterns(); - const allCodewords: Array = this.addEccAndInterleave(dataCodewords); - this.drawCodewords(allCodewords); - - // Do masking - if (msk === -1) { - // Automatically choose best mask - let minPenalty: int = 1000000000; - for (let i = 0; i < 8; i++) { - this.applyMask(i); - this.drawFormatBits(i); - const penalty: int = this.getPenaltyScore(); - if (penalty < minPenalty) { - msk = i; - minPenalty = penalty; - } - this.applyMask(i); // Undoes the mask due to XOR - } - } - assert(0 <= msk && msk <= 7); - this.mask = msk; - this.applyMask(msk); // Apply the final choice of mask - this.drawFormatBits(msk); // Overwrite old format bits - - this.isFunction = []; - } - - /*-- Accessor methods --*/ - - // Returns the color of the module (pixel) at the given coordinates, which is false - // for light or true for dark. The top left corner has the coordinates (x=0, y=0). - // If the given coordinates are out of bounds, then false (light) is returned. - public getModule(x: int, y: int): boolean { - return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; - } - - /*-- Private helper methods for constructor: Drawing function modules --*/ - - // Reads this object's version field, and draws and marks all function modules. - private drawFunctionPatterns(): void { - // Draw horizontal and vertical timing patterns - for (let i = 0; i < this.size; i++) { - this.setFunctionModule(6, i, i % 2 === 0); - this.setFunctionModule(i, 6, i % 2 === 0); - } - - // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) - this.drawFinderPattern(3, 3); - this.drawFinderPattern(this.size - 4, 3); - this.drawFinderPattern(3, this.size - 4); - - // Draw numerous alignment patterns - const alignPatPos: Array = this.getAlignmentPatternPositions(); - const numAlign: int = alignPatPos.length; - for (let i = 0; i < numAlign; i++) { - for (let j = 0; j < numAlign; j++) { - // Don't draw on the three finder corners - if ( - !( - (i === 0 && j === 0) || - (i === 0 && j === numAlign - 1) || - (i === numAlign - 1 && j === 0) - ) - ) - this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); - } - } - - // Draw configuration data - this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor - this.drawVersion(); - } - - // Draws two copies of the format bits (with its own error correction code) - // based on the given mask and this object's error correction level field. - private drawFormatBits(mask: int): void { - // Calculate error correction code and pack bits - const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3 - let rem: int = data; - for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537); - const bits = ((data << 10) | rem) ^ 0x5412; // uint15 - assert(bits >>> 15 === 0); - - // Draw first copy - for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i)); - this.setFunctionModule(8, 7, getBit(bits, 6)); - this.setFunctionModule(8, 8, getBit(bits, 7)); - this.setFunctionModule(7, 8, getBit(bits, 8)); - for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i)); - - // Draw second copy - for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); - for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); - this.setFunctionModule(8, this.size - 8, true); // Always dark - } - - // Draws two copies of the version bits (with its own error correction code), - // based on this object's version field, iff 7 <= version <= 40. - private drawVersion(): void { - if (this.version < 7) return; - - // Calculate error correction code and pack bits - let rem: int = this.version; // version is uint6, in the range [7, 40] - for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25); - const bits: int = (this.version << 12) | rem; // uint18 - assert(bits >>> 18 === 0); - - // Draw two copies - for (let i = 0; i < 18; i++) { - const color: boolean = getBit(bits, i); - const a: int = this.size - 11 + (i % 3); - const b: int = Math.floor(i / 3); - this.setFunctionModule(a, b, color); - this.setFunctionModule(b, a, color); - } - } - - // Draws a 9*9 finder pattern including the border separator, - // with the center module at (x, y). Modules can be out of bounds. - private drawFinderPattern(x: int, y: int): void { - for (let dy = -4; dy <= 4; dy++) { - for (let dx = -4; dx <= 4; dx++) { - const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm - const xx: int = x + dx; - const yy: int = y + dy; - if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) - this.setFunctionModule(xx, yy, dist !== 2 && dist !== 4); - } - } - } - - // Draws a 5*5 alignment pattern, with the center module - // at (x, y). All modules must be in bounds. - private drawAlignmentPattern(x: int, y: int): void { - for (let dy = -2; dy <= 2; dy++) { - for (let dx = -2; dx <= 2; dx++) - this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); - } - } - - // Sets the color of a module and marks it as a function module. - // Only used by the constructor. Coordinates must be in bounds. - private setFunctionModule(x: int, y: int, isDark: boolean): void { - this.modules[y][x] = isDark; - this.isFunction[y][x] = true; - } - - /*-- Private helper methods for constructor: Codewords and masking --*/ - - // Returns a new byte string representing the given data with the appropriate error correction - // codewords appended to it, based on this object's version and error correction level. - private addEccAndInterleave(data: Readonly>): Array { - const ver: int = this.version; - const ecl: QrCode.Ecc = this.errorCorrectionLevel; - if (data.length !== QrCode.getNumDataCodewords(ver, ecl)) - throw new RangeError('Invalid argument'); - - // Calculate parameter numbers - const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; - const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver]; - const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8); - const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks); - const shortBlockLen: int = Math.floor(rawCodewords / numBlocks); - - // Split data into blocks and append ECC to each block - const blocks: Array> = []; - const rsDiv: Array = QrCode.reedSolomonComputeDivisor(blockEccLen); - for (let i = 0, k = 0; i < numBlocks; i++) { - const dat: Array = data.slice( - k, - k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1) - ); - k += dat.length; - const ecc: Array = QrCode.reedSolomonComputeRemainder(dat, rsDiv); - if (i < numShortBlocks) dat.push(0); - blocks.push(dat.concat(ecc)); - } - - // Interleave (not concatenate) the bytes from every block into a single sequence - const result: Array = []; - for (let i = 0; i < blocks[0].length; i++) { - blocks.forEach((block, j) => { - // Skip the padding byte in short blocks - if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]); - }); - } - assert(result.length === rawCodewords); - return result; - } - - // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire - // data area of this QR Code. Function modules need to be marked off before this is called. - private drawCodewords(data: Readonly>): void { - if (data.length !== Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) - throw new RangeError('Invalid argument'); - let i: int = 0; // Bit index into the data - // Do the funny zigzag scan - for (let right = this.size - 1; right >= 1; right -= 2) { - // Index of right column in each column pair - if (right === 6) right = 5; - for (let vert = 0; vert < this.size; vert++) { - // Vertical counter - for (let j = 0; j < 2; j++) { - const x: int = right - j; // Actual x coordinate - const upward: boolean = ((right + 1) & 2) === 0; - const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate - if (!this.isFunction[y][x] && i < data.length * 8) { - this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); - i++; - } - // If this QR Code has any remainder bits (0 to 7), they were assigned as - // 0/false/light by the constructor and are left unchanged by this method - } - } - } - assert(i === data.length * 8); - } - - // XORs the codeword modules in this QR Code with the given mask pattern. - // The function modules must be marked and the codeword bits must be drawn - // before masking. Due to the arithmetic of XOR, calling applyMask() with - // the same mask value a second time will undo the mask. A final well-formed - // QR Code needs exactly one (not zero, two, etc.) mask applied. - private applyMask(mask: int): void { - if (mask < 0 || mask > 7) throw new RangeError('Mask value out of range'); - for (let y = 0; y < this.size; y++) { - for (let x = 0; x < this.size; x++) { - let invert: boolean; - switch (mask) { - case 0: - invert = (x + y) % 2 === 0; - break; - case 1: - invert = y % 2 === 0; - break; - case 2: - invert = x % 3 === 0; - break; - case 3: - invert = (x + y) % 3 === 0; - break; - case 4: - invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; - break; - case 5: - invert = ((x * y) % 2) + ((x * y) % 3) === 0; - break; - case 6: - invert = (((x * y) % 2) + ((x * y) % 3)) % 2 === 0; - break; - case 7: - invert = (((x + y) % 2) + ((x * y) % 3)) % 2 === 0; - break; - default: - throw new Error('Unreachable'); - } - if (!this.isFunction[y][x] && invert) this.modules[y][x] = !this.modules[y][x]; - } - } - } - - // Calculates and returns the penalty score based on state of this QR Code's current modules. - // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. - private getPenaltyScore(): int { - let result: int = 0; - - // Adjacent modules in row having same color, and finder-like patterns - for (let y = 0; y < this.size; y++) { - let runColor = false; - let runX = 0; - const runHistory = [0, 0, 0, 0, 0, 0, 0]; - for (let x = 0; x < this.size; x++) { - if (this.modules[y][x] === runColor) { - runX++; - if (runX === 5) result += QrCode.PENALTY_N1; - else if (runX > 5) result++; - } else { - this.finderPenaltyAddHistory(runX, runHistory); - if (!runColor) - result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; - runColor = this.modules[y][x]; - runX = 1; - } - } - result += - this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3; - } - // Adjacent modules in column having same color, and finder-like patterns - for (let x = 0; x < this.size; x++) { - let runColor = false; - let runY = 0; - const runHistory = [0, 0, 0, 0, 0, 0, 0]; - for (let y = 0; y < this.size; y++) { - if (this.modules[y][x] === runColor) { - runY++; - if (runY === 5) result += QrCode.PENALTY_N1; - else if (runY > 5) result++; - } else { - this.finderPenaltyAddHistory(runY, runHistory); - if (!runColor) - result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; - runColor = this.modules[y][x]; - runY = 1; - } - } - result += - this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3; - } - - // 2*2 blocks of modules having same color - for (let y = 0; y < this.size - 1; y++) { - for (let x = 0; x < this.size - 1; x++) { - const color: boolean = this.modules[y][x]; - if ( - color === this.modules[y][x + 1] && - color === this.modules[y + 1][x] && - color === this.modules[y + 1][x + 1] - ) - result += QrCode.PENALTY_N2; - } - } - - // Balance of dark and light modules - let dark: int = 0; - for (const row of this.modules) - dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark); - const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2 - // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% - const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; - assert(0 <= k && k <= 9); - result += k * QrCode.PENALTY_N4; - assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 - return result; - } - - /*-- Private helper functions --*/ - - // Returns an ascending list of positions of alignment patterns for this version number. - // Each position is in the range [0,177), and are used on both the x and y axes. - // This could be implemented as lookup table of 40 variable-length lists of integers. - private getAlignmentPatternPositions(): Array { - if (this.version === 1) return []; - - const numAlign: int = Math.floor(this.version / 7) + 2; - const step: int = - this.version === 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; - const result: Array = [6]; - for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos); - return result; - } - - // Returns the number of data bits that can be stored in a QR Code of the given version number, after - // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. - // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. - private static getNumRawDataModules(ver: int): int { - if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) - throw new RangeError('Version number out of range'); - let result: int = (16 * ver + 128) * ver + 64; - if (ver >= 2) { - const numAlign: int = Math.floor(ver / 7) + 2; - result -= (25 * numAlign - 10) * numAlign - 55; - if (ver >= 7) result -= 36; - } - assert(208 <= result && result <= 29648); - return result; - } - - // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any - // QR Code of the given version number and error correction level, with remainder bits discarded. - // This stateless pure function could be implemented as a (40*4)-cell lookup table. - private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int { - return ( - Math.floor(QrCode.getNumRawDataModules(ver) / 8) - - QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * - QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver] - ); - } - - // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be - // implemented as a lookup table over all possible parameter values, instead of as an algorithm. - private static reedSolomonComputeDivisor(degree: int): Array { - if (degree < 1 || degree > 255) throw new RangeError('Degree out of range'); - // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. - // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. - const result: Array = []; - for (let i = 0; i < degree - 1; i++) result.push(0); - result.push(1); // Start off with the monomial x^0 - - // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), - // and drop the highest monomial term which is always 1x^degree. - // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). - let root = 1; - for (let i = 0; i < degree; i++) { - // Multiply the current product by (x - r^i) - for (let j = 0; j < result.length; j++) { - result[j] = QrCode.reedSolomonMultiply(result[j], root); - if (j + 1 < result.length) result[j] ^= result[j + 1]; - } - root = QrCode.reedSolomonMultiply(root, 0x02); - } - return result; - } - - // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. - private static reedSolomonComputeRemainder( - data: Readonly>, - divisor: Readonly> - ): Array { - const result: Array = divisor.map((_) => 0); - for (const b of data) { - // Polynomial division - const factor: byte = b ^ (result.shift() as byte); - result.push(0); - divisor.forEach((coef, i) => (result[i] ^= QrCode.reedSolomonMultiply(coef, factor))); - } - return result; - } - - // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result - // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. - private static reedSolomonMultiply(x: byte, y: byte): byte { - if (x >>> 8 !== 0 || y >>> 8 !== 0) throw new RangeError('Byte out of range'); - // Russian peasant multiplication - let z: int = 0; - for (let i = 7; i >= 0; i--) { - z = (z << 1) ^ ((z >>> 7) * 0x11d); - z ^= ((y >>> i) & 1) * x; - } - assert(z >>> 8 === 0); - return z as byte; - } - - // Can only be called immediately after a light run is added, and - // returns either 0, 1, or 2. A helper function for getPenaltyScore(). - private finderPenaltyCountPatterns(runHistory: Readonly>): int { - const n: int = runHistory[1]; - assert(n <= this.size * 3); - const core: boolean = - n > 0 && - runHistory[2] === n && - runHistory[3] === n * 3 && - runHistory[4] === n && - runHistory[5] === n; - return ( - (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + - (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0) - ); - } - - // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). - private finderPenaltyTerminateAndCount( - currentRunColor: boolean, - currentRunLength: int, - runHistory: Array - ): int { - if (currentRunColor) { - // Terminate dark run - this.finderPenaltyAddHistory(currentRunLength, runHistory); - currentRunLength = 0; - } - currentRunLength += this.size; // Add light border to final run - this.finderPenaltyAddHistory(currentRunLength, runHistory); - return this.finderPenaltyCountPatterns(runHistory); - } - - // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). - private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array): void { - if (runHistory[0] === 0) currentRunLength += this.size; // Add light border to initial run - runHistory.pop(); - runHistory.unshift(currentRunLength); - } - - /*-- Constants and tables --*/ - - // The minimum version number supported in the QR Code Model 2 standard. - public static readonly MIN_VERSION: int = 1; - // The maximum version number supported in the QR Code Model 2 standard. - public static readonly MAX_VERSION: int = 40; - - // For use in getPenaltyScore(), when evaluating which mask is best. - private static readonly PENALTY_N1: int = 3; - private static readonly PENALTY_N2: int = 3; - private static readonly PENALTY_N3: int = 40; - private static readonly PENALTY_N4: int = 10; - - private static readonly ECC_CODEWORDS_PER_BLOCK: Array> = [ - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - [ - -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, - 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, - ], // Low - [ - -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - ], // Medium - [ - -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, - 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, - ], // Quartile - [ - -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, - 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, - ], // High - ]; - - private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array> = [ - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - [ - -1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, - 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25, - ], // Low - [ - -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, - 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49, - ], // Medium - [ - -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, - 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68, - ], // Quartile - [ - -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, - 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81, - ], // High - ]; - } - - // Appends the given number of low-order bits of the given value - // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. - function appendBits(val: int, len: int, bb: Array): void { - if (len < 0 || len > 31 || val >>> len !== 0) throw new RangeError('Value out of range'); - for ( - let i = len - 1; - i >= 0; - i-- // Append bit by bit - ) - bb.push((val >>> i) & 1); - } - - // Returns true iff the i'th bit of x is set to 1. - function getBit(x: int, i: int): boolean { - return ((x >>> i) & 1) !== 0; - } - - // Throws an exception if the given condition is false. - function assert(cond: boolean): void { - if (!cond) throw new Error('Assertion error'); - } - - /*---- Data segment class ----*/ - - /* - * A segment of character/binary/control data in a QR Code symbol. - * Instances of this class are immutable. - * The mid-level way to create a segment is to take the payload data - * and call a static factory function such as QrSegment.makeNumeric(). - * The low-level way to create a segment is to custom-make the bit buffer - * and call the QrSegment() constructor with appropriate values. - * This segment class imposes no length restrictions, but QR Codes have restrictions. - * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. - * Any segment longer than this is meaningless for the purpose of generating QR Codes. - */ - export class QrSegment { - /*-- Static factory functions (mid level) --*/ - - // Returns a segment representing the given binary data encoded in - // byte mode. All input byte arrays are acceptable. Any text string - // can be converted to UTF-8 bytes and encoded as a byte mode segment. - public static makeBytes(data: Readonly>): QrSegment { - const bb: Array = []; - for (const b of data) appendBits(b, 8, bb); - return new QrSegment(QrSegment.Mode.BYTE, data.length, bb); - } - - // Returns a segment representing the given string of decimal digits encoded in numeric mode. - public static makeNumeric(digits: string): QrSegment { - if (!QrSegment.isNumeric(digits)) - throw new RangeError('String contains non-numeric characters'); - const bb: Array = []; - for (let i = 0; i < digits.length; ) { - // Consume up to 3 digits per iteration - const n: int = Math.min(digits.length - i, 3); - appendBits(Number.parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); - i += n; - } - return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb); - } - - // Returns a segment representing the given text string encoded in alphanumeric mode. - // The characters allowed are: 0 to 9, A to Z (uppercase only), space, - // dollar, percent, asterisk, plus, hyphen, period, slash, colon. - public static makeAlphanumeric(text: string): QrSegment { - if (!QrSegment.isAlphanumeric(text)) - throw new RangeError('String contains unencodable characters in alphanumeric mode'); - const bb: Array = []; - let i: int; - for (i = 0; i + 2 <= text.length; i += 2) { - // Process groups of 2 - let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; - temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); - appendBits(temp, 11, bb); - } - if (i < text.length) - // 1 character remaining - appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); - return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb); - } - - // Returns a new mutable list of zero or more segments to represent the given Unicode text string. - // The result may use various segment modes and switch modes to optimize the length of the bit stream. - public static makeSegments(text: string): Array { - // Select the most efficient segment encoding automatically - if (text === '') return []; - if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)]; - if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)]; - return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))]; - } - - // Returns a segment representing an Extended Channel Interpretation - // (ECI) designator with the given assignment value. - public static makeEci(assignVal: int): QrSegment { - const bb: Array = []; - if (assignVal < 0) throw new RangeError('ECI assignment value out of range'); - if (assignVal < 1 << 7) appendBits(assignVal, 8, bb); - else if (assignVal < 1 << 14) { - appendBits(0b10, 2, bb); - appendBits(assignVal, 14, bb); - } else if (assignVal < 1000000) { - appendBits(0b110, 3, bb); - appendBits(assignVal, 21, bb); - } else throw new RangeError('ECI assignment value out of range'); - return new QrSegment(QrSegment.Mode.ECI, 0, bb); - } - - // Tests whether the given string can be encoded as a segment in numeric mode. - // A string is encodable iff each character is in the range 0 to 9. - public static isNumeric(text: string): boolean { - return QrSegment.NUMERIC_REGEX.test(text); - } - - // Tests whether the given string can be encoded as a segment in alphanumeric mode. - // A string is encodable iff each character is in the following set: 0 to 9, A to Z - // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. - public static isAlphanumeric(text: string): boolean { - return QrSegment.ALPHANUMERIC_REGEX.test(text); - } - - /*-- Constructor (low level) and fields --*/ - - // Creates a new QR Code segment with the given attributes and data. - // The character count (numChars) must agree with the mode and the bit buffer length, - // but the constraint isn't checked. The given bit buffer is cloned and stored. - public constructor( - // The mode indicator of this segment. - public readonly mode: QrSegment.Mode, - - // The length of this segment's unencoded data. Measured in characters for - // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. - // Always zero or positive. Not the same as the data's bit length. - public readonly numChars: int, - - // The data bits of this segment. Accessed through getData(). - private readonly bitData: Array - ) { - if (numChars < 0) throw new RangeError('Invalid argument'); - this.bitData = bitData.slice(); // Make defensive copy - } - - /*-- Methods --*/ - - // Returns a new copy of the data bits of this segment. - public getData(): Array { - return this.bitData.slice(); // Make defensive copy - } - - // (Package-private) Calculates and returns the number of bits needed to encode the given segments at - // the given version. The result is infinity if a segment has too many characters to fit its length field. - public static getTotalBits(segs: Readonly>, version: int): number { - let result = 0; - for (const seg of segs) { - const ccbits: int = seg.mode.numCharCountBits(version); - if (seg.numChars >= 1 << ccbits) return Number.POSITIVE_INFINITY; // The segment's length doesn't fit the field's bit width - result += 4 + ccbits + seg.bitData.length; - } - return result; - } - - // Returns a new array of bytes representing the given string encoded in UTF-8. - private static toUtf8ByteArray(str: string): Array { - str = encodeURI(str); - const result: Array = []; - for (let i = 0; i < str.length; i++) { - if (str.charAt(i) !== '%') result.push(str.charCodeAt(i)); - else { - result.push(Number.parseInt(str.substring(i + 1, i + 3), 16)); - i += 2; - } - } - return result; - } - - /*-- Constants --*/ - - // Describes precisely all strings that are encodable in numeric mode. - private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/; - - // Describes precisely all strings that are encodable in alphanumeric mode. - private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+./:-]*$/; - - // The set of all legal characters in alphanumeric mode, - // where each character value maps to the index in the string. - private static readonly ALPHANUMERIC_CHARSET: string = - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'; - } -} - -/*---- Public helper enumeration ----*/ - -export namespace qrcodegen.QrCode { - type int = number; - - /* - * The error correction level in a QR Code symbol. Immutable. - */ - export class Ecc { - /*-- Constants --*/ - - public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords - public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords - public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords - public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords - - /*-- Constructor and fields --*/ - - private constructor( - // In the range 0 to 3 (unsigned 2-bit integer). - public readonly ordinal: int, - // (Package-private) In the range 0 to 3 (unsigned 2-bit integer). - public readonly formatBits: int - ) {} - } -} - -/*---- Public helper enumeration ----*/ - -export namespace qrcodegen.QrSegment { - type int = number; - - /* - * Describes how a segment's data bits are interpreted. Immutable. - */ - export class Mode { - /*-- Constants --*/ - - public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]); - public static readonly ALPHANUMERIC = new Mode(0x2, [9, 11, 13]); - public static readonly BYTE = new Mode(0x4, [8, 16, 16]); - public static readonly KANJI = new Mode(0x8, [8, 10, 12]); - public static readonly ECI = new Mode(0x7, [0, 0, 0]); - - /*-- Constructor and fields --*/ - - private constructor( - // The mode indicator bits, which is a uint4 value (range 0 to 15). - public readonly modeBits: int, - // Number of character count bits for three different version ranges. - private readonly numBitsCharCount: [int, int, int] - ) {} - - /*-- Method --*/ - - // (Package-private) Returns the bit width of the character count field for a segment in - // this mode in a QR Code at the given version number. The result is in the range [0, 16]. - public numCharCountBits(ver: int): int { - return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; - } - } -} diff --git a/packages/es/src/wallet/wallets/ConnectedWallet.ts b/packages/es/src/wallet/wallets/ConnectedWallet.ts deleted file mode 100644 index 499d7bd79..000000000 --- a/packages/es/src/wallet/wallets/ConnectedWallet.ts +++ /dev/null @@ -1,219 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -import { - type Adapter, - type PollTxParams, - type Secp256k1PubKey, - Tx, - calculateFee, - getAccount, - pollTx, - simulateTx, - toBaseAccount, -} from '@sonr.io/es/client'; -import { - CosmosBaseV1beta1Coin as Coin, - type CosmosTxV1beta1Fee as Fee, - type CosmosTxV1beta1GetTxResponse as GetTxResponse, -} from '@sonr.io/es/protobufs'; - -import type { WalletName } from '../constants/WalletName'; -import type { WalletType } from '../constants/WalletType'; -import { extractExpectedAccountSequence } from '../utils/sequence'; - -export type UnsignedTx = { - msgs: Adapter[]; - memo?: string | undefined; - timeoutHeight?: bigint | undefined; -}; - -export type PollTxOptions = Pick; - -export type SignArbitraryResponse = { - data: string; - pubKey: string; - signature: string; -}; - -/** - * Represents a connected wallet that is ready to sign transactions. - * Use `WalletController` to create an instance of this class. - */ -export abstract class ConnectedWallet { - /** The identifier of this wallet. */ - public readonly id: WalletName; - /** The type of connection to the wallet. */ - public readonly type: WalletType; - /** The user-defined label for this wallet, if any. */ - public readonly label: string | undefined; - /** The chain ID this wallet is connected to. */ - public readonly chainId: string; - /** The public key. */ - public readonly pubKey: Secp256k1PubKey; - /** The bech32 address. */ - public readonly address: string; - /** The RPC endpoint to use for interacting with the chain. */ - public readonly rpc: string; - /** The gas price to use for transactions. */ - public readonly gasPrice: Coin; - private accountNumber: bigint | undefined; - private sequence: bigint | undefined; - - constructor( - id: WalletName, - type: WalletType, - label: string | undefined, - chainId: string, - pubKey: Secp256k1PubKey, - address: string, - rpc: string, - gasPrice: PlainMessage - ) { - this.id = id; - this.type = type; - this.label = label; - this.chainId = chainId; - this.pubKey = pubKey; - this.address = address; - this.rpc = rpc; - this.gasPrice = new Coin(gasPrice); - } - - /** - * Returns the account number and sequence for the connected address. If `fromCache` - * is true, the cached values (if they are available) will be returned instead of - * querying the auth module. - * - * @throws if the account does not exist in the auth module. - */ - public async getAuthInfo(fromCache = false): Promise<{ - accountNumber: bigint; - sequence: bigint; - }> { - if (!this.accountNumber || !this.sequence || !fromCache) { - const account = await getAccount(this.rpc, { address: this.address }); - const { accountNumber, sequence } = toBaseAccount(account); - this.accountNumber = accountNumber; - this.sequence = sequence; - } - return { - accountNumber: this.accountNumber, - sequence: this.sequence, - }; - } - - /** - * Simulates the tx and returns an estimate of the gas fees required. - * - * @throws if the tx fails to simulate. - */ - public async estimateFee({ msgs, memo }: UnsignedTx, feeMultiplier = 1.4): Promise { - const estimate = async () => { - const { sequence } = await this.getAuthInfo(true); - const { gasInfo } = await simulateTx(this.rpc, { - sequence, - memo, - tx: new Tx({ chainId: this.chainId, pubKey: this.pubKey, msgs: msgs }), - }); - if (!gasInfo) { - throw new Error('Unable to estimate fee'); - } - return calculateFee(gasInfo, this.gasPrice, feeMultiplier); - }; - // If we encounter an account sequence mismatch error, we retry exactly once - // by parsing the error for the correct sequence to use - try { - return await estimate(); - } catch (err) { - if (!(err instanceof Error)) { - // Rethrow non-errors - throw err; - } - const expectedSequence = extractExpectedAccountSequence(err); - if (!expectedSequence) { - // Rethrow errors not related to account sequence mismatch - throw err; - } - // Set the cached sequence to the one from the error message - this.sequence = expectedSequence; - return estimate(); - } - } - - /** - * Signs and broadcasts the given `unsignedTx`, returning the tx hash if successful. - * The `fee` parameter can (and should) be obtained by running `estimateFee` on - * the `unsignedTx` prior to calling this method. - * - * **Important**: successful execution of this method does not guarantee that the - * tx was successfully included in a block. Use `pollTx` to poll for the result of - * the tx. - * - * @throws if the user denies the signing of the tx. - * @throws if the tx fails to broadcast. - */ - public async broadcastTx(unsignedTx: UnsignedTx, fee: Fee): Promise { - const { accountNumber, sequence } = await this.getAuthInfo(true); - const hash = await this.signAndBroadcastTx(unsignedTx, fee, accountNumber, sequence); - // Greedily increment the sequence for the next tx. This may result in the wrong - // sequence, but if `estimateFee` was called prior to this, it will be corrected - this.sequence = sequence + 1n; - return hash; - } - - /** - * Polls for the tx matching the given `txHash` every `intervalSeconds` until it is - * included in a block or when `maxAttempts` is reached (default: 2s, 64 attempts). - * - * @throws if the tx is not included in a block after the given `maxAttempts`. - */ - public async pollTx( - txHash: string, - { maxAttempts, intervalSeconds }: PollTxOptions = {} - ): Promise>> { - return pollTx(this.rpc, { - hash: txHash, - maxAttempts, - intervalSeconds, - }); - } - - /** - * Executes `broadcastTx` and `pollTx` sequentially, returning the result of the - * tx. If `feeOrFeeMultiplier` is `undefined` or a number, an additional call to - * `estimateFee` will be made. Use this if there is no need to independently - * execute the three methods. - */ - public async broadcastTxSync( - unsignedTx: UnsignedTx, - feeOrFeeMultiplier: Fee | number = 1.4, - pollOpts: PollTxOptions = {} - ): Promise>> { - const fee = - typeof feeOrFeeMultiplier === 'number' - ? await this.estimateFee(unsignedTx, feeOrFeeMultiplier) - : feeOrFeeMultiplier; - const txHash = await this.broadcastTx(unsignedTx, fee); - return this.pollTx(txHash, pollOpts); - } - - /** - * Signs the UTF-8 encoded `data` string. Note that some mobile wallets do not - * support this method. - * - * @throws if the user denies the signing of the data. - * @throws if the wallet does not support signing arbitrary data. - */ - public abstract signArbitrary(data: string): Promise; - - /** - * Signs the given `unsignedTx` and broadcasts the resulting signed tx, returning - * the hex encoded tx hash if successful. This abstract method should be implemented - * by the concrete child classes. - */ - protected abstract signAndBroadcastTx( - unsignedTx: UnsignedTx, - fee: Fee, - accountNumber: bigint, - sequence: bigint - ): Promise; -} diff --git a/packages/es/src/wallet/wallets/WalletController.ts b/packages/es/src/wallet/wallets/WalletController.ts deleted file mode 100644 index a1b8fadcd..000000000 --- a/packages/es/src/wallet/wallets/WalletController.ts +++ /dev/null @@ -1,186 +0,0 @@ -import type { PlainMessage } from '@bufbuild/protobuf'; -import type { CosmosBaseV1beta1Coin as Coin } from '@sonr.io/es/protobufs'; - -import type { WalletName } from '../constants/WalletName'; -import { WalletType } from '../constants/WalletType'; -import type { WalletConnectV1 } from '../walletconnect/WalletConnectV1'; -import type { WalletConnectV2 } from '../walletconnect/WalletConnectV2'; -import type { ConnectedWallet } from './ConnectedWallet'; - -/** - * Represents a chain that the wallet can connect to. - */ -export type ChainInfo = { - /** - * The unique identifier for the chain (eg. `phoenix-1`). - */ - chainId: T; - /** - * A valid RPC endpoint that can be used to simulate and broadcast transactions. - */ - rpc: string; - /** - * The current gas price of the chain. - */ - gasPrice: PlainMessage; -}; - -export type EventCallback = (wallets: ConnectedWallet[]) => unknown; - -/** - * Controls initial connection to the wallet, and instantiates the - * various `ConnectedWallet` instances. - */ -export abstract class WalletController { - /** The identifier of this wallet. */ - public readonly id: WalletName; - /** Map of chain ID to connected wallets. */ - public readonly connectedWallets: Map; - private readonly onDisconnectCbs: Set; - protected readonly onAccountChangeCbs: Set; - private isWcOnDisconnectRegistered: boolean; - - constructor(id: WalletName) { - this.id = id; - this.connectedWallets = new Map(); - this.onDisconnectCbs = new Set(); - this.onAccountChangeCbs = new Set(); - this.isWcOnDisconnectRegistered = false; - } - - /** - * Returns `true` iff the wallet is installed. - */ - public abstract isInstalled(type: WalletType): Promise; - - /** - * Connects to the wallet and returns a map of `ConnectedWallet` instances. - * The keys of the map are the chain IDs. - */ - public async connect( - type: WalletType, - chains: ChainInfo[] - ): Promise> { - if (chains.length === 0) { - return new Map(); - } - let connectedWallets: Map; - if (type === WalletType.EXTENSION) { - connectedWallets = await this.connectExtension(chains); - } else { - const { wallets, wc } = await this.connectWalletConnect(chains); - if (!this.isWcOnDisconnectRegistered) { - // On WalletConnect session disconnect, remove all WalletConnect wallets - this.isWcOnDisconnectRegistered = true; - wc.onDisconnect(() => { - this.disconnect( - Array.from(this.connectedWallets.keys()).filter( - (id) => this.connectedWallets.get(id)?.type === WalletType.WALLETCONNECT - ) - ); - }); - } - connectedWallets = wallets; - } - for (const [key, value] of connectedWallets) { - this.connectedWallets.set(key, value); - } - return connectedWallets; - } - - /** - * Disconnects the wallet connected to the given `chainIds`. - */ - public disconnect(chainIds: string[]) { - const callbackIds = chainIds.filter((id) => this.connectedWallets.has(id)); - if (callbackIds.length === 0) { - return; - } - const disconnectedWallets: ConnectedWallet[] = []; - for (const id of callbackIds) { - const wallet = this.connectedWallets.get(id); - if (wallet) { - disconnectedWallets.push(wallet); - this.connectedWallets.delete(id); - } - } - for (const cb of this.onDisconnectCbs) { - cb(disconnectedWallets); - } - } - - /** - * Should be called when any account changes are detected. This will disconnect - * from all chains that were connected via the given `walletType`, and emit the - * `onAccountChange` event. - */ - protected changeAccount(walletType: WalletType) { - // Ignore if controller does not have any connected wallets - if (this.connectedWallets.size === 0) { - return; - } - // Find all wallets that were connected via the given `walletType` - const wallets = [...this.connectedWallets.values()].filter( - (wallet) => wallet.type === walletType - ); - // Disconnect from those chains - const chainIds = wallets.map((wallet) => wallet.chainId); - this.disconnect(chainIds); - // Fire the account change callbacks - for (const cb of this.onAccountChangeCbs) { - cb(wallets); - } - } - - /** - * Registers a callback that is called when the wallet is disconnected. - * Returns an `unsubscribe` function that should be called after the - * callback is no longer needed. - * - * ```ts - * const unsubscribe = walletController.onDisconnect((wallets) => { - * // do something with the wallets that were disconnected - * console.log(wallets); - * // unsubscribe from this callback (if necessary) - * unsubsribe(); - * }); - * ``` - */ - public onDisconnect(cb: EventCallback): () => void { - this.onDisconnectCbs.add(cb); - return () => this.onDisconnectCbs.delete(cb); - } - - /** - * Registers a callback that is called when the wallet's account is changed after - * the initial connection. When the account changes, the `onDisconnect` event - * will also be fired before this `onAccountChange` event. Returns an `unsubscribe` - * function that should be called after the callback is no longer needed. - * - * ```ts - * const unsubscribe = walletController.onAccountChange((wallets) => { - * // do something with the wallets that were affected - * console.log(wallets); - * // unsubscribe from this callback (if necessary) - * unsubsribe(); - * }); - * ``` - */ - public onAccountChange(cb: EventCallback): () => void { - this.onAccountChangeCbs.add(cb); - return () => this.onAccountChangeCbs.delete(cb); - } - - protected abstract connectExtension( - chains: ChainInfo[] - ): Promise>; - - protected abstract connectWalletConnect( - chains: ChainInfo[] - ): Promise<{ - wallets: Map; - wc: WalletConnectV1 | WalletConnectV2; - }>; - - protected abstract registerAccountChangeHandlers(): void; -} diff --git a/packages/es/src/wallet/wallets/WalletError.ts b/packages/es/src/wallet/wallets/WalletError.ts deleted file mode 100644 index 7347d5cf8..000000000 --- a/packages/es/src/wallet/wallets/WalletError.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Custom error class which wraps around an error thrown by a wallet. - */ -export class WalletError extends Error { - /** - * Holds the original error and type thrown by the wallet. - */ - public raw: unknown; - - constructor(message: string, raw: unknown) { - super(message); - this.name = 'WalletError'; - this.raw = raw; - } - - /** - * Returns the result of the `promise` if it resolves successfully, normalising - * any errors thrown into a `WalletError` instance. - * - * It is best to wrap all wallet API calls with this function as some wallets - * throw other data types other than actual `Error` instances. - */ - public static async wrap(promise: Promise): Promise { - try { - return await promise; - } catch (err) { - if (typeof err === 'string') { - throw new WalletError(err, err); - } - if (WalletError.isRecord(err)) { - // Takes into account normal error instances and objects with the 'error' key - throw new WalletError(err.message ?? err.error ?? 'unknown error', err); - } - throw new WalletError('unknown error', err); - } - } - - private static isRecord(value: unknown): value is Record { - return typeof value === 'object' && value != null; - } -} diff --git a/packages/es/src/wallet/wallets/mnemonic/MnemonicWallet.ts b/packages/es/src/wallet/wallets/mnemonic/MnemonicWallet.ts deleted file mode 100644 index 7dd880ce1..000000000 --- a/packages/es/src/wallet/wallets/mnemonic/MnemonicWallet.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { RpcClient, Secp256k1PubKey, Tx } from '@sonr.io/es/client'; -import { - base64, - resolveBech32Address, - resolveKeyPair, - signAmino, - signDirect, - utf8, -} from '@sonr.io/es/codec'; -import type { CosmosTxV1beta1Fee as Fee } from '@sonr.io/es/protobufs'; -import type { StdSignDoc } from '@sonr.io/es/registry'; - -import type { Prettify } from '../../../typeutils/prettify'; -import type { WalletName } from '../../constants/WalletName'; -import type { WalletType } from '../../constants/WalletType'; -import { ConnectedWallet, type SignArbitraryResponse, type UnsignedTx } from '../ConnectedWallet'; -import type { ChainInfo } from '../WalletController'; - -export type ConnectMnemonicWalletOptions = Prettify< - { - /** - * Also known as the 12-24 words seed phrase. **Warning: keep this safe!** - */ - mnemonic: string; - /** - * The address prefix for the chain (eg. "osmo"). - */ - bech32Prefix: string; - /** - * Coin type number for HD derivation (default: `118`). For Terra chains, change - * this to `330`. - */ - coinType?: number | undefined; - /** - * Address index number for HD derivation (default: `0`). - */ - index?: number | undefined; - } & ChainInfo ->; - -/** - * This wallet accepts a mnemonic (aka seed phrase) and is able to directly sign - * and broadcast transactions to the chain without relying on an external wallet - * like Keplr or Station. Use this if you want to programmatically broadcast - * transactions. Unlike the other wallets, there is no Controller class and this - * object must be instantiated directly. - * - * ```ts - * // Example usage for Osmosis chain - * const wallet = new MnemonicWallet({ - * mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", // Example 12-word mnemonic for testing - * bech32Prefix: "osmo", - * chainId: "osmosis-1", - * rpc: "https://rpc.osmosis.zone", - * gasPrice: { - * amount: "0.0025", - * denom: "uosmo", - * }, - * coinType: 118, // optional (default: 118) - * index: 0, // optional (default: 0) - * }); - * console.log("Address:", wallet.address); // prints the bech32 address - * - * // Sign an arbitrary message - * const { signature } = await wallet.signArbitrary("Hello from @sonr.io/es!"); - * console.log("Signature:", signature); - * - * // Sign and broadcast a tx - * const unsignedTx = { msgs: [...], memo: "Hello Cosmos!", timeoutHeight: 0n }; - * const res = await wallet.broadcastTxSync(unsignedTx, 1.4); // Uses 1.4x fee multiplier - * console.log("Tx result:", res); - * ``` - */ -export class MnemonicWallet extends ConnectedWallet { - public readonly publicKey: string; - public readonly privateKey: Uint8Array; - public readonly keyType: 'secp256k1' | 'ethsecp256k1'; - - constructor({ - mnemonic, - bech32Prefix, - coinType, - index, - chainId, - gasPrice, - rpc, - }: ConnectMnemonicWalletOptions) { - const { publicKey, privateKey } = resolveKeyPair(mnemonic, { - coinType, - index, - }); - const keyType = - chainId.startsWith('injective') || chainId.startsWith('dymension') - ? 'ethsecp256k1' - : 'secp256k1'; - const address = resolveBech32Address(publicKey, bech32Prefix, keyType); - super( - // We typecast here instead of adding "mnemonic" to `WalletName` and - // `WalletType` as this wallet is considered a special wallet that is - // unlikely to be used by most consumers of @sonr.io/es. - 'mnemonic' as WalletName, - 'mnemonic' as WalletType, - undefined, - chainId, - new Secp256k1PubKey({ - chainId, - key: publicKey as any, - }), - address, - rpc, - gasPrice - ); - this.publicKey = base64.encode(publicKey); - this.privateKey = privateKey; - this.keyType = keyType; - } - - public async signArbitrary(data: string): Promise { - // This sign doc follows ADR 036 specs. - // See: https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-036-arbitrary-signature.md - const doc: StdSignDoc = { - chain_id: '', - account_number: '0', - sequence: '0', - fee: { - gas: '0', - amount: [], - }, - msgs: [ - { - type: 'sign/MsgSignData', - value: { - signer: this.address, - data: base64.encode(utf8.decode(data)), - }, - }, - ], - memo: '', - }; - const signature = signAmino(doc, this.privateKey, this.keyType); - return { - data, - pubKey: this.publicKey, - signature: base64.encode(signature), - }; - } - - public async signAndBroadcastTx( - { msgs, memo, timeoutHeight }: UnsignedTx, - fee: Fee, - accountNumber: bigint, - sequence: bigint - ): Promise { - const tx = new Tx({ - chainId: this.chainId, - pubKey: this.pubKey, - msgs: msgs, - }); - const doc = tx.toSignDoc({ - accountNumber, - sequence, - fee, - memo, - timeoutHeight, - }); - const signature = signDirect(doc, this.privateKey, this.keyType); - return RpcClient.broadcastTx(this.rpc, tx.toSignedDirect(doc, signature)); - } -} diff --git a/packages/es/src/wallet/wallets/window.d.ts b/packages/es/src/wallet/wallets/window.d.ts deleted file mode 100644 index 6c42de887..000000000 --- a/packages/es/src/wallet/wallets/window.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Window as KeplrWindow } from "@sonr.io/es/registry"; - -import { Window as CompassWindow } from "./compass/types"; -import { Window as CosmostationWindow } from "./cosmostation/types"; -import { Window as LeapWindow } from "./leap/types"; -import { Window as EthereumWindow } from "./metamask-injective/types"; -import { Window as NinjiWindow } from "./ninji/types"; -import { Window as OWalletWindow } from "./owallet/types"; -import { Window as StationWindow } from "./station/types"; - -declare global { - interface Window - extends KeplrWindow, - CosmostationWindow, - StationWindow, - LeapWindow, - CompassWindow, - EthereumWindow, - NinjiWindow, - OWalletWindow {} -} diff --git a/packages/es/src/worker/README.md b/packages/es/src/worker/README.md deleted file mode 100644 index 6caef02b1..000000000 --- a/packages/es/src/worker/README.md +++ /dev/null @@ -1,443 +0,0 @@ -# Motor WASM Service Worker Integration - -This module provides TypeScript client integration for the Motor WASM service worker, enabling type-safe interactions with both DWN (Decentralized Web Node) and Wallet operations through a WebAssembly-based service worker or direct HTTP API calls. - -## Features - -- **🔧 Type-Safe Plugin Interface**: Mirrors the Go Plugin interface from `x/dwn/client/plugin` -- **🔄 Automatic Service Worker Management**: Handles registration, updates, and health monitoring -- **🌍 Cross-Environment Support**: Works in both browser and Node.js environments -- **🔄 Fallback Support**: Automatically falls back to HTTP when service workers are unavailable -- **🛡️ Comprehensive Error Handling**: Includes retries, timeouts, and detailed error reporting -- **🎯 Modern TypeScript**: Uses advanced TypeScript features for optimal developer experience - -## Architecture - -``` -Motor WASM Integration -├── types.ts # TypeScript type definitions -├── client.ts # HTTP client for Motor API calls -├── worker.ts # Service worker lifecycle management -├── plugin.ts # Main plugin implementation -└── index.ts # Entry point and exports -``` - -## Quick Start - -### Basic Usage (Auto-detection) - -```typescript -import { createMotorPlugin } from '@sonr.io/es/client/motor'; - -const plugin = await createMotorPlugin({ - debug: true, - timeout: 30000, -}); - -// Create a UCAN token -const tokenResponse = await plugin.newOriginToken({ - audience_did: 'did:sonr:example', - attenuations: [{ can: ['sign'], with: 'vault://example' }], -}); - -console.log('Token created:', tokenResponse.token); -``` - -### Browser-Specific Usage - -```typescript -import { createMotorPluginForBrowser } from '@sonr.io/es/client/motor'; - -const plugin = await createMotorPluginForBrowser('/motor-worker', { - auto_register_worker: true, - prefer_service_worker: true, - debug: true, -}); -``` - -### Node.js Usage - -```typescript -import { createMotorPluginForNode } from '@sonr.io/es/client/motor'; - -const plugin = await createMotorPluginForNode('http://localhost:8080', { - timeout: 10000, -}); -``` - -## Environment Detection - -The plugin automatically detects the environment and capabilities: - -```typescript -import { - isMotorSupported, - getMotorEnvironment, - MotorServiceWorkerManager -} from '@sonr.io/es/client/motor'; - -// Check overall support -const supported = isMotorSupported(); - -// Get detailed environment info -const env = getMotorEnvironment(); -console.log('Browser:', env.is_browser); -console.log('Service Worker Support:', env.supports_service_worker); -console.log('WebAssembly Support:', env.supports_wasm); - -// Get browser compatibility details -const compatibility = MotorServiceWorkerManager.getBrowserCompatibility(); -if (!compatibility.compatible) { - console.warn('Issues:', compatibility.issues); - console.log('Recommendations:', compatibility.recommendations); -} -``` - -## API Reference - -### Plugin Interface - -The `MotorPlugin` interface provides access to all Motor operations: - -#### UCAN Token Operations - -```typescript -// Create origin token -const originToken = await plugin.newOriginToken({ - audience_did: 'did:sonr:audience', - attenuations: [{ can: ['sign', 'encrypt'], with: 'vault://example' }], - facts: ['example-fact'], - expires_at: Date.now() + 86400000, // 24 hours -}); - -// Create attenuated token -const attenuatedToken = await plugin.newAttenuatedToken({ - parent_token: originToken.token, - audience_did: 'did:sonr:delegated', - attenuations: [{ can: ['sign'], with: 'vault://limited' }], -}); -``` - -#### Cryptographic Operations - -```typescript -// Sign data -const data = new TextEncoder().encode('Hello, World!'); -const signature = await plugin.signData({ data }); - -// Verify signature -const verification = await plugin.verifyData({ - data, - signature: signature.signature, -}); -console.log('Valid:', verification.valid); -``` - -#### Identity Operations - -```typescript -// Get issuer DID -const issuer = await plugin.getIssuerDID(); -console.log('DID:', issuer.issuer_did); -console.log('Address:', issuer.address); -``` - -#### DWN Operations - -```typescript -// Create record -const record = await plugin.createRecord({ - target: 'did:sonr:alice', - data: new TextEncoder().encode('Record data'), - schema: 'https://schema.org/Message', - published: true, - encrypt: true, -}); - -// Read record -const readResponse = await plugin.readRecord(record.record_id, 'did:sonr:alice'); - -// Update record -await plugin.updateRecord({ - record_id: record.record_id, - target: 'did:sonr:alice', - data: new TextEncoder().encode('Updated data'), -}); - -// Delete record -await plugin.deleteRecord(record.record_id, 'did:sonr:alice'); -``` - -### Service Worker Management - -```typescript -import { MotorServiceWorkerManager } from '@sonr.io/es/client/motor'; - -const manager = new MotorServiceWorkerManager({ - worker_script: '/motor-worker.js', - scope: '/motor-worker', - debug: true, -}); - -// Register service worker -const status = await manager.register(); -console.log('Registered:', status.registered); - -// Check status -const currentStatus = manager.getStatus(); -console.log('State:', currentStatus.state); - -// Update service worker -await manager.update(); - -// Send message to service worker -await manager.sendMessage({ type: 'custom-message', data: 'hello' }); - -// Cleanup -await manager.unregister(); -``` - -### Direct HTTP Client - -```typescript -import { MotorClient } from '@sonr.io/es/client/motor'; - -const client = new MotorClient({ - worker_url: 'http://localhost:8080', - timeout: 15000, - max_retries: 2, -}); - -// Test connection -const connected = await client.testConnection(); - -// Get service info -const info = await client.getServiceInfo(); - -// Health check -const health = await client.healthCheck(); -``` - -## Configuration - -### MotorPluginConfig - -```typescript -interface MotorPluginConfig extends MotorServiceWorkerConfig { - /** Whether to automatically register the service worker */ - auto_register_worker?: boolean; - /** Whether to use service worker when available */ - prefer_service_worker?: boolean; - /** Fallback configuration for direct HTTP calls */ - fallback_url?: string; -} -``` - -### MotorServiceWorkerConfig - -```typescript -interface MotorServiceWorkerConfig { - /** URL where the Motor WASM service worker is available */ - worker_url?: string; - /** Timeout for HTTP requests in milliseconds */ - timeout?: number; - /** Maximum number of retry attempts */ - max_retries?: number; - /** Whether to enable debug logging */ - debug?: boolean; -} -``` - -## Error Handling - -The plugin includes comprehensive error handling: - -```typescript -try { - const plugin = await createMotorPlugin(); - const result = await plugin.signData({ data: new Uint8Array([1, 2, 3]) }); -} catch (error) { - if (error.message.includes('Service worker not supported')) { - // Handle service worker unavailability - console.log('Falling back to HTTP client'); - } else if (error.message.includes('timeout')) { - // Handle timeout - console.log('Request timed out, retrying with increased timeout'); - } else { - // Handle other errors - console.error('Operation failed:', error); - } -} -``` - -## Event Handling - -Listen for service worker events: - -```typescript -// Service worker update available -window.addEventListener('motor-update-available', (event) => { - console.log('New service worker version available'); - // Prompt user to refresh -}); - -// Service worker health failure -window.addEventListener('motor-health-failure', (event) => { - console.warn('Service worker health check failed'); - // Implement fallback strategy -}); -``` - -## Browser Compatibility - -### Supported Browsers - -- Chrome 40+ (Service Workers) -- Firefox 44+ (Service Workers) -- Safari 11.1+ (Service Workers) -- Edge 17+ (Service Workers) - -### Required Features - -- **WebAssembly**: For WASM execution -- **Service Workers**: For background operations (browser only) -- **Fetch API**: For HTTP communication -- **Secure Context**: HTTPS required for service workers - -### Polyfills - -For older browsers, consider including: - -```html - - - - - -``` - -## Performance Considerations - -### Service Worker Benefits - -- **Background Processing**: Operations continue even when page is not active -- **Caching**: Reduces network requests for repeated operations -- **Offline Support**: Some operations can work offline -- **Resource Sharing**: Multiple tabs share the same service worker instance - -### HTTP Fallback Benefits - -- **Lower Latency**: Direct communication without service worker overhead -- **Simpler Debugging**: Easier to trace network requests -- **Better Error Handling**: More predictable error responses - -### Optimization Tips - -1. **Use appropriate timeouts** based on operation complexity -2. **Enable debug mode** during development -3. **Monitor service worker health** in production -4. **Implement proper retry logic** for transient failures -5. **Use connection pooling** for multiple operations - -## Security Considerations - -### Service Worker Security - -- Service workers must be served over HTTPS in production -- Same-origin policy applies to service worker registration -- Service worker scope determines accessible resources - -### Data Protection - -- All cryptographic operations occur in the WASM enclave -- Private keys never leave the secure execution environment -- Data encryption uses consensus-based algorithms - -### Network Security - -- All HTTP communications use secure protocols -- Request/response data is validated and sanitized -- Retry logic includes exponential backoff to prevent DoS - -## Troubleshooting - -### Common Issues - -#### Service Worker Registration Fails - -```typescript -// Check if running in secure context -if (!window.isSecureContext) { - console.error('Service workers require HTTPS or localhost'); -} - -// Check browser support -if (!('serviceWorker' in navigator)) { - console.error('Service workers not supported'); -} -``` - -#### HTTP Connection Fails - -```typescript -// Verify server is running -const client = new MotorClient({ worker_url: 'http://localhost:8080' }); -const connected = await client.testConnection(); -if (!connected) { - console.error('Motor service not available at configured URL'); -} -``` - -#### Type Errors - -```typescript -// Ensure proper type imports -import type { - MotorPlugin, - NewOriginTokenRequest, - UCANTokenResponse -} from '@sonr.io/es/client/motor'; -``` - -### Debug Mode - -Enable debug logging for detailed operation information: - -```typescript -const plugin = await createMotorPlugin({ - debug: true, // Enable debug logging - timeout: 30000, - max_retries: 3, -}); -``` - -### Health Monitoring - -Implement health monitoring for production: - -```typescript -const plugin = await createMotorPlugin(); - -// Periodic health checks -setInterval(async () => { - const connected = await plugin.testConnection(); - if (!connected) { - console.warn('Motor service connection lost'); - // Implement reconnection logic - } -}, 30000); -``` - -## Contributing - -When contributing to the Motor integration: - -1. **Follow TypeScript best practices** -2. **Add comprehensive JSDoc documentation** -3. **Include unit tests for new functionality** -4. **Update type definitions when changing APIs** -5. **Test in both browser and Node.js environments** - -## License - -This module is part of the Sonr project and follows the same licensing terms. \ No newline at end of file diff --git a/packages/es/src/worker/client.ts b/packages/es/src/worker/client.ts deleted file mode 100644 index e9b763c8c..000000000 --- a/packages/es/src/worker/client.ts +++ /dev/null @@ -1,486 +0,0 @@ -/** - * HTTP client for Motor Payment Gateway and OIDC Authorization - * - * @packageDocumentation - */ - -import type { - MotorServiceWorkerConfig, - HealthCheckResponse, - ServiceInfoResponse, - ErrorResponse, - // Payment types - PaymentInstrument, - CanMakePaymentRequest, - CanMakePaymentResponse, - PaymentRequestEvent, - PaymentHandlerResponse, - ProcessPaymentRequest, - ProcessPaymentResponse, - ValidatePaymentMethodRequest, - ValidatePaymentMethodResponse, - PaymentStatus, - RefundPaymentRequest, - RefundPaymentResponse, - // OIDC types - OIDCConfiguration, - OIDCAuthorizationRequest, - OIDCAuthorizationResponse, - OIDCTokenRequest, - OIDCTokenResponse, - OIDCUserInfo, - JWKS, -} from './types'; - -/** - * Default configuration for the Motor client - */ -const DEFAULT_CONFIG: Required = { - worker_url: '/motor-worker', - timeout: 30000, - max_retries: 3, - debug: false, -}; - -/** - * HTTP client for Motor Payment Gateway and OIDC services - */ -export class MotorClient { - private readonly config: Required; - private readonly baseUrl: string; - private serviceWorkerReady: Promise | null = null; - private useServiceWorker = false; - - constructor(config: Partial = {}) { - this.config = { ...DEFAULT_CONFIG, ...config }; - this.baseUrl = this.config.worker_url; - - this.detectServiceWorker(); - - if (this.config.debug) { - console.debug('[MotorClient] Initialized with config:', this.config); - } - } - - /** - * Detects if a Motor service worker is available - */ - private detectServiceWorker(): void { - if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) { - this.serviceWorkerReady = navigator.serviceWorker.ready.then(registration => { - if (registration.active?.scriptURL.includes('motor')) { - this.useServiceWorker = true; - if (this.config.debug) { - console.debug('[MotorClient] Motor service worker detected'); - } - return true; - } - return false; - }).catch(() => false); - } - } - - // Core HTTP Methods - - /** - * Makes an HTTP request with automatic retries - */ - private async request( - method: string, - endpoint: string, - data?: unknown - ): Promise { - const url = `${this.baseUrl}${endpoint}`; - let lastError: Error | null = null; - - for (let attempt = 1; attempt <= this.config.max_retries; attempt++) { - try { - if (this.config.debug) { - console.debug(`[MotorClient] ${method} ${url} (attempt ${attempt})`); - } - - const response = await this.performRequest(method, url, data); - - if (!response.ok) { - const errorData = await this.parseErrorResponse(response); - throw new Error(`HTTP ${response.status}: ${errorData.error || response.statusText}`); - } - - return await this.parseResponse(response); - } catch (error) { - lastError = error instanceof Error ? error : new Error(String(error)); - - if (this.config.debug) { - console.debug(`[MotorClient] Attempt ${attempt} failed:`, lastError.message); - } - - if (lastError.message.includes('HTTP 4')) { - break; - } - - if (attempt < this.config.max_retries) { - const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000); - await this.sleep(delay); - } - } - } - - throw lastError || new Error('Request failed after all retries'); - } - - /** - * Performs the actual HTTP request - */ - private async performRequest( - method: string, - url: string, - data?: unknown - ): Promise { - if (this.useServiceWorker && this.serviceWorkerReady) { - const swReady = await this.serviceWorkerReady; - if (swReady) { - return this.performServiceWorkerRequest(method, url, data); - } - } - - const headers: HeadersInit = { - 'Content-Type': 'application/json', - }; - - const requestInit: RequestInit = { - method, - headers, - mode: 'cors', - }; - - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.config.timeout); - requestInit.signal = controller.signal; - - try { - if (data && method !== 'GET') { - requestInit.body = JSON.stringify(this.serializeData(data)); - } - - return await fetch(url, requestInit); - } finally { - clearTimeout(timeoutId); - } - } - - /** - * Performs a request through the service worker - */ - private async performServiceWorkerRequest( - method: string, - url: string, - data?: unknown - ): Promise { - return new Promise((resolve, reject) => { - if (!navigator.serviceWorker.controller) { - return this.performRequest(method, url, data).then(resolve).catch(reject); - } - - const messageChannel = new MessageChannel(); - const timeout = setTimeout(() => { - reject(new Error('Service worker request timed out')); - }, this.config.timeout); - - messageChannel.port1.onmessage = (event) => { - clearTimeout(timeout); - - if (event.data.error) { - reject(new Error(event.data.error)); - } else { - const response = new Response( - JSON.stringify(event.data), - { - status: event.data.error ? 500 : 200, - headers: { 'Content-Type': 'application/json' }, - } - ); - resolve(response); - } - }; - - navigator.serviceWorker.controller.postMessage( - { - type: 'API_REQUEST', - method, - url, - data: data ? this.serializeData(data) : undefined, - }, - [messageChannel.port2] - ); - }); - } - - /** - * Parses a successful response - */ - private async parseResponse(response: Response): Promise { - const text = await response.text(); - - if (!text) { - return {} as T; - } - - try { - const parsed = JSON.parse(text); - return this.deserializeData(parsed); - } catch (error) { - throw new Error(`Failed to parse response JSON: ${error}`); - } - } - - /** - * Parses an error response - */ - private async parseErrorResponse(response: Response): Promise { - try { - const text = await response.text(); - if (text) { - return JSON.parse(text) as ErrorResponse; - } - } catch { - // Ignore parsing errors - } - - return { error: response.statusText || 'Unknown error' }; - } - - /** - * Serializes data for sending - */ - private serializeData(data: unknown): unknown { - if (data instanceof Uint8Array) { - return Array.from(data); - } - - if (data && typeof data === 'object') { - const result: Record = {}; - for (const [key, value] of Object.entries(data)) { - result[key] = this.serializeData(value); - } - return result; - } - - return data; - } - - /** - * Deserializes received data - */ - private deserializeData(data: unknown): T { - if (Array.isArray(data) && data.every(item => typeof item === 'number')) { - return new Uint8Array(data) as unknown as T; - } - - if (data && typeof data === 'object') { - const result: Record = {}; - for (const [key, value] of Object.entries(data)) { - result[key] = this.deserializeData(value); - } - return result as T; - } - - return data as T; - } - - /** - * Sleep utility - */ - private sleep(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)); - } - - // Health & Status - - /** - * Check service health - */ - async healthCheck(): Promise { - return this.request('GET', '/health'); - } - - /** - * Get service information - */ - async getServiceInfo(): Promise { - return this.request('GET', '/status'); - } - - // Payment Gateway API - - /** - * Get available payment instruments - */ - async getPaymentInstruments(): Promise { - return this.request('GET', '/payment/instruments'); - } - - /** - * Check if payment can be made - */ - async canMakePayment(request: CanMakePaymentRequest): Promise { - return this.request('POST', '/payment/canmakepayment', request); - } - - /** - * Handle payment request event - */ - async handlePaymentRequest(event: PaymentRequestEvent): Promise { - return this.request('POST', '/payment/paymentrequest', event); - } - - /** - * Process a payment - */ - async processPayment(request: ProcessPaymentRequest): Promise { - return this.request('POST', '/api/payment/process', request); - } - - /** - * Validate payment method - */ - async validatePaymentMethod(request: ValidatePaymentMethodRequest): Promise { - return this.request('POST', '/api/payment/validate', request); - } - - /** - * Get payment status - */ - async getPaymentStatus(paymentId: string): Promise { - return this.request('GET', `/api/payment/status/${paymentId}`); - } - - /** - * Process refund - */ - async refundPayment(request: RefundPaymentRequest): Promise { - return this.request('POST', '/api/payment/refund', request); - } - - // OIDC API - - /** - * Get OIDC configuration - */ - async getOIDCConfiguration(): Promise { - return this.request('GET', '/.well-known/openid-configuration'); - } - - /** - * Handle authorization - */ - async authorize(request: OIDCAuthorizationRequest): Promise { - return this.request('GET', '/authorize', request); - } - - /** - * Exchange code for tokens - */ - async token(request: OIDCTokenRequest): Promise { - return this.request('POST', '/token', request); - } - - /** - * Get user info - */ - async getUserInfo(accessToken: string): Promise { - return this.request( - 'GET', - '/userinfo', - undefined - ); - } - - /** - * Get JWKS - */ - async getJWKS(): Promise { - return this.request('GET', '/.well-known/jwks.json'); - } - - // Utility Methods - - /** - * Test connectivity - */ - async testConnection(): Promise { - try { - await this.healthCheck(); - return true; - } catch { - return false; - } - } - - /** - * Get configuration - */ - getConfig(): Required { - return { ...this.config }; - } - - /** - * Update configuration - */ - updateConfig(newConfig: Partial): void { - Object.assign(this.config, newConfig); - - if (this.config.debug) { - console.debug('[MotorClient] Updated config:', this.config); - } - } - - /** - * Send message to service worker - */ - async sendServiceWorkerMessage(type: string, data?: unknown): Promise { - if (!navigator.serviceWorker?.controller) { - throw new Error('No service worker controller available'); - } - - return new Promise((resolve, reject) => { - const messageChannel = new MessageChannel(); - const timeout = setTimeout(() => { - reject(new Error(`Service worker message timeout: ${type}`)); - }, this.config.timeout); - - messageChannel.port1.onmessage = (event) => { - clearTimeout(timeout); - - if (event.data.error) { - reject(new Error(event.data.error)); - } else { - resolve(event.data); - } - }; - - navigator.serviceWorker.controller.postMessage( - { type, data }, - [messageChannel.port2] - ); - }); - } - - /** - * Clear service worker cache - */ - async clearServiceWorkerCache(): Promise { - if (this.useServiceWorker) { - await this.sendServiceWorkerMessage('CLEAR_CACHE'); - } - } - - /** - * Check if service worker is ready - */ - async isServiceWorkerReady(): Promise { - if (!this.serviceWorkerReady) { - return false; - } - return this.serviceWorkerReady; - } -} \ No newline at end of file diff --git a/packages/es/src/worker/global.d.ts b/packages/es/src/worker/global.d.ts deleted file mode 100644 index 52ad56d21..000000000 --- a/packages/es/src/worker/global.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Global type declarations for experimental browser APIs - */ - -declare global { - interface PaymentManager { - instruments: PaymentInstruments; - userHint?: string; - canMakePayment?: boolean; - } - - interface PaymentInstruments { - set(key: string, details: any): Promise; - get(key: string): Promise; - keys(): Promise; - has(key: string): Promise; - delete(key: string): Promise; - clear(): Promise; - } - - interface ServiceWorkerRegistration { - paymentManager?: PaymentManager; - } - - interface Window { - PaymentManager?: any; - } -} - -export {}; \ No newline at end of file diff --git a/packages/es/src/worker/index.ts b/packages/es/src/worker/index.ts deleted file mode 100644 index d23b714bc..000000000 --- a/packages/es/src/worker/index.ts +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Motor WASM service worker integration for @sonr.io/es - * - * This module provides TypeScript wrapper methods for the Motor WASM service worker, - * enabling type-safe interactions with Payment Gateway and OIDC Authorization services. - * - * ## Features - * - * - **Payment Gateway**: W3C Payment Handler API implementation - * - **OIDC Authorization**: OpenID Connect authentication flows - * - **Service Worker Management**: Automatic registration and lifecycle handling - * - **Cross-Environment Support**: Works in browser and Node.js environments - * - * @packageDocumentation - */ - -// Type Exports - -// Core types -export type { - MotorPlugin, - MotorServiceWorkerConfig, -} from './types'; - -// Plugin-specific config type -export type { MotorPluginConfig } from './plugin'; - -// Payment types -export type { - PaymentInstrument, - PaymentMethod, - PaymentDetails, - CanMakePaymentRequest, - CanMakePaymentResponse, - PaymentRequestEvent, - PaymentHandlerResponse, - ProcessPaymentRequest, - ProcessPaymentResponse, - ValidatePaymentMethodRequest, - ValidatePaymentMethodResponse, - PaymentStatus, - RefundPaymentRequest, - RefundPaymentResponse, -} from './types'; - -// OIDC types -export type { - OIDCConfiguration, - OIDCAuthorizationRequest, - OIDCAuthorizationResponse, - OIDCTokenRequest, - OIDCTokenResponse, - OIDCUserInfo, - JWKS, - JWK, -} from './types'; - -// Service worker types -export type { - ServiceWorkerStatus, - EnvironmentInfo, - HealthCheckResponse, - ServiceInfoResponse, - ErrorResponse, -} from './types'; - -// Registration types -export type { RegistrationOptions } from './register'; - -// OIDC client types -export type { OIDCClientConfig } from './oidc'; - -// Class Exports - -// Main plugin implementation -export { MotorPluginImpl } from './plugin'; - -// Service worker manager -export { MotorServiceWorkerManager } from './worker'; - -// HTTP client -export { MotorClient } from './client'; - -// Payment Gateway client -export { PaymentGatewayClient, MotorPaymentHandler, MotorPaymentRequest } from './payment'; - -// OIDC client -export { OIDCClient } from './oidc'; - -// Factory Functions - -// Main factory functions -export { - createMotorPlugin, - createMotorPluginForNode, - createMotorPluginForBrowser, -} from './plugin'; - -// Payment factory functions -export { - createPaymentGatewayClient, - createPaymentHandler, - isPaymentHandlerSupported, - isPaymentRequestSupported, -} from './payment'; - -// OIDC factory functions -export { - createOIDCClient, - isOIDCCallback, - autoHandleOIDCCallback, -} from './oidc'; - -// Service worker registration utilities -export { - registerMotorServiceWorker, - unregisterMotorServiceWorker, - getMotorServiceWorkerStatus, - updateMotorServiceWorker, - createUpdatePrompt, - useMotorServiceWorker, -} from './register'; - -// Service worker lifecycle helpers -export { - getDefaultServiceWorkerManager, - waitForServiceWorker, - detectEnvironment, -} from './worker'; - -// Default Export - -/** - * Default Motor plugin instance - */ -let defaultPlugin: import('./types').MotorPlugin | null = null; - -/** - * Gets or creates the default Motor plugin instance - */ -export default async function getDefaultMotorPlugin( - config?: Partial -): Promise { - if (!defaultPlugin) { - const { createMotorPlugin } = await import('./plugin'); - defaultPlugin = await createMotorPlugin(config); - } - return defaultPlugin; -} - -// Auto-Registration - -/** - * Automatically register the Motor service worker in browser environments - */ -if (typeof window !== 'undefined' && process.env.MOTOR_DISABLE_AUTO_REGISTER !== 'true') { - import('./worker').then(({ MotorServiceWorkerManager }) => { - if (MotorServiceWorkerManager.isSupported()) { - const manager = new MotorServiceWorkerManager({ - worker_script: '/motor-worker.js', - scope: '/motor-worker', - debug: process.env.NODE_ENV === 'development', - }); - - manager.register().catch((error) => { - console.warn('[Motor] Auto-registration failed:', error); - }); - } - }).catch(() => { - // Silently ignore import errors - }); -} - -// Browser Events Setup - -/** - * Set up global event listeners for Motor service worker events - */ -if (typeof window !== 'undefined') { - window.addEventListener('motor-service-worker-update', ((event: CustomEvent) => { - console.log('[Motor] Service worker update available:', event.detail); - - window.dispatchEvent(new CustomEvent('motor-update-available', { - detail: event.detail, - })); - }) as EventListener); - - window.addEventListener('motor-service-worker-health-failure', ((event: CustomEvent) => { - console.warn('[Motor] Service worker health check failed:', event.detail); - - window.dispatchEvent(new CustomEvent('motor-health-failure', { - detail: event.detail, - })); - }) as EventListener); -} - -// Utility Functions - -/** - * Check if Motor is supported in the current environment - */ -export function isMotorSupported(): boolean { - try { - const { MotorServiceWorkerManager } = require('./worker'); - const env = MotorServiceWorkerManager.detectEnvironment(); - return env.supports_wasm && (env.supports_service_worker || env.is_node); - } catch { - return typeof WebAssembly !== 'undefined'; - } -} - -/** - * Get Motor environment information - */ -export function getMotorEnvironment(): import('./types').EnvironmentInfo { - try { - const { MotorServiceWorkerManager } = require('./worker'); - return MotorServiceWorkerManager.detectEnvironment(); - } catch { - return { - is_browser: typeof window !== 'undefined', - is_node: typeof process !== 'undefined', - supports_service_worker: false, - supports_wasm: typeof WebAssembly !== 'undefined', - supports_payment_handler: typeof window !== 'undefined' && 'PaymentManager' in window, - }; - } -} \ No newline at end of file diff --git a/packages/es/src/worker/motor-worker.js b/packages/es/src/worker/motor-worker.js deleted file mode 100644 index cc627e6e8..000000000 --- a/packages/es/src/worker/motor-worker.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Motor Service Worker - * Payment Gateway & OpenID Connect Authorization Beacon - * - * This service worker uses go-wasm-http-server to embed a Go HTTP server - * that handles payment processing and OIDC authentication flows. - */ - -// Import wasm_exec.js for Go 1.23.4 and go-wasm-http-server -importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.4/misc/wasm/wasm_exec.js'); -importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v2.2.1/sw.js'); - -// Configuration -const WASM_MODULE_URL = '/motor.wasm'; -const CACHE_NAME = 'motor-gateway-v1'; - -/** - * Service Worker lifecycle - Install event - */ -self.addEventListener('install', (event) => { - console.log('[Motor Gateway] Installing service worker...'); - - event.waitUntil( - (async () => { - try { - // Pre-cache the WASM module - const cache = await caches.open(CACHE_NAME); - await cache.add(WASM_MODULE_URL); - - console.log('[Motor Gateway] WASM module cached'); - - // Skip waiting to activate immediately - await self.skipWaiting(); - } catch (error) { - console.error('[Motor Gateway] Installation failed:', error); - } - })() - ); -}); - -/** - * Service Worker lifecycle - Activate event - */ -self.addEventListener('activate', (event) => { - console.log('[Motor Gateway] Activating service worker...'); - - event.waitUntil( - (async () => { - // Clean up old caches - const cacheNames = await caches.keys(); - await Promise.all( - cacheNames - .filter(name => name.startsWith('motor-') && name !== CACHE_NAME) - .map(name => caches.delete(name)) - ); - - // Take control of all clients - await self.clients.claim(); - - console.log('[Motor Gateway] Service worker activated'); - })() - ); -}); - -/** - * Register the Motor WASM HTTP server - * This handles all HTTP requests through the Go WASM module - */ -registerWasmHTTPListener(WASM_MODULE_URL, { - // Base path for API endpoints - base: '/', - - // Cache strategies for different endpoints - cacheStrategies: { - // Health endpoints - always fetch fresh - '/health': 'network-first', - '/status': 'network-first', - - // OIDC discovery - cache for performance - '/.well-known/openid-configuration': 'cache-first', - '/.well-known/jwks.json': 'cache-first', - - // Payment endpoints - always fetch fresh for security - '/api/payment/process': 'network-only', - '/api/payment/validate': 'network-only', - '/api/payment/status': 'network-first', - '/api/payment/refund': 'network-only', - - // Auth endpoints - no caching for security - '/authorize': 'network-only', - '/token': 'network-only', - '/userinfo': 'network-only', - } -}); - -/** - * Handle messages from clients - */ -self.addEventListener('message', async (event) => { - const { type, data } = event.data; - - try { - let result; - - switch (type) { - case 'HEALTH_CHECK': - // Check health via the WASM handler - try { - const response = await fetch('/health'); - result = await response.json(); - } catch (error) { - result = { - status: 'error', - error: error.message, - service: 'motor-gateway' - }; - } - break; - - case 'CLEAR_CACHE': - // Clear the cache - await caches.delete(CACHE_NAME); - result = { success: true, message: 'Cache cleared' }; - break; - - case 'SKIP_WAITING': - // Skip waiting for activation - await self.skipWaiting(); - result = { success: true }; - break; - - default: - result = { error: `Unknown message type: ${type}` }; - } - - // Send response back to client - if (event.ports && event.ports[0]) { - event.ports[0].postMessage(result); - } - } catch (error) { - if (event.ports && event.ports[0]) { - event.ports[0].postMessage({ - error: error.message || 'Service worker error', - }); - } - } -}); - -console.log('[Motor Gateway] Service worker loaded'); \ No newline at end of file diff --git a/packages/es/src/worker/motor.test.ts.bak b/packages/es/src/worker/motor.test.ts.bak deleted file mode 100644 index 0b10b55da..000000000 --- a/packages/es/src/worker/motor.test.ts.bak +++ /dev/null @@ -1,715 +0,0 @@ -import { describe, it, expect, beforeAll, afterAll, vi, beforeEach } from 'vitest'; -import { - createMotorPlugin, - createMotorPluginForBrowser, - createMotorPluginForNode, - MotorPlugin, - type NewOriginTokenRequest, - type SignDataRequest, - type DWNRecord, -} from './index'; -import { registerMotorServiceWorker } from './register'; - -// Mock fetch globally for all tests -global.fetch = vi.fn(); - -// Mock service worker registration for testing -const mockServiceWorker = { - ready: Promise.resolve({ - active: { state: 'activated' }, - unregister: vi.fn(), - }), - controller: { state: 'activated' }, -}; - -// Mock navigator for browser tests -const mockNavigator = { - serviceWorker: { - register: vi.fn().mockResolvedValue(mockServiceWorker), - ready: mockServiceWorker.ready, - controller: mockServiceWorker.controller, - }, -}; - -describe('Motor WASM Plugin', () => { - beforeEach(() => { - vi.clearAllMocks(); - - // Mock successful health check and other API responses - vi.mocked(fetch).mockImplementation(async (url: string | URL, options?: RequestInit) => { - const urlString = typeof url === 'string' ? url : url.toString(); - - if (process.env.NODE_ENV === 'test') { - console.debug('[Test Mock] Fetch called with URL:', urlString); - } - - // Handle health check endpoint - if (urlString.includes('/health') || urlString.endsWith('/health')) { - return { - ok: true, - status: 200, - json: async () => ({ status: 'healthy', timestamp: Date.now() }), - } as Response; - } - - // Handle UCAN token endpoints - if (urlString.includes('/wallet/newOriginToken')) { - return { - ok: true, - status: 200, - json: async () => ({ - token: 'mock_ucan_token_jwt', - issuer: 'did:sonr:issuer', - address: 'sonr1234567890', - }), - } as Response; - } - - if (urlString.includes('/wallet/newAttenuatedToken')) { - return { - ok: true, - status: 200, - json: async () => ({ - token: 'attenuated_ucan_token_jwt', - issuer: 'did:sonr:issuer', - address: 'sonr1234567890', - }), - } as Response; - } - - // Default success response for other endpoints - return { - ok: true, - status: 200, - json: async () => ({ status: 'ok' }), - text: async () => 'success', - } as Response; - }); - }); - - describe('Plugin Creation', () => { - it('should create plugin with auto-detection', async () => { - const plugin = await createMotorPlugin(); - expect(plugin).toBeDefined(); - expect(plugin.newOriginToken).toBeDefined(); - expect(plugin.signData).toBeDefined(); - expect(plugin.verifyData).toBeDefined(); - }); - - it('should create Node.js plugin explicitly', async () => { - const plugin = await createMotorPluginForNode('http://localhost:8080'); - expect(plugin).toBeDefined(); - expect(plugin.getIssuerDID).toBeDefined(); - }); - - it('should handle browser plugin creation', async () => { - // Mock browser environment - global.navigator = mockNavigator as any; - global.window = { location: { origin: 'http://localhost:3000' } } as any; - - const plugin = await createMotorPluginForBrowser('/motor-worker'); - expect(plugin).toBeDefined(); - - // Clean up - delete global.navigator; - delete global.window; - }); - }); - - describe('UCAN Token Operations', () => { - let plugin: MotorPlugin; - - beforeAll(async () => { - plugin = await createMotorPluginForNode('http://localhost:8080'); - }); - - it('should create origin token', async () => { - const request: NewOriginTokenRequest = { - audience_did: 'did:sonr:test_audience', - attenuations: [ - { - can: ['sign', 'verify'], - with: 'vault://test', - }, - ], - facts: ['test_fact'], - expires_at: Date.now() + 3600000, // 1 hour from now - }; - - // Mock the API response for newOriginToken - const mockResponse = { - token: 'mock_ucan_token_jwt', - issuer: 'did:sonr:issuer', - address: 'sonr1234567890', - }; - - vi.mocked(fetch).mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => mockResponse, - } as Response); - - const response = await plugin.newOriginToken(request); - - expect(response.token).toBe('mock_ucan_token_jwt'); - expect(response.issuer).toBe('did:sonr:issuer'); - expect(response.address).toBe('sonr1234567890'); - - // Verify the request was made correctly - expect(fetch).toHaveBeenCalledWith( - 'http://localhost:8080/wallet/newOriginToken', - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ - 'Content-Type': 'application/json', - }), - body: JSON.stringify(request), - }) - ); - }); - - it('should create attenuated token', async () => { - const request = { - parent_token: 'parent_ucan_token', - audience_did: 'did:sonr:delegated', - attenuations: [ - { - can: ['sign'], - with: 'vault://restricted', - }, - ], - }; - - const mockResponse = { - token: 'attenuated_ucan_token_jwt', - issuer: 'did:sonr:issuer', - address: 'sonr1234567890', - }; - - vi.mocked(fetch).mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => mockResponse, - } as Response); - - const response = await plugin.newAttenuatedToken(request); - - expect(response.token).toBe('attenuated_ucan_token_jwt'); - expect(request.attenuations[0].can).not.toContain('verify'); - }); - }); - - describe('Cryptographic Operations', () => { - let plugin: MotorPlugin; - - beforeAll(async () => { - plugin = await createMotorPluginForNode('http://localhost:8080'); - }); - - it('should sign and verify data', async () => { - const data = new TextEncoder().encode('Test message'); - const signRequest: SignDataRequest = { data }; - - // Mock signature response - const mockSignature = new Uint8Array([1, 2, 3, 4, 5]); - - // Validate sign request - expect(signRequest.data).toBeInstanceOf(Uint8Array); - expect(signRequest.data).toEqual(data); - - // Validate verify request structure - const verifyRequest = { - data, - signature: mockSignature, - }; - - expect(verifyRequest.data).toEqual(data); - expect(verifyRequest.signature).toBeInstanceOf(Uint8Array); - }); - - it('should handle binary data correctly', () => { - const binaryData = new Uint8Array([0xff, 0xfe, 0xfd, 0xfc]); - const base64 = btoa(String.fromCharCode(...binaryData)); - const decoded = Uint8Array.from(atob(base64), c => c.charCodeAt(0)); - - expect(decoded).toEqual(binaryData); - }); - }); - - describe('DWN Operations', () => { - let plugin: MotorPlugin; - - beforeAll(async () => { - plugin = await createMotorPluginForNode('http://localhost:8080'); - }); - - it('should create DWN record', async () => { - const record: Partial = { - schema: 'https://schema.org/Person', - data: new TextEncoder().encode(JSON.stringify({ - name: 'Test User', - email: 'test@example.com', - })), - is_encrypted: false, - }; - - // Validate record structure - expect(record.schema).toBeDefined(); - expect(record.data).toBeInstanceOf(Uint8Array); - expect(record.is_encrypted).toBe(false); - }); - - it('should handle encrypted records', async () => { - const record: Partial = { - schema: 'https://schema.org/SecureData', - data: new TextEncoder().encode(JSON.stringify({ sensitive: 'information' })), - is_encrypted: true, - }; - - // Validate encryption flag - expect(record.is_encrypted).toBe(true); - expect(record.data).toBeDefined(); - }); - - it('should update existing record', async () => { - const updateRequest = { - record_id: 'existing_record_123', - data: { updated: 'value' }, - }; - - // Validate update structure - expect(updateRequest.record_id).toBeDefined(); - expect(updateRequest.data).toHaveProperty('updated'); - }); - - it('should delete record', async () => { - const deleteRequest = { - record_id: 'record_to_delete', - }; - - // Validate delete request - expect(deleteRequest.record_id).toBe('record_to_delete'); - }); - }); - - describe('Service Worker Registration', () => { - beforeAll(() => { - global.navigator = mockNavigator as any; - global.window = { - location: { origin: 'http://localhost:3000' }, - isSecureContext: true, - } as any; - // Mock the process object for environment detection - global.process = { - env: { NODE_ENV: 'test' }, - versions: { node: '18.0.0' }, - } as any; - }); - - afterAll(() => { - delete global.navigator; - delete global.window; - delete global.process; - }); - - it('should register service worker in mock browser environment', async () => { - // Simplified test without complex mocking - expect(mockNavigator.serviceWorker.register).toBeDefined(); - expect(typeof mockNavigator.serviceWorker.register).toBe('function'); - }); - - it('should handle registration options', async () => { - const options = { - scope: '/api/motor', - updateViaCache: 'none' as const, - }; - - // Test that options object is properly structured - expect(options.scope).toBe('/api/motor'); - expect(options.updateViaCache).toBe('none'); - }); - - it('should handle non-service-worker environment gracefully', async () => { - // Test the actual error case without mocking environment - const originalNavigator = global.navigator; - delete (global as any).navigator; - - const result = await registerMotorServiceWorker({ workerUrl: '/motor-sw.js' }); - expect(result).toBeNull(); - - // Restore navigator - global.navigator = originalNavigator; - }); - - it('should detect secure context requirement', async () => { - // Mock insecure context - const originalSecureContext = window.isSecureContext; - Object.defineProperty(window, 'isSecureContext', { - value: false, - writable: true, - }); - - const onError = vi.fn(); - const result = await registerMotorServiceWorker({ onError }); - - expect(result).toBeNull(); - expect(onError).toHaveBeenCalledWith( - expect.objectContaining({ - message: expect.stringContaining('secure context'), - }) - ); - - // Restore - Object.defineProperty(window, 'isSecureContext', { - value: originalSecureContext, - writable: true, - }); - }); - - it('should handle service worker lifecycle events', async () => { - const onSuccess = vi.fn(); - const onUpdateFound = vi.fn(); - const onReady = vi.fn(); - - // Mock service worker with lifecycle states - const mockWorker = { - state: 'installing', - addEventListener: vi.fn((event, handler) => { - if (event === 'statechange') { - // Simulate state changes - setTimeout(() => { - mockWorker.state = 'installed'; - handler(); - }, 10); - setTimeout(() => { - mockWorker.state = 'activated'; - handler(); - }, 20); - } - }), - postMessage: vi.fn(), - }; - - const mockRegistration = { - installing: mockWorker, - waiting: null, - active: null, - scope: '/', - updateViaCache: 'none', - update: vi.fn().mockResolvedValue(undefined), - unregister: vi.fn().mockResolvedValue(true), - addEventListener: vi.fn(), - }; - - mockNavigator.serviceWorker.register = vi.fn().mockResolvedValue(mockRegistration); - mockNavigator.serviceWorker.ready = Promise.resolve(mockRegistration); - - const registration = await registerMotorServiceWorker({ - onSuccess, - onUpdateFound, - onReady, - debug: true, - }); - - expect(registration).toBeTruthy(); - expect(onSuccess).toHaveBeenCalledWith(mockRegistration); - expect(onReady).toHaveBeenCalledWith(mockRegistration); - }); - }); - - describe('Service Worker Communication', () => { - let client: MotorPlugin; - - beforeAll(async () => { - // Mock MessageChannel - global.MessageChannel = vi.fn().mockImplementation(() => ({ - port1: { - onmessage: null, - postMessage: vi.fn(), - }, - port2: { - onmessage: null, - postMessage: vi.fn(), - }, - })); - - // Mock service worker controller - global.navigator = { - ...mockNavigator, - serviceWorker: { - ...mockNavigator.serviceWorker, - controller: { - postMessage: vi.fn((message, ports) => { - // Simulate service worker response - setTimeout(() => { - if (ports && ports[0] && ports[0].onmessage) { - ports[0].onmessage({ - data: { success: true, type: message.type }, - }); - } - }, 10); - }), - }, - }, - } as any; - - client = await createMotorPluginForNode('http://localhost:8080'); - }); - - afterAll(() => { - delete global.MessageChannel; - }); - - it('should send messages to service worker', async () => { - const mockClient = client as any; - - if (mockClient.client && typeof mockClient.client.sendServiceWorkerMessage === 'function') { - const response = await mockClient.client.sendServiceWorkerMessage('HEALTH_CHECK'); - expect(response).toHaveProperty('success', true); - expect(response).toHaveProperty('type', 'HEALTH_CHECK'); - } - }); - - it('should handle service worker API requests', async () => { - const mockClient = client as any; - - if (mockClient.client && mockClient.client.performServiceWorkerRequest) { - // Mock the service worker request - const mockResponse = await mockClient.client.performServiceWorkerRequest( - 'POST', - '/api/motor/wallet/sign', - { data: new Uint8Array([1, 2, 3]) } - ); - - expect(mockResponse).toBeDefined(); - } - }); - - it('should fallback to HTTP when service worker is unavailable', async () => { - // Remove service worker controller - const originalController = navigator.serviceWorker.controller; - Object.defineProperty(navigator.serviceWorker, 'controller', { - value: null, - writable: true, - }); - - const mockClient = client as any; - - // Should fallback to regular fetch - const response = await mockClient.client.healthCheck(); - expect(response).toBeDefined(); - - // Restore controller - Object.defineProperty(navigator.serviceWorker, 'controller', { - value: originalController, - writable: true, - }); - }); - }); - - describe('Service Worker Caching', () => { - let cacheStorage: Map>; - - beforeAll(() => { - // Mock Cache API - cacheStorage = new Map(); - - global.caches = { - open: vi.fn(async (name) => { - if (!cacheStorage.has(name)) { - cacheStorage.set(name, new Map()); - } - const cache = cacheStorage.get(name)!; - - return { - match: vi.fn(async (request) => { - const url = typeof request === 'string' ? request : request.url; - return cache.get(url) || null; - }), - put: vi.fn(async (request, response) => { - const url = typeof request === 'string' ? request : request.url; - cache.set(url, response); - }), - addAll: vi.fn(async (urls) => { - for (const url of urls) { - cache.set(url, new Response('cached')); - } - }), - delete: vi.fn(async (request) => { - const url = typeof request === 'string' ? request : request.url; - return cache.delete(url); - }), - }; - }), - keys: vi.fn(async () => Array.from(cacheStorage.keys())), - delete: vi.fn(async (name) => cacheStorage.delete(name)), - } as any; - }); - - afterAll(() => { - delete global.caches; - }); - - it('should cache WASM module', async () => { - const cache = await caches.open('motor-wasm-v1'); - await cache.addAll(['/motor.wasm']); - - const cached = await cache.match('/motor.wasm'); - expect(cached).toBeTruthy(); - }); - - it('should cache API responses', async () => { - const cache = await caches.open('motor-api-v1'); - const response = new Response(JSON.stringify({ issuer_did: 'did:sonr:test' })); - await cache.put('/motor/cache/issuer-did', response); - - const cached = await cache.match('/motor/cache/issuer-did'); - expect(cached).toBeTruthy(); - - const data = await cached?.json(); - expect(data).toHaveProperty('issuer_did', 'did:sonr:test'); - }); - - it('should clear cache on demand', async () => { - const cache = await caches.open('motor-api-v1'); - await cache.put('/test', new Response('test')); - - await caches.delete('motor-api-v1'); - const keys = await caches.keys(); - expect(keys).not.toContain('motor-api-v1'); - }); - }); - - describe('Service Worker Offline Support', () => { - let onlineStatus = true; - - beforeAll(() => { - // Mock online/offline status - Object.defineProperty(navigator, 'onLine', { - get: () => onlineStatus, - configurable: true, - }); - - // Mock IndexedDB - global.indexedDB = { - open: vi.fn(() => ({ - onsuccess: null, - onerror: null, - onupgradeneeded: null, - result: { - transaction: vi.fn(() => ({ - objectStore: vi.fn(() => ({ - add: vi.fn().mockResolvedValue(1), - getAll: vi.fn().mockResolvedValue([]), - delete: vi.fn().mockResolvedValue(undefined), - })), - })), - }, - })), - } as any; - }); - - afterAll(() => { - delete global.indexedDB; - }); - - it('should queue requests when offline', async () => { - onlineStatus = false; - - // Simulate offline request queueing - const requestQueue: any[] = []; - const queueRequest = (req: any) => { - requestQueue.push(req); - return Promise.resolve(); - }; - - const request = { - url: '/api/motor/wallet/sign', - method: 'POST', - body: { data: 'test' }, - }; - - await queueRequest(request); - expect(requestQueue).toHaveLength(1); - expect(requestQueue[0]).toEqual(request); - }); - - it('should process queued requests when back online', async () => { - onlineStatus = true; - - const processQueue = async (queue: any[]) => { - const processed = []; - for (const req of queue) { - // Simulate processing - processed.push(req); - } - return processed; - }; - - const queue = [ - { url: '/api/1', method: 'POST' }, - { url: '/api/2', method: 'GET' }, - ]; - - const processed = await processQueue(queue); - expect(processed).toHaveLength(2); - }); - }); - - describe('Error Handling', () => { - let plugin: MotorPlugin; - - beforeAll(async () => { - plugin = await createMotorPluginForNode('http://localhost:8080'); - }); - - it('should handle network errors', async () => { - // Test with invalid endpoint - const badPlugin = await createMotorPluginForNode('http://invalid:99999'); - - // Plugin should still be created but operations will fail - expect(badPlugin).toBeDefined(); - }); - - it('should validate input parameters', async () => { - const invalidRequest = { - audience_did: '', // Invalid empty DID - attenuations: [], - }; - - // Should validate before sending - expect(invalidRequest.audience_did).toBe(''); - }); - - it('should handle malformed responses', () => { - const malformedJson = '{"incomplete": '; - - expect(() => JSON.parse(malformedJson)).toThrow(); - }); - }); - - describe('Type Safety', () => { - it('should enforce correct types for UCAN requests', () => { - const request: NewOriginTokenRequest = { - audience_did: 'did:sonr:test', - attenuations: [{ can: ['sign'] }], - facts: ['fact1'], - not_before: 1000, - expires_at: 2000, - }; - - // TypeScript should enforce these types - expect(typeof request.audience_did).toBe('string'); - expect(Array.isArray(request.attenuations)).toBe(true); - expect(typeof request.expires_at).toBe('number'); - }); - - it('should handle Uint8Array for binary data', () => { - const data = new Uint8Array([1, 2, 3]); - const request: SignDataRequest = { data }; - - expect(request.data).toBeInstanceOf(Uint8Array); - expect(request.data.length).toBe(3); - }); - }); -}); \ No newline at end of file diff --git a/packages/es/src/worker/oidc.ts b/packages/es/src/worker/oidc.ts deleted file mode 100644 index 96dda54c8..000000000 --- a/packages/es/src/worker/oidc.ts +++ /dev/null @@ -1,529 +0,0 @@ -/** - * OpenID Connect (OIDC) client for Motor Authorization Beacon - * - * @packageDocumentation - */ - -import type { - OIDCConfiguration, - OIDCAuthorizationRequest, - OIDCAuthorizationResponse, - OIDCTokenRequest, - OIDCTokenResponse, - OIDCUserInfo, - JWKS, - MotorServiceWorkerConfig, -} from './types'; - -/** - * OIDC client configuration - */ -export interface OIDCClientConfig extends MotorServiceWorkerConfig { - /** Client ID for OIDC */ - client_id: string; - /** Redirect URI for authorization callback */ - redirect_uri: string; - /** Client secret (for confidential clients) */ - client_secret?: string; - /** Requested scopes */ - scope?: string; - /** Response type */ - response_type?: string; - /** Use PKCE for authorization code flow */ - use_pkce?: boolean; - /** Auto-refresh tokens */ - auto_refresh?: boolean; -} - -/** - * OIDC Authorization client for Motor - */ -export class OIDCClient { - private readonly baseUrl: string; - private readonly config: OIDCClientConfig; - private discoveryCache?: OIDCConfiguration; - private accessToken?: string; - private refreshToken?: string; - private idToken?: string; - private tokenExpiresAt?: number; - private codeVerifier?: string; - private codeChallenge?: string; - - constructor(config: OIDCClientConfig) { - this.config = { - worker_url: '/api', - timeout: 30000, - max_retries: 3, - debug: false, - scope: 'openid profile email', - response_type: 'code', - use_pkce: true, - auto_refresh: true, - ...config, - }; - this.baseUrl = this.config.worker_url || '/api'; - } - - /** - * Make an API request - */ - private async request( - method: string, - endpoint: string, - data?: unknown, - headers?: Record - ): Promise { - const url = `${this.baseUrl}${endpoint}`; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.config.timeout || 30000); - - try { - const response = await fetch(url, { - method, - headers: { - 'Content-Type': 'application/json', - ...headers, - }, - body: data ? JSON.stringify(data) : undefined, - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - if (!response.ok) { - const error = await response.text(); - throw new Error(`OIDC API error: ${response.status} - ${error}`); - } - - return await response.json(); - } catch (error) { - clearTimeout(timeoutId); - if (error instanceof Error && error.name === 'AbortError') { - throw new Error('OIDC request timed out'); - } - throw error; - } - } - - /** - * Get OIDC discovery configuration - */ - async getConfiguration(): Promise { - if (!this.discoveryCache) { - this.discoveryCache = await this.request( - 'GET', - '/.well-known/openid-configuration' - ); - } - return this.discoveryCache; - } - - /** - * Generate PKCE code verifier and challenge - */ - private generatePKCE(): { verifier: string; challenge: string } { - const verifier = this.generateRandomString(128); - const challenge = this.base64UrlEncode( - crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)) - ); - - return { verifier, challenge }; - } - - /** - * Generate random string for state/nonce/PKCE - */ - private generateRandomString(length: number): string { - const array = new Uint8Array(length); - crypto.getRandomValues(array); - return this.base64UrlEncode(array); - } - - /** - * Base64 URL encode - */ - private base64UrlEncode(data: ArrayBuffer | Uint8Array | Promise): string { - if (data instanceof Promise) { - throw new Error('Cannot encode Promise directly'); - } - - const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data; - let binary = ''; - bytes.forEach(byte => binary += String.fromCharCode(byte)); - - return btoa(binary) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); - } - - /** - * Build authorization URL - */ - async buildAuthorizationUrl(options: Partial = {}): Promise { - const config = await this.getConfiguration(); - const state = this.generateRandomString(32); - const nonce = this.generateRandomString(32); - - const params: OIDCAuthorizationRequest = { - client_id: this.config.client_id, - redirect_uri: this.config.redirect_uri, - response_type: this.config.response_type || 'code', - scope: this.config.scope || 'openid profile email', - state, - nonce, - ...options, - }; - - // Add PKCE if enabled - if (this.config.use_pkce) { - const pkce = this.generatePKCE(); - this.codeVerifier = pkce.verifier; - this.codeChallenge = pkce.challenge; - params.code_challenge = pkce.challenge; - params.code_challenge_method = 'S256'; - } - - // Store state and nonce for validation - sessionStorage.setItem('oidc_state', state); - sessionStorage.setItem('oidc_nonce', nonce); - - const url = new URL(config.authorization_endpoint); - Object.entries(params).forEach(([key, value]) => { - if (value !== undefined) { - url.searchParams.append(key, String(value)); - } - }); - - return url.toString(); - } - - /** - * Start authorization flow - */ - async authorize(options: Partial = {}): Promise { - const authUrl = await this.buildAuthorizationUrl(options); - window.location.href = authUrl; - } - - /** - * Open authorization in popup - */ - async authorizePopup(options: Partial = {}): Promise { - const authUrl = await this.buildAuthorizationUrl(options); - - const popup = window.open( - authUrl, - 'oidc_auth', - 'width=500,height=600,menubar=no,toolbar=no' - ); - - if (!popup) { - throw new Error('Failed to open authorization popup'); - } - - return new Promise((resolve, reject) => { - const checkInterval = setInterval(() => { - try { - if (popup.closed) { - clearInterval(checkInterval); - reject(new Error('Authorization popup was closed')); - return; - } - - // Check if redirected back - if (popup.location.href.startsWith(this.config.redirect_uri)) { - clearInterval(checkInterval); - - const url = new URL(popup.location.href); - const response = this.parseAuthorizationResponse(url); - - popup.close(); - resolve(response); - } - } catch (e) { - // Cross-origin, ignore - } - }, 500); - }); - } - - /** - * Parse authorization response from URL - */ - private parseAuthorizationResponse(url: URL): OIDCAuthorizationResponse { - const params = url.searchParams; - const hashParams = new URLSearchParams(url.hash.slice(1)); - - // Check for error - const error = params.get('error') || hashParams.get('error'); - if (error) { - throw new Error(`Authorization error: ${error} - ${params.get('error_description') || ''}`); - } - - // Validate state - const state = params.get('state') || hashParams.get('state'); - const savedState = sessionStorage.getItem('oidc_state'); - if (state !== savedState) { - throw new Error('State mismatch - possible CSRF attack'); - } - - return { - code: params.get('code') || undefined, - access_token: hashParams.get('access_token') || undefined, - token_type: hashParams.get('token_type') || undefined, - id_token: hashParams.get('id_token') || undefined, - state: state || undefined, - expires_in: hashParams.get('expires_in') ? parseInt(hashParams.get('expires_in')!) : undefined, - scope: hashParams.get('scope') || undefined, - }; - } - - /** - * Handle authorization callback - */ - async handleCallback(url?: string): Promise { - const callbackUrl = new URL(url || window.location.href); - const response = this.parseAuthorizationResponse(callbackUrl); - - if (response.code) { - // Exchange code for tokens - return await this.exchangeCode(response.code); - } else if (response.access_token) { - // Implicit flow - this.accessToken = response.access_token; - this.idToken = response.id_token; - if (response.expires_in) { - this.tokenExpiresAt = Date.now() + response.expires_in * 1000; - } - - return { - access_token: response.access_token, - token_type: response.token_type || 'Bearer', - expires_in: response.expires_in || 3600, - id_token: response.id_token, - scope: response.scope, - }; - } - - throw new Error('No authorization code or access token in response'); - } - - /** - * Exchange authorization code for tokens - */ - async exchangeCode(code: string): Promise { - const request: OIDCTokenRequest = { - grant_type: 'authorization_code', - code, - redirect_uri: this.config.redirect_uri, - client_id: this.config.client_id, - client_secret: this.config.client_secret, - }; - - // Add PKCE verifier if used - if (this.codeVerifier) { - request.code_verifier = this.codeVerifier; - } - - const response = await this.request('POST', '/token', request); - - // Store tokens - this.accessToken = response.access_token; - this.refreshToken = response.refresh_token; - this.idToken = response.id_token; - if (response.expires_in) { - this.tokenExpiresAt = Date.now() + response.expires_in * 1000; - } - - // Clear PKCE values - this.codeVerifier = undefined; - this.codeChallenge = undefined; - - return response; - } - - /** - * Refresh access token - */ - async refreshAccessToken(): Promise { - if (!this.refreshToken) { - throw new Error('No refresh token available'); - } - - const request: OIDCTokenRequest = { - grant_type: 'refresh_token', - refresh_token: this.refreshToken, - client_id: this.config.client_id, - client_secret: this.config.client_secret, - scope: this.config.scope, - }; - - const response = await this.request('POST', '/token', request); - - // Update tokens - this.accessToken = response.access_token; - if (response.refresh_token) { - this.refreshToken = response.refresh_token; - } - if (response.expires_in) { - this.tokenExpiresAt = Date.now() + response.expires_in * 1000; - } - - return response; - } - - /** - * Get user information - */ - async getUserInfo(): Promise { - if (!this.accessToken) { - throw new Error('No access token available'); - } - - // Auto-refresh if expired - if (this.config.auto_refresh && this.isTokenExpired()) { - await this.refreshAccessToken(); - } - - return await this.request( - 'GET', - '/userinfo', - undefined, - { - 'Authorization': `Bearer ${this.accessToken}`, - } - ); - } - - /** - * Get JSON Web Key Set - */ - async getJWKS(): Promise { - const config = await this.getConfiguration(); - const jwksUrl = new URL(config.jwks_uri); - - // If JWKS is on the same origin, use our request method - if (jwksUrl.origin === window.location.origin) { - return await this.request('GET', jwksUrl.pathname); - } - - // Otherwise fetch directly - const response = await fetch(config.jwks_uri); - if (!response.ok) { - throw new Error(`Failed to fetch JWKS: ${response.status}`); - } - - return await response.json(); - } - - /** - * Logout / revoke tokens - */ - async logout(): Promise { - // Clear local tokens - this.accessToken = undefined; - this.refreshToken = undefined; - this.idToken = undefined; - this.tokenExpiresAt = undefined; - - // Clear session storage - sessionStorage.removeItem('oidc_state'); - sessionStorage.removeItem('oidc_nonce'); - - // TODO: Call revocation endpoint if available - } - - /** - * Check if token is expired - */ - isTokenExpired(): boolean { - if (!this.tokenExpiresAt) { - return true; - } - // Consider expired 60 seconds before actual expiry - return Date.now() >= this.tokenExpiresAt - 60000; - } - - /** - * Get current access token - */ - getAccessToken(): string | undefined { - return this.accessToken; - } - - /** - * Get current ID token - */ - getIdToken(): string | undefined { - return this.idToken; - } - - /** - * Get current refresh token - */ - getRefreshToken(): string | undefined { - return this.refreshToken; - } - - /** - * Set tokens manually (for testing or restoration) - */ - setTokens(tokens: { - access_token?: string; - refresh_token?: string; - id_token?: string; - expires_in?: number; - }): void { - this.accessToken = tokens.access_token; - this.refreshToken = tokens.refresh_token; - this.idToken = tokens.id_token; - if (tokens.expires_in) { - this.tokenExpiresAt = Date.now() + tokens.expires_in * 1000; - } - } -} - -/** - * Create an OIDC client - */ -export function createOIDCClient(config: OIDCClientConfig): OIDCClient { - return new OIDCClient(config); -} - -/** - * Check if we're on a callback URL - */ -export function isOIDCCallback(redirectUri: string): boolean { - const currentUrl = window.location.href; - return currentUrl.startsWith(redirectUri) && - (currentUrl.includes('code=') || currentUrl.includes('access_token=') || currentUrl.includes('error=')); -} - -/** - * Auto-handle OIDC callback if on callback URL - */ -export async function autoHandleOIDCCallback( - client: OIDCClient, - redirectUri: string, - onSuccess?: (tokens: OIDCTokenResponse) => void, - onError?: (error: Error) => void -): Promise { - if (!isOIDCCallback(redirectUri)) { - return; - } - - try { - const tokens = await client.handleCallback(); - if (onSuccess) { - onSuccess(tokens); - } - - // Clean up URL - window.history.replaceState({}, document.title, redirectUri); - } catch (error) { - if (onError) { - onError(error instanceof Error ? error : new Error(String(error))); - } - } -} \ No newline at end of file diff --git a/packages/es/src/worker/payment-handler.d.ts b/packages/es/src/worker/payment-handler.d.ts deleted file mode 100644 index fcdd4eeea..000000000 --- a/packages/es/src/worker/payment-handler.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * W3C Payment Handler API type declarations - * These are experimental APIs not yet in standard TypeScript definitions - */ - -interface PaymentManager { - instruments: PaymentInstruments; - userHint?: string; - canMakePayment?: boolean; -} - -interface PaymentInstruments { - set(key: string, details: PaymentInstrument): Promise; - get(key: string): Promise; - keys(): Promise; - has(key: string): Promise; - delete(key: string): Promise; - clear(): Promise; -} - -interface PaymentInstrument { - name: string; - icons?: Array<{ - src: string; - sizes?: string; - type?: string; - }>; - method?: string; - capabilities?: { - [key: string]: any; - }; -} - -interface ServiceWorkerRegistration { - paymentManager?: PaymentManager; -} - -interface Window { - PaymentManager?: any; -} - -export {}; \ No newline at end of file diff --git a/packages/es/src/worker/payment.ts b/packages/es/src/worker/payment.ts deleted file mode 100644 index 7f0f93b6a..000000000 --- a/packages/es/src/worker/payment.ts +++ /dev/null @@ -1,323 +0,0 @@ -/** - * W3C Payment Handler API client for Motor Payment Gateway - * - * @packageDocumentation - */ - -/// - -import type { - PaymentInstrument, - PaymentMethod, - PaymentRequestEvent, - PaymentHandlerResponse, - CanMakePaymentRequest, - CanMakePaymentResponse, - ProcessPaymentRequest, - ProcessPaymentResponse, - ValidatePaymentMethodRequest, - ValidatePaymentMethodResponse, - PaymentStatus, - RefundPaymentRequest, - RefundPaymentResponse, - MotorServiceWorkerConfig, -} from './types'; - -/** - * Payment Gateway client for Motor service worker - */ -export class PaymentGatewayClient { - private readonly baseUrl: string; - private readonly config: MotorServiceWorkerConfig; - - constructor(config: MotorServiceWorkerConfig = {}) { - this.config = { - worker_url: '/api', - timeout: 30000, - max_retries: 3, - debug: false, - ...config, - }; - this.baseUrl = this.config.worker_url || '/api'; - } - - /** - * Make an API request to the payment gateway - */ - private async request( - method: string, - endpoint: string, - data?: unknown - ): Promise { - const url = `${this.baseUrl}${endpoint}`; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.config.timeout || 30000); - - try { - const response = await fetch(url, { - method, - headers: { - 'Content-Type': 'application/json', - }, - body: data ? JSON.stringify(data) : undefined, - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - if (!response.ok) { - const error = await response.text(); - throw new Error(`Payment API error: ${response.status} - ${error}`); - } - - return await response.json(); - } catch (error) { - clearTimeout(timeoutId); - if (error instanceof Error && error.name === 'AbortError') { - throw new Error('Payment request timed out'); - } - throw error; - } - } - - /** - * Get available payment instruments - */ - async getPaymentInstruments(): Promise { - return this.request('GET', '/payment/instruments'); - } - - /** - * Check if payment can be made with given methods - */ - async canMakePayment(request: CanMakePaymentRequest): Promise { - return this.request('POST', '/payment/canmakepayment', request); - } - - /** - * Handle W3C Payment Request Event - */ - async handlePaymentRequest(event: PaymentRequestEvent): Promise { - return this.request('POST', '/payment/paymentrequest', event); - } - - /** - * Process a payment transaction - */ - async processPayment(request: ProcessPaymentRequest): Promise { - return this.request('POST', '/payment/process', request); - } - - /** - * Validate a payment method - */ - async validatePaymentMethod(request: ValidatePaymentMethodRequest): Promise { - return this.request('POST', '/payment/validate', request); - } - - /** - * Get payment status by ID - */ - async getPaymentStatus(paymentId: string): Promise { - return this.request('GET', `/payment/status/${paymentId}`); - } - - /** - * Process a refund - */ - async refundPayment(request: RefundPaymentRequest): Promise { - return this.request('POST', '/payment/refund', request); - } -} - -/** - * W3C Payment Handler implementation for Motor - */ -export class MotorPaymentHandler { - private client: PaymentGatewayClient; - private registered = false; - - constructor(config?: MotorServiceWorkerConfig) { - this.client = new PaymentGatewayClient(config); - } - - /** - * Register the payment handler with the browser - */ - async register(): Promise { - if (!('PaymentManager' in window)) { - throw new Error('Payment Handler API not supported in this browser'); - } - - const registration = await navigator.serviceWorker.ready; - - if (!registration.paymentManager) { - throw new Error('Payment Manager not available in service worker'); - } - - // Get available instruments from the server - const instruments = await this.client.getPaymentInstruments(); - - // Register each instrument with the browser - for (const instrument of instruments) { - if (instrument.enabled) { - await registration.paymentManager.instruments.set(instrument.id, { - name: instrument.name, - icons: instrument.iconUrl ? [{ src: instrument.iconUrl, sizes: '32x32', type: 'image/png' }] : undefined, - method: instrument.type, - }); - } - } - - this.registered = true; - } - - /** - * Unregister all payment instruments - */ - async unregister(): Promise { - if (!('PaymentManager' in window)) { - return; - } - - const registration = await navigator.serviceWorker.ready; - - if (!registration.paymentManager) { - return; - } - - await registration.paymentManager.instruments.clear(); - this.registered = false; - } - - /** - * Check if payment handler is registered - */ - isRegistered(): boolean { - return this.registered; - } - - /** - * Get the payment gateway client - */ - getClient(): PaymentGatewayClient { - return this.client; - } -} - -/** - * Payment Request builder for Motor - */ -export class MotorPaymentRequest { - private methods: PaymentMethod[] = []; - private details: any = null; - private options: PaymentOptions = {}; - - /** - * Add a payment method - */ - addMethod(method: PaymentMethod): this { - this.methods.push(method); - return this; - } - - /** - * Set payment details - */ - setDetails(details: any): this { - this.details = details; - return this; - } - - /** - * Set payment options - */ - setOptions(options: PaymentOptions): this { - this.options = options; - return this; - } - - /** - * Build and show the payment request - */ - async show(): Promise { - if (!('PaymentRequest' in window)) { - throw new Error('Payment Request API not supported'); - } - - if (this.methods.length === 0) { - throw new Error('At least one payment method is required'); - } - - if (!this.details) { - throw new Error('Payment details are required'); - } - - const request = new PaymentRequest(this.methods, this.details, this.options); - - // Check if payment can be made - const canMake = await request.canMakePayment(); - if (!canMake) { - throw new Error('No supported payment methods available'); - } - - // Show the payment UI - return await request.show(); - } - - /** - * Create a payment request for a simple transaction - */ - static simple( - amount: number, - currency: string, - label: string, - methods: PaymentMethod[] = [{ supportedMethods: 'basic-card' }] - ): MotorPaymentRequest { - const request = new MotorPaymentRequest(); - - methods.forEach(method => request.addMethod(method)); - - request.setDetails({ - total: { - label, - amount: { - currency, - value: amount.toFixed(2), - }, - }, - }); - - return request; - } -} - -/** - * Create a payment gateway client - */ -export function createPaymentGatewayClient(config?: MotorServiceWorkerConfig): PaymentGatewayClient { - return new PaymentGatewayClient(config); -} - -/** - * Create a payment handler - */ -export function createPaymentHandler(config?: MotorServiceWorkerConfig): MotorPaymentHandler { - return new MotorPaymentHandler(config); -} - -/** - * Check if Payment Handler API is supported - */ -export function isPaymentHandlerSupported(): boolean { - return typeof window !== 'undefined' && - 'serviceWorker' in navigator && - 'PaymentManager' in window; -} - -/** - * Check if Payment Request API is supported - */ -export function isPaymentRequestSupported(): boolean { - return typeof window !== 'undefined' && 'PaymentRequest' in window; -} \ No newline at end of file diff --git a/packages/es/src/worker/plugin.ts b/packages/es/src/worker/plugin.ts deleted file mode 100644 index 811b63ff9..000000000 --- a/packages/es/src/worker/plugin.ts +++ /dev/null @@ -1,349 +0,0 @@ -/** - * Motor plugin implementation for Payment Gateway and OIDC Authorization - * - * @packageDocumentation - */ - -import type { - MotorPlugin, - MotorServiceWorkerConfig, - // Payment types - PaymentInstrument, - CanMakePaymentRequest, - CanMakePaymentResponse, - PaymentRequestEvent, - PaymentHandlerResponse, - ProcessPaymentRequest, - ProcessPaymentResponse, - ValidatePaymentMethodRequest, - ValidatePaymentMethodResponse, - PaymentStatus, - RefundPaymentRequest, - RefundPaymentResponse, - // OIDC types - OIDCConfiguration, - OIDCAuthorizationRequest, - OIDCAuthorizationResponse, - OIDCTokenRequest, - OIDCTokenResponse, - OIDCUserInfo, - JWKS, - // Service types - HealthCheckResponse, - ServiceInfoResponse, -} from './types'; - -import { MotorClient } from './client'; -import { MotorServiceWorkerManager } from './worker'; -import { PaymentGatewayClient } from './payment'; -import { OIDCClient } from './oidc'; - -/** - * Configuration for the Motor plugin - */ -export interface MotorPluginConfig extends MotorServiceWorkerConfig { - /** Whether to automatically register the service worker */ - auto_register_worker?: boolean; - /** Whether to use service worker when available */ - prefer_service_worker?: boolean; - /** Fallback configuration for direct HTTP calls */ - fallback_url?: string; - /** OIDC client ID */ - oidc_client_id?: string; - /** OIDC redirect URI */ - oidc_redirect_uri?: string; -} - -/** - * Default plugin configuration - */ -const DEFAULT_PLUGIN_CONFIG: Required = { - worker_url: '/motor-worker', - timeout: 30000, - max_retries: 3, - debug: false, - auto_register_worker: true, - prefer_service_worker: true, - fallback_url: 'http://localhost:8080', - oidc_client_id: 'motor-client', - oidc_redirect_uri: window?.location?.origin || 'http://localhost:3000', -}; - -/** - * Motor plugin implementation - */ -export class MotorPluginImpl implements MotorPlugin { - private readonly config: Required; - private client: MotorClient; - private paymentClient: PaymentGatewayClient; - private oidcClient?: OIDCClient; - private workerManager?: MotorServiceWorkerManager; - private isInitialized = false; - - constructor(config: Partial = {}) { - this.config = { ...DEFAULT_PLUGIN_CONFIG, ...config }; - this.client = new MotorClient(this.config); - this.paymentClient = new PaymentGatewayClient(this.config); - - if (this.config.oidc_client_id) { - this.oidcClient = new OIDCClient({ - ...this.config, - client_id: this.config.oidc_client_id, - redirect_uri: this.config.oidc_redirect_uri, - }); - } - - if (this.config.debug) { - console.debug('[MotorPlugin] Initialized with config:', this.config); - } - } - - /** - * Initialize the plugin - */ - async initialize(): Promise { - if (this.isInitialized) { - return; - } - - if (this.config.debug) { - console.debug('[MotorPlugin] Initializing...'); - } - - if (this.config.prefer_service_worker && MotorServiceWorkerManager.isSupported()) { - try { - await this.setupServiceWorker(); - } catch (error) { - if (this.config.debug) { - console.warn('[MotorPlugin] Service worker setup failed, using fallback:', error); - } - this.setupFallback(); - } - } else { - this.setupFallback(); - } - - this.isInitialized = true; - - if (this.config.debug) { - console.debug('[MotorPlugin] Initialization complete'); - } - } - - /** - * Setup service worker - */ - private async setupServiceWorker(): Promise { - this.workerManager = new MotorServiceWorkerManager({ - worker_script: '/motor-worker.js', - scope: '/', - debug: this.config.debug, - }); - - if (this.config.auto_register_worker) { - const registration = await this.workerManager.register(); - if (!registration) { - throw new Error('Failed to register service worker'); - } - } - - // Wait for service worker to be ready - await navigator.serviceWorker.ready; - - this.client.updateConfig({ - worker_url: this.config.worker_url, - }); - } - - /** - * Setup fallback HTTP client - */ - private setupFallback(): void { - this.client.updateConfig({ - worker_url: this.config.fallback_url, - }); - } - - // Payment Gateway Operations - - async getPaymentInstruments(): Promise { - await this.ensureInitialized(); - return this.paymentClient.getPaymentInstruments(); - } - - async canMakePayment(request: CanMakePaymentRequest): Promise { - await this.ensureInitialized(); - return this.paymentClient.canMakePayment(request); - } - - async handlePaymentRequest(event: PaymentRequestEvent): Promise { - await this.ensureInitialized(); - return this.paymentClient.handlePaymentRequest(event); - } - - async processPayment(request: ProcessPaymentRequest): Promise { - await this.ensureInitialized(); - return this.paymentClient.processPayment(request); - } - - async validatePaymentMethod(request: ValidatePaymentMethodRequest): Promise { - await this.ensureInitialized(); - return this.paymentClient.validatePaymentMethod(request); - } - - async getPaymentStatus(paymentId: string): Promise { - await this.ensureInitialized(); - return this.paymentClient.getPaymentStatus(paymentId); - } - - async refundPayment(request: RefundPaymentRequest): Promise { - await this.ensureInitialized(); - return this.paymentClient.refundPayment(request); - } - - // OIDC Operations - - async getOIDCConfiguration(): Promise { - await this.ensureInitialized(); - if (!this.oidcClient) { - throw new Error('OIDC client not configured'); - } - return this.oidcClient.getConfiguration(); - } - - async authorize(request: OIDCAuthorizationRequest): Promise { - await this.ensureInitialized(); - if (!this.oidcClient) { - throw new Error('OIDC client not configured'); - } - const authUrl = await this.oidcClient.buildAuthorizationUrl(request); - window.location.href = authUrl; - return {} as OIDCAuthorizationResponse; - } - - async token(request: OIDCTokenRequest): Promise { - await this.ensureInitialized(); - return this.client.token(request); - } - - async getUserInfo(accessToken: string): Promise { - await this.ensureInitialized(); - if (!this.oidcClient) { - throw new Error('OIDC client not configured'); - } - this.oidcClient.setTokens({ access_token: accessToken }); - return this.oidcClient.getUserInfo(); - } - - async getJWKS(): Promise { - await this.ensureInitialized(); - if (!this.oidcClient) { - throw new Error('OIDC client not configured'); - } - return this.oidcClient.getJWKS(); - } - - // Health & Status - - async healthCheck(): Promise { - await this.ensureInitialized(); - return this.client.healthCheck(); - } - - async getServiceInfo(): Promise { - await this.ensureInitialized(); - return this.client.getServiceInfo(); - } - - // Utility Methods - - /** - * Ensure plugin is initialized - */ - private async ensureInitialized(): Promise { - if (!this.isInitialized) { - await this.initialize(); - } - } - - /** - * Get the HTTP client - */ - getClient(): MotorClient { - return this.client; - } - - /** - * Get the payment client - */ - getPaymentClient(): PaymentGatewayClient { - return this.paymentClient; - } - - /** - * Get the OIDC client - */ - getOIDCClient(): OIDCClient | undefined { - return this.oidcClient; - } - - /** - * Get service worker manager - */ - getServiceWorkerManager(): MotorServiceWorkerManager | undefined { - return this.workerManager; - } - - /** - * Check if plugin is initialized - */ - isReady(): boolean { - return this.isInitialized; - } -} - -// Factory Functions - -/** - * Create a Motor plugin with auto-detection - */ -export async function createMotorPlugin( - config?: Partial -): Promise { - const plugin = new MotorPluginImpl(config); - await plugin.initialize(); - return plugin; -} - -/** - * Create a Motor plugin for browser environment - */ -export async function createMotorPluginForBrowser( - workerUrl = '/motor-worker', - config?: Partial -): Promise { - const plugin = new MotorPluginImpl({ - ...config, - worker_url: workerUrl, - prefer_service_worker: true, - }); - await plugin.initialize(); - return plugin; -} - -/** - * Create a Motor plugin for Node.js environment - */ -export async function createMotorPluginForNode( - serverUrl = 'http://localhost:8080', - config?: Partial -): Promise { - const plugin = new MotorPluginImpl({ - ...config, - worker_url: serverUrl, - prefer_service_worker: false, - auto_register_worker: false, - }); - await plugin.initialize(); - return plugin; -} \ No newline at end of file diff --git a/packages/es/src/worker/register.ts b/packages/es/src/worker/register.ts deleted file mode 100644 index 011592954..000000000 --- a/packages/es/src/worker/register.ts +++ /dev/null @@ -1,446 +0,0 @@ -/** - * Service Worker Registration Helper for Motor WASM - * Provides utilities for registering and managing the Motor service worker in web applications. - */ - -import type { MotorServiceWorkerConfig } from './types'; - -export interface RegistrationOptions { - /** URL to the service worker script */ - workerUrl?: string; - /** Service worker scope */ - scope?: string; - /** Whether to skip waiting during update */ - skipWaiting?: boolean; - /** Whether to enable debug logging */ - debug?: boolean; - /** Callback when registration succeeds */ - onSuccess?: (registration: ServiceWorkerRegistration) => void; - /** Callback when registration fails */ - onError?: (error: Error) => void; - /** Callback when an update is found */ - onUpdateFound?: (registration: ServiceWorkerRegistration) => void; - /** Callback when the worker is ready */ - onReady?: (registration: ServiceWorkerRegistration) => void; -} - -const DEFAULT_OPTIONS: Required = { - workerUrl: '/motor-worker.js', - scope: '/', - skipWaiting: true, - debug: false, - onSuccess: () => {}, - onError: () => {}, - onUpdateFound: () => {}, - onReady: () => {}, -}; - -/** - * Registers the Motor service worker with comprehensive lifecycle management. - * @param options Registration options - * @returns Promise resolving to the service worker registration - */ -export async function registerMotorServiceWorker( - options: RegistrationOptions = {} -): Promise { - const config = { ...DEFAULT_OPTIONS, ...options }; - - // Check browser support - if (!('serviceWorker' in navigator)) { - const error = new Error('Service workers are not supported in this browser'); - config.onError(error); - if (config.debug) { - console.error('[Motor Register]', error.message); - } - return null; - } - - // Check for secure context (HTTPS or localhost) - if (!window.isSecureContext) { - const error = new Error('Service workers require a secure context (HTTPS or localhost)'); - config.onError(error); - if (config.debug) { - console.error('[Motor Register]', error.message); - } - return null; - } - - try { - if (config.debug) { - console.log('[Motor Register] Registering service worker:', config.workerUrl); - } - - // Register the service worker - const registration = await navigator.serviceWorker.register(config.workerUrl, { - scope: config.scope, - type: 'classic', - updateViaCache: 'none', // Always check for updates - }); - - if (config.debug) { - console.log('[Motor Register] Service worker registered successfully'); - } - - // Set up event listeners - setupEventListeners(registration, config); - - // Handle immediate activation for first install - if (registration.installing) { - await waitForActivation(registration, config); - } - - // Check for updates - await registration.update(); - - // Call success callback - config.onSuccess(registration); - - // Wait for the service worker to be ready - const readyRegistration = await navigator.serviceWorker.ready; - config.onReady(readyRegistration); - - return registration; - } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)); - config.onError(err); - if (config.debug) { - console.error('[Motor Register] Registration failed:', err); - } - return null; - } -} - -/** - * Sets up event listeners for service worker lifecycle events. - */ -function setupEventListeners( - registration: ServiceWorkerRegistration, - config: Required -): void { - // Listen for update found - registration.addEventListener('updatefound', () => { - if (config.debug) { - console.log('[Motor Register] New service worker update found'); - } - - const newWorker = registration.installing; - if (newWorker) { - newWorker.addEventListener('statechange', () => { - if (config.debug) { - console.log('[Motor Register] Service worker state changed:', newWorker.state); - } - - if (newWorker.state === 'installed' && navigator.serviceWorker.controller) { - // New update available - config.onUpdateFound(registration); - - if (config.skipWaiting) { - // Tell the new worker to skip waiting - newWorker.postMessage({ type: 'SKIP_WAITING' }); - } - } - }); - } - }); - - // Listen for controller change (new worker activated) - navigator.serviceWorker.addEventListener('controllerchange', () => { - if (config.debug) { - console.log('[Motor Register] Controller changed, reloading may be needed'); - } - }); - - // Listen for messages from the service worker - navigator.serviceWorker.addEventListener('message', (event) => { - if (config.debug) { - console.log('[Motor Register] Message from service worker:', event.data); - } - }); -} - -/** - * Waits for the service worker to activate. - */ -async function waitForActivation( - registration: ServiceWorkerRegistration, - config: Required -): Promise { - return new Promise((resolve) => { - const worker = registration.installing || registration.waiting; - - if (!worker) { - resolve(); - return; - } - - if (worker.state === 'activated') { - resolve(); - return; - } - - worker.addEventListener('statechange', function onStateChange() { - if (worker.state === 'activated') { - worker.removeEventListener('statechange', onStateChange); - if (config.debug) { - console.log('[Motor Register] Service worker activated'); - } - resolve(); - } - }); - }); -} - -/** - * Unregisters all Motor service workers. - * @returns Promise resolving to whether unregistration was successful - */ -export async function unregisterMotorServiceWorker(): Promise { - if (!('serviceWorker' in navigator)) { - return false; - } - - try { - const registrations = await navigator.serviceWorker.getRegistrations(); - - const unregistrations = registrations - .filter(reg => reg.active?.scriptURL.includes('motor')) - .map(reg => reg.unregister()); - - const results = await Promise.all(unregistrations); - return results.some(result => result === true); - } catch (error) { - console.error('[Motor Register] Failed to unregister:', error); - return false; - } -} - -/** - * Checks if a Motor service worker is currently registered and active. - * @returns Promise resolving to registration status - */ -export async function getMotorServiceWorkerStatus(): Promise<{ - registered: boolean; - active: boolean; - waiting: boolean; - installing: boolean; - registration?: ServiceWorkerRegistration; -}> { - if (!('serviceWorker' in navigator)) { - return { - registered: false, - active: false, - waiting: false, - installing: false, - }; - } - - try { - const registrations = await navigator.serviceWorker.getRegistrations(); - const motorRegistration = registrations.find(reg => - reg.active?.scriptURL.includes('motor') || - reg.waiting?.scriptURL.includes('motor') || - reg.installing?.scriptURL.includes('motor') - ); - - if (!motorRegistration) { - return { - registered: false, - active: false, - waiting: false, - installing: false, - }; - } - - return { - registered: true, - active: !!motorRegistration.active, - waiting: !!motorRegistration.waiting, - installing: !!motorRegistration.installing, - registration: motorRegistration, - }; - } catch (error) { - console.error('[Motor Register] Failed to get status:', error); - return { - registered: false, - active: false, - waiting: false, - installing: false, - }; - } -} - -/** - * Updates the Motor service worker if an update is available. - * @returns Promise resolving to whether an update was performed - */ -export async function updateMotorServiceWorker(): Promise { - const status = await getMotorServiceWorkerStatus(); - - if (!status.registered || !status.registration) { - return false; - } - - try { - await status.registration.update(); - - // Check if there's a waiting worker - if (status.registration.waiting) { - // Tell the waiting worker to skip waiting - status.registration.waiting.postMessage({ type: 'SKIP_WAITING' }); - return true; - } - - return false; - } catch (error) { - console.error('[Motor Register] Failed to update:', error); - return false; - } -} - -/** - * React hook for Motor service worker registration (if using React). - * This is a conditional export that only works when React is available. - * @param options Registration options - * @returns Service worker registration state - */ -export function useMotorServiceWorker(options: RegistrationOptions = {}) { - if (typeof window === 'undefined') { - return { - registration: null, - isRegistered: false, - isActive: false, - error: null, - }; - } - - // Check if React is available - let useState: any; - let useEffect: any; - - try { - // Try to get React from the global scope if it exists - const globalReact = (globalThis as any).React || (window as any).React; - useState = globalReact?.useState; - useEffect = globalReact?.useEffect; - } catch { - // React not available - } - - // If React hooks aren't available, return a static state - if (!useState || !useEffect) { - const staticState = { - registration: null, - isRegistered: false, - isActive: false, - error: null, - }; - - // Still attempt registration but without React state management - registerMotorServiceWorker(options).catch(() => {}); - - return staticState; - } - - const [state, setState] = useState({ - registration: null as ServiceWorkerRegistration | null, - isRegistered: false, - isActive: false, - error: null as Error | null, - }); - - useEffect(() => { - let mounted = true; - - const register = async () => { - try { - const registration = await registerMotorServiceWorker({ - ...options, - onSuccess: (reg) => { - if (mounted) { - setState({ - registration: reg, - isRegistered: true, - isActive: !!reg.active, - error: null, - }); - } - options.onSuccess?.(reg); - }, - onError: (err) => { - if (mounted) { - setState((prev: any) => ({ ...prev, error: err })); - } - options.onError?.(err); - }, - }); - - if (mounted && registration) { - setState({ - registration, - isRegistered: true, - isActive: !!registration.active, - error: null, - }); - } - } catch (error) { - if (mounted) { - const err = error instanceof Error ? error : new Error(String(error)); - setState((prev: any) => ({ ...prev, error: err })); - } - } - }; - - register(); - - return () => { - mounted = false; - }; - }, []); - - return state; -} - -/** - * Utility to create a Motor service worker update prompt for the user. - * @param options Prompt options - * @returns Update prompt handler - */ -export function createUpdatePrompt(options: { - message?: string; - confirmText?: string; - cancelText?: string; - onUpdate?: () => void; - onCancel?: () => void; -} = {}) { - const { - message = 'A new version of Motor is available. Would you like to update?', - confirmText = 'Update', - cancelText = 'Later', - onUpdate = () => window.location.reload(), - onCancel = () => {}, - } = options; - - return async (registration: ServiceWorkerRegistration) => { - if (!registration.waiting) { - return; - } - - // You can implement your own UI here - // This is a simple confirm dialog example - const shouldUpdate = window.confirm(message); - - if (shouldUpdate) { - registration.waiting.postMessage({ type: 'SKIP_WAITING' }); - - // Listen for the controller change - navigator.serviceWorker.addEventListener('controllerchange', () => { - onUpdate(); - }); - } else { - onCancel(); - } - }; -} - -// Export a default registration function for easy use -export default registerMotorServiceWorker; \ No newline at end of file diff --git a/packages/es/src/worker/types.ts b/packages/es/src/worker/types.ts deleted file mode 100644 index f8f20933e..000000000 --- a/packages/es/src/worker/types.ts +++ /dev/null @@ -1,783 +0,0 @@ -/** - * TypeScript type definitions for Motor Payment Gateway & OIDC Authorization - * - * @packageDocumentation - */ - -// ╭─────────────────────────────────────────────────────────╮ -// │ Payment Gateway Types │ -// ╰─────────────────────────────────────────────────────────╯ - -/** - * Payment instrument configuration - */ -export interface PaymentInstrument { - /** Unique identifier for the instrument */ - id: string; - /** Display name for the instrument */ - name: string; - /** Payment method type (e.g., "card", "bank", "crypto") */ - type: string; - /** Whether this instrument is enabled */ - enabled: boolean; - /** Supported currencies */ - supportedCurrencies?: string[]; - /** Icon URL for the instrument */ - iconUrl?: string; -} - -/** - * Payment method details - */ -export interface PaymentMethod { - /** Payment method identifier */ - supportedMethods: string; - /** Method-specific data */ - data?: Record; -} - -/** - * Payment details for a transaction - */ -export interface PaymentDetails { - /** Unique transaction ID */ - id: string; - /** Total amount */ - total: { - label: string; - amount: { - currency: string; - value: string; - }; - }; - /** Display items */ - displayItems?: Array<{ - label: string; - amount: { - currency: string; - value: string; - }; - }>; - /** Modifiers for specific payment methods */ - modifiers?: Array<{ - supportedMethods: string; - total?: { - label: string; - amount: { - currency: string; - value: string; - }; - }; - additionalDisplayItems?: Array<{ - label: string; - amount: { - currency: string; - value: string; - }; - }>; - data?: Record; - }>; -} - -/** - * Request to check if payment can be made - */ -export interface CanMakePaymentRequest { - /** Origin of the payment request */ - origin: string; - /** Payment methods to check */ - methodData: PaymentMethod[]; - /** Payment modifiers */ - modifiers?: Array<{ - supportedMethods: string; - data?: Record; - }>; -} - -/** - * Response for can make payment check - */ -export interface CanMakePaymentResponse { - /** Whether payment can be made */ - canMakePayment: boolean; -} - -/** - * Payment request event data (W3C Payment Handler API) - */ -export interface PaymentRequestEvent { - /** Payment request ID */ - paymentRequestId: string; - /** Payment request origin */ - paymentRequestOrigin: string; - /** Top-level origin */ - topOrigin: string; - /** Payment method data */ - methodData: PaymentMethod[]; - /** Total amount */ - total: { - currency: string; - value: string; - }; - /** Additional payment details */ - modifiers?: Array<{ - supportedMethods: string; - total?: { - currency: string; - value: string; - }; - data?: Record; - }>; - /** Instrument key for the payment */ - instrumentKey?: string; -} - -/** - * Payment response from handler - */ -export interface PaymentHandlerResponse { - /** Payment method name */ - methodName: string; - /** Payment details */ - details: Record; -} - -/** - * Request to process a payment - */ -export interface ProcessPaymentRequest { - /** Payment method */ - method: string; - /** Amount in smallest currency unit */ - amount: number; - /** Currency code (e.g., "USD", "EUR") */ - currency: string; - /** Payment description */ - description?: string; - /** Customer information */ - customer?: { - email?: string; - name?: string; - id?: string; - }; - /** Additional metadata */ - metadata?: Record; - /** Idempotency key for duplicate prevention */ - idempotencyKey?: string; -} - -/** - * Response from payment processing - */ -export interface ProcessPaymentResponse { - /** Payment ID */ - paymentId: string; - /** Payment status */ - status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled'; - /** Amount processed */ - amount: number; - /** Currency used */ - currency: string; - /** Transaction reference */ - transactionRef?: string; - /** Processing timestamp */ - processedAt: number; - /** Error message if failed */ - error?: string; - /** Next action required (e.g., 3D Secure) */ - nextAction?: { - type: string; - redirectUrl?: string; - data?: Record; - }; -} - -/** - * Request to validate payment method - */ -export interface ValidatePaymentMethodRequest { - /** Payment method type */ - method: string; - /** Method-specific data to validate */ - data: Record; -} - -/** - * Response from payment method validation - */ -export interface ValidatePaymentMethodResponse { - /** Whether the payment method is valid */ - valid: boolean; - /** Validation errors if any */ - errors?: string[]; - /** Sanitized/normalized data */ - normalizedData?: Record; -} - -/** - * Payment status information - */ -export interface PaymentStatus { - /** Payment ID */ - paymentId: string; - /** Current status */ - status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled' | 'refunded'; - /** Amount */ - amount: number; - /** Currency */ - currency: string; - /** Creation timestamp */ - createdAt: number; - /** Last update timestamp */ - updatedAt: number; - /** Transaction details */ - transaction?: { - id: string; - reference: string; - method: string; - }; - /** Refund information if applicable */ - refund?: { - amount: number; - reason?: string; - refundedAt: number; - }; -} - -/** - * Request to refund a payment - */ -export interface RefundPaymentRequest { - /** Payment ID to refund */ - paymentId: string; - /** Amount to refund (partial refund if less than original) */ - amount?: number; - /** Refund reason */ - reason?: string; - /** Additional metadata */ - metadata?: Record; -} - -/** - * Response from payment refund - */ -export interface RefundPaymentResponse { - /** Refund ID */ - refundId: string; - /** Payment ID */ - paymentId: string; - /** Refund status */ - status: 'pending' | 'processing' | 'completed' | 'failed'; - /** Amount refunded */ - amount: number; - /** Currency */ - currency: string; - /** Refund timestamp */ - refundedAt: number; - /** Error message if failed */ - error?: string; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ OIDC Types │ -// ╰─────────────────────────────────────────────────────────╯ - -/** - * OIDC Discovery configuration - */ -export interface OIDCConfiguration { - /** Issuer identifier */ - issuer: string; - /** Authorization endpoint */ - authorization_endpoint: string; - /** Token endpoint */ - token_endpoint: string; - /** UserInfo endpoint */ - userinfo_endpoint: string; - /** JWKS URI */ - jwks_uri: string; - /** Registration endpoint (optional) */ - registration_endpoint?: string; - /** Supported scopes */ - scopes_supported: string[]; - /** Supported response types */ - response_types_supported: string[]; - /** Supported response modes */ - response_modes_supported?: string[]; - /** Supported grant types */ - grant_types_supported?: string[]; - /** Supported ACR values */ - acr_values_supported?: string[]; - /** Subject types supported */ - subject_types_supported: string[]; - /** ID token signing algorithms */ - id_token_signing_alg_values_supported: string[]; - /** ID token encryption algorithms */ - id_token_encryption_alg_values_supported?: string[]; - /** ID token encryption methods */ - id_token_encryption_enc_values_supported?: string[]; - /** UserInfo signing algorithms */ - userinfo_signing_alg_values_supported?: string[]; - /** UserInfo encryption algorithms */ - userinfo_encryption_alg_values_supported?: string[]; - /** UserInfo encryption methods */ - userinfo_encryption_enc_values_supported?: string[]; - /** Request object signing algorithms */ - request_object_signing_alg_values_supported?: string[]; - /** Request object encryption algorithms */ - request_object_encryption_alg_values_supported?: string[]; - /** Request object encryption methods */ - request_object_encryption_enc_values_supported?: string[]; - /** Token endpoint auth methods */ - token_endpoint_auth_methods_supported?: string[]; - /** Token endpoint auth signing algorithms */ - token_endpoint_auth_signing_alg_values_supported?: string[]; - /** Display values supported */ - display_values_supported?: string[]; - /** Claim types supported */ - claim_types_supported?: string[]; - /** Claims supported */ - claims_supported?: string[]; - /** Service documentation */ - service_documentation?: string; - /** Claims locales supported */ - claims_locales_supported?: string[]; - /** UI locales supported */ - ui_locales_supported?: string[]; - /** Claims parameter supported */ - claims_parameter_supported?: boolean; - /** Request parameter supported */ - request_parameter_supported?: boolean; - /** Request URI parameter supported */ - request_uri_parameter_supported?: boolean; - /** Require request URI registration */ - require_request_uri_registration?: boolean; - /** OP policy URI */ - op_policy_uri?: string; - /** OP terms of service URI */ - op_tos_uri?: string; - /** PKCE code challenge methods supported */ - code_challenge_methods_supported?: string[]; -} - -/** - * OIDC Authorization request - */ -export interface OIDCAuthorizationRequest { - /** Client identifier */ - client_id: string; - /** Redirect URI */ - redirect_uri: string; - /** Response type (e.g., "code", "token") */ - response_type: string; - /** Requested scopes */ - scope: string; - /** State parameter for CSRF protection */ - state?: string; - /** Nonce for replay protection */ - nonce?: string; - /** Response mode (e.g., "query", "fragment") */ - response_mode?: string; - /** Display mode (e.g., "page", "popup") */ - display?: string; - /** Authentication prompt (e.g., "none", "login") */ - prompt?: string; - /** Maximum authentication age */ - max_age?: number; - /** UI locales */ - ui_locales?: string; - /** ID token hint */ - id_token_hint?: string; - /** Login hint */ - login_hint?: string; - /** ACR values */ - acr_values?: string; - /** PKCE code challenge */ - code_challenge?: string; - /** PKCE code challenge method */ - code_challenge_method?: string; -} - -/** - * OIDC Authorization response - */ -export interface OIDCAuthorizationResponse { - /** Authorization code */ - code?: string; - /** Access token (for implicit flow) */ - access_token?: string; - /** Token type */ - token_type?: string; - /** ID token */ - id_token?: string; - /** State parameter */ - state?: string; - /** Expiration time */ - expires_in?: number; - /** Authorized scopes */ - scope?: string; -} - -/** - * OIDC Token request - */ -export interface OIDCTokenRequest { - /** Grant type (e.g., "authorization_code", "refresh_token") */ - grant_type: string; - /** Authorization code (for authorization_code grant) */ - code?: string; - /** Redirect URI (for authorization_code grant) */ - redirect_uri?: string; - /** Client ID */ - client_id: string; - /** Client secret */ - client_secret?: string; - /** Refresh token (for refresh_token grant) */ - refresh_token?: string; - /** Requested scopes (for refresh_token grant) */ - scope?: string; - /** PKCE code verifier */ - code_verifier?: string; -} - -/** - * OIDC Token response - */ -export interface OIDCTokenResponse { - /** Access token */ - access_token: string; - /** Token type (usually "Bearer") */ - token_type: string; - /** Expiration time in seconds */ - expires_in: number; - /** Refresh token */ - refresh_token?: string; - /** ID token */ - id_token?: string; - /** Authorized scopes */ - scope?: string; - /** Error code */ - error?: string; - /** Error description */ - error_description?: string; -} - -/** - * OIDC UserInfo response - */ -export interface OIDCUserInfo { - /** Subject identifier */ - sub: string; - /** Full name */ - name?: string; - /** Given name */ - given_name?: string; - /** Family name */ - family_name?: string; - /** Middle name */ - middle_name?: string; - /** Nickname */ - nickname?: string; - /** Preferred username */ - preferred_username?: string; - /** Profile URL */ - profile?: string; - /** Profile picture URL */ - picture?: string; - /** Website URL */ - website?: string; - /** Email address */ - email?: string; - /** Email verified flag */ - email_verified?: boolean; - /** Gender */ - gender?: string; - /** Birth date */ - birthdate?: string; - /** Time zone */ - zoneinfo?: string; - /** Locale */ - locale?: string; - /** Phone number */ - phone_number?: string; - /** Phone number verified flag */ - phone_number_verified?: boolean; - /** Address */ - address?: { - formatted?: string; - street_address?: string; - locality?: string; - region?: string; - postal_code?: string; - country?: string; - }; - /** Last updated timestamp */ - updated_at?: number; - /** Additional custom claims */ - [key: string]: unknown; -} - -/** - * JSON Web Key Set - */ -export interface JWKS { - /** Array of JSON Web Keys */ - keys: JWK[]; -} - -/** - * JSON Web Key - */ -export interface JWK { - /** Key type (e.g., "RSA", "EC") */ - kty: string; - /** Key use (e.g., "sig", "enc") */ - use?: string; - /** Key operations */ - key_ops?: string[]; - /** Algorithm */ - alg?: string; - /** Key ID */ - kid?: string; - /** X.509 URL */ - x5u?: string; - /** X.509 certificate chain */ - x5c?: string[]; - /** X.509 certificate SHA-1 thumbprint */ - x5t?: string; - /** X.509 certificate SHA-256 thumbprint */ - 'x5t#S256'?: string; - - // RSA specific - /** RSA modulus */ - n?: string; - /** RSA exponent */ - e?: string; - - // EC specific - /** Elliptic curve */ - crv?: string; - /** EC x coordinate */ - x?: string; - /** EC y coordinate */ - y?: string; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Service Worker Types │ -// ╰─────────────────────────────────────────────────────────╯ - -/** - * Configuration for the Motor service worker - */ -export interface MotorServiceWorkerConfig { - /** URL where the Motor WASM service worker is available */ - worker_url?: string; - /** Timeout for HTTP requests in milliseconds */ - timeout?: number; - /** Maximum number of retry attempts */ - max_retries?: number; - /** Whether to enable debug logging */ - debug?: boolean; -} - -/** - * Health check response from the Motor service worker - */ -export interface HealthCheckResponse { - /** Service status */ - status: string; - /** Service name */ - service: string; - /** Service version */ - version?: string; - /** Current timestamp */ - time?: number; - /** Additional health details */ - details?: { - payment_gateway?: boolean; - oidc_provider?: boolean; - memory_usage?: number; - uptime?: number; - }; -} - -/** - * Service information response - */ -export interface ServiceInfoResponse { - /** Service name */ - service: string; - /** Service version */ - version: string; - /** Service description */ - description: string; - /** Available endpoints by category */ - endpoints: { - payment: string[]; - oidc: string[]; - health: string[]; - }; - /** Service capabilities */ - capabilities?: { - payment_methods?: string[]; - oidc_flows?: string[]; - supported_currencies?: string[]; - }; -} - -/** - * Generic error response structure - */ -export interface ErrorResponse { - /** Error message */ - error: string; - /** Error code */ - code?: string; - /** Additional error details */ - details?: Record; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Plugin Interface │ -// ╰─────────────────────────────────────────────────────────╯ - -/** - * Main interface for the Motor plugin providing Payment Gateway and OIDC services - */ -export interface MotorPlugin { - // Payment Gateway Operations - - /** - * Get available payment instruments - * @returns Promise resolving to payment instruments - */ - getPaymentInstruments(): Promise; - - /** - * Check if payment can be made - * @param request Can make payment request - * @returns Promise resolving to whether payment can be made - */ - canMakePayment(request: CanMakePaymentRequest): Promise; - - /** - * Handle payment request event (W3C Payment Handler API) - * @param event Payment request event - * @returns Promise resolving to payment response - */ - handlePaymentRequest(event: PaymentRequestEvent): Promise; - - /** - * Process a payment transaction - * @param request Payment processing request - * @returns Promise resolving to payment response - */ - processPayment(request: ProcessPaymentRequest): Promise; - - /** - * Validate a payment method - * @param request Payment method validation request - * @returns Promise resolving to validation response - */ - validatePaymentMethod(request: ValidatePaymentMethodRequest): Promise; - - /** - * Get payment status - * @param paymentId Payment identifier - * @returns Promise resolving to payment status - */ - getPaymentStatus(paymentId: string): Promise; - - /** - * Process a refund - * @param request Refund request - * @returns Promise resolving to refund response - */ - refundPayment(request: RefundPaymentRequest): Promise; - - // OIDC Operations - - /** - * Get OIDC configuration - * @returns Promise resolving to OIDC configuration - */ - getOIDCConfiguration(): Promise; - - /** - * Handle authorization request - * @param request Authorization request - * @returns Promise resolving to authorization response - */ - authorize(request: OIDCAuthorizationRequest): Promise; - - /** - * Exchange authorization code for tokens - * @param request Token request - * @returns Promise resolving to token response - */ - token(request: OIDCTokenRequest): Promise; - - /** - * Get user information - * @param accessToken Access token - * @returns Promise resolving to user info - */ - getUserInfo(accessToken: string): Promise; - - /** - * Get JSON Web Key Set - * @returns Promise resolving to JWKS - */ - getJWKS(): Promise; - - // Health & Status - - /** - * Check service health - * @returns Promise resolving to health status - */ - healthCheck(): Promise; - - /** - * Get service information - * @returns Promise resolving to service info - */ - getServiceInfo(): Promise; -} - -// ╭─────────────────────────────────────────────────────────╮ -// │ Utility Types │ -// ╰─────────────────────────────────────────────────────────╯ - -/** - * Environment detection results - */ -export interface EnvironmentInfo { - /** Whether running in a browser environment */ - is_browser: boolean; - /** Whether running in Node.js */ - is_node: boolean; - /** Whether service workers are supported */ - supports_service_worker: boolean; - /** Whether WebAssembly is supported */ - supports_wasm: boolean; - /** Whether Payment Handler API is supported */ - supports_payment_handler?: boolean; -} - -/** - * Service worker registration status - */ -export interface ServiceWorkerStatus { - /** Whether a service worker is registered */ - registered: boolean; - /** Service worker state */ - state?: string; - /** Service worker URL */ - url?: string; - /** Registration timestamp */ - registered_at?: number; - /** Whether service worker is ready */ - ready?: boolean; -} \ No newline at end of file diff --git a/packages/es/src/worker/worker.ts b/packages/es/src/worker/worker.ts deleted file mode 100644 index 82fa863c7..000000000 --- a/packages/es/src/worker/worker.ts +++ /dev/null @@ -1,394 +0,0 @@ -/** - * Service worker lifecycle management for Motor WASM - */ - -import type { ServiceWorkerStatus, EnvironmentInfo } from './types'; - -/** - * Detects the current environment capabilities - */ -export function detectEnvironment(): EnvironmentInfo { - const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; - const isNode = typeof process !== 'undefined' && process.versions && process.versions.node; - const supportsServiceWorker = isBrowser && 'serviceWorker' in navigator; - const supportsWasm = typeof WebAssembly !== 'undefined'; - - return { - is_browser: isBrowser, - is_node: !!isNode, - supports_service_worker: supportsServiceWorker, - supports_wasm: supportsWasm, - }; -} - -/** - * Registers the Motor service worker - */ -export async function registerMotorServiceWorker( - workerUrl: string, - options?: RegistrationOptions -): Promise { - const env = detectEnvironment(); - - if (!env.supports_service_worker) { - throw new Error('Service workers are not supported in this environment'); - } - - if (!env.supports_wasm) { - throw new Error('WebAssembly is not supported in this environment'); - } - - try { - // Register the service worker - const registration = await navigator.serviceWorker.register(workerUrl, { - scope: options?.scope || '/', - type: options?.type || 'classic', - updateViaCache: options?.updateViaCache || 'imports', - }); - - // Wait for the service worker to be ready - await navigator.serviceWorker.ready; - - console.log('Motor service worker registered successfully'); - return registration; - } catch (error) { - console.error('Failed to register Motor service worker:', error); - throw error; - } -} - -/** - * Unregisters the Motor service worker - */ -export async function unregisterMotorServiceWorker(): Promise { - const env = detectEnvironment(); - - if (!env.supports_service_worker) { - return false; - } - - try { - const registrations = await navigator.serviceWorker.getRegistrations(); - - for (const registration of registrations) { - // Check if this is the Motor service worker - if (registration.active?.scriptURL.includes('motr')) { - const success = await registration.unregister(); - if (success) { - console.log('Motor service worker unregistered successfully'); - } - return success; - } - } - - return false; - } catch (error) { - console.error('Failed to unregister Motor service worker:', error); - return false; - } -} - -/** - * Gets the current Motor service worker status - */ -export async function getMotorServiceWorkerStatus(): Promise { - const env = detectEnvironment(); - - if (!env.supports_service_worker) { - return { registered: false }; - } - - try { - const registrations = await navigator.serviceWorker.getRegistrations(); - - for (const registration of registrations) { - // Check if this is the Motor service worker - if (registration.active?.scriptURL.includes('motr')) { - return { - registered: true, - state: registration.active.state, - url: registration.active.scriptURL, - registered_at: Date.now(), - }; - } - } - - return { registered: false }; - } catch (error) { - console.error('Failed to get Motor service worker status:', error); - return { registered: false }; - } -} - -/** - * Configuration for MotorServiceWorkerManager - */ -export interface MotorServiceWorkerManagerConfig { - worker_script: string; - scope?: string; - debug?: boolean; - type?: WorkerType; - updateViaCache?: ServiceWorkerUpdateViaCache; -} - -/** - * Service Worker Manager class for advanced lifecycle management - */ -export class MotorServiceWorkerManager { - private registration?: ServiceWorkerRegistration; - private config: MotorServiceWorkerManagerConfig; - private updateCheckInterval?: number; - private debug: boolean; - - constructor(config: MotorServiceWorkerManagerConfig) { - this.config = config; - this.debug = config.debug || false; - } - - /** - * Checks if service workers are supported in the current environment - */ - static isSupported(): boolean { - const env = detectEnvironment(); - return env.supports_service_worker; - } - - /** - * Detects the current environment capabilities - */ - static detectEnvironment(): EnvironmentInfo { - return detectEnvironment(); - } - - /** - * Gets browser compatibility information - */ - static getBrowserCompatibility(): { - compatible: boolean; - issues: string[]; - recommendations: string[]; - } { - const env = detectEnvironment(); - const issues: string[] = []; - const recommendations: string[] = []; - - if (!env.is_browser && !env.is_node) { - issues.push('Unknown environment'); - recommendations.push('Use a modern browser or Node.js'); - } - - if (env.is_browser && !env.supports_service_worker) { - issues.push('Service workers not supported'); - recommendations.push('Use a modern browser with service worker support'); - } - - if (!env.supports_wasm) { - issues.push('WebAssembly not supported'); - recommendations.push('Update your browser or Node.js version'); - } - - return { - compatible: issues.length === 0, - issues, - recommendations, - }; - } - - /** - * Registers and initializes the service worker - */ - async register(): Promise { - if (this.registration) { - return this.registration; - } - - const options: RegistrationOptions = { - scope: this.config.scope, - type: this.config.type, - updateViaCache: this.config.updateViaCache, - }; - - this.registration = await registerMotorServiceWorker(this.config.worker_script, options); - - // Set up update checking - this.startUpdateChecking(); - - // Listen for service worker events - this.attachEventListeners(); - - return this.registration; - } - - /** - * Unregisters the service worker - */ - async unregister(): Promise { - this.stopUpdateChecking(); - - if (this.registration) { - const success = await this.registration.unregister(); - if (success) { - this.registration = undefined; - } - return success; - } - - return await unregisterMotorServiceWorker(); - } - - /** - * Checks for service worker updates - */ - async checkForUpdates(): Promise { - if (!this.registration) { - return; - } - - try { - await this.registration.update(); - if (this.debug) { - console.log('Checked for Motor service worker updates'); - } - } catch (error) { - console.error('Failed to check for updates:', error); - } - } - - /** - * Gets the current status - */ - async getStatus(): Promise { - if (!this.registration) { - return { registered: false }; - } - - const worker = this.registration.active || this.registration.waiting || this.registration.installing; - - if (!worker) { - return { registered: false }; - } - - return { - registered: true, - state: worker.state, - url: worker.scriptURL, - registered_at: Date.now(), - }; - } - - /** - * Sends a message to the service worker - */ - async sendMessage(message: any): Promise { - if (!this.registration?.active) { - throw new Error('Service worker is not active'); - } - - this.registration.active.postMessage(message); - } - - /** - * Starts periodic update checking - */ - private startUpdateChecking(intervalMs: number = 3600000): void { - if (this.updateCheckInterval) { - return; - } - - this.updateCheckInterval = window.setInterval(() => { - this.checkForUpdates(); - }, intervalMs); - } - - /** - * Stops periodic update checking - */ - private stopUpdateChecking(): void { - if (this.updateCheckInterval) { - clearInterval(this.updateCheckInterval); - this.updateCheckInterval = undefined; - } - } - - /** - * Attaches event listeners for service worker events - */ - private attachEventListeners(): void { - if (!this.registration) { - return; - } - - this.registration.addEventListener('updatefound', () => { - if (this.debug) { - console.log('Motor service worker update found'); - } - - const newWorker = this.registration!.installing; - if (newWorker) { - newWorker.addEventListener('statechange', () => { - if (this.debug) { - console.log('Motor service worker state changed:', newWorker.state); - } - - if (newWorker.state === 'activated') { - console.log('Motor service worker updated and activated'); - } - }); - } - }); - - // Listen for messages from the service worker - navigator.serviceWorker.addEventListener('message', (event) => { - if (this.debug) { - console.log('Message from Motor service worker:', event.data); - } - }); - } -} - -/** - * Default service worker manager instance - */ -let defaultManager: MotorServiceWorkerManager | undefined; - -/** - * Gets or creates the default service worker manager - */ -export function getDefaultServiceWorkerManager( - config?: MotorServiceWorkerManagerConfig -): MotorServiceWorkerManager { - if (!defaultManager && config) { - defaultManager = new MotorServiceWorkerManager(config); - } - - if (!defaultManager) { - throw new Error('Motor service worker manager not initialized'); - } - - return defaultManager; -} - -/** - * Waits for the service worker to be ready - */ -export async function waitForServiceWorker(timeoutMs: number = 30000): Promise { - const env = detectEnvironment(); - - if (!env.supports_service_worker) { - throw new Error('Service workers are not supported'); - } - - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - reject(new Error('Service worker registration timed out')); - }, timeoutMs); - - navigator.serviceWorker.ready.then((registration) => { - clearTimeout(timeout); - resolve(registration); - }).catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); -} \ No newline at end of file diff --git a/packages/es/test/plugins.test.ts b/packages/es/test/plugins.test.ts deleted file mode 100644 index a4280afcf..000000000 --- a/packages/es/test/plugins.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, it, expect } from 'vitest'; -// TODO: Fix import path - should be '../src/plugin' not '../src/plugins' -// import * as plugins from '../src/plugins'; - -describe.skip('Plugins Module', () => { - it('should export motor namespace', () => { - expect(plugins.motor).toBeDefined(); - }); - - it('should export vault namespace', () => { - expect(plugins.vault).toBeDefined(); - }); - - it('should export VaultClient', () => { - expect(plugins.VaultClient).toBeDefined(); - }); - - it('should export createVaultClient', () => { - expect(plugins.createVaultClient).toBeDefined(); - expect(typeof plugins.createVaultClient).toBe('function'); - }); - - it('should export MotorPluginImpl', () => { - expect(plugins.MotorPluginImpl).toBeDefined(); - }); - - it('should export createMotorPlugin', () => { - expect(plugins.createMotorPlugin).toBeDefined(); - expect(typeof plugins.createMotorPlugin).toBe('function'); - }); - - it('should export VaultError and VaultErrorCode', () => { - expect(plugins.VaultError).toBeDefined(); - expect(plugins.VaultErrorCode).toBeDefined(); - }); - - it('should export VaultStorageManager', () => { - expect(plugins.vault.VaultStorageManager).toBeDefined(); - expect(typeof plugins.vault.VaultStorageManager).toBe('function'); - }); - - it('should export storage-related types', () => { - // These are TypeScript types, so we check if they're re-exported properly - // by checking that the module has the expected structure - expect(plugins.vault).toHaveProperty('AccountVaultDatabase'); - expect(plugins.vault).toHaveProperty('defaultStorageManager'); - }); -}); - -describe.skip('Plugin Imports', () => { - it('should be able to import from @sonr.io/es/plugins', async () => { - // This test verifies the package.json exports are correct - const pluginsModule = await import('../dist/plugins/index.js'); - expect(pluginsModule).toBeDefined(); - expect(pluginsModule.motor).toBeDefined(); - expect(pluginsModule.vault).toBeDefined(); - }); - - it('should be able to import vault directly', async () => { - const vaultModule = await import('../dist/plugins/vault/index.js'); - expect(vaultModule).toBeDefined(); - expect(vaultModule.VaultClient).toBeDefined(); - }); - - it('should be able to import storage components from vault', async () => { - const vaultModule = await import('../dist/plugins/vault/index.js'); - expect(vaultModule.VaultStorageManager).toBeDefined(); - expect(vaultModule.AccountVaultDatabase).toBeDefined(); - expect(vaultModule.defaultStorageManager).toBeDefined(); - }); - - it('should be able to import motor directly', async () => { - const motorModule = await import('../dist/plugins/motor/index.js'); - expect(motorModule).toBeDefined(); - expect(motorModule.MotorPluginImpl).toBeDefined(); - }); -}); - -describe.skip('VaultClient Storage Integration', () => { - it('should create vault client with storage disabled by default', () => { - const client = plugins.createVaultClient(); - expect(client).toBeDefined(); - expect(client).toBeInstanceOf(plugins.VaultClient); - }); - - it('should create vault client with storage enabled', () => { - const client = plugins.createVaultClient({ - enablePersistence: true, - autoCleanup: false - }); - expect(client).toBeDefined(); - expect(client).toBeInstanceOf(plugins.VaultClient); - }); - - it('should have storage management methods', () => { - const client = plugins.createVaultClient({ - enablePersistence: true - }); - - // Check that all storage methods exist - expect(typeof client.persistState).toBe('function'); - expect(typeof client.loadPersistedState).toBe('function'); - expect(typeof client.clearPersistedState).toBe('function'); - expect(typeof client.saveToken).toBe('function'); - expect(typeof client.getPersistedTokens).toBe('function'); - expect(typeof client.removeExpiredTokens).toBe('function'); - expect(typeof client.switchAccount).toBe('function'); - expect(typeof client.listPersistedAccounts).toBe('function'); - expect(typeof client.removeAccount).toBe('function'); - }); -}); \ No newline at end of file diff --git a/packages/es/test/setup.ts b/packages/es/test/setup.ts deleted file mode 100644 index 07a1bb06a..000000000 --- a/packages/es/test/setup.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Test setup file for vitest - */ - -import { expect, afterEach, vi } from 'vitest'; -import { cleanup } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import 'fake-indexeddb/auto'; - -// Cleanup after each test -afterEach(() => { - cleanup(); -}); - -// Mock window.crypto for WebAuthn tests -if (typeof window !== 'undefined' && !window.crypto) { - Object.defineProperty(window, 'crypto', { - value: { - getRandomValues: (arr: Uint8Array) => { - for (let i = 0; i < arr.length; i++) { - arr[i] = Math.floor(Math.random() * 256); - } - return arr; - }, - subtle: {} as SubtleCrypto, - }, - }); -} - -// Mock localStorage -const localStorageMock = { - getItem: vi.fn(), - setItem: vi.fn(), - removeItem: vi.fn(), - clear: vi.fn(), -}; - -if (typeof window !== 'undefined') { - Object.defineProperty(window, 'localStorage', { - value: localStorageMock, - }); -} \ No newline at end of file diff --git a/packages/es/tests/integration/ipfs-integration.test.ts b/packages/es/tests/integration/ipfs-integration.test.ts deleted file mode 100644 index 5def1661f..000000000 --- a/packages/es/tests/integration/ipfs-integration.test.ts +++ /dev/null @@ -1,425 +0,0 @@ -/** - * Integration tests for IPFS/Helia with Docker IPFS nodes - * - * These tests require Docker and docker-compose to be running with IPFS nodes. - * Run with: docker-compose up -d ipfs - */ - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { IPFSClient, createIPFSClient } from '../../src/client/services/ipfs'; -// TODO: Fix imports - vault/enclave and client-ipfs paths are incorrect -// import { EnclaveIPFSManager } from '../../src/plugins/vault/enclave'; -import { EnclaveIPFSManager } from '../../src/plugin/enclave'; -import { IPFSCache } from '../../src/client/services/ipfs-cache'; -// import { VaultClientWithIPFS } from '../../src/plugins/vault/client-ipfs'; -import { VaultClientWithIPFS } from '../../src/plugin/client-ipfs'; -// import type { EnclaveDataWithCID } from '../../src/plugins/vault/enclave'; -import type { EnclaveDataWithCID } from '../../src/plugin/enclave'; - -// Skip these tests in CI environment or when IPFS is not available -const skipIntegrationTests = process.env.CI === 'true' || process.env.SKIP_INTEGRATION === 'true'; - -describe.skipIf(skipIntegrationTests)('IPFS Integration Tests', () => { - let ipfsClient: IPFSClient; - let enclaveManager: EnclaveIPFSManager; - let cache: IPFSCache; - - beforeAll(async () => { - // Initialize IPFS client with local node - ipfsClient = await createIPFSClient({ - gateways: ['http://localhost:8080', 'http://localhost:5001'], - enablePersistence: true, - }); - - // Create enclave manager - enclaveManager = new EnclaveIPFSManager(ipfsClient, { - encryptionRequired: false, // Simplified for testing - pinningEnabled: true, - maxRetries: 3, - }); - - // Initialize cache - cache = new IPFSCache({ - maxSize: 100, - ttl: 300000, - enablePersistence: true, - }); - }, 30000); // Allow 30 seconds for initialization - - afterAll(async () => { - await ipfsClient.cleanup(); - await cache.destroy(); - }); - - describe('Basic IPFS Operations', () => { - it('should connect to IPFS node and get status', async () => { - const status = await ipfsClient.getNodeStatus(); - - expect(status.peerId).toBeDefined(); - expect(status.isOnline).toBe(true); - console.log('Connected to IPFS node:', status.peerId); - }); - - it('should store and retrieve data', async () => { - const testData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - - const { cid } = await ipfsClient.addEnclaveData(testData); - expect(cid).toBeDefined(); - - const retrieved = await ipfsClient.getEnclaveData(cid); - expect(retrieved).toEqual(testData); - }); - - it('should store and retrieve strings', async () => { - const testString = 'Hello IPFS from Sonr integration test!'; - - const cid = await ipfsClient.addString(testString); - expect(cid).toBeDefined(); - - const retrieved = await ipfsClient.getString(cid); - expect(retrieved).toBe(testString); - }); - }); - - describe('Large File Handling', () => { - it('should handle large enclave data (1MB)', async () => { - const largeData = new Uint8Array(1024 * 1024); // 1MB - // Fill with random data - for (let i = 0; i < largeData.length; i++) { - largeData[i] = Math.floor(Math.random() * 256); - } - - const { cid, size } = await ipfsClient.addEnclaveData(largeData); - expect(cid).toBeDefined(); - expect(size).toBe(largeData.length); - - const retrieved = await ipfsClient.getEnclaveData(cid); - expect(retrieved.length).toBe(largeData.length); - expect(retrieved).toEqual(largeData); - }, 60000); // Allow 60 seconds for large file - - it('should handle chunked data retrieval', async () => { - // Create data that will be chunked - const chunkSize = 256 * 1024; // 256KB chunks - const totalSize = chunkSize * 3; // 768KB - const chunkedData = new Uint8Array(totalSize); - - // Fill with pattern for verification - for (let i = 0; i < chunkedData.length; i++) { - chunkedData[i] = i % 256; - } - - const { cid } = await ipfsClient.addEnclaveData(chunkedData); - const retrieved = await ipfsClient.getEnclaveData(cid); - - // Verify data integrity - expect(retrieved.length).toBe(totalSize); - for (let i = 0; i < 100; i++) { - const idx = Math.floor(Math.random() * totalSize); - expect(retrieved[idx]).toBe(idx % 256); - } - }); - }); - - describe('MPC Enclave Storage', () => { - it('should store and retrieve MPC enclave data', async () => { - const enclaveData: EnclaveDataWithCID = { - publicKey: 'test-public-key-12345', - privateKeyShares: ['share1', 'share2', 'share3'], - threshold: 2, - parties: 3, - encryptionMetadata: { - algorithm: 'AES-256-GCM', - keyVersion: 1, - consensusHeight: 1000, - nonce: 'test-nonce-123', - }, - }; - - const payload = new TextEncoder().encode(JSON.stringify(enclaveData)); - - const result = await enclaveManager.storeEnclaveData(enclaveData, payload); - expect(result.cid).toBeDefined(); - expect(result.isPinned).toBe(true); - - const retrieved = await enclaveManager.retrieveEnclaveData(result.cid); - const decoded = JSON.parse(new TextDecoder().decode(retrieved)); - expect(decoded.publicKey).toBe(enclaveData.publicKey); - }); - - it('should verify enclave data integrity', async () => { - const testData = new Uint8Array([10, 20, 30, 40, 50]); - const { cid } = await ipfsClient.addEnclaveData(testData); - - const enclaveData: EnclaveDataWithCID = { - publicKey: 'integrity-test-key', - privateKeyShares: ['share1'], - threshold: 1, - parties: 1, - }; - - const isValid = await enclaveManager.verifyEnclaveDataIntegrity(cid, testData); - expect(isValid).toBe(true); - - const tamperedData = new Uint8Array([10, 20, 30, 40, 51]); // Changed last byte - const isInvalid = await enclaveManager.verifyEnclaveDataIntegrity(cid, tamperedData); - expect(isInvalid).toBe(false); - }); - }); - - describe('Pinning Operations', () => { - it('should pin and unpin content', async () => { - const testData = new Uint8Array([100, 200, 50]); - const { cid } = await ipfsClient.addEnclaveData(testData); - - await ipfsClient.pin(cid); - let isPinned = await ipfsClient.isPinned(cid); - expect(isPinned).toBe(true); - - await ipfsClient.unpin(cid); - isPinned = await ipfsClient.isPinned(cid); - expect(isPinned).toBe(false); - }); - - it('should list all pinned CIDs', async () => { - const data1 = new Uint8Array([1, 1, 1]); - const data2 = new Uint8Array([2, 2, 2]); - - const { cid: cid1 } = await ipfsClient.addEnclaveData(data1); - const { cid: cid2 } = await ipfsClient.addEnclaveData(data2); - - await ipfsClient.pin(cid1); - await ipfsClient.pin(cid2); - - const pins = await ipfsClient.listPins(); - expect(pins).toContain(cid1); - expect(pins).toContain(cid2); - }); - }); - - describe('Caching Integration', () => { - it('should cache retrieved data', async () => { - const testData = new Uint8Array([111, 222, 333]); - const { cid } = await ipfsClient.addEnclaveData(testData); - - // First retrieval - from IPFS - const start1 = Date.now(); - await cache.set(cid, testData); - const time1 = Date.now() - start1; - - // Second retrieval - from cache - const start2 = Date.now(); - const cached = await cache.get(cid); - const time2 = Date.now() - start2; - - expect(cached).toEqual(testData); - expect(time2).toBeLessThan(time1); // Cache should be faster - - const stats = cache.getStats(); - expect(stats.hits).toBeGreaterThan(0); - }); - - it('should preload multiple CIDs into cache', async () => { - const cids: string[] = []; - const dataMap = new Map(); - - // Store multiple items - for (let i = 0; i < 5; i++) { - const data = new Uint8Array([i, i, i]); - const { cid } = await ipfsClient.addEnclaveData(data); - cids.push(cid); - dataMap.set(cid, data); - } - - // Preload into cache - await cache.preload(cids, async (cid) => { - return await ipfsClient.getEnclaveData(cid); - }); - - // Verify all are cached - for (const cid of cids) { - expect(await cache.has(cid)).toBe(true); - const cached = await cache.get(cid); - expect(cached).toEqual(dataMap.get(cid)); - } - }); - }); - - describe('Network Failure Recovery', () => { - it('should retry on transient failures', async () => { - // This test simulates retry logic - const enclaveData: EnclaveDataWithCID = { - publicKey: 'retry-test-key', - privateKeyShares: ['share1'], - threshold: 1, - parties: 1, - }; - - const payload = new Uint8Array([99, 99, 99]); - - // Store data (should succeed even with retries configured) - const result = await enclaveManager.storeEnclaveData(enclaveData, payload); - expect(result.cid).toBeDefined(); - - // Retrieve with retry logic - const retrieved = await enclaveManager.retrieveEnclaveData(result.cid); - expect(retrieved).toEqual(payload); - }); - - it('should use gateway fallback when direct connection fails', async () => { - const testData = new Uint8Array([77, 88, 99]); - const { cid } = await ipfsClient.addEnclaveData(testData); - - // Test verified fetch with fallback - const response = await ipfsClient.verifiedFetch(cid); - expect(response.ok).toBe(true); - }); - }); - - describe('Batch Operations', () => { - it('should batch store multiple enclaves', async () => { - const enclaves = []; - - for (let i = 0; i < 3; i++) { - const enclaveData: EnclaveDataWithCID = { - publicKey: `batch-key-${i}`, - privateKeyShares: [`share-${i}`], - threshold: 1, - parties: 1, - }; - - const payload = new Uint8Array([i, i, i]); - enclaves.push({ data: enclaveData, payload }); - } - - const results = await enclaveManager.batchStoreEnclaves(enclaves); - - expect(results).toHaveLength(3); - for (const result of results) { - expect(result.cid).toBeDefined(); - expect(result.isPinned).toBe(true); - } - }); - }); - - describe('VaultClient IPFS Integration', () => { - it('should initialize VaultClient with IPFS', async () => { - const vaultClient = new VaultClientWithIPFS({ - chainId: 'test-chain', - enableIPFSPersistence: true, - ipfsGateways: ['http://localhost:8080'], - }); - - // Initialize with IPFS (skip WASM for integration test) - try { - await vaultClient.initializeWithIPFS(); - - const status = await vaultClient.getIPFSStatus(); - expect(status.peerId).toBeDefined(); - expect(status.isOnline).toBe(true); - - await vaultClient.cleanup(); - } catch (error) { - // WASM initialization might fail in test environment - // But IPFS should still be initialized - if (error.message.includes('WASM')) { - console.log('WASM initialization skipped in test'); - } else { - throw error; - } - } - }); - }); - - describe('Data Persistence', () => { - it('should persist data across client reconnections', async () => { - const testData = new Uint8Array([50, 60, 70, 80, 90]); - const { cid } = await ipfsClient.addEnclaveData(testData); - - // Clean up current client - await ipfsClient.cleanup(); - - // Create new client - const newClient = await createIPFSClient({ - gateways: ['http://localhost:8080'], - }); - - // Should still be able to retrieve the data - const retrieved = await newClient.getEnclaveData(cid); - expect(retrieved).toEqual(testData); - - await newClient.cleanup(); - }); - }); - - describe('CID Validation', () => { - it('should validate CID format', async () => { - const invalidCids = [ - 'invalid-cid', - '12345', - '', - 'Qm', // Too short - ]; - - for (const invalidCid of invalidCids) { - await expect(ipfsClient.getEnclaveData(invalidCid)).rejects.toThrow(); - } - }); - - it('should handle non-existent CIDs gracefully', async () => { - const nonExistentCid = 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG'; - - // This should timeout or throw after retries - await expect( - Promise.race([ - ipfsClient.getEnclaveData(nonExistentCid), - new Promise((_, reject) => - setTimeout(() => reject(new Error('Timeout')), 5000) - ) - ]) - ).rejects.toThrow(); - }); - }); -}); - -// Performance benchmarks (optional, run with --bench flag) -describe.skipIf(skipIntegrationTests)('IPFS Performance Benchmarks', () => { - let ipfsClient: IPFSClient; - - beforeAll(async () => { - ipfsClient = await createIPFSClient({ - gateways: ['http://localhost:8080'], - }); - }); - - afterAll(async () => { - await ipfsClient.cleanup(); - }); - - it('should measure storage performance', async () => { - const sizes = [1024, 10240, 102400]; // 1KB, 10KB, 100KB - const results: any[] = []; - - for (const size of sizes) { - const data = new Uint8Array(size); - crypto.getRandomValues(data); - - const start = performance.now(); - const { cid } = await ipfsClient.addEnclaveData(data); - const storeTime = performance.now() - start; - - const retrieveStart = performance.now(); - await ipfsClient.getEnclaveData(cid); - const retrieveTime = performance.now() - retrieveStart; - - results.push({ - size: `${size / 1024}KB`, - storeTime: `${storeTime.toFixed(2)}ms`, - retrieveTime: `${retrieveTime.toFixed(2)}ms`, - throughput: `${(size / storeTime * 1000 / 1024).toFixed(2)}KB/s`, - }); - } - - console.table(results); - }); -}); \ No newline at end of file diff --git a/packages/es/tsconfig.json b/packages/es/tsconfig.json deleted file mode 100644 index ddc5c63b5..000000000 --- a/packages/es/tsconfig.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "compilerOptions": { - "lib": ["ES2022", "DOM"], - "target": "ES2022", - "module": "ES2022", - "baseUrl": ".", - "paths": { - "@sonr.io/es/*": ["./src/*"] - }, - "outDir": "./dist", - "rootDir": "./src", - // `node16` is too strict and causes type errors for imported pkgs. - // We use `tsc-alias` to help add the file extensions instead. - "moduleResolution": "bundler", - "forceConsistentCasingInFileNames": true, - "isolatedModules": true, - "esModuleInterop": true, - "skipLibCheck": true, - - // Relaxed type checking to allow build with existing issues - "strict": false, - "noImplicitAny": false, - "noFallthroughCasesInSwitch": false, - "strictNullChecks": false, - "noUnusedLocals": false, - "noUnusedParameters": false, - "noImplicitReturns": false, - "allowUnreachableCode": true, - "allowUnusedLabels": true, - "noUncheckedIndexedAccess": false, - - "declaration": true, - "declarationMap": true, - "sourceMap": true - }, - "include": ["src"], - "exclude": ["dist", "node_modules", "**/*.test.ts", "**/__tests__/**"], - "tsc-alias": { - // Add file extensions to imports/exports for ESM compatibility. - "resolveFullPaths": true, - // See: https://github.com/justkey007/tsc-alias/discussions/110. - "replacers": { - "base-url": { - "enabled": false - } - } - } -} diff --git a/packages/es/vitest.config.ts b/packages/es/vitest.config.ts deleted file mode 100644 index 07148bf7c..000000000 --- a/packages/es/vitest.config.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { defineConfig } from 'vitest/config'; -import path from 'path'; - -export default defineConfig({ - test: { - globals: true, - environment: 'jsdom', - setupFiles: ['./test/setup.ts'], - exclude: [ - '**/node_modules/**', - '**/dist/**', - '**/test/plugins.test.ts', - '**/src/client/services/__tests__/ipfs.test.ts', - '**/tests/integration/ipfs-integration.test.ts', - ], - coverage: { - provider: 'v8', - reporter: ['text', 'json', 'html'], - exclude: [ - 'node_modules/', - 'test/', - '*.config.ts', - '**/*.d.ts', - '**/*.test.ts', - '**/index.ts', - ], - }, - }, - resolve: { - alias: { - '@': path.resolve(__dirname, './src'), - }, - }, -}); \ No newline at end of file diff --git a/packages/pkl/.cz.toml b/packages/pkl/.cz.toml deleted file mode 100644 index 67041a987..000000000 --- a/packages/pkl/.cz.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "@sonr.io/pkl@v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "npm" -update_changelog_on_bump = true -major_version_zero = true -pre_bump_hooks = ["bash ../../scripts/hook-bump-pre.sh"] -post_bump_hooks = ["pnpm --filter '@sonr.io/pkl' publish --no-git-checks"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(pkg-pkl\\)(!)?:" diff --git a/packages/pkl/Makefile b/packages/pkl/Makefile deleted file mode 100755 index 1182cb41f..000000000 --- a/packages/pkl/Makefile +++ /dev/null @@ -1,83 +0,0 @@ -# Makefile for pkljar - Pkl configuration management -.PHONY: all release dist docker json-schema-to-pkl upload-module upload-release clean clean-out clean-dist clean-npx-cache - -# Default target - run release and dist -all: release dist npm-publish clean-npx-cache - -# Package Pkl files and upload to R2 -release: clean-out - @pkl project package packages/*/ - @gum log --level debug "Publishing to Cloudflare R2" - @$(MAKE) upload-release - @rm -rf .out - -# Distribute Pkl files and upload to R2 -dist: clean-dist - @fd -e pkl . -t f -x sh -c 'mkdir -p dist/$$(dirname {}) && cp {} dist/$$(dirname {})/' - @mv dist/packages/* dist/ - @rm -rf dist/basePklProject.pkl - @rm -rf dist/packages - @gum log --level debug "Publishing to Cloudflare R2" - @$(MAKE) upload-module - @rm -rf dist - -# Interactive JSON Schema to Pkl conversion -json-schema-to-pkl: - @SCHEMA=$$(gum file --file --header "Select a JSON schema file to convert to PKL") && \ - PACKAGE=package://pkg.pkl-lang.org/pkl-pantry/org.json_schema.contrib@1.1.4#/generate.pkl && \ - gum log --level debug "Converting $$SCHEMA to PKL" && \ - pkl eval $$PACKAGE -m . -p source=$$SCHEMA && \ - (gum confirm "Delete source file?" && rm $$SCHEMA || gum log --level debug "Skipping delete") - -# Upload module to R2 (internal) -upload-module: - @rclone copy dist/ r2:pklmod/ - -# Upload release to R2 (internal) -upload-release: - @rclone copy .out/ r2:pkljar/ - -# Clean targets -clean-out: - @rm -rf .out - -clean-dist: - @rm -rf dist - -clean-npx-cache: - @gum log --level debug "Clearing npx cache" - @npx clear-npx-cache -y 2>/dev/null || true - @gum log --level debug "NPX cache cleared" - -clean: clean-out clean-dist - @rm -rf build/ - -# Test npx functionality -npx-test: - @gum log --level debug "Testing pkljar CLI via npm run" - @npm start - -# Publish to npm with version patch bump -npm-publish: - @gum log --level debug "Bumping version patch" - @npm version patch --no-git-tag-version - @gum log --level debug "Publishing pkljar to npm" - @npm publish - -# Help target -help: - @echo "Usage: make " - @echo "" - @echo "Available targets:" - @echo " all : Package and distribute Pkl files (default)" - @echo " release : Package Pkl files and upload to R2" - @echo " dist : Distribute Pkl files and upload to R2" - @echo " docker : Build multi-platform Docker image" - @echo " json-schema-to-pkl : Convert JSON schema to Pkl interactively" - @echo " npx-test : Test pkljar CLI via npm run" - @echo " npm-publish : Publish pkljar package to npm (with version bump)" - @echo " clean : Remove all build artifacts" - @echo " clean-npx-cache : Clear npx cache for testing fresh installs" - @echo " help : Show this help message" - -.PHONY: help npx-test npm-publish diff --git a/packages/pkl/README.md b/packages/pkl/README.md deleted file mode 100644 index c17ca804a..000000000 --- a/packages/pkl/README.md +++ /dev/null @@ -1,294 +0,0 @@ -# pkljar - -> Interactive CLI for generating type-safe Sonr Network configurations using Apple's Pkl language - -[![npm version](https://img.shields.io/npm/v/@sonr.io/pkljar.svg)](https://www.npmjs.com/package/@sonr.io/pkljar) -[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC) - -## Overview - -`pkljar` is a comprehensive configuration management system for the Sonr Network that provides an interactive CLI to generate, validate, and distribute type-safe configuration files. Built on Apple's Pkl configuration language, it ensures compile-time validation and type safety for all service configurations. - -## Features - -- 🎯 **Interactive CLI** - User-friendly prompts for selecting and configuring Pkl packages -- 📦 **Pre-built Packages** - Ready-to-use configuration packages for Sonr services -- 🔒 **Type Safety** - Compile-time validation using Pkl's strong typing system -- 🌐 **Remote Package Resolution** - Automatic fetching from `mod.pkl.sh` repository -- 🎨 **Multiple Output Formats** - Support for YAML, JSON, TOML, XML, and more -- 🐳 **Docker Support** - Multi-platform Docker images for containerized deployments - -## Installation - -### Using npm - -```bash -npm install -g @sonr.io/pkljar -``` - -### Using npx (no installation required) - -```bash -npx @sonr.io/pkljar -``` - -### Using Docker - -```bash -docker run onsonr/pkljar eval_beam -``` - -## Quick Start - -1. Run the CLI: - ```bash - pkljar - ``` - -2. Select a package from the interactive menu: - - `sonr.beam` - Matrix/Element communication bridge - - `sonr.core` - Core Sonr Network configuration - - `sonr.hway` - Highway node configuration - - `sonr.testnet` - Testnet deployment configuration - -3. Choose a module to evaluate (e.g., Config, Docker, Starship) - -4. Specify output directory and format - -5. Configuration files are generated in your specified directory - -## Available Packages - -### sonr.beam -Matrix bridge configuration for Sonr Network communication. - -**Modules:** -- `Config.pkl` - Main configuration -- `Element.pkl` - Element client configuration -- `Hookshot.pkl` - GitHub/GitLab bridge configuration -- `Synapse.pkl` - Matrix server configuration - -### sonr.core -Core Sonr Network blockchain configuration. - -**Modules:** -- `Config.pkl` - Core network configuration -- `Keys.pkl` - Key management configuration -- `UCAN.pkl` - UCAN authorization configuration -- `Wallet.pkl` - Wallet service configuration - -### sonr.hway -Highway node configuration for network routing. - -**Modules:** -- `Config.pkl` - Highway node configuration - -### sonr.testnet -Testnet deployment configurations. - -**Modules:** -- `Docker.pkl` - Docker Compose configuration -- `Starship.pkl` - Kubernetes deployment via Starship - -## CLI Usage - -### Interactive Mode (Default) - -```bash -pkljar -``` - -Launches an interactive prompt that guides you through: -1. Package selection -2. Module selection -3. Output directory configuration -4. Format selection (YAML, JSON, TOML, etc.) - -### Output Formats - -The CLI supports multiple output formats: -- `auto` - Use module's default format -- `yaml` - YAML format -- `json` - JSON format -- `jsonnet` - Jsonnet format -- `pcf` - Pkl Configuration Format -- `plist` - Property List format -- `properties` - Java Properties format -- `textproto` - Text Protocol Buffer format -- `xml` - XML format - -## Development - -### Project Structure - -``` -pkljar/ -├── src/ -│ └── index.js # CLI entry point -├── packages/ # Pkl package definitions -│ ├── sonr.beam/ # Matrix bridge packages -│ ├── sonr.core/ # Core network packages -│ ├── sonr.hway/ # Highway node packages -│ └── sonr.testnet/ # Testnet packages -├── docker/ # Docker configurations -└── Makefile # Build automation -``` - -### Building from Source - -```bash -# Clone the repository -git clone https://github.com/sonr-io/pkljar.git -cd pkljar - -# Install dependencies -npm install - -# Run locally -npm start - -# Build packages -make release - -# Build Docker image -make docker -``` - -### Creating Custom Packages - -1. Create a new directory in `packages/` following the naming convention: - ```bash - mkdir packages/myorg.myservice - ``` - -2. Create a `PklProject` file: - ```pkl - amends "../../basePklProject.pkl" - - dependencies { - ["base.web"] = import("../base.web/PklProject") - } - ``` - -3. Define your configuration modules - -4. Build and publish: - ```bash - make release - ``` - -## Docker Usage - -### Pre-built Commands - -```bash -# Generate Beam configuration -docker run onsonr/pkljar eval_beam - -# Generate Synapse configuration -docker run onsonr/pkljar eval_beam_synapse - -# Generate Hookshot configuration -docker run onsonr/pkljar eval_beam_hookshot -``` - -### Custom Evaluation - -```bash -docker run -v $(pwd)/output:/output onsonr/pkljar \ - pkl eval -m /output https://mod.pkl.sh/sonr.core/Config.pkl -``` - -## API Reference - -### Package Resolution - -All packages are resolved from the `mod.pkl.sh` repository: -``` -https://mod.pkl.sh/{package}/{module} -``` - -Example: -``` -https://mod.pkl.sh/sonr.core/Config.pkl -``` - -### Module Structure - -Each Pkl module follows this structure: -```pkl -@ModuleInfo { minPklVersion = "0.27.0" } -module package.name.ModuleName - -// Type definitions -class ConfigClass { - property: Type -} - -// Configuration instance -config: ConfigClass = new ConfigClass { - property = value -} - -// Output configuration -output { - renderer = new YamlRenderer {} -} -``` - -## Advanced Configuration - -### Environment-Specific Overrides - -Use Pkl's conditional logic for environment-specific configurations: - -```pkl -config = new ServiceConfig { - host = if (env == "production") - "prod.example.com" - else - "localhost" -} -``` - -### Multi-File Output - -Generate multiple configuration files from a single module: - -```pkl -output { - files { - ["config/app.toml"] = appConfig.output - ["config/client.toml"] = clientConfig.output - ["docker-compose.yml"] = dockerConfig.output - } -} -``` - -## Contributing - -We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. - -### Development Workflow - -1. Fork the repository -2. Create a feature branch -3. Make your changes -4. Run tests: `pkl test packages/*/` -5. Submit a pull request - -## Support - -- **Issues**: [GitHub Issues](https://github.com/sonr-io/pkljar/issues) -- **Documentation**: [Pkl Language Documentation](https://pkl-lang.org) -- **Community**: [Sonr Discord](https://discord.gg/sonr) - -## License - -ISC License - see [LICENSE](LICENSE) file for details. - -## Acknowledgments - -- Built with [Pkl](https://pkl-lang.org) by Apple -- CLI powered by [@clack/prompts](https://github.com/natemoo-re/clack) -- Pkl runtime by [@pkl-community/pkl](https://github.com/pkl-community/pkl-npm) \ No newline at end of file diff --git a/packages/pkl/cli/index.js b/packages/pkl/cli/index.js deleted file mode 100755 index 91e6845a9..000000000 --- a/packages/pkl/cli/index.js +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env node - -import { setTimeout } from 'node:timers/promises'; -import { exec } from 'node:child_process'; -import { promisify } from 'node:util'; -import * as p from '@clack/prompts'; -import color from 'picocolors'; -import { getExePath } from '@pkl-community/pkl'; - -const execAsync = promisify(exec); -const pklPath = getExePath(); - -// Static list of available packages on mod.pkl.sh -const AVAILABLE_PACKAGES = [ - 'sonr.beam', - 'sonr.core', - 'sonr.hway', - 'sonr.testnet' -]; - -// Module options for each package type -const MODULE_OPTIONS = { - default: [ - { value: 'Config.pkl', label: 'Config', hint: 'Main configuration module' }, - { value: 'PklProject', label: 'Project', hint: 'Project definition' }, - ], - 'sonr.beam': [ - { value: 'Config.pkl', label: 'Config', hint: 'Main configuration' }, - { value: 'Element.pkl', label: 'Element', hint: 'Element configuration' }, - { value: 'Hookshot.pkl', label: 'Hookshot', hint: 'Hookshot configuration' }, - { value: 'Synapse.pkl', label: 'Synapse', hint: 'Synapse configuration' }, - { value: 'PklProject', label: 'Project', hint: 'Project definition' }, - ], - 'sonr.core': [ - { value: 'Config.pkl', label: 'Config', hint: 'Core configuration' }, - { value: 'Keys.pkl', label: 'Keys', hint: 'Key management' }, - { value: 'UCAN.pkl', label: 'UCAN', hint: 'UCAN configuration' }, - { value: 'Wallet.pkl', label: 'Wallet', hint: 'Wallet configuration' }, - { value: 'PklProject', label: 'Project', hint: 'Project definition' }, - ], - 'sonr.testnet': [ - { value: 'Starship.pkl', label: 'Starship', hint: 'Starship K8s configuration' }, - { value: 'Docker.pkl', label: 'Docker', hint: 'Docker Compose configuration' }, - ], -}; - -async function getAvailablePackages() { - // Always return static list of packages available on mod.pkl.sh - return AVAILABLE_PACKAGES; -} - -async function main() { - console.clear(); - - await setTimeout(500); - - p.intro(`${color.bgCyan(color.black(' Sonr PKL '))} - Configuration CLI`); - - try { - // Get available packages - const availablePackages = await getAvailablePackages(); - - if (availablePackages.length === 0) { - p.cancel('No packages found.'); - process.exit(1); - } - - const config = await p.group( - { - package: () => - p.select({ - message: 'Select a Pkl package to evaluate', - options: availablePackages.map(pkg => ({ - value: pkg, - label: pkg, - hint: `https://mod.pkl.sh/${pkg}/` - })), - maxItems: 10 - }), - module: ({ results }) => { - const moduleOpts = MODULE_OPTIONS[results.package] || MODULE_OPTIONS.default; - return p.select({ - message: 'Select module to evaluate', - options: moduleOpts, - maxItems: 8 - }); - }, - outputPath: () => - p.text({ - message: 'Output directory path', - placeholder: './data', - initialValue: './data', - validate: value => { - if (!value) return 'Output path is required'; - return; - } - }), - format: () => - p.select({ - message: 'Output format', - options: [ - { value: 'auto', label: 'Auto (from module)', hint: 'Use module\'s default format' }, - { value: 'yaml', label: 'YAML' }, - { value: 'json', label: 'JSON' }, - { value: 'jsonnet', label: 'Jsonnet' }, - { value: 'pcf', label: 'PCF (Pkl Configuration Format)' }, - { value: 'plist', label: 'Property List' }, - { value: 'properties', label: 'Java Properties' }, - { value: 'textproto', label: 'Text Proto' }, - { value: 'xml', label: 'XML' }, - ], - initialValue: 'auto', - maxItems: 8 - }), - }, - { - onCancel: () => { - p.cancel('Operation cancelled.'); - process.exit(0); - }, - } - ); - - const s = p.spinner(); - - // Always use remote packages from mod.pkl.sh - const moduleUrl = `https://mod.pkl.sh/${config.package}/${config.module}`; - - let pklCommand = `"${pklPath}" eval -m ${config.outputPath}`; - - if (config.format !== 'auto') { - pklCommand += ` -f ${config.format}`; - } - - pklCommand += ` ${moduleUrl}`; - - s.start(`Evaluating ${config.package}/${config.module}...`); - - try { - const { stdout, stderr } = await execAsync(pklCommand); - - s.stop(`Successfully evaluated ${config.package}`); - - if (stdout) { - p.note(stdout.trim(), 'Output'); - } - - if (stderr) { - p.log.warning(stderr.trim()); - } - - p.outro(`Configuration generated in ${color.cyan(config.outputPath)}`); - - } catch (error) { - s.stop('Evaluation failed'); - p.log.error(`Failed to evaluate module: ${error.message}`); - - if (error.stderr) { - p.log.error(error.stderr); - } - - process.exit(1); - } - - } catch (error) { - p.log.error(`An error occurred: ${error.message}`); - process.exit(1); - } -} - -main().catch(console.error); diff --git a/packages/pkl/package.json b/packages/pkl/package.json deleted file mode 100644 index dce850d52..000000000 --- a/packages/pkl/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@sonr.io/pkl", - "version": "0.1.0", - "description": "A Pkl project for configuring the Sonr Network. This package resolves Pkl packages and includes the required cli.", - "homepage": "https://github.com/sonr-io/pkljar#readme", - "bugs": { - "url": "https://github.com/sonr-io/pkljar/issues" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/sonr-io/pkljar.git" - }, - "publishConfig": { - "access": "public" - }, - "license": "ISC", - "author": "Sonr DAO", - "type": "module", - "bin": { - "pkljar": "./cli/index.js" - }, - "scripts": { - "cli:start": "node src/index.js", - "test": "echo 'No tests defined for @sonr.io/pkl'", - "release": "cz --no-raise 6,21 bump --yes --increment PATCH" - }, - "dependencies": { - "@clack/prompts": "^0.11.0", - "@pkl-community/pkl": "^0.28.2", - "picocolors": "^1.1.1" - }, - "devDependencies": { - "bun-types": "^1.2.20", - "csstype": "^3.1.3", - "sisteransi": "^1.0.5", - "typescript": "^5.9.2", - "undici-types": "^7.10.0" - } -} diff --git a/packages/pkl/src/base.web/Manifest.pkl b/packages/pkl/src/base.web/Manifest.pkl deleted file mode 100644 index 482a998dd..000000000 --- a/packages/pkl/src/base.web/Manifest.pkl +++ /dev/null @@ -1,56 +0,0 @@ -module base.webapi.Manifest - -name: String -short_name: String -description: String? -display: ("fullscreen"|"standalone"|"minimal-ui"|"browser")? -display_override: Listing? -theme_color: String? -background_color: String? -orientation: ("any"|"natural"|"landscape"|"portrait")? -start_url: String -scope: String? -service_worker: ServiceWorker? -icons: Listing? -related_applications: Listing? -prefer_related_applications: Boolean? -shortcuts: Listing? -file_handlers: Listing? -protocol_handlers: Listing? - -class ServiceWorker { - scope: String - src: String - use_cache: Boolean -} - -class ShortcutIcon { - src: String - sizes: String - type: String? - purpose: String? -} - -class RelatedApplication { - platform: String - url: String? - id: String? -} - -class Shortcut { - name: String - short_name: String? - description: String? - url: String - icons: Listing? -} - -class FileHandler { - action: String - accept: Mapping> -} - -class ProtocolHandler { - scheme: String - url: String -} diff --git a/packages/pkl/src/base.web/OpenIDPayload.pkl b/packages/pkl/src/base.web/OpenIDPayload.pkl deleted file mode 100644 index 5a0422cf1..000000000 --- a/packages/pkl/src/base.web/OpenIDPayload.pkl +++ /dev/null @@ -1,62 +0,0 @@ -module base.did.OpenIDPayload - -verified_claims: VerifiedClaims - -class VerifiedClaims { - verification: Verification - claims: Claims -} - -class Verification { - trust_framework: String - time: String - verification_process: String - evidence: Listing -} - -class Evidence { - type: String - check_details: Listing - time: String - document_details: DocumentDetails -} - -class CheckDetail { - check_method: String -} - -class DocumentDetails { - type: String - issuer: Issuer - document_number: String? - date_of_issuance: String - date_of_expiry: String? -} - -class Issuer { - name: String - country: String - region: String? - street_address: String? -} - -class Claims { - given_name: String - family_name: String - birthdate: String - place_of_birth: PlaceOfBirth - nationalities: Listing - address: Address -} - -class PlaceOfBirth { - country: String - locality: String -} - -class Address { - locality: String - postal_code: String - country: String - street_address: String -} diff --git a/packages/pkl/src/base.web/PklProject b/packages/pkl/src/base.web/PklProject deleted file mode 100644 index 61e26b651..000000000 --- a/packages/pkl/src/base.web/PklProject +++ /dev/null @@ -1,5 +0,0 @@ -amends "../basePklProject.pkl" - -package { - version = "0.0.1" -} diff --git a/packages/pkl/src/base.web/PklProject.deps.json b/packages/pkl/src/base.web/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/base.web/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/base.web/VerifiableCredential.pkl b/packages/pkl/src/base.web/VerifiableCredential.pkl deleted file mode 100644 index 2f2235cc4..000000000 --- a/packages/pkl/src/base.web/VerifiableCredential.pkl +++ /dev/null @@ -1,19 +0,0 @@ -module base.did.VerifiableCredential - -`@context`: Listing -id: String -type: Listing -issuer: String -issuanceDate: String -credentialSubject: CredentialSubject -credentialSchema: CredentialSchema - -class CredentialSubject { - id: String - emailAddress: String -} - -class CredentialSchema { - id: String - type: String -} diff --git a/packages/pkl/src/basePklProject.pkl b/packages/pkl/src/basePklProject.pkl deleted file mode 100644 index 8cd2a6639..000000000 --- a/packages/pkl/src/basePklProject.pkl +++ /dev/null @@ -1,55 +0,0 @@ -// PklProject template for Sonr.io packages -module basePklProject - -amends "pkl:Project" - -import "pkl:reflect" - -// Automatically determine package name from directory structure -local myModule = reflect.Module(module) - -local packageName: String = - findRootModule(myModule) - .relativePathTo(module) - .last - -local function findRootModule(mod: reflect.Module): Module = - let (supermodule = mod.supermodule) - if (supermodule == null || !supermodule.isAmend) mod.reflectee - else findRootModule(supermodule) - -// Find all test files -const local allTests = import*("**/tests/**.pkl").keys.filter((it) -> !it.contains("tests/fixtures/")) - -// Package configuration -package { - name = packageName - baseUri = "package://pkl.sh/\(name)" - packageZipUrl = "https://github.com/sonr-io/pkljar/releases/download/v\(version)/\(name)-\(version).zip" - license = "Apache-2.0" - - authors { - "Sonr.io " - } - - exclude { - "examples/**" - "tests/**" - "**/.DS_Store" - "**/.idea/**" - } - - description = myModule.docComment - issueTracker = "https://github.com/sonr-io/pkljar/issues" - sourceCode = "https://github.com/sonr-io/pkljar/tree/v\(version)/packages/\(name)" - sourceCodeUrlScheme = "https://github.com/sonr-io/pkljar/blob/v\(version)/packages/\(name)%{path}#L%{line}-%{endLine}" -} - - -// Default dependencies (can be extended in specific PklProject files) -dependencies { - // Common dependencies can be added here - // ["example-dep"] { - // uri = "package://pkl.sh/example-dep@1.0.0" - // } -} diff --git a/packages/pkl/src/cosmos.chain/App.pkl b/packages/pkl/src/cosmos.chain/App.pkl deleted file mode 100644 index e74b21418..000000000 --- a/packages/pkl/src/cosmos.chain/App.pkl +++ /dev/null @@ -1,81 +0,0 @@ -open module cosmos.chain.App - -`minimum-gas-prices`: String -`query-gas-limit`: String -`pruning-keep-recent`: String -`pruning-interval`: String -`halt-height`: Number -`halt-time`: Number -`min-retain-blocks`: Number -`inter-block-cache`: Boolean -`index-events`: Listing -`iavl-cache-size`: Number -`iavl-disable-fastnode`: Boolean -`app-db-backend`: String -`grpc-web`: GrpcWeb -`state-sync`: StateSync - -pruning: String -telemetry: Telemetry -api: Api -grpc: Grpc -streaming: Streaming -mempool: Mempool - -class Telemetry { - `service-name`: String - enabled: Boolean - `enable-hostname`: Boolean - `enable-hostname-label`: Boolean - `enable-service-label`: Boolean - `prometheus-retention-time`: Number - `global-labels`: Listing - `metrics-sink`: String - `statsd-addr`: String - `datadog-hostname`: String -} - -class Api { - enable: Boolean - swagger: Boolean - address: String - `max-open-connections`: Number - `rpc-read-timeout`: Number - `rpc-write-timeout`: Number - `rpc-max-body-bytes`: Number - `enabled-unsafe-cors`: Boolean -} - -class Grpc { - enable: Boolean - address: String - `max-recv-msg-size`: String - `max-send-msg-size`: String -} - -class GrpcWeb { - enable: Boolean -} - -class StateSync { - `snapshot-interval`: Number - `snapshot-keep-recent`: Number -} - -class Streaming { - abci: Abci -} - -class Abci { - keys: Listing - plugin: String - `stop-node-on-err`: Boolean -} - -class Mempool { - `max-txs`: Number -} - -output { - renderer = new toml.Renderer {} -} diff --git a/packages/pkl/src/cosmos.chain/Client.pkl b/packages/pkl/src/cosmos.chain/Client.pkl deleted file mode 100644 index 61130aa7e..000000000 --- a/packages/pkl/src/cosmos.chain/Client.pkl +++ /dev/null @@ -1,16 +0,0 @@ -open module cosmos.chain.Client - -`chain-id`: String - -`keyring-backend`: String - -output: String - -node: String - -`broadcast-mode`: String - - -output { - renderer = new toml.Renderer {} -} diff --git a/packages/pkl/src/cosmos.chain/Config.pkl b/packages/pkl/src/cosmos.chain/Config.pkl deleted file mode 100644 index 9bf37f1bd..000000000 --- a/packages/pkl/src/cosmos.chain/Config.pkl +++ /dev/null @@ -1,141 +0,0 @@ -open module cosmos.chain.Config - -version: String -proxy_app: String -moniker: String -db_backend: String -db_dir: String -log_level: String -log_format: String -genesis_file: String -priv_validator_key_file: String -priv_validator_state_file: String -priv_validator_laddr: String -node_key_file: String -abci: String -filter_peers: Boolean - -rpc: Rpc -p2p: P2p -mempool: Mempool -statesync: Statesync -blocksync: Blocksync -consensus: Consensus -storage: Storage -tx_index: TxIndex -instrumentation: Instrumentation - -class Rpc { - laddr: String - cors_allowed_origins: Listing - cors_allowed_methods: Listing - cors_allowed_headers: Listing - grpc_laddr: String - grpc_max_open_connections: Number - unsafe: Boolean - max_open_connections: Number - max_subscription_clients: Number - max_subscriptions_per_client: Number - experimental_subscription_buffer_size: Number - experimental_websocket_write_buffer_size: Number - experimental_close_on_slow_client: Boolean - timeout_broadcast_tx_commit: String - max_request_batch_size: Number - max_body_bytes: Number - max_header_bytes: Number - tls_cert_file: String - tls_key_file: String - pprof_laddr: String -} - -class P2p { - laddr: String - external_address: String - seeds: String - persistent_peers: String - addr_book_file: String - addr_book_strict: Boolean - max_num_inbound_peers: Number - max_num_outbound_peers: Number - unconditional_peer_ids: String - persistent_peers_max_dial_period: String - flush_throttle_timeout: String - max_packet_msg_payload_size: Number - send_rate: Number - recv_rate: Number - pex: Boolean - seed_mode: Boolean - private_peer_ids: String - allow_duplicate_ip: Boolean - handshake_timeout: String - dial_timeout: String -} - -class Mempool { - type: String - recheck: Boolean - recheck_timeout: String - broadcast: Boolean - wal_dir: String - size: Number - max_txs_bytes: Number - cache_size: Number - `keep-invalid-txs-in-cache`: Boolean - max_tx_bytes: Number - max_batch_bytes: Number - experimental_max_gossip_connections_to_persistent_peers: Number - experimental_max_gossip_connections_to_non_persistent_peers: Number -} - -class Statesync { - enable: Boolean - rpc_servers: String - trust_height: Number - trust_hash: String - trust_period: String - discovery_time: String - temp_dir: String - chunk_request_timeout: String - chunk_fetchers: String -} - -class Blocksync { - version: String -} - -class Consensus { - wal_file: String - timeout_propose: String - timeout_propose_delta: String - timeout_prevote: String - timeout_prevote_delta: String - timeout_precommit: String - timeout_precommit_delta: String - timeout_commit: String - double_sign_check_height: Number - skip_timeout_commit: Boolean - create_empty_blocks: Boolean - create_empty_blocks_interval: String - peer_gossip_sleep_duration: String - peer_query_maj23_sleep_duration: String -} - -class Storage { - discard_abci_responses: Boolean -} - -class TxIndex { - indexer: String - `psql-conn`: String -} - -class Instrumentation { - prometheus: Boolean - prometheus_listen_addr: String - max_open_connections: Number - namespace: String -} - -output { - renderer = new toml.Renderer {} -} diff --git a/packages/pkl/src/cosmos.chain/Genesis.pkl b/packages/pkl/src/cosmos.chain/Genesis.pkl deleted file mode 100644 index f98a04afe..000000000 --- a/packages/pkl/src/cosmos.chain/Genesis.pkl +++ /dev/null @@ -1,518 +0,0 @@ -open module cosmos.chain.Genesis - -app_name: String -app_version: String -genesis_time: String -chain_id: String -initial_height: Number -app_hash: Any -app_state: AppState -consensus: Consensus - -class AppState { - `07-tendermint`: Any - auth: Auth - authz: Authz - bank: Bank - capability: Capability - circuit: Circuit - consensus: Any - crisis: Crisis - did: Svc - distribution: Distribution - dwn: Dwn - evidence: Evidence - feegrant: Feegrant - feeibc: Feeibc - genutil: Genutil - globalfee: Globalfee - gov: Gov - group: Group - ibc: Ibc - interchainaccounts: Interchainaccounts - mint: Mint - nft: Nft - packetfowardmiddleware: Packetfowardmiddleware - params: Any - poa: Poa - slashing: Slashing - staking: Staking - svc: Svc - tokenfactory: Tokenfactory - transfer: Transfer - upgrade: Vesting - vesting: Vesting -} - -class Auth { - params: Params - accounts: Listing -} - -class Params { - max_memo_characters: String - tx_sig_limit: String - tx_size_cost_per_byte: String - sig_verify_cost_ed25519: String - sig_verify_cost_secp256k1: String -} - -class Account { - `@type`: String - address: String - pub_key: Any - account_number: String - sequence: String -} - -class Authz { - authorization: Listing -} - -class Bank { - params: BankParams - balances: Listing - supply: Listing - denom_metadata: Listing - send_enabled: Listing -} - -class BankParams { - send_enabled: Listing - default_send_enabled: Boolean -} - -class Balance { - address: String - coins: Listing -} - -class ExpeditedMinDeposit { - denom: String - amount: String -} - -class Capability { - index: String - owners: Listing -} - -class Circuit { - account_permissions: Listing - disabled_type_urls: Listing -} - -class Crisis { - constant_fee: ExpeditedMinDeposit -} - -class Svc { - params: SvcParams -} - -class SvcParams { - attenuations: Listing -} - -class Distribution { - params: DistributionParams - fee_pool: FeePool - delegator_withdraw_infos: Listing - previous_proposer: String - outstanding_rewards: Listing - validator_accumulated_commissions: Listing - validator_historical_rewards: Listing - validator_current_rewards: Listing - delegator_starting_infos: Listing - validator_slash_events: Listing -} - -class DistributionParams { - community_tax: String - base_proposer_reward: String - bonus_proposer_reward: String - withdraw_addr_enabled: Boolean -} - -class FeePool { - community_pool: Listing -} - -class Dwn { - params: DwnParams -} - -class DwnParams { - attenuations: Listing - allowed_operators: Listing -} - -class Evidence { - evidence: Listing -} - -class Feegrant { - allowances: Listing -} - -class Feeibc { - identified_fees: Listing - fee_enabled_channels: Listing - registered_payees: Listing - registered_counterparty_payees: Listing - forward_relayers: Listing -} - -class Genutil { - gen_txs: Listing -} - -class GenTx { - body: Body - auth_info: AuthInfo - signatures: Listing -} - -class Body { - messages: Listing - memo: String - timeout_height: String - extension_options: Listing - non_critical_extension_options: Listing -} - -class Message { - `@type`: String - description: Description - commission: Commission - min_self_delegation: String - delegator_address: String - validator_address: String - pubkey: PublicKey - value: ExpeditedMinDeposit -} - -class Description { - moniker: String - identity: String - website: String - security_contact: String - details: String -} - -class Commission { - rate: String - max_rate: String - max_change_rate: String -} - -class PublicKey { - `@type`: String - key: String -} - -class AuthInfo { - signer_infos: Listing - fee: Fee - tip: Any -} - -class SignerInfo { - public_key: PublicKey - mode_info: ModeInfo - sequence: String -} - -class ModeInfo { - single: Single -} - -class Single { - mode: String -} - -class Fee { - amount: Listing - gas_limit: String - payer: String - granter: String -} - -class Globalfee { - params: GlobalfeeParams -} - -class GlobalfeeParams { - minimum_gas_prices: Listing -} - -class MinimumGasPrice { - amount: String - denom: String -} - -class Gov { - starting_proposal_id: String - deposits: Listing - votes: Listing - proposals: Listing - deposit_params: Any - voting_params: Any - tally_params: Any - params: GovParams - constitution: String -} - -class GovParams { - min_deposit: Listing - max_deposit_period: String - voting_period: String - quorum: String - threshold: String - veto_threshold: String - min_initial_deposit_ratio: String - proposal_cancel_ratio: String - proposal_cancel_dest: String - expedited_voting_period: String - expedited_threshold: String - expedited_min_deposit: Listing - burn_vote_quorum: Boolean - burn_proposal_deposit_prevote: Boolean - burn_vote_veto: Boolean - min_deposit_ratio: String -} - -class Group { - group_seq: String - groups: Listing - group_members: Listing - group_policy_seq: String - group_policies: Listing - proposal_seq: String - proposals: Listing - votes: Listing -} - -class Ibc { - client_genesis: ClientGenesis - connection_genesis: ConnectionGenesis - channel_genesis: ChannelGenesis -} - -class ClientGenesis { - clients: Listing - clients_consensus: Listing - clients_metadata: Listing - params: ClientGenesisParams - create_localhost: Boolean - next_client_sequence: String -} - -class ClientGenesisParams { - allowed_clients: Listing -} - -class ConnectionGenesis { - connections: Listing - client_connection_paths: Listing - next_connection_sequence: String - params: ConnectionGenesisParams -} - -class ConnectionGenesisParams { - max_expected_time_per_block: String -} - -class ChannelGenesis { - channels: Listing - acknowledgements: Listing - commitments: Listing - receipts: Listing - send_sequences: Listing - recv_sequences: Listing - ack_sequences: Listing - next_channel_sequence: String - params: ChannelGenesisParams -} - -class ChannelGenesisParams { - upgrade_timeout: UpgradeTimeout -} - -class UpgradeTimeout { - height: Height - timestamp: String -} - -class Height { - revision_number: String - revision_height: String -} - -class Interchainaccounts { - controller_genesis_state: ControllerGenesisState - host_genesis_state: HostGenesisState -} - -class ControllerGenesisState { - active_channels: Listing - interchain_accounts: Listing - ports: Listing - params: ControllerGenesisStateParams -} - -class ControllerGenesisStateParams { - controller_enabled: Boolean -} - -class HostGenesisState { - active_channels: Listing - interchain_accounts: Listing - port: String - params: HostGenesisStateParams -} - -class HostGenesisStateParams { - host_enabled: Boolean - allow_messages: Listing -} - -class Mint { - minter: Minter - params: MintParams -} - -class Minter { - inflation: String - annual_provisions: String -} - -class MintParams { - mint_denom: String - inflation_rate_change: String - inflation_max: String - inflation_min: String - goal_bonded: String - blocks_per_year: String -} - -class Nft { - classes: Listing - entries: Listing -} - -class Packetfowardmiddleware { - params: PacketfowardmiddlewareParams - in_flight_packets: Vesting -} - -class PacketfowardmiddlewareParams { - fee_percentage: String -} - -class Vesting { -} - -class Poa { - params: PoaParams -} - -class PoaParams { - admins: Listing - allow_validator_self_exit: Boolean -} - -class Slashing { - params: SlashingParams - signing_infos: Listing - missed_blocks: Listing -} - -class SlashingParams { - signed_blocks_window: String - min_signed_per_window: String - downtime_jail_duration: String - slash_fraction_double_sign: String - slash_fraction_downtime: String -} - -class Staking { - params: StakingParams - last_total_power: String - last_validator_powers: Listing - validators: Listing - delegations: Listing - unbonding_delegations: Listing - redelegations: Listing - exported: Boolean -} - -class StakingParams { - unbonding_time: String - max_validators: Number - max_entries: Number - historical_entries: Number - bond_denom: String - min_commission_rate: String -} - -class Tokenfactory { - params: TokenfactoryParams - factory_denoms: Listing -} - -class TokenfactoryParams { - denom_creation_fee: Listing - denom_creation_gas_consume: Number -} - -class Transfer { - port_id: String - denom_traces: Listing - params: TransferParams - total_escrowed: Listing -} - -class TransferParams { - send_enabled: Boolean - receive_enabled: Boolean -} - -class Consensus { - params: ConsensusParams -} - -class ConsensusParams { - block: Block - evidence: ParamsEvidence - validator: Validator - version: Version - abci: Abci -} - -class Block { - max_bytes: String - max_gas: String -} - -class ParamsEvidence { - max_age_num_blocks: String - max_age_duration: String - max_bytes: String -} - -class Validator { - pub_key_types: Listing -} - -class Version { - app: String -} - -class Abci { - vote_extensions_enable_height: String -} - -output { - renderer = new json.Renderer {} -} diff --git a/packages/pkl/src/cosmos.chain/PklProject b/packages/pkl/src/cosmos.chain/PklProject deleted file mode 100644 index 65f5411a5..000000000 --- a/packages/pkl/src/cosmos.chain/PklProject +++ /dev/null @@ -1,12 +0,0 @@ -amends "../basePklProject.pkl" - - -dependencies { - ["toml"] { uri = "package://pkg.pkl-lang.org/pkl-pantry/pkl.toml@1.0.2" } -} - -package { - version = "0.0.1" - description = "Cosmos chain configuration for Sonr.io" -} - diff --git a/packages/pkl/src/cosmos.chain/PklProject.deps.json b/packages/pkl/src/cosmos.chain/PklProject.deps.json deleted file mode 100644 index 7148ca727..000000000 --- a/packages/pkl/src/cosmos.chain/PklProject.deps.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": { - "package://pkg.pkl-lang.org/pkl-pantry/pkl.toml@1": { - "type": "remote", - "uri": "projectpackage://pkg.pkl-lang.org/pkl-pantry/pkl.toml@1.0.2", - "checksums": { - "sha256": "45fea4cf14e7d776e131b338efe2a7016f86c87b0c0f532409f728033bd82f71" - } - } - } -} diff --git a/packages/pkl/src/cosmos.params/Asset.pkl b/packages/pkl/src/cosmos.params/Asset.pkl deleted file mode 100644 index 751205651..000000000 --- a/packages/pkl/src/cosmos.params/Asset.pkl +++ /dev/null @@ -1,51 +0,0 @@ -/// Generated schema for Root -/// -/// This module was generated from JSON Schema from -/// . -/// -/// WARN: The root schema describes open-ended properties, but this is not possible to describe at the -/// module level. -module cosmos.params.Asset - -class Coin { - type: String - denom: String - name: String - symbol: String - description: String - decimals: Number - image: String - coinGeckoId: String - ibc_info: IbcInfo? - bridge_info: BridgeInfo? -} - -class BridgeInfo { - path: String - enable: Boolean - counterparty: BridgeCounterparty -} - -class BridgeCounterparty { - chain: String - contract: String -} - -class IbcInfo { - path: String - client: IbcClient - counterparty: IbcCounterparty -} - -class IbcClient { - channel: String - port: String -} - -class IbcCounterparty { - channel: String - port: String - chain: String - denom: String -} - diff --git a/packages/pkl/src/cosmos.params/Chain.pkl b/packages/pkl/src/cosmos.params/Chain.pkl deleted file mode 100644 index 4b9069326..000000000 --- a/packages/pkl/src/cosmos.params/Chain.pkl +++ /dev/null @@ -1,74 +0,0 @@ -open module cosmos.chain.Params - -class Chain { - chain_id_cosmos: String - chain_name: String - chain_image: String - staking_asset_denom: String - staking_asset_symbol: String - staking_asset_image: String - bech_account_prefix: String - bech_validator_prefix: String - origin_genesis_time: String - api_name: String - is_support_mintscan: Boolean - account_type: Listing - cosmos_fee_info: CosmosFeeInfo - grpc_endpoint: Listing - lcd_endpoint: Listing - explorer: Explorer - about: About - forum: Forum - description: Description -} - -class AccountType { - hd_path: String? - pubkey_style: String? - pubkey_type: String? - is_default: Boolean? -} - -class CosmosFeeInfo { - base: String? - rate: Listing - is_simulable: Boolean? - simulated_gas_multiply: Number? - init_gas_limit: Number? - fee_threshold: String? -} - -class LcdEndpoint { - provider: String? - url: String? -} - -class Explorer { - name: String? - url: String? - account: String? - tx: String? - proposal: String? -} - -class About { - website: String? - docs: String? - github: String? - blog: String? - twitter: String? - discord: String? - telegram: String? - youtube: String? - coingecko: String? -} - -class Forum { - main: String? -} - -class Description { - ko: String? - en: String? - ja: String? -} diff --git a/packages/pkl/src/cosmos.params/PklProject b/packages/pkl/src/cosmos.params/PklProject deleted file mode 100644 index 61e26b651..000000000 --- a/packages/pkl/src/cosmos.params/PklProject +++ /dev/null @@ -1,5 +0,0 @@ -amends "../basePklProject.pkl" - -package { - version = "0.0.1" -} diff --git a/packages/pkl/src/cosmos.params/PklProject.deps.json b/packages/pkl/src/cosmos.params/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/cosmos.params/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/ipfs.node/Config.pkl b/packages/pkl/src/ipfs.node/Config.pkl deleted file mode 100644 index 9680bdd85..000000000 --- a/packages/pkl/src/ipfs.node/Config.pkl +++ /dev/null @@ -1,275 +0,0 @@ -open module ipfs.node.Config - -API: API - -Addresses: Addresses - -AutoNAT: Dynamic - -Bootstrap: Listing - -DNS: DNS - -Datastore: Datastore - -Discovery: Discovery - -Experimental: Experimental - -Gateway: Gateway - -Identity: Identity - -Internal: Dynamic - -Ipns: Ipns - -Migration: Migration - -Mounts: Mounts - -Peering: Peering - -Pinning: Pinning - -Plugins: Plugins - -Provider: Provider - -Pubsub: Pubsub - -Reprovider: Reprovider - -Routing: Routing - -Swarm: Swarm - -class API { - HTTPHeaders: HTTPHeaders -} - -class HTTPHeaders { - `Access-Control-Allow-Origin`: Listing -} - -class Addresses { - API: String - - Announce: Listing - - AppendAnnounce: Listing - - Gateway: String - - NoAnnounce: Listing - - Swarm: Listing -} - -class DNS { - Resolvers: Dynamic -} - -class Datastore { - BloomFilterSize: Int - - GCPeriod: String - - HashOnRead: Boolean - - Spec: Spec - - StorageGCWatermark: Int - - StorageMax: String -} - -class Spec { - mounts: Listing - - type: String -} - -class MountsItem0 { - child: Child - - mountpoint: String - - prefix: String - - type: String -} - -class Child { - path: String - - shardFunc: String - - sync: Boolean - - type: String -} - -class MountsItem1 { - child: MountsItem1Child - - mountpoint: String - - prefix: String - - type: String -} - -class MountsItem1Child { - compression: String - - path: String - - type: String -} - -class Discovery { - MDNS: MDNS -} - -class MDNS { - Enabled: Boolean -} - -class Experimental { - AcceleratedDHTClient: Boolean - - FilestoreEnabled: Boolean - - GraphsyncEnabled: Boolean - - Libp2pStreamMounting: Boolean - - P2pHttpProxy: Boolean - - StrategicProviding: Boolean - - UrlstoreEnabled: Boolean -} - -class Gateway { - APICommands: Listing - - HTTPHeaders: GatewayHTTPHeaders - - NoDNSLink: Boolean - - NoFetch: Boolean - - PathPrefixes: Listing - - PublicGateways: Any - - RootRedirect: String - - Writable: Boolean -} - -class GatewayHTTPHeaders { - `Access-Control-Allow-Headers`: Listing - - `Access-Control-Allow-Methods`: Listing - - `Access-Control-Allow-Origin`: Listing -} - -class Identity { - PeerID: String - - PrivKey: String -} - -class Ipns { - RecordLifetime: String - - RepublishPeriod: String - - ResolveCacheSize: Int -} - -class Migration { - DownloadSources: Listing - - Keep: String -} - -class Mounts { - FuseAllowOther: Boolean - - IPFS: String - - IPNS: String -} - -class Peering { - Peers: Listing -} - -class PeersItem11 { - Addrs: Listing - - ID: String -} - -class Pinning { - RemoteServices: Dynamic -} - -class Plugins { - Plugins: Any -} - -class Provider { - Strategy: String -} - -class Pubsub { - DisableSigning: Boolean - - Router: String -} - -class Reprovider { - Interval: String - - Strategy: String -} - -class Routing { - Methods: Any - - Routers: Any - - Type: String -} - -class Swarm { - AddrFilters: Any - - ConnMgr: Dynamic - - DisableBandwidthMetrics: Boolean - - DisableNatPortMap: Boolean - - RelayClient: Dynamic - - RelayService: Dynamic - - ResourceMgr: Dynamic - - Transports: Transports -} - -class Transports { - Multiplexers: Dynamic - - Network: Dynamic - - Security: Dynamic -} diff --git a/packages/pkl/src/ipfs.node/PklProject b/packages/pkl/src/ipfs.node/PklProject deleted file mode 100644 index 61e26b651..000000000 --- a/packages/pkl/src/ipfs.node/PklProject +++ /dev/null @@ -1,5 +0,0 @@ -amends "../basePklProject.pkl" - -package { - version = "0.0.1" -} diff --git a/packages/pkl/src/ipfs.node/PklProject.deps.json b/packages/pkl/src/ipfs.node/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/ipfs.node/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/matrix.element/Config.pkl b/packages/pkl/src/matrix.element/Config.pkl deleted file mode 100644 index afcd753ff..000000000 --- a/packages/pkl/src/matrix.element/Config.pkl +++ /dev/null @@ -1,186 +0,0 @@ -open module matrix.element.Config - -default_server_config: DefaultServerConfig - -disable_custom_urls: Boolean - -disable_guests: Boolean - -disable_login_language_selector: Boolean - -disable_3pid_login: Boolean - -brand: String - -integrations_ui_url: String - -integrations_rest_url: String - -integrations_widgets_urls: Listing - -branding: Branding - -posthog: Posthog - -default_country_code: String - -show_labs_settings: Boolean - -features: Features - -default_federate: Boolean - -default_theme: String - -room_directory: RoomDirectory - -enable_presence_by_hs_url: EnablePresenceByHsUrl - -setting_defaults: SettingDefaults - -jitsi: Jitsi - -element_call: ElementCall - -map_style_url: String - -settings_defaults: SettingsDefaults - -class DefaultServerConfig { - `m.homeserver`: MHomeserver - - `m.identity_server`: MIdentityServer - - `org.matrix.msc3575.proxy`: OrgMatrixMsc3575Proxy -} - -class MHomeserver { - base_url: String - - server_name: String -} - -class MIdentityServer { - base_url: String -} - -class OrgMatrixMsc3575Proxy { - url: String -} - -class Branding { - welcome_background_url: String - - auth_header_logo_url: String -} - -class Posthog { - api_host: String - - project_api_key: String -} - -class Features { - feature_wysiwyg_composer: Boolean - - feature_pinning: Boolean - - feature_oidc_native_flow: Boolean - - feature_sliding_sync: Boolean - - feature_custom_themes: Boolean -} - -class RoomDirectory { - servers: Listing -} - -class EnablePresenceByHsUrl { - `https://bm.chat`: Boolean - - `https://matrix-client.matrix.org`: Boolean -} - -class SettingDefaults { - breadcrumbs: Boolean -} - -class Jitsi { - preferred_domain: String -} - -class ElementCall { - url: String - - participant_limit: Number - - brand: String -} - -class SettingsDefaults { - custom_themes: Listing -} - -class CustomTheme { - name: String - - is_dark: Boolean - - colors: Colors -} - -class Colors { - `accent-color`: String - - `primary-color`: String - - `warning-color`: String - - alert: String? - - `sidebar-color`: String - - `roomlist-background-color`: String - - `roomlist-text-color`: String - - `roomlist-text-secondary-color`: String - - `roomlist-highlights-color`: String - - `roomlist-separator-color`: String - - `timeline-background-color`: String - - `timeline-text-color`: String - - `secondary-content`: String? - - `tertiary-content`: String? - - `timeline-text-secondary-color`: String - - `timeline-highlights-color`: String - - `reaction-row-button-selected-bg-color`: String? - - `menu-selected-color`: String? - - `focus-bg-color`: String? - - `room-highlight-color`: String? - - `togglesw-off-color`: String? - - `other-user-pill-bg-color`: String? - - `username-colors`: Listing? - - `avatar-background-colors`: Listing? -} - - -output { - renderer = new JsonRenderer {} -} diff --git a/packages/pkl/src/matrix.element/PklProject b/packages/pkl/src/matrix.element/PklProject deleted file mode 100644 index d96630006..000000000 --- a/packages/pkl/src/matrix.element/PklProject +++ /dev/null @@ -1,6 +0,0 @@ -amends "../basePklProject.pkl" - - -package { - version = "0.0.1" -} diff --git a/packages/pkl/src/matrix.element/PklProject.deps.json b/packages/pkl/src/matrix.element/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/matrix.element/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/matrix.server/AppService.pkl b/packages/pkl/src/matrix.server/AppService.pkl deleted file mode 100644 index bd85c4962..000000000 --- a/packages/pkl/src/matrix.server/AppService.pkl +++ /dev/null @@ -1,35 +0,0 @@ -open module matrix.service.AppService - -id: String - -as_token: String - -hs_token: String - -namespaces: Namespaces - -sender_localpart: String - -url: String - -rate_limited: Boolean - -`de.sorunome.msc2409.push_ephemeral`: Boolean - -push_ephemeral: Boolean - -`org.matrix.msc3202`: Boolean - -class Namespaces { - rooms: Listing - - users: Listing - - aliases: Listing -} - -class Alias { - regex: String - - exclusive: Boolean -} diff --git a/packages/pkl/src/matrix.server/PklProject b/packages/pkl/src/matrix.server/PklProject deleted file mode 100644 index 97d019d80..000000000 --- a/packages/pkl/src/matrix.server/PklProject +++ /dev/null @@ -1,5 +0,0 @@ -amends "../basePklProject.pkl" - -package { - version = "0.0.2" -} diff --git a/packages/pkl/src/matrix.server/PklProject.deps.json b/packages/pkl/src/matrix.server/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/matrix.server/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/matrix.server/Synapse.pkl b/packages/pkl/src/matrix.server/Synapse.pkl deleted file mode 100644 index f8c99cb4d..000000000 --- a/packages/pkl/src/matrix.server/Synapse.pkl +++ /dev/null @@ -1,53 +0,0 @@ -open module matrix.synapse.Synapse - -server_name: String -pid_file: String -public_baseurl: String -extra_well_known_client_content: ExtraWellKnownClientContent -app_service_config_files: Listing -listeners: Listing -database: Database -log_config: String -enable_registration: Boolean -enable_registration_without_verification: Boolean -media_store_path: String -report_stats: Boolean -signing_key_path: String -trusted_key_servers: Listing - -class ExtraWellKnownClientContent { - `org.matrix.msc3575.proxy`: OrgMatrixMsc3575Proxy -} - -class OrgMatrixMsc3575Proxy { - url: String -} - -class Listener { - port: Number - tls: Boolean - type: String - x_forwarded: Boolean - resources: Listing -} - -class Resource { - names: Listing - compress: Boolean -} - -class Database { - name: String - args: Args -} - -class Args { - user: String - password: String - dbname: String - host: String -} - -class TrustedKeyServer { - server_name: String -} diff --git a/packages/pkl/src/sonr.testnet/Config.pkl b/packages/pkl/src/sonr.testnet/Config.pkl deleted file mode 100644 index 0dcca5428..000000000 --- a/packages/pkl/src/sonr.testnet/Config.pkl +++ /dev/null @@ -1,13 +0,0 @@ -module sonr.beam - -import "chain/app.pkl" as app -import "chain/client.pkl" as client -import "chain/config.pkl" as config - -output { - files { - ["config/app.toml"] = app.output - ["config/client.toml"] = client.output - ["config/config.toml"] = config.output - } -} diff --git a/packages/pkl/src/sonr.testnet/PklProject b/packages/pkl/src/sonr.testnet/PklProject deleted file mode 100644 index 61e26b651..000000000 --- a/packages/pkl/src/sonr.testnet/PklProject +++ /dev/null @@ -1,5 +0,0 @@ -amends "../basePklProject.pkl" - -package { - version = "0.0.1" -} diff --git a/packages/pkl/src/sonr.testnet/PklProject.deps.json b/packages/pkl/src/sonr.testnet/PklProject.deps.json deleted file mode 100644 index 9712574ff..000000000 --- a/packages/pkl/src/sonr.testnet/PklProject.deps.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "schemaVersion": 1, - "resolvedDependencies": {} -} diff --git a/packages/pkl/src/sonr.testnet/chain/app.pkl b/packages/pkl/src/sonr.testnet/chain/app.pkl deleted file mode 100644 index e27747f5b..000000000 --- a/packages/pkl/src/sonr.testnet/chain/app.pkl +++ /dev/null @@ -1,70 +0,0 @@ -extends "https://mod.pkl.sh/cosmos.chain/App.pkl" - -`minimum-gas-prices` = "0usnr" -`query-gas-limit` = "0" -`pruning-keep-recent` = "0" -`pruning-interval` = "0" -`halt-height` = 0 -`halt-time` = 0 -`min-retain-blocks` = 0 -`inter-block-cache` = true -`index-events` { -} -`iavl-cache-size` = 781250 -`iavl-disable-fastnode` = true -`app-db-backend` = "goleveldb" - -`grpc-web` { - enable = true -} - -`state-sync` { - `snapshot-interval` = 0 - `snapshot-keep-recent` = 2 -} - -pruning = "default" -telemetry { - `service-name` = "sonr-node" - enabled = false - `enable-hostname` = false - `enable-hostname-label` = true - `enable-service-label` = true - `prometheus-retention-time` = 0 - `global-labels` { - } - `metrics-sink` = "" - `statsd-addr` = "" - `datadog-hostname` = "" -} - -api { - enable = true - swagger = true - address = "tcp://0.0.0.0:1317" - `max-open-connections` = 1000 - `rpc-read-timeout` = 10 - `rpc-write-timeout` = 0 - `rpc-max-body-bytes` = 1000000 - `enabled-unsafe-cors` = false -} - -grpc { - enable = true - address = "0.0.0.0:9090" - `max-recv-msg-size` = "10485760" - `max-send-msg-size` = "2147483647" -} - -streaming { - abci { - keys { - } - plugin = "" - `stop-node-on-err` = true - } -} - -mempool { - `max-txs` = 5000 -} diff --git a/packages/pkl/src/sonr.testnet/chain/client.pkl b/packages/pkl/src/sonr.testnet/chain/client.pkl deleted file mode 100644 index 98cea8ff2..000000000 --- a/packages/pkl/src/sonr.testnet/chain/client.pkl +++ /dev/null @@ -1,7 +0,0 @@ -extends "https://mod.pkl.sh/cosmos.chain/Client.pkl" - -`chain-id` = "sonr-testnet-1" -`keyring-backend` = "test" -output = "text" -node = "tcp://localhost:26657" -`broadcast-mode` = "sync" diff --git a/packages/pkl/src/sonr.testnet/chain/config.pkl b/packages/pkl/src/sonr.testnet/chain/config.pkl deleted file mode 100644 index e04efd5b8..000000000 --- a/packages/pkl/src/sonr.testnet/chain/config.pkl +++ /dev/null @@ -1,139 +0,0 @@ -extends "https://mod.pkl.sh/cosmos.chain/Config.pkl" - -version = "v0.38.12" -proxy_app = "tcp://127.0.0.1:26658" -moniker = "florence" -db_backend = "goleveldb" -db_dir = "data" -log_level = "info" -log_format = "plain" -genesis_file = "config/genesis.json" -priv_validator_key_file = "config/priv_validator_key.json" -priv_validator_state_file = "data/priv_validator_state.json" -priv_validator_laddr = "" -node_key_file = "config/node_key.json" -abci = "socket" -filter_peers = false - -rpc { - laddr = "tcp://0.0.0.0:26657" - cors_allowed_origins {} - cors_allowed_methods { - "GET" - "POST" - "HEAD" - } - cors_allowed_headers { - "Accept" - "Accept-Encoding" - "Authorization" - "Origin" - "Content-Type" - "X-Requested-With" - "X-Server-Time" - } - grpc_laddr = "" - grpc_max_open_connections = 900 - unsafe = false - max_open_connections = 900 - max_subscription_clients = 100 - max_subscriptions_per_client = 5 - experimental_subscription_buffer_size = 200 - experimental_websocket_write_buffer_size = 200 - experimental_close_on_slow_client = false - timeout_broadcast_tx_commit = "10s" - max_request_batch_size = 10 - max_body_bytes = 1000000 - max_header_bytes = 1048576 - tls_cert_file = "" - tls_key_file = "" - pprof_laddr = "localhost:6060" -} - -p2p { - laddr = "tcp://0.0.0.0:26656" - external_address = "" - seeds = "" - persistent_peers = "" - addr_book_file = "config/addrbook.json" - addr_book_strict = true - max_num_inbound_peers = 40 - max_num_outbound_peers = 10 - unconditional_peer_ids = "" - persistent_peers_max_dial_period = "0s" - flush_throttle_timeout = "100ms" - max_packet_msg_payload_size = 1024 - send_rate = 5120000 - recv_rate = 5120000 - pex = true - seed_mode = false - private_peer_ids = "" - allow_duplicate_ip = false - handshake_timeout = "20s" - dial_timeout = "3s" -} - -mempool { - type = "flood" - recheck = true - recheck_timeout = "1s" - broadcast = true - wal_dir = "" - size = 5000 - max_txs_bytes = 1073741824 - cache_size = 10000 - `keep-invalid-txs-in-cache` = false - max_tx_bytes = 1048576 - max_batch_bytes = 0 - experimental_max_gossip_connections_to_persistent_peers = 0 - experimental_max_gossip_connections_to_non_persistent_peers = 0 -} - -statesync { - enable = false - rpc_servers = "" - trust_height = 0 - trust_hash = "" - trust_period = "168h0m0s" - discovery_time = "15s" - temp_dir = "" - chunk_request_timeout = "10s" - chunk_fetchers = "4" -} - -blocksync { - version = "v0" -} - -consensus { - wal_file = "data/cs.wal/wal" - timeout_propose = "3s" - timeout_propose_delta = "500ms" - timeout_prevote = "1s" - timeout_prevote_delta = "500ms" - timeout_precommit = "1s" - timeout_precommit_delta = "500ms" - timeout_commit = "5s" - double_sign_check_height = 0 - skip_timeout_commit = false - create_empty_blocks = true - create_empty_blocks_interval = "0s" - peer_gossip_sleep_duration = "100ms" - peer_query_maj23_sleep_duration = "2s" -} - -storage { - discard_abci_responses = false -} - -tx_index { - indexer = "kv" - `psql-conn` = "" -} - -instrumentation { - prometheus = false - prometheus_listen_addr = ":26660" - max_open_connections = 3 - namespace = "cometbft" -} diff --git a/packages/pkl/src/sonr.testnet/chain/genesis.pkl b/packages/pkl/src/sonr.testnet/chain/genesis.pkl deleted file mode 100644 index 7f1b647a1..000000000 --- a/packages/pkl/src/sonr.testnet/chain/genesis.pkl +++ /dev/null @@ -1,2 +0,0 @@ -extends "https://mod.pkl.sh/cosmos.chain/Genesis.pkl" - diff --git a/packages/sdk/.cz.toml b/packages/sdk/.cz.toml deleted file mode 100644 index 75a413939..000000000 --- a/packages/sdk/.cz.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "@sonr.io/sdk@v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "npm" -update_changelog_on_bump = true -major_version_zero = true -pre_bump_hooks = ["bash ../../scripts/hook-bump-pre.sh"] -post_bump_hooks = ["pnpm --filter '@sonr.io/sdk' publish --no-git-checks"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(pkg-sdk\\)(!)?:" diff --git a/packages/sdk/README.md b/packages/sdk/README.md deleted file mode 100644 index aa0c6db27..000000000 --- a/packages/sdk/README.md +++ /dev/null @@ -1,298 +0,0 @@ -# @sonr.io/sdk - -This is the TypeScript SDK for Highway WebAuthn authentication gateway. It provides a comprehensive client library for interacting with Highway APIs, including WebAuthn authentication, session management, and blockchain operations. - -## Features - -- **WebAuthn Client**: Complete WebAuthn registration and authentication flows -- **Session Management**: Automatic session handling and token management -- **Type Safety**: Full TypeScript support with comprehensive type definitions -- **HTTP Client**: Configured HTTP client with automatic retries and error handling -- **Blockchain Integration**: Client methods for DID and blockchain operations -- **Environment Support**: Configurable for development, staging, and production - -## Installation - -```bash -npm install @sonr.io/sdk -# or -yarn add @sonr.io/sdk -# or -pnpm add @sonr.io/sdk -``` - -## Usage - -### Basic Setup - -```typescript -import { HighwaySDK } from "@sonr.io/sdk"; - -const sdk = new HighwaySDK({ - apiUrl: "https://api.yourdomain.com", - environment: "production", -}); -``` - -### WebAuthn Authentication - -```typescript -// Register a new user -try { - const registrationResult = await sdk.auth.register({ - username: "user@example.com", - displayName: "John Doe", - }); - - console.log("Registration successful:", registrationResult); -} catch (error) { - console.error("Registration failed:", error); -} - -// Authenticate existing user -try { - const authResult = await sdk.auth.authenticate({ - username: "user@example.com", - }); - - console.log("Authentication successful:", authResult); -} catch (error) { - console.error("Authentication failed:", error); -} -``` - -### Session Management - -```typescript -// Get current session -const session = await sdk.session.getCurrent(); - -// Validate session -const isValid = await sdk.session.validate(); - -// Logout -await sdk.session.logout(); -``` - -### Blockchain Operations - -```typescript -// Create DID -const didResult = await sdk.blockchain.createDID({ - username: "user@example.com", - credentialId: "webauthn-credential-id", - publicKey: "public-key-data", -}); - -// Resolve DID -const didDocument = await sdk.blockchain.resolveDID("did:sonr:123456789"); -``` - -## API Reference - -### HighwaySDK - -The main SDK class that provides access to all Highway services. - -#### Constructor Options - -```typescript -interface HighwaySDKOptions { - apiUrl: string; - environment?: "development" | "staging" | "production"; - timeout?: number; - retries?: number; -} -``` - -#### Methods - -- `auth`: WebAuthn authentication methods -- `session`: Session management methods -- `blockchain`: Blockchain and DID operations -- `profile`: User profile management - -### Authentication (`sdk.auth`) - -- `register(options)`: Register new WebAuthn credential -- `authenticate(options)`: Authenticate with WebAuthn -- `getProfile()`: Get current user profile - -### Session (`sdk.session`) - -- `getCurrent()`: Get current session information -- `validate()`: Validate current session -- `logout()`: End current session - -### Blockchain (`sdk.blockchain`) - -- `createDID(options)`: Create new DID document -- `resolveDID(id)`: Resolve DID document by ID -- `getHealth()`: Get blockchain service health - -## Development Roadmap - -### 🔮 **Future Implementation** (Planned) - -- [ ] **SDK Core**: TypeScript SDK with HTTP client configuration -- [ ] **Authentication Module**: WebAuthn registration and authentication methods -- [ ] **Session Management**: Automatic session handling and token management -- [ ] **Blockchain Module**: DID creation and resolution methods -- [ ] **Profile Management**: User profile operations and management -- [ ] **Type Definitions**: Comprehensive TypeScript type definitions -- [ ] **Error Handling**: Robust error handling and retry logic - -### 🚧 **Production Readiness** (Next) - -- [ ] **Testing Suite**: Unit tests for all SDK methods -- [ ] **Documentation**: Complete API documentation and examples -- [ ] **Performance Optimization**: Request caching and optimization -- [ ] **Bundle Optimization**: Tree-shaking and minimal bundle size -- [ ] **Browser Support**: Cross-browser compatibility testing -- [ ] **Node.js Support**: Server-side usage support - -### 🔮 **Future Enhancements** - -- [ ] **React Hooks**: React hooks for easy integration -- [ ] **Vue Composables**: Vue.js composables for Vue applications -- [ ] **Offline Support**: Offline capability with background sync -- [ ] **Real-time Features**: WebSocket support for real-time updates -- [ ] **Advanced Caching**: Intelligent caching strategies -- [ ] **Plugin System**: Extensible plugin architecture - -## Error Handling - -The SDK provides comprehensive error handling: - -```typescript -import { HighwayError, WebAuthnError, SessionError } from "@sonr.io/sdk"; - -try { - await sdk.auth.register(options); -} catch (error) { - if (error instanceof WebAuthnError) { - console.error("WebAuthn error:", error.message); - } else if (error instanceof SessionError) { - console.error("Session error:", error.message); - } else if (error instanceof HighwayError) { - console.error("Highway error:", error.message); - } -} -``` - -## Configuration - -### Environment Variables - -```env -# Default API URL -HIGHWAY_API_URL=https://api.yourdomain.com - -# Development -HIGHWAY_API_URL=http://localhost:8080 -``` - -### SDK Configuration - -```typescript -const sdk = new HighwaySDK({ - apiUrl: process.env.HIGHWAY_API_URL || "https://api.yourdomain.com", - environment: process.env.NODE_ENV || "production", - timeout: 10000, - retries: 3, -}); -``` - -## Development - -```bash -# Install dependencies -pnpm install - -# Build the SDK -pnpm build - -# Run tests -pnpm test - -# Run tests in watch mode -pnpm test:watch -``` - -## Integration Examples - -### React Application - -```typescript -import { HighwaySDK } from "@sonr.io/sdk"; -import { useEffect, useState } from "react"; - -function useHighway() { - const [sdk] = useState( - () => - new HighwaySDK({ - apiUrl: process.env.NEXT_PUBLIC_API_URL!, - }) - ); - - return sdk; -} - -function AuthComponent() { - const sdk = useHighway(); - - const handleRegister = async () => { - try { - await sdk.auth.register({ - username: "user@example.com", - displayName: "John Doe", - }); - } catch (error) { - console.error("Registration failed:", error); - } - }; - - return ; -} -``` - -### Node.js Application - -```typescript -import { HighwaySDK } from "@sonr.io/sdk"; - -const sdk = new HighwaySDK({ - apiUrl: "https://api.yourdomain.com", - environment: "production", -}); - -async function createUser() { - try { - const result = await sdk.auth.register({ - username: "user@example.com", - displayName: "John Doe", - }); - - console.log("User created:", result); - } catch (error) { - console.error("Failed to create user:", error); - } -} -``` - -## Dependencies - -- **TypeScript**: ^5.3.0 -- **Axios**: ^1.6.0 (HTTP client) -- **Zod**: ^3.22.0 (Schema validation) -- **@simplewebauthn/browser**: ^9.0.0 (WebAuthn client) - -## Contributing - -When contributing to the SDK: - -1. Follow TypeScript best practices -2. Add comprehensive type definitions -3. Include unit tests for new features -4. Update documentation and examples -5. Ensure backward compatibility diff --git a/packages/sdk/package.json b/packages/sdk/package.json deleted file mode 100644 index 95ee1bba9..000000000 --- a/packages/sdk/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "@sonr.io/sdk", - "version": "0.0.11", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "type": "module", - "publishConfig": { - "access": "public" - }, - "files": [ - "dist", - "src" - ], - "scripts": { - "build": "tsc && tsc-alias", - "dev": "concurrently \"tsc -w\" \"tsc-alias -w\"", - "clean": "rm -rf dist", - "test": "echo 'No tests defined for @sonr.io/sdk'", - "lint": "biome check .", - "format": "biome format . --write", - "typecheck": "tsc --noEmit", - "prepublishOnly": "pnpm build", - "release": "cz --no-raise 6,21 bump --yes --increment PATCH" - }, - "dependencies": { - "@simplewebauthn/browser": "^10.0.0", - "@simplewebauthn/types": "^10.0.0", - "@sonr.io/es": "workspace:*" - }, - "devDependencies": { - "@types/node": "^20.12.2", - "concurrently": "^8.0.1", - "rimraf": "^5.0.0", - "tsc-alias": "^1.8.6", - "typescript": "^5.3.3", - "vitest": "^1.3.0" - } -} diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts deleted file mode 100644 index f18d75bdd..000000000 --- a/packages/sdk/src/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export class HighwaySDK { - private apiUrl: string; - - constructor(config: { apiUrl?: string } = {}) { - this.apiUrl = config.apiUrl || 'https://api.highway.sonr.io'; - } - - async health(): Promise { - const response = await fetch(`${this.apiUrl}/health`); - return response.json(); - } -} - -export default HighwaySDK; - -// Export WebAuthn module -export * from './webauthn'; diff --git a/packages/sdk/src/webauthn/client.ts b/packages/sdk/src/webauthn/client.ts deleted file mode 100644 index 7023f743f..000000000 --- a/packages/sdk/src/webauthn/client.ts +++ /dev/null @@ -1,318 +0,0 @@ -/** - * WebAuthn client for Sonr SDK - */ - -import { - startAuthentication, - startRegistration, -} from '@simplewebauthn/browser'; -import type { - PublicKeyCredentialCreationOptionsJSON, - PublicKeyCredentialRequestOptionsJSON, - RegistrationResponseJSON, - AuthenticationResponseJSON, -} from '@simplewebauthn/types'; - -import type { - WebAuthnRegistrationOptions, - WebAuthnAuthenticationOptions, - WebAuthnRegistrationResult, - WebAuthnAuthenticationResult, - RegisterStartRequest, - RegisterStartResponse, - DIDDocument, - DIDDocumentMetadata, -} from './types'; - -export class WebAuthnClient { - private apiUrl: string; - private origin: string; - - constructor(apiUrl: string, origin?: string) { - this.apiUrl = apiUrl; - this.origin = origin || 'http://localhost:3000'; - } - - /** - * Register a new user with WebAuthn - */ - async register(options: WebAuthnRegistrationOptions): Promise { - try { - // Step 1: Call RegisterStart query to get WebAuthn options - const startRequest: RegisterStartRequest = { - assertion_value: options.email || options.tel || options.username, - assertion_type: options.email ? 'email' : options.tel ? 'tel' : 'username', - service_origin: options.origin || this.origin, - }; - - const startResponse = await this.callRegisterStart(startRequest); - - // Step 2: Create WebAuthn credential creation options - const creationOptions: PublicKeyCredentialCreationOptionsJSON = { - challenge: startResponse.challenge, - rp: startResponse.rp, - user: { - id: startResponse.user.id, - name: options.username, - displayName: options.displayName || options.username, - }, - pubKeyCredParams: (startResponse.pubKeyCredParams as PublicKeyCredentialCreationOptionsJSON['pubKeyCredParams']) || [ - { type: 'public-key' as const, alg: -7 }, // ES256 - { type: 'public-key' as const, alg: -257 }, // RS256 - ], - timeout: startResponse.timeout || 60000, - attestation: startResponse.attestation || 'direct', - authenticatorSelection: startResponse.authenticatorSelection || { - authenticatorAttachment: 'platform', - requireResidentKey: false, - residentKey: 'preferred', - userVerification: 'preferred', - }, - }; - - // Step 3: Start WebAuthn registration ceremony - const credential = await startRegistration(creationOptions); - - // Step 4: Submit registration to blockchain - const result = await this.submitRegistration({ - ...options, - credential, - challenge: startResponse.challenge, - }); - - return result; - } catch (error) { - console.error('WebAuthn registration error:', error); - return { - success: false, - error: error instanceof Error ? error.message : 'Registration failed', - }; - } - } - - /** - * Authenticate a user with WebAuthn - */ - async authenticate(options: WebAuthnAuthenticationOptions): Promise { - try { - // Step 1: Get authentication options from the server - const authOptions = await this.getAuthenticationOptions(options.username); - - // Step 2: Create WebAuthn authentication options - const requestOptions: PublicKeyCredentialRequestOptionsJSON = { - challenge: authOptions.challenge, - rpId: authOptions.rpId, - timeout: authOptions.timeout || 60000, - userVerification: authOptions.userVerification || 'preferred', - allowCredentials: authOptions.allowCredentials, - }; - - // Step 3: Start WebAuthn authentication ceremony - const credential = await startAuthentication(requestOptions); - - // Step 4: Verify authentication with the server - const result = await this.verifyAuthentication({ - username: options.username, - credential, - challenge: authOptions.challenge, - }); - - return result; - } catch (error) { - console.error('WebAuthn authentication error:', error); - return { - success: false, - error: error instanceof Error ? error.message : 'Authentication failed', - }; - } - } - - /** - * Call RegisterStart query - */ - private async callRegisterStart(request: RegisterStartRequest): Promise { - const response = await fetch(`${this.apiUrl}/did/v1/register/start`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request), - }); - - if (!response.ok) { - const error = await response.json().catch(() => ({ error: 'RegisterStart failed' })) as { error: string }; - throw new Error(error.error || 'RegisterStart failed'); - } - - const data = await response.json() as any; - - // Transform the response to match WebAuthn options format - return { - challenge: data.challenge || this.generateChallenge(), - rp: { - id: data.rp?.id || new URL(this.origin).hostname, - name: data.rp?.name || 'Sonr Network', - }, - user: { - id: data.user?.id || this.generateUserId(), - name: data.user?.name || request.assertion_value, - displayName: data.user?.displayName || request.assertion_value, - }, - pubKeyCredParams: data.pubKeyCredParams || [ - { type: 'public-key' as const, alg: -7 }, // ES256 - { type: 'public-key' as const, alg: -257 }, // RS256 - ], - timeout: data.timeout, - attestation: data.attestation, - authenticatorSelection: data.authenticatorSelection, - }; - } - - /** - * Submit registration to blockchain - */ - private async submitRegistration(data: { - username: string; - email?: string; - tel?: string; - createVault?: boolean; - credential: RegistrationResponseJSON; - challenge: string; - }): Promise { - const response = await fetch(`${this.apiUrl}/did/v1/tx/register-webauthn-credential`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - username: data.username, - assertion_value: data.email || data.tel || data.username, - assertion_type: data.email ? 'email' : data.tel ? 'tel' : 'username', - webauthn_credential: { - credential_id: data.credential.id, - public_key: data.credential.response.publicKey, - attestation_object: data.credential.response.attestationObject, - client_data_json: data.credential.response.clientDataJSON, - authenticator_attachment: data.credential.authenticatorAttachment, - }, - create_vault: data.createVault ?? true, - challenge: data.challenge, - }), - }); - - if (!response.ok) { - const error = await response.json().catch(() => ({ error: 'Registration submission failed' })) as { error: string }; - throw new Error(error.error || 'Registration submission failed'); - } - - const result = await response.json() as any; - return { - success: true, - did: result.did, - vaultId: result.vault_id, - credential: result.credential, - ucanToken: result.ucan_token, - }; - } - - /** - * Get authentication options - */ - private async getAuthenticationOptions(username: string): Promise { - const response = await fetch(`${this.apiUrl}/did/v1/login/start`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ username }), - }); - - if (!response.ok) { - const error = await response.json().catch(() => ({ error: 'Failed to get authentication options' })) as { error: string }; - throw new Error(error.error || 'Failed to get authentication options'); - } - - return response.json(); - } - - /** - * Verify authentication - */ - private async verifyAuthentication(data: { - username: string; - credential: AuthenticationResponseJSON; - challenge: string; - }): Promise { - const response = await fetch(`${this.apiUrl}/did/v1/login/finish`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - username: data.username, - credential: data.credential, - challenge: data.challenge, - }), - }); - - if (!response.ok) { - const error = await response.json().catch(() => ({ error: 'Authentication verification failed' })) as { error: string }; - throw new Error(error.error || 'Authentication verification failed'); - } - - const result = await response.json() as any; - return { - success: true, - did: result.did, - vaultId: result.vault_id, - sessionToken: result.session_token, - }; - } - - /** - * Get DID document - */ - async getDIDDocument(did: string): Promise<{ document: DIDDocument; metadata: DIDDocumentMetadata }> { - const response = await fetch(`${this.apiUrl}/did/v1/document/${did}`, { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - const error = await response.json().catch(() => ({ error: 'Failed to get DID document' })) as { error: string }; - throw new Error(error.error || 'Failed to get DID document'); - } - - const data = await response.json() as { did_document: DIDDocument; did_document_metadata: DIDDocumentMetadata }; - return { - document: data.did_document, - metadata: data.did_document_metadata, - }; - } - - /** - * Generate a random challenge - */ - private generateChallenge(): string { - const array = new Uint8Array(32); - crypto.getRandomValues(array); - return btoa(String.fromCharCode(...array)) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); - } - - /** - * Generate a random user ID - */ - private generateUserId(): string { - const array = new Uint8Array(16); - crypto.getRandomValues(array); - return btoa(String.fromCharCode(...array)) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); - } -} \ No newline at end of file diff --git a/packages/sdk/src/webauthn/index.ts b/packages/sdk/src/webauthn/index.ts deleted file mode 100644 index 20aee84bf..000000000 --- a/packages/sdk/src/webauthn/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * WebAuthn module exports - */ - -export { WebAuthnClient } from './client'; -export * from './types'; \ No newline at end of file diff --git a/packages/sdk/src/webauthn/types.ts b/packages/sdk/src/webauthn/types.ts deleted file mode 100644 index ca12e8293..000000000 --- a/packages/sdk/src/webauthn/types.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** - * WebAuthn types for Sonr SDK - */ - -export interface WebAuthnRegistrationOptions { - username: string; - displayName?: string; - email?: string; - tel?: string; - createVault?: boolean; - origin?: string; -} - -export interface WebAuthnAuthenticationOptions { - username: string; - origin?: string; -} - -export interface WebAuthnCredential { - id: string; - rawId: string; - type: string; - publicKey: string; - counter: number; - createdAt: string; -} - -export interface RegisterStartRequest { - assertion_value: string; - assertion_type: 'email' | 'tel' | 'username'; - service_origin: string; -} - -export interface RegisterStartResponse { - challenge: string; - rp: { - id: string; - name: string; - }; - user: { - id: string; - name: string; - displayName: string; - }; - pubKeyCredParams: Array<{ - type: string; - alg: number; - }>; - timeout?: number; - attestation?: AttestationConveyancePreference; - authenticatorSelection?: AuthenticatorSelectionCriteria; -} - -export interface AuthenticatorSelectionCriteria { - authenticatorAttachment?: AuthenticatorAttachment; - requireResidentKey?: boolean; - residentKey?: ResidentKeyRequirement; - userVerification?: UserVerificationRequirement; -} - -export type AuthenticatorAttachment = 'platform' | 'cross-platform'; -export type ResidentKeyRequirement = 'discouraged' | 'preferred' | 'required'; -export type UserVerificationRequirement = 'required' | 'preferred' | 'discouraged'; -export type AttestationConveyancePreference = 'none' | 'indirect' | 'direct' | 'enterprise'; - -export interface WebAuthnRegistrationResult { - success: boolean; - did?: string; - vaultId?: string; - credential?: WebAuthnCredential; - ucanToken?: string; - error?: string; -} - -export interface WebAuthnAuthenticationResult { - success: boolean; - did?: string; - vaultId?: string; - sessionToken?: string; - error?: string; -} - -export interface DIDDocument { - id: string; - controller: string[]; - verificationMethod?: VerificationMethod[]; - authentication?: Array; - assertionMethod?: Array; - keyAgreement?: Array; - capabilityInvocation?: Array; - capabilityDelegation?: Array; - service?: ServiceEndpoint[]; -} - -export interface VerificationMethod { - id: string; - type: string; - controller: string; - publicKeyBase58?: string; - publicKeyBase64?: string; - publicKeyJwk?: any; // JsonWebKey interface from Web Crypto API - publicKeyMultibase?: string; -} - -export interface ServiceEndpoint { - id: string; - type: string | string[]; - serviceEndpoint: string | string[] | Record; -} - -export interface DIDDocumentMetadata { - created?: string; - updated?: string; - deactivated?: boolean; - versionId?: string; - nextUpdate?: string; - nextVersionId?: string; - equivalentId?: string[]; - canonicalId?: string; - ucanDelegationChain?: string; -} \ No newline at end of file diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json deleted file mode 100644 index fba7fe0a0..000000000 --- a/packages/sdk/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "target": "ES2022", - "lib": ["ES2022"], - "module": "ESNext", - "moduleResolution": "bundler", - "outDir": "./dist", - "rootDir": "./src", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "allowJs": true, - "declaration": true, - "declarationMap": true, - "isolatedModules": true, - "noEmit": false, - "composite": true - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "test"] -} diff --git a/packages/ui/.cz.toml b/packages/ui/.cz.toml deleted file mode 100644 index 31985db19..000000000 --- a/packages/ui/.cz.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.commitizen] -name = "cz_customize" -tag_format = "@sonr.io/ui@v$version" -ignored_tag_formats = ["*/v${version}", "v${version}"] -version_scheme = "semver" -version_provider = "npm" -update_changelog_on_bump = true -major_version_zero = true -pre_bump_hooks = ["bash ../../scripts/hook-bump-pre.sh"] -post_bump_hooks = ["pnpm --filter '@sonr.io/ui' publish --no-git-checks"] - -[tool.commitizen.customize] -bump_pattern = "^(feat|fix|refactor|perf|BREAKING CHANGE)" -bump_map = { "BREAKING CHANGE" = "MAJOR", "feat" = "MINOR", "fix" = "PATCH", "refactor" = "PATCH", "perf" = "PATCH" } -default_bump = "PATCH" -changelog_pattern = "^(feat|fix|refactor|docs|build)\\(pkg-ui\\)(!)?:" diff --git a/packages/ui/README.md b/packages/ui/README.md deleted file mode 100644 index 301b15710..000000000 --- a/packages/ui/README.md +++ /dev/null @@ -1,168 +0,0 @@ -# @sonr.io/ui - -Centralized UI component library for the Sonr ecosystem using shadcn/ui. - -## 🎨 Overview - -This package provides a fully centralized component library following shadcn/ui patterns. All UI components, styles, and utilities are managed exclusively in this package and imported by web applications. No components are duplicated in individual apps. - -## 📦 Installation - -The package is already configured in the monorepo. Web applications import components directly: - -```tsx -import { Button, Alert, Input } from "@sonr.io/ui"; -import { cn } from "@sonr.io/ui"; -``` - -## 🚀 Adding New Components - -**All components are managed centrally in this package.** To add new shadcn components: - -```bash -# Navigate to the UI package (REQUIRED) -cd packages/ui - -# Add a new component using shadcn CLI -npx shadcn@latest add dialog - -# The component will be added to src/components/ui/ -``` - -⚠️ **Important**: Never run `npx shadcn add` from web application directories. All components must be added here. - -## 📁 Structure - -``` -packages/ui/ -├── src/ -│ ├── components/ -│ │ ├── ui/ # shadcn components (managed by CLI) -│ │ │ ├── button.tsx -│ │ │ ├── input.tsx -│ │ │ └── alert.tsx -│ │ └── index.ts # Main exports -│ ├── lib/ -│ │ └── utils.ts # cn utility function -│ └── styles/ -│ └── globals.css # Theme and CSS variables -├── components.json # shadcn CLI configuration -├── tailwind.config.js # Tailwind configuration -└── README.md # This file -``` - -## 🎨 Theming - -The primary brand color is `#17c2ff` (cyan). All theme variables are defined in `src/styles/globals.css`: - -- **Light mode**: CSS variables under `:root` -- **Dark mode**: CSS variables under `.dark` -- **Primary color**: HSL(195, 100%, 54%) - -## 💻 Usage in Applications - -### 1. Import Global Styles - -In your app's `globals.css`: - -```css -@import "@sonr.io/ui/styles/globals.css"; - -/* App-specific styles below if needed */ -``` - -### 2. Import Components - -```tsx -import { Button, Input, Alert, AlertTitle, AlertDescription } from "@sonr.io/ui"; -import { cn } from "@sonr.io/ui"; - -export function MyComponent() { - return ( -
- - - - - - Success! - Your action was completed. - -
- ); -} -``` - -## 🧩 Available Components - -### Core Components (shadcn/ui) - -- **Button**: Multiple variants (default, destructive, outline, secondary, ghost, link) -- **Input**: Styled form input with full accessibility -- **Alert**: Alert messages with title and description support -- **Card**: Container with header, content, and footer sections - -### Utility Functions - -- **cn()**: Class name utility for merging Tailwind classes - -## 🛠️ Development - -```bash -# Install dependencies -pnpm install - -# Lint the package -pnpm lint - -# Type check -pnpm exec tsc --noEmit - -# Add new shadcn component -npx shadcn@latest add [component-name] -``` - -## 📋 Centralized Workflow - -This monorepo follows a **fully centralized** UI component strategy: - -1. ✅ **Single Source of Truth**: All UI components live only in `packages/ui` -2. ✅ **No Duplication**: Web apps do not have their own UI components -3. ✅ **Consistent Theming**: All apps share the exact same theme -4. ✅ **Simplified Maintenance**: Update once, affects all apps -5. ✅ **shadcn CLI Management**: Run all shadcn commands from `packages/ui` only - -## ⚠️ Important Guidelines - -- **Never** create components.json in web applications -- **Never** run `npx shadcn add` from app directories -- **Always** add new components from the `packages/ui` directory -- **Always** export new components from `src/components/index.ts` - -## 🔄 Migration from Distributed to Centralized - -If migrating from a distributed component structure: - -1. Remove any `components.json` files from web apps -2. Delete any shadcn components from app directories -3. Update imports to use `@sonr.io/ui` -4. Import global styles from the UI package - -## 📝 Component Addition Checklist - -When adding a new shadcn component: - -- [ ] Navigate to `packages/ui` directory -- [ ] Run `npx shadcn@latest add [component]` -- [ ] Export component from `src/components/index.ts` -- [ ] Test import in a web application -- [ ] Update this README with the new component - -## 🚀 Future Enhancements - -- [ ] Storybook for component documentation -- [ ] Unit tests for all components -- [ ] Additional shadcn components as needed -- [ ] Custom Sonr-specific components \ No newline at end of file diff --git a/packages/ui/components.json b/packages/ui/components.json deleted file mode 100644 index 90e25f5fd..000000000 --- a/packages/ui/components.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "default", - "rsc": true, - "tsx": true, - "tailwind": { - "config": "tailwind.config.js", - "css": "src/styles/globals.css", - "baseColor": "slate", - "cssVariables": true, - "prefix": "" - }, - "aliases": { - "components": "@sonr.io/ui/components", - "utils": "@sonr.io/ui/lib/utils", - "ui": "@sonr.io/ui/components", - "hooks": "@sonr.io/ui/hooks", - "lib": "@sonr.io/ui/lib" - }, - "iconLibrary": "lucide-react" -} diff --git a/packages/ui/package.json b/packages/ui/package.json deleted file mode 100644 index fa086dd3b..000000000 --- a/packages/ui/package.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "name": "@sonr.io/ui", - "version": "0.0.10", - "private": true, - "main": "src/components/index.ts", - "types": "src/components/index.ts", - "exports": { - ".": "./src/components/index.ts", - "./components": "./src/components/index.ts", - "./components/*": "./src/components/*.tsx", - "./components/ui/*": "./src/components/ui/*.tsx", - "./components/dashboard/*": "./src/components/dashboard/*.tsx", - "./lib/utils": "./src/lib/utils.ts", - "./lib/*": "./src/lib/*.ts", - "./hooks": "./src/hooks/index.ts", - "./hooks/*": "./src/hooks/*.ts", - "./styles/*": "./src/styles/*" - }, - "publishConfig": { - "access": "public" - }, - "scripts": { - "build": "tsc --noEmit", - "build:ui": "tsc --noEmit", - "dev": "tsc --noEmit --watch", - "clean": "rm -rf dist", - "test": "echo 'No tests defined for @sonr.io/ui'", - "lint": "biome lint .", - "format": "biome format . --write", - "check": "biome check .", - "typecheck": "tsc --noEmit", - "release": "cz --no-raise 6,21 bump --yes --increment PATCH" - }, - "peerDependencies": { - "react": "^18.2.0", - "react-dom": "^18.2.0" - }, - "dependencies": { - "@radix-ui/react-checkbox": "^1.3.3", - "@radix-ui/react-collapsible": "^1.1.12", - "@radix-ui/react-dialog": "^1.1.15", - "@radix-ui/react-dropdown-menu": "^2.1.16", - "@radix-ui/react-label": "^2.1.7", - "@radix-ui/react-popover": "^1.1.15", - "@radix-ui/react-progress": "^1.1.7", - "@radix-ui/react-select": "^2.2.6", - "@radix-ui/react-separator": "^1.1.7", - "@radix-ui/react-slot": "^1.2.3", - "@radix-ui/react-tabs": "^1.1.13", - "@radix-ui/react-toggle": "^1.1.10", - "@radix-ui/react-tooltip": "^1.2.8", - "@react-three/fiber": "^9.3.0", - "@sonr.io/com": "workspace:*", - "@types/three": "^0.180.0", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "cmdk": "^1.1.1", - "date-fns": "^4.1.0", - "framer-motion": "^12.23.12", - "lucide-react": "^0.263.1", - "next": "14.2.32", - "react-day-picker": "^9.9.0", - "react-hook-form": "^7.62.0", - "recharts": "^3.1.2", - "tailwind-merge": "^2.5.4", - "three": "^0.180.0", - "zod": "^4.1.5" - }, - "devDependencies": { - "@biomejs/biome": "^2.1.2", - "@types/react": "^18.3.23", - "@types/react-dom": "^19.1.9", - "concurrently": "^8.0.1", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "tailwindcss": "^3.4.17", - "tailwindcss-animate": "^1.0.7", - "tsc-alias": "^1.8.6", - "typescript": "^5.3.0" - } -} diff --git a/packages/ui/src/components/SignInWithSonr.tsx b/packages/ui/src/components/SignInWithSonr.tsx deleted file mode 100644 index 009bf58e3..000000000 --- a/packages/ui/src/components/SignInWithSonr.tsx +++ /dev/null @@ -1,268 +0,0 @@ -import { type VariantProps, cva } from 'class-variance-authority'; -import * as React from 'react'; -import { cn } from '../lib/utils'; - -export const signInButtonVariants = cva( - 'inline-flex items-center justify-center gap-3 rounded-lg font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50', - { - variants: { - variant: { - default: - 'bg-gradient-to-r from-purple-600 to-indigo-600 text-white hover:from-purple-700 hover:to-indigo-700 shadow-lg hover:shadow-xl', - outline: - 'border-2 border-purple-600 text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-950', - ghost: 'text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-950', - dark: 'bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200', - }, - size: { - default: 'h-12 px-6 text-base', - sm: 'h-10 px-4 text-sm', - lg: 'h-14 px-8 text-lg', - }, - }, - defaultVariants: { - variant: 'default', - size: 'default', - }, - } -); - -interface SignInWithSonrProps - extends React.ButtonHTMLAttributes, - VariantProps { - /** - * OAuth client ID for your application - */ - clientId: string; - /** - * OAuth redirect URI after authentication - */ - redirectUri: string; - /** - * OAuth scopes to request - */ - scopes?: string[]; - /** - * OAuth state parameter for CSRF protection - */ - state?: string; - /** - * Custom authorization endpoint URL - */ - authorizationUrl?: string; - /** - * Loading state - */ - isLoading?: boolean; - /** - * Custom text for the button - */ - text?: string; - /** - * Show Sonr logo - */ - showLogo?: boolean; - /** - * Callback when authorization starts - */ - onAuthStart?: () => void; - /** - * Callback on authorization error - */ - onAuthError?: (error: Error) => void; -} - -/** - * SignInWithSonr button component for OAuth authentication - */ -export const SignInWithSonr = React.forwardRef( - ( - { - className, - variant, - size, - clientId, - redirectUri, - scopes = ['openid', 'profile'], - state, - authorizationUrl = '/oauth2/authorize', - isLoading = false, - text = 'Sign in with Sonr', - showLogo = true, - onAuthStart, - onAuthError, - disabled, - onClick, - ...props - }, - ref - ) => { - const handleClick = React.useCallback( - async (e: React.MouseEvent) => { - e.preventDefault(); - - if (isLoading || disabled) { - return; - } - - // Call custom onClick if provided - if (onClick) { - onClick(e); - } - - // Call auth start callback - if (onAuthStart) { - onAuthStart(); - } - - try { - // Build OAuth authorization URL - const params = new URLSearchParams({ - response_type: 'code', - client_id: clientId, - redirect_uri: redirectUri, - scope: scopes.join(' '), - state: state || generateRandomState(), - }); - - // Add PKCE challenge for public clients - const codeVerifier = generateCodeVerifier(); - const codeChallenge = await generateCodeChallenge(codeVerifier); - - // Store code verifier in session storage - sessionStorage.setItem('sonr_oauth_code_verifier', codeVerifier); - - params.append('code_challenge', codeChallenge); - params.append('code_challenge_method', 'S256'); - - // Construct full authorization URL - const fullAuthUrl = `${authorizationUrl}?${params.toString()}`; - - // Redirect to authorization endpoint - window.location.href = fullAuthUrl; - } catch (error) { - if (onAuthError) { - onAuthError(error as Error); - } - console.error('Failed to initiate OAuth flow:', error); - } - }, - [ - clientId, - redirectUri, - scopes, - state, - authorizationUrl, - isLoading, - disabled, - onClick, - onAuthStart, - onAuthError, - ] - ); - - return ( - - ); - } -); - -SignInWithSonr.displayName = 'SignInWithSonr'; - -/** - * Sonr logo SVG component - */ -const SonrLogo = () => ( - - - - - -); - -/** - * Loading spinner component - */ -const LoadingSpinner = () => ( - - - - -); - -/** - * Generate random state for CSRF protection - */ -function generateRandomState(): string { - const array = new Uint8Array(32); - crypto.getRandomValues(array); - return btoa(String.fromCharCode(...array)) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); -} - -/** - * Generate PKCE code verifier - */ -function generateCodeVerifier(): string { - const array = new Uint8Array(32); - crypto.getRandomValues(array); - return btoa(String.fromCharCode(...array)) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); -} - -/** - * Generate PKCE code challenge from verifier - */ -async function generateCodeChallenge(verifier: string): Promise { - const encoder = new TextEncoder(); - const data = encoder.encode(verifier); - const digest = await crypto.subtle.digest('SHA-256', data); - return btoa(String.fromCharCode(...new Uint8Array(digest))) - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=/g, ''); -} - -export default SignInWithSonr; diff --git a/packages/ui/src/components/SignInWithSonrModal.tsx b/packages/ui/src/components/SignInWithSonrModal.tsx deleted file mode 100644 index 09ef6fec4..000000000 --- a/packages/ui/src/components/SignInWithSonrModal.tsx +++ /dev/null @@ -1,350 +0,0 @@ -import { X } from 'lucide-react'; -import * as React from 'react'; -import { cn } from '../lib/utils'; -import { SignInWithSonr } from './SignInWithSonr'; - -interface SignInWithSonrModalProps { - /** - * Whether the modal is open - */ - isOpen: boolean; - /** - * Callback when modal should close - */ - onClose: () => void; - /** - * OAuth client ID - */ - clientId: string; - /** - * OAuth redirect URI - */ - redirectUri: string; - /** - * OAuth scopes to request - */ - scopes?: string[]; - /** - * Modal title - */ - title?: string; - /** - * Modal description - */ - description?: string; - /** - * Show terms and privacy links - */ - showTerms?: boolean; - /** - * Terms URL - */ - termsUrl?: string; - /** - * Privacy URL - */ - privacyUrl?: string; - /** - * Custom authorization URL - */ - authorizationUrl?: string; - /** - * Additional content to show below the button - */ - children?: React.ReactNode; - /** - * Callback when auth starts - */ - onAuthStart?: () => void; - /** - * Callback on auth error - */ - onAuthError?: (error: Error) => void; -} - -/** - * Modal component for SignInWithSonr authentication - */ -export const SignInWithSonrModal: React.FC = ({ - isOpen, - onClose, - clientId, - redirectUri, - scopes = ['openid', 'profile'], - title = 'Sign in to continue', - description = 'Use your Sonr account to securely sign in', - showTerms = true, - termsUrl = '/terms', - privacyUrl = '/privacy', - authorizationUrl, - children, - onAuthStart, - onAuthError, -}) => { - const [isLoading, setIsLoading] = React.useState(false); - - // Handle escape key - React.useEffect(() => { - const handleEscape = (e: KeyboardEvent) => { - if (e.key === 'Escape' && isOpen) { - onClose(); - } - }; - - document.addEventListener('keydown', handleEscape); - return () => document.removeEventListener('keydown', handleEscape); - }, [isOpen, onClose]); - - // Prevent body scroll when modal is open - React.useEffect(() => { - if (isOpen) { - document.body.style.overflow = 'hidden'; - } else { - document.body.style.overflow = ''; - } - - return () => { - document.body.style.overflow = ''; - }; - }, [isOpen]); - - if (!isOpen) return null; - - const handleAuthStart = () => { - setIsLoading(true); - if (onAuthStart) { - onAuthStart(); - } - }; - - const handleAuthError = (error: Error) => { - setIsLoading(false); - if (onAuthError) { - onAuthError(error); - } - }; - - return ( - <> - {/* Backdrop */} -