├── .editorconfig ├── .github └── workflows │ ├── audit.yml │ ├── build.yml │ └── semver.yml ├── .gitignore ├── ARCH.md ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.toml ├── GLOSSARY.md ├── LICENSE-APACHE ├── LICENSE-MIT ├── LICENSE.md ├── README.md ├── SECURITY.md ├── bench ├── Cargo.toml ├── README.md └── benches │ └── bench.rs ├── ci ├── check-compiles.sh ├── check-each-commit.sh ├── check-lint.sh ├── ci-tests.sh └── ci-tx-sync-tests.sh ├── codecov.yml ├── contrib └── download_bitcoind_electrs.sh ├── ext-functional-test-demo ├── Cargo.toml └── src │ └── main.rs ├── fuzz ├── .gitignore ├── Cargo.toml ├── README.md ├── ci-fuzz.sh ├── src │ ├── base32.rs │ ├── bech32_parse.rs │ ├── bin │ │ ├── base32_target.rs │ │ ├── bech32_parse_target.rs │ │ ├── bolt11_deser_target.rs │ │ ├── chanmon_consistency_target.rs │ │ ├── chanmon_deser_target.rs │ │ ├── feature_flags_target.rs │ │ ├── fromstr_to_netaddress_target.rs │ │ ├── full_stack_target.rs │ │ ├── gen_target.sh │ │ ├── indexedmap_target.rs │ │ ├── invoice_deser_target.rs │ │ ├── invoice_request_deser_target.rs │ │ ├── lsps_message_target.rs │ │ ├── msg_accept_channel_target.rs │ │ ├── msg_accept_channel_v2_target.rs │ │ ├── msg_announcement_signatures_target.rs │ │ ├── msg_blinded_message_path_target.rs │ │ ├── msg_channel_announcement_target.rs │ │ ├── msg_channel_details_target.rs │ │ ├── msg_channel_ready_target.rs │ │ ├── msg_channel_reestablish_target.rs │ │ ├── msg_channel_update_target.rs │ │ ├── msg_closing_complete_target.rs │ │ ├── msg_closing_sig_target.rs │ │ ├── msg_closing_signed_target.rs │ │ ├── msg_commitment_signed_target.rs │ │ ├── msg_decoded_onion_error_packet_target.rs │ │ ├── msg_error_message_target.rs │ │ ├── msg_funding_created_target.rs │ │ ├── msg_funding_signed_target.rs │ │ ├── msg_gossip_timestamp_filter_target.rs │ │ ├── msg_init_target.rs │ │ ├── msg_node_announcement_target.rs │ │ ├── msg_open_channel_target.rs │ │ ├── msg_open_channel_v2_target.rs │ │ ├── msg_ping_target.rs │ │ ├── msg_pong_target.rs │ │ ├── msg_query_channel_range_target.rs │ │ ├── msg_query_short_channel_ids_target.rs │ │ ├── msg_reply_channel_range_target.rs │ │ ├── msg_reply_short_channel_ids_end_target.rs │ │ ├── msg_revoke_and_ack_target.rs │ │ ├── msg_shutdown_target.rs │ │ ├── msg_splice_ack_target.rs │ │ ├── msg_splice_init_target.rs │ │ ├── msg_splice_locked_target.rs │ │ ├── msg_stfu_target.rs │ │ ├── msg_tx_abort_target.rs │ │ ├── msg_tx_ack_rbf_target.rs │ │ ├── msg_tx_add_input_target.rs │ │ ├── msg_tx_add_output_target.rs │ │ ├── msg_tx_complete_target.rs │ │ ├── msg_tx_init_rbf_target.rs │ │ ├── msg_tx_remove_input_target.rs │ │ ├── msg_tx_remove_output_target.rs │ │ ├── msg_tx_signatures_target.rs │ │ ├── msg_update_add_htlc_target.rs │ │ ├── msg_update_fail_htlc_target.rs │ │ ├── msg_update_fail_malformed_htlc_target.rs │ │ ├── msg_update_fee_target.rs │ │ ├── msg_update_fulfill_htlc_target.rs │ │ ├── offer_deser_target.rs │ │ ├── onion_hop_data_target.rs │ │ ├── onion_message_target.rs │ │ ├── peer_crypt_target.rs │ │ ├── process_network_graph_target.rs │ │ ├── process_onion_failure_target.rs │ │ ├── refund_deser_target.rs │ │ ├── router_target.rs │ │ ├── target_template.txt │ │ └── zbase32_target.rs │ ├── bolt11_deser.rs │ ├── chanmon_consistency.rs │ ├── chanmon_deser.rs │ ├── feature_flags.rs │ ├── fromstr_to_netaddress.rs │ ├── full_stack.rs │ ├── indexedmap.rs │ ├── invoice_deser.rs │ ├── invoice_request_deser.rs │ ├── lib.rs │ ├── lsps_message.rs │ ├── msg_targets │ │ ├── gen_target.sh │ │ ├── mod.rs │ │ ├── msg_accept_channel.rs │ │ ├── msg_accept_channel_v2.rs │ │ ├── msg_announcement_signatures.rs │ │ ├── msg_blinded_message_path.rs │ │ ├── msg_channel_announcement.rs │ │ ├── msg_channel_details.rs │ │ ├── msg_channel_ready.rs │ │ ├── msg_channel_reestablish.rs │ │ ├── msg_channel_update.rs │ │ ├── msg_closing_complete.rs │ │ ├── msg_closing_sig.rs │ │ ├── msg_closing_signed.rs │ │ ├── msg_commitment_signed.rs │ │ ├── msg_decoded_onion_error_packet.rs │ │ ├── msg_error_message.rs │ │ ├── msg_funding_created.rs │ │ ├── msg_funding_signed.rs │ │ ├── msg_gossip_timestamp_filter.rs │ │ ├── msg_init.rs │ │ ├── msg_node_announcement.rs │ │ ├── msg_open_channel.rs │ │ ├── msg_open_channel_v2.rs │ │ ├── msg_ping.rs │ │ ├── msg_pong.rs │ │ ├── msg_query_channel_range.rs │ │ ├── msg_query_short_channel_ids.rs │ │ ├── msg_reply_channel_range.rs │ │ ├── msg_reply_short_channel_ids_end.rs │ │ ├── msg_revoke_and_ack.rs │ │ ├── msg_shutdown.rs │ │ ├── msg_splice_ack.rs │ │ ├── msg_splice_init.rs │ │ ├── msg_splice_locked.rs │ │ ├── msg_stfu.rs │ │ ├── msg_target_template.txt │ │ ├── msg_tx_abort.rs │ │ ├── msg_tx_ack_rbf.rs │ │ ├── msg_tx_add_input.rs │ │ ├── msg_tx_add_output.rs │ │ ├── msg_tx_complete.rs │ │ ├── msg_tx_init_rbf.rs │ │ ├── msg_tx_remove_input.rs │ │ ├── msg_tx_remove_output.rs │ │ ├── msg_tx_signatures.rs │ │ ├── msg_update_add_htlc.rs │ │ ├── msg_update_fail_htlc.rs │ │ ├── msg_update_fail_malformed_htlc.rs │ │ ├── msg_update_fee.rs │ │ ├── msg_update_fulfill_htlc.rs │ │ ├── msg_warning_message.rs │ │ └── utils.rs │ ├── offer_deser.rs │ ├── onion_hop_data.rs │ ├── onion_message.rs │ ├── peer_crypt.rs │ ├── process_network_graph.rs │ ├── process_onion_failure.rs │ ├── refund_deser.rs │ ├── router.rs │ ├── utils │ │ ├── mod.rs │ │ ├── test_logger.rs │ │ └── test_persister.rs │ └── zbase32.rs ├── targets.h └── write-seeds │ ├── Cargo.toml │ └── src │ └── main.rs ├── lightning-background-processor ├── Cargo.toml └── src │ └── lib.rs ├── lightning-block-sync ├── Cargo.toml └── src │ ├── convert.rs │ ├── gossip.rs │ ├── http.rs │ ├── init.rs │ ├── lib.rs │ ├── poll.rs │ ├── rest.rs │ ├── rpc.rs │ ├── test_utils.rs │ └── utils.rs ├── lightning-custom-message ├── Cargo.toml └── src │ └── lib.rs ├── lightning-dns-resolver ├── Cargo.toml └── src │ └── lib.rs ├── lightning-invoice ├── .gitignore ├── Cargo.toml ├── README.md ├── src │ ├── de.rs │ ├── lib.rs │ ├── ser.rs │ ├── tb.rs │ └── test_ser_de.rs └── tests │ └── ser_de.rs ├── lightning-liquidity ├── Cargo.toml ├── README.md ├── src │ ├── events │ │ ├── event_queue.rs │ │ └── mod.rs │ ├── lib.rs │ ├── lsps0 │ │ ├── client.rs │ │ ├── event.rs │ │ ├── mod.rs │ │ ├── msgs.rs │ │ ├── ser.rs │ │ └── service.rs │ ├── lsps1 │ │ ├── client.rs │ │ ├── event.rs │ │ ├── mod.rs │ │ ├── msgs.rs │ │ └── service.rs │ ├── lsps2 │ │ ├── client.rs │ │ ├── event.rs │ │ ├── mod.rs │ │ ├── msgs.rs │ │ ├── payment_queue.rs │ │ ├── service.rs │ │ └── utils.rs │ ├── manager.rs │ ├── message_queue.rs │ ├── sync │ │ ├── debug_sync.rs │ │ ├── fairrwlock.rs │ │ ├── mod.rs │ │ ├── nostd_sync.rs │ │ └── test_lockorder_checks.rs │ ├── tests │ │ ├── mod.rs │ │ └── utils.rs │ └── utils.rs └── tests │ ├── common │ └── mod.rs │ ├── lsps0_integration_tests.rs │ └── lsps2_integration_tests.rs ├── lightning-macros ├── Cargo.toml └── src │ └── lib.rs ├── lightning-net-tokio ├── Cargo.toml └── src │ └── lib.rs ├── lightning-persister ├── Cargo.toml └── src │ ├── fs_store.rs │ ├── lib.rs │ ├── test_utils.rs │ └── utils.rs ├── lightning-rapid-gossip-sync ├── Cargo.toml ├── README.md ├── res │ └── .gitignore └── src │ ├── lib.rs │ └── processing.rs ├── lightning-tests ├── Cargo.toml └── src │ ├── lib.rs │ └── upgrade_downgrade_tests.rs ├── lightning-transaction-sync ├── Cargo.toml ├── src │ ├── common.rs │ ├── electrum.rs │ ├── error.rs │ ├── esplora.rs │ └── lib.rs └── tests │ └── integration_tests.rs ├── lightning-types ├── Cargo.toml └── src │ ├── features.rs │ ├── lib.rs │ ├── payment.rs │ ├── routing.rs │ └── string.rs ├── lightning ├── Cargo.toml └── src │ ├── blinded_path │ ├── message.rs │ ├── mod.rs │ ├── payment.rs │ └── utils.rs │ ├── chain │ ├── chaininterface.rs │ ├── chainmonitor.rs │ ├── channelmonitor.rs │ ├── mod.rs │ ├── onchaintx.rs │ ├── package.rs │ └── transaction.rs │ ├── crypto │ ├── chacha20.rs │ ├── chacha20poly1305rfc.rs │ ├── mod.rs │ ├── poly1305.rs │ ├── streams.rs │ └── utils.rs │ ├── events │ ├── bump_transaction │ │ ├── mod.rs │ │ └── sync.rs │ └── mod.rs │ ├── io │ └── mod.rs │ ├── lib.rs │ ├── ln │ ├── async_payments_tests.rs │ ├── async_signer_tests.rs │ ├── blinded_payment_tests.rs │ ├── bolt11_payment_tests.rs │ ├── chan_utils.rs │ ├── chanmon_update_fail_tests.rs │ ├── channel.rs │ ├── channel_acceptance_tests.rs │ ├── channel_keys.rs │ ├── channel_state.rs │ ├── channel_type_tests.rs │ ├── channelmanager.rs │ ├── dual_funding_tests.rs │ ├── features.rs │ ├── functional_test_utils.rs │ ├── functional_tests.rs │ ├── htlc_reserve_unit_tests.rs │ ├── inbound_payment.rs │ ├── interactivetxs.rs │ ├── invoice_utils.rs │ ├── max_payment_path_len_tests.rs │ ├── mod.rs │ ├── monitor_tests.rs │ ├── msgs.rs │ ├── offers_tests.rs │ ├── onion_payment.rs │ ├── onion_route_tests.rs │ ├── onion_utils.rs │ ├── our_peer_storage.rs │ ├── outbound_payment.rs │ ├── payment_tests.rs │ ├── peer_channel_encryptor.rs │ ├── peer_handler.rs │ ├── priv_short_conf_tests.rs │ ├── quiescence_tests.rs │ ├── reload_tests.rs │ ├── reorg_tests.rs │ ├── script.rs │ ├── shutdown_tests.rs │ ├── splicing_tests.rs │ ├── types.rs │ ├── update_fee_tests.rs │ └── wire.rs │ ├── offers │ ├── async_receive_offer_cache.rs │ ├── flow.rs │ ├── invoice.rs │ ├── invoice_error.rs │ ├── invoice_macros.rs │ ├── invoice_request.rs │ ├── merkle.rs │ ├── mod.rs │ ├── nonce.rs │ ├── offer.rs │ ├── parse.rs │ ├── payer.rs │ ├── refund.rs │ ├── signer.rs │ ├── static_invoice.rs │ └── test_utils.rs │ ├── onion_message │ ├── async_payments.rs │ ├── dns_resolution.rs │ ├── functional_tests.rs │ ├── messenger.rs │ ├── mod.rs │ ├── offers.rs │ └── packet.rs │ ├── routing │ ├── gossip.rs │ ├── log_approx.rs │ ├── mod.rs │ ├── router.rs │ ├── scoring.rs │ ├── test_utils.rs │ └── utxo.rs │ ├── sign │ ├── ecdsa.rs │ ├── mod.rs │ ├── taproot.rs │ └── type_resolver.rs │ ├── sync │ ├── debug_sync.rs │ ├── fairrwlock.rs │ ├── mod.rs │ ├── nostd_sync.rs │ └── test_lockorder_checks.rs │ └── util │ ├── anchor_channel_reserves.rs │ ├── async_poll.rs │ ├── atomic_counter.rs │ ├── base32.rs │ ├── byte_utils.rs │ ├── config.rs │ ├── dyn_signer.rs │ ├── errors.rs │ ├── fuzz_wrappers.rs │ ├── hash_tables.rs │ ├── indexed_map.rs │ ├── logger.rs │ ├── macro_logger.rs │ ├── message_signing.rs │ ├── mod.rs │ ├── mut_global.rs │ ├── persist.rs │ ├── scid_utils.rs │ ├── ser.rs │ ├── ser_macros.rs │ ├── sweep.rs │ ├── test_channel_signer.rs │ ├── test_utils.rs │ ├── time.rs │ ├── transaction_utils.rs │ └── wakers.rs ├── msrv-no-dev-deps-check ├── Cargo.toml └── src │ └── lib.rs ├── no-std-check ├── Cargo.toml └── src │ └── lib.rs ├── pending_changelog ├── .empty_folder ├── 3137-accept-dual-funding-without-contributing.txt ├── 3531-buggy-router-leak.txt ├── 3604-upgrades-prior-to-113-not-supported.txt ├── 3638-0.2-upgrade-without-counterparty-node-id-in-monitor-not-supported.txt ├── 3664-downgrades-to-0.0.115-not-supported.txt ├── 3678-channel-type-check.txt └── 3700-reason-in-handling-failed.txt ├── possiblyrandom ├── Cargo.toml └── src │ └── lib.rs └── rustfmt.toml /.editorconfig: -------------------------------------------------------------------------------- 1 | # see https://editorconfig.org for more options, and setup instructions for your editor 2 | 3 | [*] 4 | indent_style = tab 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | -------------------------------------------------------------------------------- /.github/workflows/audit.yml: -------------------------------------------------------------------------------- 1 | name: Security Audit 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | - cron: '0 0 * * *' 6 | 7 | jobs: 8 | audit: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | issues: write 12 | checks: write 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: rustsec/audit-check@v1.4.1 16 | with: 17 | token: ${{ secrets.GITHUB_TOKEN }} 18 | ignore: "RUSTSEC-2021-0145" 19 | # RUSTSEC-2021-0145 pertains `atty`, which is a depencency of 20 | # `criterion`. While the latter removed the depencency in its 21 | # newest version, it would also require a higher `rustc`. We 22 | # therefore avoid bumping it to allow benchmarking with our 23 | # `rustc` 1.63 MSRV. 24 | -------------------------------------------------------------------------------- /.github/workflows/semver.yml: -------------------------------------------------------------------------------- 1 | name: SemVer checks 2 | on: 3 | push: 4 | branches-ignore: 5 | - master 6 | pull_request: 7 | branches-ignore: 8 | - master 9 | 10 | jobs: 11 | semver-checks: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout source code 15 | uses: actions/checkout@v4 16 | - name: Install Rust stable toolchain 17 | run: | 18 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile=minimal --default-toolchain stable 19 | rustup override set stable 20 | - name: Check SemVer with default features 21 | uses: obi1kenobi/cargo-semver-checks-action@v2 22 | with: 23 | feature-group: default-features 24 | - name: Check SemVer *without* default features 25 | uses: obi1kenobi/cargo-semver-checks-action@v2 26 | with: 27 | feature-group: only-explicit-features 28 | - name: Check lightning-background-processor SemVer 29 | uses: obi1kenobi/cargo-semver-checks-action@v2 30 | with: 31 | package: lightning-background-processor 32 | feature-group: only-explicit-features 33 | - name: Check lightning-block-sync SemVer 34 | uses: obi1kenobi/cargo-semver-checks-action@v2 35 | with: 36 | package: lightning-block-sync 37 | feature-group: only-explicit-features 38 | features: rpc-client,rest-client 39 | - name: Check lightning-transaction-sync electrum SemVer 40 | uses: obi1kenobi/cargo-semver-checks-action@v2 41 | with: 42 | manifest-path: lightning-transaction-sync/Cargo.toml 43 | feature-group: only-explicit-features 44 | features: electrum 45 | - name: Check lightning-transaction-sync esplora-blocking SemVer 46 | uses: obi1kenobi/cargo-semver-checks-action@v2 47 | with: 48 | manifest-path: lightning-transaction-sync/Cargo.toml 49 | feature-group: only-explicit-features 50 | features: esplora-blocking 51 | - name: Check lightning-transaction-sync esplora-async SemVer 52 | uses: obi1kenobi/cargo-semver-checks-action@v2 53 | with: 54 | manifest-path: lightning-transaction-sync/Cargo.toml 55 | feature-group: only-explicit-features 56 | features: esplora-async 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | c-bindings-gen/target/ 3 | lightning-c-bindings/target/ 4 | lightning-c-bindings/a.out 5 | /hfuzz_target/ 6 | /net-tokio/target/ 7 | **/*.rs.bk 8 | Cargo.lock 9 | .idea 10 | lightning/target 11 | lightning/net_graph-*.bin 12 | lightning-rapid-gossip-sync/res/full_graph.lngossip 13 | lightning-custom-message/target 14 | lightning-transaction-sync/target 15 | lightning-dns-resolver/target 16 | ext-functional-test-demo/target 17 | no-std-check/target 18 | msrv-no-dev-deps-check/target 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | 4 | # When the workspace members change, make sure to update the list here as well 5 | # as in `ci/ci-tests.sh`. 6 | members = [ 7 | "lightning", 8 | "lightning-types", 9 | "lightning-block-sync", 10 | "lightning-invoice", 11 | "lightning-net-tokio", 12 | "lightning-persister", 13 | "lightning-background-processor", 14 | "lightning-rapid-gossip-sync", 15 | "lightning-custom-message", 16 | "lightning-macros", 17 | "lightning-dns-resolver", 18 | "lightning-liquidity", 19 | "possiblyrandom", 20 | ] 21 | 22 | exclude = [ 23 | "lightning-transaction-sync", 24 | "lightning-tests", 25 | "ext-functional-test-demo", 26 | "no-std-check", 27 | "msrv-no-dev-deps-check", 28 | "bench", 29 | ] 30 | 31 | # Our tests do actual crypto and lots of work, the tradeoff for -O2 is well 32 | # worth it. Note that we only apply optimizations to dependencies, not workspace 33 | # crates themselves. 34 | # https://doc.rust-lang.org/cargo/reference/profiles.html#profile-selection 35 | [profile.dev.package."*"] 36 | opt-level = 2 37 | 38 | # It appears some minimal optimizations are required to inline many std methods 39 | # and reduce the otherwise-substantial time spent in std self-checks. We do so 40 | # here but ensure we keep LTO disabled as otherwise we're re-optimizing all our 41 | # dependencies every time we make any local changes. 42 | [profile.dev] 43 | opt-level = 1 44 | lto = "off" 45 | 46 | [profile.release] 47 | opt-level = 3 48 | lto = true 49 | panic = "abort" 50 | 51 | [workspace.lints.rust.unexpected_cfgs] 52 | level = "forbid" 53 | # When adding a new cfg attribute, ensure that it is added to this list. 54 | # 55 | # Note that Cargo automatically declares corresponding cfgs for every feature 56 | # defined in the member-level [features] tables as "expected". 57 | check-cfg = [ 58 | "cfg(fuzzing)", 59 | "cfg(secp256k1_fuzz)", 60 | "cfg(hashes_fuzz)", 61 | "cfg(test)", 62 | "cfg(debug_assertions)", 63 | "cfg(c_bindings)", 64 | "cfg(ldk_bench)", 65 | "cfg(ldk_test_vectors)", 66 | "cfg(taproot)", 67 | "cfg(require_route_graph_test)", 68 | "cfg(splicing)", 69 | "cfg(async_payments)", 70 | "cfg(simple_close)", 71 | ] 72 | -------------------------------------------------------------------------------- /GLOSSARY.md: -------------------------------------------------------------------------------- 1 | # Glossary 2 | 3 | This document gathers the canonical Lightning nomenclature used by LDK contributors. Note, they may diverge from the BOLT specs or the ones used by the wider Lightning community; the test of time has revealed that it can be hard to agree on terminology. The following terms are employed with a best effort across the codebase aiming to reduce confusion. 4 | 5 | ### Channel Initiator 6 | 7 | The channel initiator is the entity who is taking the decision to open a channel. Finalization relies upon the counterparty's channel acceptance policy. Within current protocol version, the initiator has the burden of paying channel onchain fees. 8 | 9 | ### Holder/Counterparty 10 | 11 | Inspired by financial cryptography, a holder is an owner of a given digital value. In Lightning, the holder is the entity operating the current node, of which the interests are served by the implementation during channel operations. The counterparty is the entity participating in the channel operation as a peer, but of whom the interests are not of concern by the implementation. 12 | 13 | Used across the `Channel` data structure, part of the channel-management subsystem. 14 | 15 | ### Broadcaster/Countersignatory 16 | 17 | In Lightning, states are symmetric but punishment is asymmetric, which forces channel parties to hold different commitment transactions. At transaction construction, the broadcaster designates the entity that has the unilateral capability to broadcast the transaction. The countersignatory is the entity providing signatures for the broadcastable transaction and thus verifying it encodes the off-chain states. At any point in time, there should be two "latest" commitment transactions that have been processed by each party's implementation, one where the holder is the broadcaster and the counterparty is countersignatory, and one where the holder is the countersignatory and the counterparty is the broadcaster. 18 | 19 | Used across the channel-utils library (`chan_utils.rs`). 20 | 21 | ### Watchtower 22 | 23 | A watchtower is an external untrusted service that can only publish justice transactions. The security property of watchtowers is that if you subscribe to *N* of them, you will be safe if at least 1 does the right thing. 24 | 25 | A (future) deployment configuration of the monitoring (`ChainMonitor`) subsystem. 26 | 27 | ### Monitor Replicas 28 | 29 | An instance of a highly available distributed channel-monitor. It must have a correctly working HSM, because they have sensitive keys that can cause loss of all funds in the channel. 30 | 31 | A deployment configuration of the monitoring (`ChainMonitor`) subsystem. 32 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy of 2 | this software and associated documentation files (the "Software"), to deal in 3 | the Software without restriction, including without limitation the rights to 4 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 5 | the Software, and to permit persons to whom the Software is furnished to do so, 6 | subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 13 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 14 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 15 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 16 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 17 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | This software is licensed under [Apache 2.0](LICENSE-APACHE) or 2 | [MIT](LICENSE-MIT), at your option. 3 | 4 | Some files retain their own copyright notice, however, for full authorship 5 | information, see version control history. 6 | 7 | Except as otherwise noted in individual files, all files in this repository are 8 | licensed under the Apache License, Version 2.0 or the MIT license , at your option. 11 | 12 | You may not use, copy, modify, merge, publish, distribute, sublicense, and/or 13 | sell copies of this software or any files in this repository except in 14 | accordance with one or both of these licenses. 15 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Please report security vulnerabilities, including denial-of-service 6 | vulnerabilities such as spurious panics, via email to 7 | security@lightningdevkit.org. 8 | 9 | If possible, please PGP-encrypt such emails to the following keys (available on 10 | keyservers and WKD via `gpg --auto-key-locate wkd --locate-external-keys 11 | ldk-security-1@mattcorallo.com ldk-security-2@mattcorallo.com`). Please include 12 | your own public key as an attachment or inline for replies. 13 | 14 | * 07DF3E57A548CCFB7530709189BBB8663E2E65CE (Matt Corallo) 15 | * 5DBC576CCCF546CA72AB06CE912EF12EA67705F5 (Jeffrey Czyz) 16 | * 0A156842CF60B58BD826ABDD808FC696767C6147 (Wilmer Paulino) 17 | * BD6EED4D339EDBF7E7CE7F8836153082BDF676FD (Elias Rohrer) 18 | * 6E0287D8849AE741E47CC586FD3E106A2CE099B4 (Valentine Wallace) 19 | * 69CFEA635D0E6E6F13FD9D9136D932FCAC0305F0 (Arik Sosman) 20 | -------------------------------------------------------------------------------- /bench/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-bench" 3 | version = "0.0.1" 4 | authors = ["Matt Corallo"] 5 | edition = "2021" 6 | 7 | [[bench]] 8 | name = "bench" 9 | harness = false 10 | 11 | [dependencies] 12 | lightning = { path = "../lightning", features = ["_test_utils", "criterion"] } 13 | lightning-persister = { path = "../lightning-persister", features = ["criterion"] } 14 | lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync", features = ["criterion"] } 15 | criterion = { version = "0.4", default-features = false } 16 | 17 | [profile.release] 18 | opt-level = 3 19 | codegen-units = 1 20 | lto = true 21 | panic = "abort" 22 | debug = true 23 | -------------------------------------------------------------------------------- /bench/README.md: -------------------------------------------------------------------------------- 1 | This crate uses criterion to benchmark various LDK functions. 2 | 3 | It can be run as `RUSTFLAGS=--cfg=ldk_bench cargo bench`. 4 | -------------------------------------------------------------------------------- /bench/benches/bench.rs: -------------------------------------------------------------------------------- 1 | extern crate lightning; 2 | extern crate lightning_persister; 3 | 4 | extern crate criterion; 5 | 6 | use criterion::{criterion_group, criterion_main}; 7 | 8 | criterion_group!(benches, 9 | // Note that benches run in the order given here. Thus, they're sorted according to how likely 10 | // developers are to be working on the specific code listed, then by runtime. 11 | lightning::routing::router::benches::generate_routes_with_zero_penalty_scorer, 12 | lightning::routing::router::benches::generate_mpp_routes_with_zero_penalty_scorer, 13 | lightning::routing::router::benches::generate_routes_with_probabilistic_scorer, 14 | lightning::routing::router::benches::generate_mpp_routes_with_probabilistic_scorer, 15 | lightning::routing::router::benches::generate_large_mpp_routes_with_probabilistic_scorer, 16 | lightning::routing::router::benches::generate_routes_with_nonlinear_probabilistic_scorer, 17 | lightning::routing::router::benches::generate_mpp_routes_with_nonlinear_probabilistic_scorer, 18 | lightning::routing::router::benches::generate_large_mpp_routes_with_nonlinear_probabilistic_scorer, 19 | lightning::sign::benches::bench_get_secure_random_bytes, 20 | lightning::ln::channelmanager::bench::bench_sends, 21 | lightning_persister::fs_store::bench::bench_sends, 22 | lightning_rapid_gossip_sync::bench::bench_reading_full_graph_from_file, 23 | lightning::routing::gossip::benches::read_network_graph, 24 | lightning::routing::gossip::benches::write_network_graph, 25 | lightning::routing::scoring::benches::decay_100k_channel_bounds); 26 | criterion_main!(benches); 27 | -------------------------------------------------------------------------------- /ci/check-compiles.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | set -x 4 | echo "Testing $(git log -1 --oneline)" 5 | cargo check 6 | cargo doc 7 | cargo doc --document-private-items 8 | cd fuzz && RUSTFLAGS="--cfg=fuzzing --cfg=secp256k1_fuzz --cfg=hashes_fuzz" cargo check --features=stdin_fuzz 9 | cd ../lightning && cargo check --no-default-features 10 | cd .. && RUSTC_BOOTSTRAP=1 RUSTFLAGS="--cfg=c_bindings" cargo check -Z avoid-dev-deps 11 | -------------------------------------------------------------------------------- /ci/check-each-commit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | if [ "$1" = "" ]; then 3 | echo "USAGE: $0 remote/head_branch" 4 | echo "eg $0 upstream/main" 5 | exit 1 6 | fi 7 | 8 | set -e 9 | set -x 10 | 11 | if [ "$(git log --pretty="%H %D" | grep "^[0-9a-f]*.* $1")" = "" ]; then 12 | echo "It seems like the current checked-out commit is not based on $1" 13 | exit 1 14 | fi 15 | git rebase --exec ci/check-compiles.sh "$1" 16 | -------------------------------------------------------------------------------- /ci/ci-tx-sync-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eox pipefail 3 | 4 | RUSTC_MINOR_VERSION=$(rustc --version | awk '{ split($2,a,"."); print a[2] }') 5 | 6 | pushd lightning-transaction-sync 7 | 8 | # Some crates require pinning to meet our MSRV even for our downstream users, 9 | # which we do here. 10 | # Further crates which appear only as dev-dependencies are pinned further down. 11 | function PIN_RELEASE_DEPS { 12 | return 0 # Don't fail the script if our rustc is higher than the last check 13 | } 14 | 15 | PIN_RELEASE_DEPS # pin the release dependencies 16 | 17 | # Starting with version 0.5.11, the `home` crate has an MSRV of rustc 1.81.0. 18 | [ "$RUSTC_MINOR_VERSION" -lt 81 ] && cargo update -p home --precise "0.5.9" --verbose 19 | 20 | # Starting with version 1.2.0, the `idna_adapter` crate has an MSRV of rustc 1.81.0. 21 | [ "$RUSTC_MINOR_VERSION" -lt 81 ] && cargo update -p idna_adapter --precise "1.1.0" --verbose 22 | 23 | export RUST_BACKTRACE=1 24 | 25 | echo -e "\n\nChecking Transaction Sync Clients with features." 26 | cargo check --verbose --color always --features esplora-blocking 27 | cargo check --verbose --color always --features esplora-async 28 | cargo check --verbose --color always --features esplora-async-https 29 | cargo check --verbose --color always --features electrum 30 | 31 | if [ -z "$CI_ENV" ] && [[ -z "$BITCOIND_EXE" || -z "$ELECTRS_EXE" ]]; then 32 | echo -e "\n\nSkipping testing Transaction Sync Clients due to BITCOIND_EXE or ELECTRS_EXE being unset." 33 | cargo check --tests 34 | else 35 | echo -e "\n\nTesting Transaction Sync Clients with features." 36 | cargo test --verbose --color always --features esplora-blocking 37 | cargo test --verbose --color always --features esplora-async 38 | cargo test --verbose --color always --features esplora-async-https 39 | cargo test --verbose --color always --features electrum 40 | fi 41 | 42 | popd 43 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: 5 | target: auto 6 | threshold: 1% 7 | base: auto 8 | informational: false 9 | patch: 10 | default: 11 | target: auto 12 | threshold: 100% 13 | base: auto 14 | -------------------------------------------------------------------------------- /contrib/download_bitcoind_electrs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eox pipefail 3 | 4 | # The tests of `lightning-transaction-sync` require `electrs` and `bitcoind` 5 | # binaries. Here, we download the binaries, validate them, and export their 6 | # location via `ELECTRS_EXE`/`BITCOIND_EXE` which will be used by the 7 | # `electrsd`/`bitcoind` crates in our tests. 8 | 9 | HOST_PLATFORM="$(rustc --version --verbose | grep "host:" | awk '{ print $2 }')" 10 | ELECTRS_DL_ENDPOINT="https://github.com/RCasatta/electrsd/releases/download/electrs_releases" 11 | ELECTRS_VERSION="esplora_a33e97e1a1fc63fa9c20a116bb92579bbf43b254" 12 | BITCOIND_DL_ENDPOINT="https://bitcoincore.org/bin/" 13 | BITCOIND_VERSION="28.1" 14 | if [[ "$HOST_PLATFORM" == *linux* ]]; then 15 | ELECTRS_DL_FILE_NAME=electrs_linux_"$ELECTRS_VERSION".zip 16 | ELECTRS_DL_HASH="865e26a96e8df77df01d96f2f569dcf9622fc87a8d99a9b8fe30861a4db9ddf1" 17 | BITCOIND_DL_FILE_NAME=bitcoin-"$BITCOIND_VERSION"-x86_64-linux-gnu.tar.gz 18 | BITCOIND_DL_HASH="07f77afd326639145b9ba9562912b2ad2ccec47b8a305bd075b4f4cb127b7ed7" 19 | elif [[ "$HOST_PLATFORM" == *darwin* ]]; then 20 | ELECTRS_DL_FILE_NAME=electrs_macos_"$ELECTRS_VERSION".zip 21 | ELECTRS_DL_HASH="2d5ff149e8a2482d3658e9b386830dfc40c8fbd7c175ca7cbac58240a9505bcd" 22 | BITCOIND_DL_FILE_NAME=bitcoin-"$BITCOIND_VERSION"-x86_64-apple-darwin.tar.gz 23 | BITCOIND_DL_HASH="c85d1a0ebedeff43b99db2c906b50f14547b84175a4d0ebb039a9809789af280" 24 | else 25 | printf "\n\n" 26 | echo "Unsupported platform: $HOST_PLATFORM Exiting.." 27 | exit 1 28 | fi 29 | 30 | DL_TMP_DIR=$(mktemp -d) 31 | trap 'rm -rf -- "$DL_TMP_DIR"' EXIT 32 | 33 | pushd "$DL_TMP_DIR" 34 | ELECTRS_DL_URL="$ELECTRS_DL_ENDPOINT"/"$ELECTRS_DL_FILE_NAME" 35 | curl -L -o "$ELECTRS_DL_FILE_NAME" "$ELECTRS_DL_URL" 36 | echo "$ELECTRS_DL_HASH $ELECTRS_DL_FILE_NAME"|shasum -a 256 -c 37 | unzip "$ELECTRS_DL_FILE_NAME" 38 | export ELECTRS_EXE="$DL_TMP_DIR"/electrs 39 | chmod +x "$ELECTRS_EXE" 40 | 41 | BITCOIND_DL_URL="$BITCOIND_DL_ENDPOINT"/bitcoin-core-"$BITCOIND_VERSION"/"$BITCOIND_DL_FILE_NAME" 42 | curl -L -o "$BITCOIND_DL_FILE_NAME" "$BITCOIND_DL_URL" 43 | echo "$BITCOIND_DL_HASH $BITCOIND_DL_FILE_NAME"|shasum -a 256 -c 44 | tar xzf "$BITCOIND_DL_FILE_NAME" 45 | export BITCOIND_EXE="$DL_TMP_DIR"/bitcoin-"$BITCOIND_VERSION"/bin/bitcoind 46 | chmod +x "$BITCOIND_EXE" 47 | popd 48 | -------------------------------------------------------------------------------- /ext-functional-test-demo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ext-functional-tester" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [features] 7 | test-broken = [] 8 | 9 | [dependencies] 10 | lightning = { path = "../lightning", features = ["_externalize_tests"] } 11 | -------------------------------------------------------------------------------- /ext-functional-test-demo/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("{} tests were exported", lightning::get_xtests().len()); 3 | } 4 | 5 | #[cfg(test)] 6 | #[allow(unused)] 7 | mod tests { 8 | use lightning::ln::functional_tests::*; 9 | use lightning::util::dyn_signer::{DynKeysInterfaceTrait, DynSigner}; 10 | use lightning::util::test_utils::{TestSignerFactory, SIGNER_FACTORY}; 11 | use std::panic::catch_unwind; 12 | use std::sync::Arc; 13 | use std::time::Duration; 14 | 15 | struct BrokenSignerFactory(); 16 | 17 | impl TestSignerFactory for BrokenSignerFactory { 18 | fn make_signer( 19 | &self, _seed: &[u8; 32], _now: Duration, 20 | ) -> Box> { 21 | panic!() 22 | } 23 | } 24 | 25 | #[cfg(feature = "test-broken")] 26 | #[test] 27 | fn test_broken() { 28 | SIGNER_FACTORY.set(Arc::new(BrokenSignerFactory())); 29 | catch_unwind(|| fake_network_test()).unwrap_err(); 30 | } 31 | 32 | #[cfg(not(feature = "test-broken"))] 33 | #[test] 34 | fn test_default_one() { 35 | test_htlc_on_chain_success(); 36 | } 37 | 38 | #[cfg(not(feature = "test-broken"))] 39 | #[test] 40 | fn test_default_all() { 41 | let mut failed_tests = Vec::new(); 42 | for test in lightning::get_xtests() { 43 | print!("Running test: {}", test.test_name); 44 | let mut pass = catch_unwind(|| (test.test_fn)()).is_ok(); 45 | if test.should_panic { 46 | pass = !pass; 47 | } 48 | if !pass { 49 | failed_tests.push(test.test_name); 50 | } 51 | } 52 | if !failed_tests.is_empty() { 53 | println!("Failed tests:"); 54 | for test in failed_tests.iter() { 55 | println!("- {}", test); 56 | } 57 | } 58 | println!("Done with {} failures", failed_tests.len()); 59 | assert!(failed_tests.is_empty()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /fuzz/.gitignore: -------------------------------------------------------------------------------- 1 | hfuzz_target 2 | target 3 | hfuzz_workspace 4 | corpus 5 | -------------------------------------------------------------------------------- /fuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-fuzz" 3 | version = "0.0.1" 4 | authors = ["Automatically generated"] 5 | publish = false 6 | edition = "2021" 7 | # Because the function is unused it gets dropped before we link lightning, so 8 | # we have to duplicate build.rs here. Note that this is only required for 9 | # fuzzing mode. 10 | 11 | [package.metadata] 12 | cargo-fuzz = true 13 | 14 | [features] 15 | afl_fuzz = ["afl"] 16 | honggfuzz_fuzz = ["honggfuzz"] 17 | libfuzzer_fuzz = ["libfuzzer-sys"] 18 | stdin_fuzz = [] 19 | 20 | [dependencies] 21 | lightning = { path = "../lightning", features = ["regex", "_test_utils"] } 22 | lightning-invoice = { path = "../lightning-invoice" } 23 | lightning-liquidity = { path = "../lightning-liquidity" } 24 | lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" } 25 | bech32 = "0.11.0" 26 | bitcoin = { version = "0.32.2", features = ["secp-lowmemory"] } 27 | 28 | afl = { version = "0.12", optional = true } 29 | honggfuzz = { version = "0.5", optional = true, default-features = false } 30 | libfuzzer-sys = { version = "0.4", optional = true } 31 | 32 | [build-dependencies] 33 | cc = "1.0" 34 | 35 | # Prevent this from interfering with workspaces 36 | [workspace] 37 | members = ["."] 38 | 39 | [profile.release] 40 | lto = true 41 | codegen-units = 1 42 | debug-assertions = true 43 | overflow-checks = true 44 | 45 | # When testing a large fuzz corpus, -O1 offers a nice speedup 46 | [profile.dev] 47 | opt-level = 1 48 | 49 | [lib] 50 | name = "lightning_fuzz" 51 | path = "src/lib.rs" 52 | crate-type = ["rlib", "dylib", "staticlib"] 53 | 54 | [lints.rust.unexpected_cfgs] 55 | level = "forbid" 56 | # When adding a new cfg attribute, ensure that it is added to this list. 57 | check-cfg = [ 58 | "cfg(fuzzing)", 59 | "cfg(secp256k1_fuzz)", 60 | "cfg(hashes_fuzz)", 61 | "cfg(taproot)", 62 | ] 63 | -------------------------------------------------------------------------------- /fuzz/ci-fuzz.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | set -x 4 | 5 | pushd src/msg_targets 6 | rm msg_*.rs 7 | ./gen_target.sh 8 | [ "$(git diff)" != "" ] && exit 1 9 | popd 10 | pushd src/bin 11 | rm *_target.rs 12 | ./gen_target.sh 13 | [ "$(git diff)" != "" ] && exit 1 14 | popd 15 | 16 | export RUSTFLAGS="--cfg=secp256k1_fuzz --cfg=hashes_fuzz" 17 | 18 | mkdir -p hfuzz_workspace/full_stack_target/input 19 | pushd write-seeds 20 | RUSTFLAGS="$RUSTFLAGS --cfg=fuzzing" cargo run ../hfuzz_workspace/full_stack_target/input 21 | popd 22 | 23 | cargo install --color always --force honggfuzz --no-default-features 24 | # Because we're fuzzing relatively few iterations, the maximum possible 25 | # compiler optimizations aren't necessary, so switch to defaults. 26 | sed -i 's/lto = true//' Cargo.toml 27 | sed -i 's/codegen-units = 1//' Cargo.toml 28 | 29 | export HFUZZ_BUILD_ARGS="--features honggfuzz_fuzz" 30 | 31 | cargo --color always hfuzz build 32 | for TARGET in src/bin/*.rs; do 33 | FILENAME=$(basename $TARGET) 34 | FILE="${FILENAME%.*}" 35 | HFUZZ_RUN_ARGS="--exit_upon_crash -v -n2" 36 | if [ "$FILE" = "chanmon_consistency_target" ]; then 37 | HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -F 64 -N1000" 38 | elif [ "$FILE" = "process_network_graph_target" -o "$FILE" = "full_stack_target" -o "$FILE" = "router_target" ]; then 39 | HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N10000" 40 | elif [ "$FILE" = "indexedmap_target" ]; then 41 | HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N100000" 42 | else 43 | HFUZZ_RUN_ARGS="$HFUZZ_RUN_ARGS -N1000000" 44 | fi 45 | export HFUZZ_RUN_ARGS 46 | cargo --color always hfuzz run $FILE 47 | if [ -f hfuzz_workspace/$FILE/HONGGFUZZ.REPORT.TXT ]; then 48 | cat hfuzz_workspace/$FILE/HONGGFUZZ.REPORT.TXT 49 | for CASE in hfuzz_workspace/$FILE/SIG*; do 50 | cat $CASE | xxd -p 51 | done 52 | exit 1 53 | fi 54 | done 55 | -------------------------------------------------------------------------------- /fuzz/src/base32.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use lightning::util::base32; 11 | 12 | use crate::utils::test_logger; 13 | 14 | #[inline] 15 | pub fn do_test(data: &[u8]) { 16 | if let Ok(s) = std::str::from_utf8(data) { 17 | let first_decoding = base32::Alphabet::RFC4648 { padding: true }.decode(s); 18 | if let Ok(first_decoding) = first_decoding { 19 | let encoding_response = 20 | base32::Alphabet::RFC4648 { padding: true }.encode(&first_decoding); 21 | assert_eq!(encoding_response, s.to_ascii_uppercase()); 22 | let second_decoding = 23 | base32::Alphabet::RFC4648 { padding: true }.decode(&encoding_response).unwrap(); 24 | assert_eq!(first_decoding, second_decoding); 25 | } 26 | } 27 | 28 | if let Ok(s) = std::str::from_utf8(data) { 29 | let first_decoding = base32::Alphabet::RFC4648 { padding: false }.decode(s); 30 | if let Ok(first_decoding) = first_decoding { 31 | let encoding_response = 32 | base32::Alphabet::RFC4648 { padding: false }.encode(&first_decoding); 33 | assert_eq!(encoding_response, s.to_ascii_uppercase()); 34 | let second_decoding = 35 | base32::Alphabet::RFC4648 { padding: false }.decode(&encoding_response).unwrap(); 36 | assert_eq!(first_decoding, second_decoding); 37 | } 38 | } 39 | 40 | let encode_response = base32::Alphabet::RFC4648 { padding: false }.encode(&data); 41 | let decode_response = 42 | base32::Alphabet::RFC4648 { padding: false }.decode(&encode_response).unwrap(); 43 | assert_eq!(data, decode_response); 44 | 45 | let encode_response = base32::Alphabet::RFC4648 { padding: true }.encode(&data); 46 | let decode_response = 47 | base32::Alphabet::RFC4648 { padding: true }.decode(&encode_response).unwrap(); 48 | assert_eq!(data, decode_response); 49 | } 50 | 51 | pub fn base32_test(data: &[u8], _out: Out) { 52 | do_test(data); 53 | } 54 | 55 | #[no_mangle] 56 | pub extern "C" fn base32_run(data: *const u8, datalen: usize) { 57 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); 58 | } 59 | -------------------------------------------------------------------------------- /fuzz/src/bech32_parse.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use crate::utils::test_logger; 11 | use core::convert::TryFrom; 12 | use lightning::offers::parse::{Bech32Encode, Bolt12ParseError}; 13 | 14 | #[inline] 15 | pub fn do_test(data: &[u8], _out: Out) { 16 | if let Ok(bech32_encoded) = std::str::from_utf8(data) { 17 | if let Ok(bytes) = Bytes::from_bech32_str(bech32_encoded) { 18 | let bech32_encoded = bytes.to_string(); 19 | assert_eq!(bytes, Bytes::from_bech32_str(&bech32_encoded).unwrap()); 20 | } 21 | } 22 | } 23 | 24 | #[derive(Debug, PartialEq)] 25 | struct Bytes(Vec); 26 | 27 | impl Bech32Encode for Bytes { 28 | const BECH32_HRP: &'static str = "lno"; 29 | } 30 | 31 | impl AsRef<[u8]> for Bytes { 32 | fn as_ref(&self) -> &[u8] { 33 | &self.0 34 | } 35 | } 36 | 37 | impl TryFrom> for Bytes { 38 | type Error = Bolt12ParseError; 39 | fn try_from(data: Vec) -> Result { 40 | Ok(Bytes(data)) 41 | } 42 | } 43 | 44 | impl core::fmt::Display for Bytes { 45 | fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { 46 | self.fmt_bech32_str(f) 47 | } 48 | } 49 | 50 | pub fn bech32_parse_test(data: &[u8], out: Out) { 51 | do_test(data, out); 52 | } 53 | 54 | #[no_mangle] 55 | pub extern "C" fn bech32_parse_run(data: *const u8, datalen: usize) { 56 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 57 | } 58 | -------------------------------------------------------------------------------- /fuzz/src/bin/gen_target.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "#include " > ../../targets.h 4 | GEN_TEST() { 5 | cat target_template.txt | sed s/TARGET_NAME/$1/ | sed s/TARGET_MOD/$2$1/ > $1_target.rs 6 | echo "void $1_run(const unsigned char* data, size_t data_len);" >> ../../targets.h 7 | } 8 | 9 | GEN_TEST bech32_parse 10 | GEN_TEST chanmon_deser 11 | GEN_TEST chanmon_consistency 12 | GEN_TEST full_stack 13 | GEN_TEST invoice_deser 14 | GEN_TEST invoice_request_deser 15 | GEN_TEST offer_deser 16 | GEN_TEST bolt11_deser 17 | GEN_TEST onion_message 18 | GEN_TEST peer_crypt 19 | GEN_TEST process_network_graph 20 | GEN_TEST process_onion_failure 21 | GEN_TEST refund_deser 22 | GEN_TEST router 23 | GEN_TEST zbase32 24 | GEN_TEST indexedmap 25 | GEN_TEST onion_hop_data 26 | GEN_TEST base32 27 | GEN_TEST fromstr_to_netaddress 28 | GEN_TEST feature_flags 29 | GEN_TEST lsps_message 30 | 31 | GEN_TEST msg_accept_channel msg_targets:: 32 | GEN_TEST msg_announcement_signatures msg_targets:: 33 | GEN_TEST msg_channel_reestablish msg_targets:: 34 | GEN_TEST msg_closing_signed msg_targets:: 35 | GEN_TEST msg_closing_complete msg_targets:: 36 | GEN_TEST msg_closing_sig msg_targets:: 37 | GEN_TEST msg_commitment_signed msg_targets:: 38 | GEN_TEST msg_decoded_onion_error_packet msg_targets:: 39 | GEN_TEST msg_funding_created msg_targets:: 40 | GEN_TEST msg_channel_ready msg_targets:: 41 | GEN_TEST msg_funding_signed msg_targets:: 42 | GEN_TEST msg_init msg_targets:: 43 | GEN_TEST msg_open_channel msg_targets:: 44 | GEN_TEST msg_revoke_and_ack msg_targets:: 45 | GEN_TEST msg_shutdown msg_targets:: 46 | GEN_TEST msg_update_fail_htlc msg_targets:: 47 | GEN_TEST msg_update_fail_malformed_htlc msg_targets:: 48 | GEN_TEST msg_update_fee msg_targets:: 49 | GEN_TEST msg_update_fulfill_htlc msg_targets:: 50 | 51 | GEN_TEST msg_channel_announcement msg_targets:: 52 | GEN_TEST msg_node_announcement msg_targets:: 53 | GEN_TEST msg_query_short_channel_ids msg_targets:: 54 | GEN_TEST msg_reply_short_channel_ids_end msg_targets:: 55 | GEN_TEST msg_query_channel_range msg_targets:: 56 | GEN_TEST msg_reply_channel_range msg_targets:: 57 | GEN_TEST msg_gossip_timestamp_filter msg_targets:: 58 | 59 | GEN_TEST msg_update_add_htlc msg_targets:: 60 | GEN_TEST msg_error_message msg_targets:: 61 | GEN_TEST msg_channel_update msg_targets:: 62 | 63 | GEN_TEST msg_ping msg_targets:: 64 | GEN_TEST msg_pong msg_targets:: 65 | 66 | GEN_TEST msg_channel_details msg_targets:: 67 | 68 | GEN_TEST msg_open_channel_v2 msg_targets:: 69 | GEN_TEST msg_accept_channel_v2 msg_targets:: 70 | GEN_TEST msg_tx_add_input msg_targets:: 71 | GEN_TEST msg_tx_add_output msg_targets:: 72 | GEN_TEST msg_tx_remove_input msg_targets:: 73 | GEN_TEST msg_tx_remove_output msg_targets:: 74 | GEN_TEST msg_tx_complete msg_targets:: 75 | GEN_TEST msg_tx_signatures msg_targets:: 76 | GEN_TEST msg_tx_init_rbf msg_targets:: 77 | GEN_TEST msg_tx_ack_rbf msg_targets:: 78 | GEN_TEST msg_tx_abort msg_targets:: 79 | 80 | GEN_TEST msg_stfu msg_targets:: 81 | 82 | GEN_TEST msg_splice_init msg_targets:: 83 | GEN_TEST msg_splice_ack msg_targets:: 84 | GEN_TEST msg_splice_locked msg_targets:: 85 | 86 | GEN_TEST msg_blinded_message_path msg_targets:: 87 | -------------------------------------------------------------------------------- /fuzz/src/bolt11_deser.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use crate::utils::test_logger; 11 | use bech32::Fe32; 12 | use bitcoin::secp256k1::{Secp256k1, SecretKey}; 13 | use lightning_invoice::{ 14 | Base32Iterable, Bolt11Invoice, FromBase32, RawBolt11Invoice, RawDataPart, RawHrp, 15 | RawTaggedField, TaggedField, 16 | }; 17 | use std::str::FromStr; 18 | 19 | #[inline] 20 | pub fn do_test(data: &[u8], _out: Out) { 21 | // Read a fake HRP length byte 22 | let hrp_len = std::cmp::min(*data.get(0).unwrap_or(&0) as usize, data.len()); 23 | if let Ok(s) = std::str::from_utf8(&data[..hrp_len]) { 24 | let hrp = match RawHrp::from_str(s) { 25 | Ok(hrp) => hrp, 26 | Err(_) => return, 27 | }; 28 | let bech32 = 29 | data.iter().skip(hrp_len).map(|x| Fe32::try_from(x % 32).unwrap()).collect::>(); 30 | let invoice_data = match RawDataPart::from_base32(&bech32) { 31 | Ok(invoice) => invoice, 32 | Err(_) => return, 33 | }; 34 | 35 | let invoice_data_base32 = invoice_data.fe_iter().collect::>(); 36 | // Our data encoding is not worse than the input 37 | assert!(invoice_data_base32.len() <= bech32.len()); 38 | 39 | // Our data serialization is loss-less 40 | assert_eq!( 41 | RawDataPart::from_base32(&invoice_data_base32).expect("faild parsing out own encoding"), 42 | invoice_data 43 | ); 44 | 45 | if invoice_data.tagged_fields.iter().any(|field| { 46 | matches!(field, RawTaggedField::KnownSemantics(TaggedField::PayeePubKey(_))) 47 | }) { 48 | // We could forge a signature using the fact that signing is insecure in fuzz mode, but 49 | // easier to just skip and rely on the fact that no-PayeePubKey invoices do pubkey 50 | // recovery 51 | return; 52 | } 53 | 54 | let raw_invoice = RawBolt11Invoice { hrp, data: invoice_data }; 55 | let signed_raw_invoice = match raw_invoice.sign(|hash| { 56 | let private_key = SecretKey::from_slice(&[42; 32]).unwrap(); 57 | Ok::<_, ()>(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)) 58 | }) { 59 | Ok(inv) => inv, 60 | Err(_) => return, 61 | }; 62 | 63 | if let Ok(invoice) = Bolt11Invoice::from_signed(signed_raw_invoice) { 64 | invoice.amount_milli_satoshis(); 65 | } 66 | } 67 | } 68 | 69 | pub fn bolt11_deser_test(data: &[u8], out: Out) { 70 | do_test(data, out); 71 | } 72 | 73 | #[no_mangle] 74 | pub extern "C" fn bolt11_deser_run(data: *const u8, datalen: usize) { 75 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 76 | } 77 | -------------------------------------------------------------------------------- /fuzz/src/chanmon_deser.rs: -------------------------------------------------------------------------------- 1 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 2 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 3 | 4 | use bitcoin::hash_types::BlockHash; 5 | 6 | use lightning::chain::channelmonitor; 7 | use lightning::util::ser::{ReadableArgs, Writeable, Writer}; 8 | use lightning::util::test_channel_signer::TestChannelSigner; 9 | use lightning::util::test_utils::OnlyReadsKeysInterface; 10 | 11 | use crate::utils::test_logger; 12 | 13 | use lightning::io::Cursor; 14 | 15 | struct VecWriter(Vec); 16 | impl Writer for VecWriter { 17 | fn write_all(&mut self, buf: &[u8]) -> Result<(), ::lightning::io::Error> { 18 | self.0.extend_from_slice(buf); 19 | Ok(()) 20 | } 21 | } 22 | 23 | #[inline] 24 | pub fn do_test(data: &[u8], _out: Out) { 25 | if let Ok((latest_block_hash, monitor)) = 26 | <(BlockHash, channelmonitor::ChannelMonitor)>::read( 27 | &mut Cursor::new(data), 28 | (&OnlyReadsKeysInterface {}, &OnlyReadsKeysInterface {}), 29 | ) { 30 | let mut w = VecWriter(Vec::new()); 31 | monitor.write(&mut w).unwrap(); 32 | let deserialized_copy = 33 | <(BlockHash, channelmonitor::ChannelMonitor)>::read( 34 | &mut Cursor::new(&w.0), 35 | (&OnlyReadsKeysInterface {}, &OnlyReadsKeysInterface {}), 36 | ) 37 | .unwrap(); 38 | assert!(latest_block_hash == deserialized_copy.0); 39 | assert!(monitor == deserialized_copy.1); 40 | } 41 | } 42 | 43 | pub fn chanmon_deser_test(data: &[u8], out: Out) { 44 | do_test(data, out); 45 | } 46 | 47 | #[no_mangle] 48 | pub extern "C" fn chanmon_deser_run(data: *const u8, datalen: usize) { 49 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 50 | } 51 | -------------------------------------------------------------------------------- /fuzz/src/feature_flags.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use lightning::types::features::FeatureFlags; 11 | 12 | use crate::utils::test_logger; 13 | 14 | use std::ops::{Deref, DerefMut}; 15 | 16 | /// Check various methods on [`FeatureFlags`] given `v` which should be equal to `feat` and an 17 | /// `old_v` which should be equal to `old_feat`. 18 | fn check_eq(v: &Vec, feat: &FeatureFlags, old_v: &mut Vec, old_feat: &mut FeatureFlags) { 19 | assert_eq!(v.len(), feat.len()); 20 | assert_eq!(v.deref(), feat.deref()); 21 | assert_eq!(old_v.deref_mut(), old_feat.deref_mut()); 22 | 23 | let mut feat_clone = feat.clone(); 24 | assert!(feat_clone == *feat); 25 | 26 | // Test iteration over the `FeatureFlags` with the base iterator 27 | let mut feat_iter = feat.iter(); 28 | let mut vec_iter = v.iter(); 29 | assert_eq!(feat_iter.len(), vec_iter.len()); 30 | while let Some(feat) = feat_iter.next() { 31 | let v = vec_iter.next().unwrap(); 32 | assert_eq!(*feat, *v); 33 | } 34 | assert!(vec_iter.next().is_none()); 35 | 36 | // Do the same test of iteration over the `FeatureFlags` with the mutable iterator 37 | let mut feat_iter = feat_clone.iter_mut(); 38 | let mut vec_iter = v.iter(); 39 | assert_eq!(feat_iter.len(), vec_iter.len()); 40 | while let Some(feat) = feat_iter.next() { 41 | let v = vec_iter.next().unwrap(); 42 | assert_eq!(*feat, *v); 43 | } 44 | assert!(vec_iter.next().is_none()); 45 | 46 | assert_eq!(v < old_v, feat < old_feat); 47 | assert_eq!(v.partial_cmp(old_v), feat.partial_cmp(old_feat)); 48 | } 49 | 50 | #[inline] 51 | pub fn do_test(data: &[u8]) { 52 | if data.len() % 3 != 0 { 53 | return; 54 | } 55 | let mut vec = Vec::new(); 56 | let mut features = FeatureFlags::empty(); 57 | 58 | // For each 3-tuple in the input, interpret the first byte as a "command", the second byte as 59 | // an index within `vec`/`features` to mutate, and the third byte as a value. 60 | for step in data.windows(3) { 61 | let mut old_vec = vec.clone(); 62 | let mut old_features = features.clone(); 63 | match step[0] { 64 | 0 => { 65 | vec.resize(step[1] as usize, step[2]); 66 | features.resize(step[1] as usize, step[2]); 67 | }, 68 | 1 => { 69 | if vec.len() > step[1] as usize { 70 | vec[step[1] as usize] = step[2]; 71 | features[step[1] as usize] = step[2]; 72 | } 73 | }, 74 | 2 => { 75 | if vec.len() > step[1] as usize { 76 | *vec.iter_mut().skip(step[1] as usize).next().unwrap() = step[2]; 77 | *features.iter_mut().skip(step[1] as usize).next().unwrap() = step[2]; 78 | } 79 | }, 80 | _ => {}, 81 | } 82 | // After each mutation, check that `vec` and `features` remain the same, and pass the 83 | // previous state for testing comparisons. 84 | check_eq(&vec, &features, &mut old_vec, &mut old_features); 85 | } 86 | 87 | check_eq(&vec, &features, &mut vec.clone(), &mut features.clone()); 88 | } 89 | 90 | pub fn feature_flags_test(data: &[u8], _out: Out) { 91 | do_test(data); 92 | } 93 | 94 | #[no_mangle] 95 | pub extern "C" fn feature_flags_run(data: *const u8, datalen: usize) { 96 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); 97 | } 98 | -------------------------------------------------------------------------------- /fuzz/src/fromstr_to_netaddress.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use core::str::FromStr; 11 | use lightning::ln::msgs::SocketAddress; 12 | 13 | use crate::utils::test_logger; 14 | 15 | #[inline] 16 | pub fn do_test(data: &[u8]) { 17 | if let Ok(s) = std::str::from_utf8(data) { 18 | let _ = SocketAddress::from_str(s); 19 | } 20 | } 21 | 22 | pub fn fromstr_to_netaddress_test(data: &[u8], _out: Out) { 23 | do_test(data); 24 | } 25 | 26 | #[no_mangle] 27 | pub extern "C" fn fromstr_to_netaddress_run(data: *const u8, datalen: usize) { 28 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); 29 | } 30 | -------------------------------------------------------------------------------- /fuzz/src/invoice_deser.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use crate::utils::test_logger; 11 | use lightning::offers::invoice::Bolt12Invoice; 12 | use lightning::util::ser::Writeable; 13 | use std::convert::TryFrom; 14 | 15 | #[inline] 16 | pub fn do_test(data: &[u8], _out: Out) { 17 | if let Ok(invoice) = Bolt12Invoice::try_from(data.to_vec()) { 18 | let mut bytes = Vec::with_capacity(data.len()); 19 | invoice.write(&mut bytes).unwrap(); 20 | assert_eq!(data, bytes); 21 | } 22 | } 23 | 24 | pub fn invoice_deser_test(data: &[u8], out: Out) { 25 | do_test(data, out); 26 | } 27 | 28 | #[no_mangle] 29 | pub extern "C" fn invoice_deser_run(data: *const u8, datalen: usize) { 30 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 31 | } 32 | -------------------------------------------------------------------------------- /fuzz/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | extern crate bitcoin; 11 | extern crate lightning; 12 | extern crate lightning_rapid_gossip_sync; 13 | 14 | #[cfg(not(fuzzing))] 15 | compile_error!("Fuzz targets need cfg=fuzzing"); 16 | 17 | #[cfg(not(hashes_fuzz))] 18 | compile_error!("Fuzz targets need cfg=hashes_fuzz"); 19 | 20 | #[cfg(not(secp256k1_fuzz))] 21 | compile_error!("Fuzz targets need cfg=secp256k1_fuzz"); 22 | 23 | pub mod utils; 24 | 25 | pub mod base32; 26 | pub mod bech32_parse; 27 | pub mod bolt11_deser; 28 | pub mod chanmon_consistency; 29 | pub mod chanmon_deser; 30 | pub mod feature_flags; 31 | pub mod fromstr_to_netaddress; 32 | pub mod full_stack; 33 | pub mod indexedmap; 34 | pub mod invoice_deser; 35 | pub mod invoice_request_deser; 36 | pub mod lsps_message; 37 | pub mod offer_deser; 38 | pub mod onion_hop_data; 39 | pub mod onion_message; 40 | pub mod peer_crypt; 41 | pub mod process_network_graph; 42 | pub mod process_onion_failure; 43 | pub mod refund_deser; 44 | pub mod router; 45 | pub mod zbase32; 46 | 47 | pub mod msg_targets; 48 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/mod.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(rustfmt, rustfmt_skip)] 2 | mod utils; 3 | pub mod msg_accept_channel; 4 | pub mod msg_announcement_signatures; 5 | pub mod msg_closing_signed; 6 | pub mod msg_closing_complete; 7 | pub mod msg_closing_sig; 8 | pub mod msg_commitment_signed; 9 | pub mod msg_funding_created; 10 | pub mod msg_channel_ready; 11 | pub mod msg_funding_signed; 12 | pub mod msg_gossip_timestamp_filter; 13 | pub mod msg_init; 14 | pub mod msg_open_channel; 15 | pub mod msg_ping; 16 | pub mod msg_pong; 17 | pub mod msg_query_channel_range; 18 | pub mod msg_reply_short_channel_ids_end; 19 | pub mod msg_revoke_and_ack; 20 | pub mod msg_shutdown; 21 | pub mod msg_update_add_htlc; 22 | pub mod msg_update_fail_htlc; 23 | pub mod msg_update_fail_malformed_htlc; 24 | pub mod msg_update_fee; 25 | pub mod msg_update_fulfill_htlc; 26 | pub mod msg_channel_reestablish; 27 | pub mod msg_decoded_onion_error_packet; 28 | pub mod msg_channel_announcement; 29 | pub mod msg_node_announcement; 30 | pub mod msg_channel_update; 31 | pub mod msg_query_short_channel_ids; 32 | pub mod msg_reply_channel_range; 33 | pub mod msg_error_message; 34 | pub mod msg_warning_message; 35 | pub mod msg_channel_details; 36 | pub mod msg_open_channel_v2; 37 | pub mod msg_accept_channel_v2; 38 | pub mod msg_tx_add_input; 39 | pub mod msg_tx_add_output; 40 | pub mod msg_tx_remove_input; 41 | pub mod msg_tx_remove_output; 42 | pub mod msg_tx_complete; 43 | pub mod msg_tx_signatures; 44 | pub mod msg_tx_init_rbf; 45 | pub mod msg_tx_ack_rbf; 46 | pub mod msg_tx_abort; 47 | pub mod msg_stfu; 48 | pub mod msg_splice_init; 49 | pub mod msg_splice_ack; 50 | pub mod msg_splice_locked; 51 | pub mod msg_blinded_message_path; 52 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_accept_channel.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_accept_channel_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::AcceptChannel, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_accept_channel_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::AcceptChannel, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_accept_channel_v2.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_accept_channel_v2_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::AcceptChannelV2, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_accept_channel_v2_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::AcceptChannelV2, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_announcement_signatures.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_announcement_signatures_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::AnnouncementSignatures, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_announcement_signatures_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::AnnouncementSignatures, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_blinded_message_path.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_blinded_message_path_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::blinded_path::message::BlindedMessagePath, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_blinded_message_path_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::blinded_path::message::BlindedMessagePath, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_channel_announcement.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_channel_announcement_test(data: &[u8], _out: Out) { 20 | test_msg_exact!(lightning::ln::msgs::ChannelAnnouncement, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_channel_announcement_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_exact!(lightning::ln::msgs::ChannelAnnouncement, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_channel_details.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_channel_details_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::channel_state::ChannelDetails, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_channel_details_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::channel_state::ChannelDetails, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_channel_ready.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_channel_ready_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ChannelReady, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_channel_ready_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ChannelReady, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_channel_reestablish.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_channel_reestablish_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ChannelReestablish, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_channel_reestablish_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ChannelReestablish, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_channel_update.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_channel_update_test(data: &[u8], _out: Out) { 20 | test_msg_exact!(lightning::ln::msgs::ChannelUpdate, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_channel_update_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_exact!(lightning::ln::msgs::ChannelUpdate, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_closing_complete.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_closing_complete_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ClosingComplete, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_closing_complete_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ClosingComplete, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_closing_sig.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_closing_sig_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ClosingSig, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_closing_sig_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ClosingSig, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_closing_signed.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_closing_signed_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ClosingSigned, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_closing_signed_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ClosingSigned, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_commitment_signed.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_commitment_signed_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::CommitmentSigned, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_commitment_signed_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::CommitmentSigned, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_decoded_onion_error_packet.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_decoded_onion_error_packet_test(data: &[u8], _out: Out) { 20 | test_msg!(lightning::ln::msgs::DecodedOnionErrorPacket, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_decoded_onion_error_packet_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg!(lightning::ln::msgs::DecodedOnionErrorPacket, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_error_message.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_error_message_test(data: &[u8], _out: Out) { 20 | test_msg_hole!(lightning::ln::msgs::ErrorMessage, data, 32, 2); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_error_message_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_hole!(lightning::ln::msgs::ErrorMessage, data, 32, 2); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_funding_created.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_funding_created_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::FundingCreated, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_funding_created_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::FundingCreated, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_funding_signed.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_funding_signed_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::FundingSigned, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_funding_signed_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::FundingSigned, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_gossip_timestamp_filter.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_gossip_timestamp_filter_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::GossipTimestampFilter, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_gossip_timestamp_filter_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::GossipTimestampFilter, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_init.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_init_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::Init, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_init_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::Init, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_node_announcement.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_node_announcement_test(data: &[u8], _out: Out) { 20 | test_msg_exact!(lightning::ln::msgs::NodeAnnouncement, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_node_announcement_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_exact!(lightning::ln::msgs::NodeAnnouncement, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_open_channel.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_open_channel_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::OpenChannel, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_open_channel_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::OpenChannel, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_open_channel_v2.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_open_channel_v2_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::OpenChannelV2, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_open_channel_v2_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::OpenChannelV2, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_ping.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_ping_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::Ping, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_ping_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::Ping, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_pong.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_pong_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::Pong, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_pong_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::Pong, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_query_channel_range.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_query_channel_range_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::QueryChannelRange, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_query_channel_range_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::QueryChannelRange, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_query_short_channel_ids.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_query_short_channel_ids_test(data: &[u8], _out: Out) { 20 | test_msg!(lightning::ln::msgs::QueryShortChannelIds, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_query_short_channel_ids_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg!(lightning::ln::msgs::QueryShortChannelIds, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_reply_channel_range.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_reply_channel_range_test(data: &[u8], _out: Out) { 20 | test_msg!(lightning::ln::msgs::ReplyChannelRange, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_reply_channel_range_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg!(lightning::ln::msgs::ReplyChannelRange, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_reply_short_channel_ids_end.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_reply_short_channel_ids_end_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::ReplyShortChannelIdsEnd, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_reply_short_channel_ids_end_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::ReplyShortChannelIdsEnd, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_revoke_and_ack.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_revoke_and_ack_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::RevokeAndACK, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_revoke_and_ack_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::RevokeAndACK, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_shutdown.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_shutdown_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::Shutdown, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_shutdown_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::Shutdown, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_splice_ack.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_splice_ack_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::SpliceAck, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_splice_ack_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::SpliceAck, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_splice_init.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_splice_init_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::SpliceInit, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_splice_init_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::SpliceInit, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_splice_locked.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_splice_locked_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::SpliceLocked, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_splice_locked_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::SpliceLocked, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_stfu.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_stfu_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::Stfu, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_stfu_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::Stfu, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_target_template.txt: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn TARGET_NAME_test(data: &[u8], _out: Out) { 20 | TEST_MSG!(MSG_TARGET, dataEXTRA_ARGS); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn TARGET_NAME_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | TEST_MSG!(MSG_TARGET, dataEXTRA_ARGS); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_abort.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_abort_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxAbort, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_abort_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxAbort, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_ack_rbf.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_ack_rbf_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxAckRbf, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_ack_rbf_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxAckRbf, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_add_input.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_add_input_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxAddInput, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_add_input_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxAddInput, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_add_output.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_add_output_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxAddOutput, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_add_output_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxAddOutput, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_complete.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_complete_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxComplete, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_complete_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxComplete, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_init_rbf.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_init_rbf_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxInitRbf, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_init_rbf_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxInitRbf, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_remove_input.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_remove_input_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxRemoveInput, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_remove_input_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxRemoveInput, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_remove_output.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_remove_output_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxRemoveOutput, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_remove_output_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxRemoveOutput, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_tx_signatures.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_tx_signatures_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::TxSignatures, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_tx_signatures_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::TxSignatures, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_update_add_htlc.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_update_add_htlc_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::UpdateAddHTLC, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_update_add_htlc_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::UpdateAddHTLC, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_update_fail_htlc.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_update_fail_htlc_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::UpdateFailHTLC, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_update_fail_htlc_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::UpdateFailHTLC, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_update_fail_malformed_htlc.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_update_fail_malformed_htlc_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::UpdateFailMalformedHTLC, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_update_fail_malformed_htlc_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::UpdateFailMalformedHTLC, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_update_fee.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_update_fee_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::UpdateFee, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_update_fee_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::UpdateFee, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_update_fulfill_htlc.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_update_fulfill_htlc_test(data: &[u8], _out: Out) { 20 | test_msg_simple!(lightning::ln::msgs::UpdateFulfillHTLC, data); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_update_fulfill_htlc_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_simple!(lightning::ln::msgs::UpdateFulfillHTLC, data); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/msg_targets/msg_warning_message.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | #![cfg_attr(rustfmt, rustfmt_skip)] 14 | 15 | use crate::msg_targets::utils::VecWriter; 16 | use crate::utils::test_logger; 17 | 18 | #[inline] 19 | pub fn msg_warning_message_test(data: &[u8], _out: Out) { 20 | test_msg_hole!(lightning::ln::msgs::WarningMessage, data, 32, 2); 21 | } 22 | 23 | #[no_mangle] 24 | pub extern "C" fn msg_warning_message_run(data: *const u8, datalen: usize) { 25 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 26 | test_msg_hole!(lightning::ln::msgs::WarningMessage, data, 32, 2); 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/offer_deser.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use crate::utils::test_logger; 11 | use bitcoin::secp256k1::Secp256k1; 12 | use core::convert::TryFrom; 13 | use lightning::ln::channelmanager::PaymentId; 14 | use lightning::ln::inbound_payment::ExpandedKey; 15 | use lightning::offers::invoice_request::InvoiceRequest; 16 | use lightning::offers::nonce::Nonce; 17 | use lightning::offers::offer::{Amount, Offer, Quantity}; 18 | use lightning::offers::parse::Bolt12SemanticError; 19 | use lightning::sign::EntropySource; 20 | use lightning::util::ser::Writeable; 21 | 22 | #[inline] 23 | pub fn do_test(data: &[u8], _out: Out) { 24 | if let Ok(offer) = Offer::try_from(data.to_vec()) { 25 | let mut bytes = Vec::with_capacity(data.len()); 26 | offer.write(&mut bytes).unwrap(); 27 | assert_eq!(data, bytes); 28 | 29 | let mut buffer = Vec::new(); 30 | 31 | if let Ok(invoice_request) = build_request(&offer) { 32 | invoice_request.write(&mut buffer).unwrap(); 33 | } 34 | } 35 | } 36 | 37 | struct FixedEntropy; 38 | 39 | impl EntropySource for FixedEntropy { 40 | fn get_secure_random_bytes(&self) -> [u8; 32] { 41 | [42; 32] 42 | } 43 | } 44 | 45 | fn build_request(offer: &Offer) -> Result { 46 | let expanded_key = ExpandedKey::new([42; 32]); 47 | let entropy = FixedEntropy {}; 48 | let nonce = Nonce::from_entropy_source(&entropy); 49 | let secp_ctx = Secp256k1::new(); 50 | let payment_id = PaymentId([1; 32]); 51 | 52 | let mut builder = offer.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)?; 53 | 54 | builder = match offer.amount() { 55 | None => builder.amount_msats(1000).unwrap(), 56 | Some(Amount::Bitcoin { amount_msats }) => builder.amount_msats(amount_msats + 1)?, 57 | Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency), 58 | }; 59 | 60 | builder = match offer.supported_quantity() { 61 | Quantity::Bounded(n) => builder.quantity(n.get()).unwrap(), 62 | Quantity::Unbounded => builder.quantity(10).unwrap(), 63 | Quantity::One => builder, 64 | }; 65 | 66 | builder.build_and_sign() 67 | } 68 | 69 | pub fn offer_deser_test(data: &[u8], out: Out) { 70 | do_test(data, out); 71 | } 72 | 73 | #[no_mangle] 74 | pub extern "C" fn offer_deser_run(data: *const u8, datalen: usize) { 75 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 76 | } 77 | -------------------------------------------------------------------------------- /fuzz/src/onion_hop_data.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | // This file is auto-generated by gen_target.sh based on msg_target_template.txt 11 | // To modify it, modify msg_target_template.txt and run gen_target.sh instead. 12 | 13 | use crate::utils::test_logger; 14 | use lightning::util::test_utils; 15 | 16 | #[inline] 17 | pub fn onion_hop_data_test(data: &[u8], _out: Out) { 18 | use bitcoin::secp256k1::PublicKey; 19 | use lightning::util::ser::ReadableArgs; 20 | let mut r = ::lightning::io::Cursor::new(data); 21 | let node_signer = test_utils::TestNodeSigner::new(test_utils::privkey(42)); 22 | let _ = , 24 | &test_utils::TestNodeSigner, 25 | )>>::read(&mut r, (None, &&node_signer)); 26 | } 27 | 28 | #[no_mangle] 29 | pub extern "C" fn onion_hop_data_run(data: *const u8, datalen: usize) { 30 | use bitcoin::secp256k1::PublicKey; 31 | use lightning::util::ser::ReadableArgs; 32 | let data = unsafe { std::slice::from_raw_parts(data, datalen) }; 33 | let mut r = ::lightning::io::Cursor::new(data); 34 | let node_signer = test_utils::TestNodeSigner::new(test_utils::privkey(42)); 35 | let _ = , 37 | &test_utils::TestNodeSigner, 38 | )>>::read(&mut r, (None, &&node_signer)); 39 | } 40 | -------------------------------------------------------------------------------- /fuzz/src/peer_crypt.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use lightning::ln::peer_channel_encryptor::{MessageBuf, PeerChannelEncryptor}; 11 | use lightning::util::test_utils::TestNodeSigner; 12 | 13 | use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; 14 | 15 | use crate::utils::test_logger; 16 | 17 | #[inline] 18 | fn slice_to_be16(v: &[u8]) -> u16 { 19 | ((v[0] as u16) << 8 * 1) | ((v[1] as u16) << 8 * 0) 20 | } 21 | 22 | #[inline] 23 | pub fn do_test(data: &[u8]) { 24 | let mut read_pos = 0; 25 | macro_rules! get_slice { 26 | ($len: expr) => {{ 27 | let slice_len = $len as usize; 28 | if data.len() < read_pos + slice_len { 29 | return; 30 | } 31 | read_pos += slice_len; 32 | &data[read_pos - slice_len..read_pos] 33 | }}; 34 | } 35 | 36 | let secp_ctx = Secp256k1::signing_only(); 37 | 38 | let our_network_key = match SecretKey::from_slice(get_slice!(32)) { 39 | Ok(key) => key, 40 | Err(_) => return, 41 | }; 42 | let node_signer = TestNodeSigner::new(our_network_key); 43 | let ephemeral_key = match SecretKey::from_slice(get_slice!(32)) { 44 | Ok(key) => key, 45 | Err(_) => return, 46 | }; 47 | 48 | let mut crypter = if get_slice!(1)[0] != 0 { 49 | let their_pubkey = match PublicKey::from_slice(get_slice!(33)) { 50 | Ok(key) => key, 51 | Err(_) => return, 52 | }; 53 | let mut crypter = PeerChannelEncryptor::new_outbound(their_pubkey, ephemeral_key); 54 | crypter.get_act_one(&secp_ctx); 55 | match crypter.process_act_two(get_slice!(50), &&node_signer) { 56 | Ok(_) => {}, 57 | Err(_) => return, 58 | } 59 | assert!(crypter.is_ready_for_encryption()); 60 | crypter 61 | } else { 62 | let mut crypter = PeerChannelEncryptor::new_inbound(&&node_signer); 63 | match crypter.process_act_one_with_keys( 64 | get_slice!(50), 65 | &&node_signer, 66 | ephemeral_key, 67 | &secp_ctx, 68 | ) { 69 | Ok(_) => {}, 70 | Err(_) => return, 71 | } 72 | match crypter.process_act_three(get_slice!(66)) { 73 | Ok(_) => {}, 74 | Err(_) => return, 75 | } 76 | assert!(crypter.is_ready_for_encryption()); 77 | crypter 78 | }; 79 | let mut buf = [0; 65536 + 16]; 80 | loop { 81 | if get_slice!(1)[0] == 0 { 82 | crypter.encrypt_buffer(MessageBuf::from_encoded(&get_slice!(slice_to_be16( 83 | get_slice!(2) 84 | )))); 85 | } else { 86 | let len = match crypter.decrypt_length_header(get_slice!(16 + 2)) { 87 | Ok(len) => len, 88 | Err(_) => return, 89 | }; 90 | buf[..len as usize + 16].copy_from_slice(&get_slice!(len as usize + 16)); 91 | match crypter.decrypt_message(&mut buf[..len as usize + 16]) { 92 | Ok(_) => {}, 93 | Err(_) => return, 94 | } 95 | } 96 | } 97 | } 98 | 99 | pub fn peer_crypt_test(data: &[u8], _out: Out) { 100 | do_test(data); 101 | } 102 | 103 | #[no_mangle] 104 | pub extern "C" fn peer_crypt_run(data: *const u8, datalen: usize) { 105 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); 106 | } 107 | -------------------------------------------------------------------------------- /fuzz/src/process_network_graph.rs: -------------------------------------------------------------------------------- 1 | // Imports that need to be added manually 2 | use lightning_rapid_gossip_sync::RapidGossipSync; 3 | 4 | use crate::utils::test_logger; 5 | 6 | /// Actual fuzz test, method signature and name are fixed 7 | fn do_test(data: &[u8], out: Out) { 8 | let logger = test_logger::TestLogger::new("".to_owned(), out); 9 | let network_graph = 10 | lightning::routing::gossip::NetworkGraph::new(bitcoin::Network::Bitcoin, &logger); 11 | let rapid_sync = RapidGossipSync::new(&network_graph, &logger); 12 | let _ = rapid_sync.update_network_graph(data); 13 | } 14 | 15 | /// Method that needs to be added manually, {name}_test 16 | pub fn process_network_graph_test(data: &[u8], out: Out) { 17 | do_test(data, out); 18 | } 19 | 20 | /// Method that needs to be added manually, {name}_run 21 | #[no_mangle] 22 | pub extern "C" fn process_network_graph_run(data: *const u8, datalen: usize) { 23 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}); 24 | } 25 | -------------------------------------------------------------------------------- /fuzz/src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | pub mod test_logger; 11 | pub mod test_persister; 12 | -------------------------------------------------------------------------------- /fuzz/src/utils/test_logger.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use lightning::util::logger::{Logger, Record}; 11 | use std::io::Write; 12 | use std::sync::{Arc, Mutex}; 13 | 14 | pub trait Output: Clone + 'static { 15 | fn locked_write(&self, data: &[u8]); 16 | } 17 | 18 | #[derive(Clone)] 19 | pub struct DevNull {} 20 | impl Output for DevNull { 21 | fn locked_write(&self, _data: &[u8]) {} 22 | } 23 | #[derive(Clone)] 24 | pub struct StringBuffer(Arc>); 25 | impl Output for StringBuffer { 26 | fn locked_write(&self, data: &[u8]) { 27 | self.0.lock().unwrap().push_str(&String::from_utf8(data.to_vec()).unwrap()); 28 | } 29 | } 30 | impl StringBuffer { 31 | pub fn new() -> Self { 32 | Self(Arc::new(Mutex::new(String::new()))) 33 | } 34 | pub fn into_string(self) -> String { 35 | Arc::try_unwrap(self.0).unwrap().into_inner().unwrap() 36 | } 37 | } 38 | 39 | pub struct TestLogger { 40 | id: String, 41 | out: Out, 42 | } 43 | impl TestLogger { 44 | pub fn new(id: String, out: Out) -> TestLogger { 45 | TestLogger { id, out } 46 | } 47 | } 48 | 49 | struct LockedWriteAdapter<'a, Out: Output>(&'a Out); 50 | impl<'a, Out: Output> Write for LockedWriteAdapter<'a, Out> { 51 | fn write(&mut self, data: &[u8]) -> Result { 52 | self.0.locked_write(data); 53 | Ok(data.len()) 54 | } 55 | fn flush(&mut self) -> Result<(), std::io::Error> { 56 | Ok(()) 57 | } 58 | } 59 | 60 | impl Logger for TestLogger { 61 | fn log(&self, record: Record) { 62 | write!( 63 | LockedWriteAdapter(&self.out), 64 | "{:<5} {} [{} : {}] {}\n", 65 | record.level.to_string(), 66 | self.id, 67 | record.module_path, 68 | record.line, 69 | record.args 70 | ) 71 | .unwrap(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /fuzz/src/utils/test_persister.rs: -------------------------------------------------------------------------------- 1 | use lightning::chain; 2 | use lightning::chain::{chainmonitor, channelmonitor}; 3 | use lightning::util::persist::MonitorName; 4 | use lightning::util::test_channel_signer::TestChannelSigner; 5 | 6 | use std::sync::Mutex; 7 | 8 | pub struct TestPersister { 9 | pub update_ret: Mutex, 10 | } 11 | impl chainmonitor::Persist for TestPersister { 12 | fn persist_new_channel( 13 | &self, _monitor_name: MonitorName, 14 | _data: &channelmonitor::ChannelMonitor, 15 | ) -> chain::ChannelMonitorUpdateStatus { 16 | self.update_ret.lock().unwrap().clone() 17 | } 18 | 19 | fn update_persisted_channel( 20 | &self, _monitor_name: MonitorName, _update: Option<&channelmonitor::ChannelMonitorUpdate>, 21 | _data: &channelmonitor::ChannelMonitor, 22 | ) -> chain::ChannelMonitorUpdateStatus { 23 | self.update_ret.lock().unwrap().clone() 24 | } 25 | 26 | fn archive_persisted_channel(&self, _monitor_name: MonitorName) {} 27 | } 28 | -------------------------------------------------------------------------------- /fuzz/src/zbase32.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | use lightning::util::base32; 11 | 12 | use crate::utils::test_logger; 13 | 14 | #[inline] 15 | pub fn do_test(data: &[u8]) { 16 | let res = base32::Alphabet::ZBase32.encode(data); 17 | assert_eq!(&base32::Alphabet::ZBase32.decode(&res).unwrap()[..], data); 18 | 19 | if let Ok(s) = std::str::from_utf8(data) { 20 | let res = base32::Alphabet::ZBase32.decode(s); 21 | if let Ok(decoded) = res { 22 | assert_eq!(&base32::Alphabet::ZBase32.encode(&decoded), &s.to_ascii_lowercase()); 23 | } 24 | } 25 | } 26 | 27 | pub fn zbase32_test(data: &[u8], _out: Out) { 28 | do_test(data); 29 | } 30 | 31 | #[no_mangle] 32 | pub extern "C" fn zbase32_run(data: *const u8, datalen: usize) { 33 | do_test(unsafe { std::slice::from_raw_parts(data, datalen) }); 34 | } 35 | -------------------------------------------------------------------------------- /fuzz/write-seeds/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-fuzz-write-seeds" 3 | version = "0.0.1" 4 | authors = ["Automatically generated"] 5 | publish = false 6 | edition = "2021" 7 | 8 | [features] 9 | 10 | [dependencies] 11 | lightning-fuzz = { path = "../" } 12 | 13 | # Prevent this from interfering with workspaces 14 | [workspace] 15 | members = ["."] 16 | -------------------------------------------------------------------------------- /fuzz/write-seeds/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut iter = std::env::args(); 3 | iter.next().unwrap(); // program name 4 | let path = iter.next().expect("Requires a path as the first argument"); 5 | lightning_fuzz::full_stack::write_fst_seeds(&path); 6 | } 7 | -------------------------------------------------------------------------------- /lightning-background-processor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-background-processor" 3 | version = "0.2.0+git" 4 | authors = ["Valentine Wallace "] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | description = """ 8 | Utilities to perform required background tasks for Rust Lightning. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [features] 17 | std = ["lightning/std", "lightning-liquidity/std", "bitcoin-io/std", "bitcoin_hashes/std"] 18 | 19 | default = ["std"] 20 | 21 | [dependencies] 22 | bitcoin = { version = "0.32.2", default-features = false } 23 | bitcoin_hashes = { version = "0.14.0", default-features = false } 24 | bitcoin-io = { version = "0.1.2", default-features = false } 25 | lightning = { version = "0.2.0", path = "../lightning", default-features = false } 26 | lightning-rapid-gossip-sync = { version = "0.2.0", path = "../lightning-rapid-gossip-sync", default-features = false } 27 | lightning-liquidity = { version = "0.2.0", path = "../lightning-liquidity", default-features = false } 28 | 29 | [dev-dependencies] 30 | tokio = { version = "1.35", features = [ "macros", "rt", "rt-multi-thread", "sync", "time" ] } 31 | lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] } 32 | lightning-invoice = { version = "0.34.0", path = "../lightning-invoice" } 33 | lightning-persister = { version = "0.2.0", path = "../lightning-persister" } 34 | 35 | [lints] 36 | workspace = true 37 | -------------------------------------------------------------------------------- /lightning-block-sync/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-block-sync" 3 | version = "0.2.0+git" 4 | authors = ["Jeffrey Czyz", "Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | description = """ 8 | Utilities to fetch the chain data from a block source and feed them into Rust Lightning. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [features] 17 | rest-client = [ "serde_json", "chunked_transfer" ] 18 | rpc-client = [ "serde_json", "chunked_transfer" ] 19 | 20 | [dependencies] 21 | bitcoin = "0.32.2" 22 | lightning = { version = "0.2.0", path = "../lightning" } 23 | tokio = { version = "1.35", features = [ "io-util", "net", "time", "rt" ], optional = true } 24 | serde_json = { version = "1.0", optional = true } 25 | chunked_transfer = { version = "1.4", optional = true } 26 | 27 | [dev-dependencies] 28 | lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] } 29 | tokio = { version = "1.35", features = [ "macros", "rt" ] } 30 | 31 | [lints] 32 | workspace = true 33 | -------------------------------------------------------------------------------- /lightning-block-sync/src/utils.rs: -------------------------------------------------------------------------------- 1 | use bitcoin::hex::{FromHex, HexToArrayError}; 2 | use bitcoin::pow::Work; 3 | 4 | pub fn hex_to_work(hex: &str) -> Result { 5 | let bytes = <[u8; 32]>::from_hex(hex)?; 6 | Ok(Work::from_be_bytes(bytes)) 7 | } 8 | 9 | #[cfg(test)] 10 | mod tests { 11 | use super::*; 12 | use bitcoin::pow::Work; 13 | 14 | #[test] 15 | fn hex_to_work_empty_str() { 16 | assert!(hex_to_work("").is_err()); 17 | } 18 | 19 | #[test] 20 | fn hex_to_work_too_short_str() { 21 | let hex = String::from_utf8(vec![b'0'; 32]).unwrap(); 22 | assert!(hex_to_work(&hex).is_err()); 23 | } 24 | 25 | #[test] 26 | fn hex_to_work_too_long_str() { 27 | let hex = String::from_utf8(vec![b'0'; 128]).unwrap(); 28 | assert!(hex_to_work(&hex).is_err()); 29 | } 30 | 31 | #[test] 32 | fn hex_to_work_odd_length_str() { 33 | let hex = String::from_utf8(vec![b'0'; 65]).unwrap(); 34 | assert!(hex_to_work(&hex).is_err()); 35 | } 36 | 37 | #[test] 38 | fn hex_to_work_invalid_char() { 39 | let hex = String::from_utf8(vec![b'G'; 64]).unwrap(); 40 | assert!(hex_to_work(&hex).is_err()); 41 | } 42 | 43 | #[test] 44 | fn hex_to_work_lowercase_str() { 45 | let hex: String = std::iter::repeat("1a").take(32).collect(); 46 | assert_eq!(hex_to_work(&hex).unwrap(), Work::from_be_bytes([0x1a; 32])); 47 | } 48 | 49 | #[test] 50 | fn hex_to_work_uppercase_str() { 51 | let hex: String = std::iter::repeat("1A").take(32).collect(); 52 | assert_eq!(hex_to_work(&hex).unwrap(), Work::from_be_bytes([0x1A; 32])); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /lightning-custom-message/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-custom-message" 3 | version = "0.2.0+git" 4 | authors = ["Jeffrey Czyz"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | description = """ 8 | Utilities for supporting custom peer-to-peer messages in LDK. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [dependencies] 17 | bitcoin = "0.32.2" 18 | lightning = { version = "0.2.0", path = "../lightning" } 19 | 20 | [lints] 21 | workspace = true 22 | -------------------------------------------------------------------------------- /lightning-dns-resolver/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-dns-resolver" 3 | version = "0.3.0+git" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = "A crate which implements DNSSEC resolution for lightning clients over bLIP 32 using `tokio` and the `dnssec-prover` crate." 8 | edition = "2021" 9 | 10 | [dependencies] 11 | lightning = { version = "0.2.0", path = "../lightning", default-features = false } 12 | lightning-types = { version = "0.3.0", path = "../lightning-types", default-features = false } 13 | dnssec-prover = { version = "0.6", default-features = false, features = [ "std", "tokio" ] } 14 | tokio = { version = "1.0", default-features = false, features = ["rt"] } 15 | 16 | [dev-dependencies] 17 | bitcoin = { version = "0.32" } 18 | tokio = { version = "1.0", default-features = false, features = ["macros", "time"] } 19 | lightning = { version = "0.2.0", path = "../lightning", features = ["dnssec", "_test_utils"] } 20 | -------------------------------------------------------------------------------- /lightning-invoice/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | **/*.rs.bk 3 | Cargo.lock -------------------------------------------------------------------------------- /lightning-invoice/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-invoice" 3 | description = "Data structures to parse and serialize BOLT11 lightning invoices" 4 | version = "0.34.0+git" 5 | authors = ["Sebastian Geisler "] 6 | documentation = "https://docs.rs/lightning-invoice/" 7 | license = "MIT OR Apache-2.0" 8 | keywords = [ "lightning", "bitcoin", "invoice", "BOLT11" ] 9 | readme = "README.md" 10 | repository = "https://github.com/lightningdevkit/rust-lightning/" 11 | edition = "2021" 12 | 13 | [package.metadata.docs.rs] 14 | all-features = true 15 | rustdoc-args = ["--cfg", "docsrs"] 16 | 17 | [features] 18 | std = [] 19 | 20 | [dependencies] 21 | bech32 = { version = "0.11.0", default-features = false } 22 | lightning-types = { version = "0.3.0", path = "../lightning-types", default-features = false } 23 | serde = { version = "1.0", optional = true, default-features = false, features = ["alloc"] } 24 | bitcoin = { version = "0.32.2", default-features = false, features = ["secp-recovery"] } 25 | 26 | [dev-dependencies] 27 | serde_json = { version = "1"} 28 | hashbrown = { version = "0.13", default-features = false } 29 | 30 | [lints] 31 | workspace = true 32 | -------------------------------------------------------------------------------- /lightning-invoice/README.md: -------------------------------------------------------------------------------- 1 | # lightning-invoice 2 | [![Docs.rs](https://docs.rs/lightning-invoice/badge.svg)](https://docs.rs/lightning-invoice/) 3 | 4 | This repo provides data structures for BOLT 11 lightning invoices and 5 | functions to parse and serialize these from and to bech32. 6 | 7 | **Please be sure to run the test suite since we need to check assumptions 8 | regarding `SystemTime`'s bounds on your platform. You can also call `check_platform` 9 | on startup or in your test suite to do so.** 10 | -------------------------------------------------------------------------------- /lightning-invoice/src/tb.rs: -------------------------------------------------------------------------------- 1 | pub trait Bool {} 2 | 3 | #[derive(Copy, Clone)] 4 | pub struct True {} 5 | 6 | #[derive(Copy, Clone)] 7 | pub struct False {} 8 | 9 | impl Bool for True {} 10 | impl Bool for False {} 11 | -------------------------------------------------------------------------------- /lightning-liquidity/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-liquidity" 3 | version = "0.2.0+git" 4 | authors = ["John Cantrell ", "Elias Rohrer "] 5 | homepage = "https://lightningdevkit.org/" 6 | license = "MIT OR Apache-2.0" 7 | edition = "2021" 8 | description = "Types and primitives to integrate a spec-compliant LSP with an LDK-based node." 9 | repository = "https://github.com/lightningdevkit/lightning-liquidity/" 10 | readme = "README.md" 11 | keywords = ["bitcoin", "lightning", "ldk", "bdk"] 12 | categories = ["cryptography::cryptocurrencies"] 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [features] 17 | default = ["std"] 18 | std = ["lightning/std"] 19 | backtrace = ["dep:backtrace"] 20 | 21 | [dependencies] 22 | lightning = { version = "0.2.0", path = "../lightning", default-features = false } 23 | lightning-types = { version = "0.3.0", path = "../lightning-types", default-features = false } 24 | lightning-invoice = { version = "0.34.0", path = "../lightning-invoice", default-features = false, features = ["serde"] } 25 | 26 | bitcoin = { version = "0.32.2", default-features = false, features = ["serde"] } 27 | 28 | chrono = { version = "0.4", default-features = false, features = ["serde", "alloc"] } 29 | serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } 30 | serde_json = { version = "1.0", default-features = false, features = ["alloc"] } 31 | backtrace = { version = "0.3", optional = true } 32 | 33 | [dev-dependencies] 34 | lightning = { version = "0.2.0", path = "../lightning", default-features = false, features = ["_test_utils"] } 35 | lightning-invoice = { version = "0.34.0", path = "../lightning-invoice", default-features = false, features = ["serde", "std"] } 36 | lightning-persister = { version = "0.2.0", path = "../lightning-persister", default-features = false } 37 | 38 | proptest = "1.0.0" 39 | tokio = { version = "1.35", default-features = false, features = [ "rt-multi-thread", "time", "sync", "macros" ] } 40 | parking_lot = { version = "0.12", default-features = false } 41 | 42 | [lints.rust.unexpected_cfgs] 43 | level = "forbid" 44 | # When adding a new cfg attribute, ensure that it is added to this list. 45 | check-cfg = [ 46 | "cfg(lsps1_service)", 47 | "cfg(c_bindings)", 48 | "cfg(backtrace)", 49 | "cfg(ldk_bench)", 50 | ] 51 | -------------------------------------------------------------------------------- /lightning-liquidity/README.md: -------------------------------------------------------------------------------- 1 | # lightning-liquidity 2 | 3 | The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP with an LDK-based node. To this end, this crate provides client-side as well as service-side logic to implement the LSPS specifications. 4 | 5 | **Note**: Service-side support is currently considered "beta", i.e., not fully 6 | ready for production use. 7 | 8 | Currently the following specifications are supported: 9 | - [bLIP-50 / LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. 10 | - [bLIP-51 / LSPS1] allows to order Lightning channels from an LSP. This is useful when the client needs 11 | inbound Lightning liquidity for which they are willing and able to pay in bitcoin. 12 | - [bLIP-52 / LSPS2] allows to generate a special invoice for which, when paid, an LSP 13 | will open a "just-in-time" channel. This is useful for the initial 14 | on-boarding of clients as the channel opening fees are deducted from the 15 | incoming payment, i.e., no funds are required client-side to initiate this 16 | flow. 17 | 18 | To get started, you'll want to setup a `LiquidityManager` and configure it to be the `CustomMessageHandler` of your LDK node. You can then call `LiquidityManager::lsps1_client_handler` / `LiquidityManager::lsps2_client_handler`, or `LiquidityManager::lsps2_service_handler`, to access the respective client-side or service-side handlers. 19 | 20 | `LiquidityManager` uses an eventing system to notify the user about important updates to the protocol flow. To this end, you will need to handle events emitted via one of the event handling methods provided by `LiquidityManager`, e.g., `LiquidityManager::next_event`. 21 | 22 | [bLIP-50 / LSPS0]: https://github.com/lightning/blips/blob/master/blip-0050.md 23 | [bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md 24 | [bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md 25 | -------------------------------------------------------------------------------- /lightning-liquidity/src/events/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Events are surfaced by the library to indicate some action must be taken 11 | //! by the end-user. 12 | //! 13 | //! Because we don't have a built-in runtime, it's up to the end-user to poll 14 | //! [`LiquidityManager::get_and_clear_pending_events`] to receive events. 15 | //! 16 | //! [`LiquidityManager::get_and_clear_pending_events`]: crate::LiquidityManager::get_and_clear_pending_events 17 | 18 | mod event_queue; 19 | 20 | pub(crate) use event_queue::EventQueue; 21 | pub use event_queue::MAX_EVENT_QUEUE_SIZE; 22 | 23 | use crate::lsps0; 24 | use crate::lsps1; 25 | use crate::lsps2; 26 | 27 | /// An event which you should probably take some action in response to. 28 | #[derive(Debug, Clone, PartialEq, Eq)] 29 | pub enum LiquidityEvent { 30 | /// An LSPS0 client event. 31 | LSPS0Client(lsps0::event::LSPS0ClientEvent), 32 | /// An LSPS1 (Channel Request) client event. 33 | LSPS1Client(lsps1::event::LSPS1ClientEvent), 34 | /// An LSPS1 (Channel Request) server event. 35 | #[cfg(lsps1_service)] 36 | LSPS1Service(lsps1::event::LSPS1ServiceEvent), 37 | /// An LSPS2 (JIT Channel) client event. 38 | LSPS2Client(lsps2::event::LSPS2ClientEvent), 39 | /// An LSPS2 (JIT Channel) server event. 40 | LSPS2Service(lsps2::event::LSPS2ServiceEvent), 41 | } 42 | 43 | impl From for LiquidityEvent { 44 | fn from(event: lsps0::event::LSPS0ClientEvent) -> Self { 45 | Self::LSPS0Client(event) 46 | } 47 | } 48 | 49 | impl From for LiquidityEvent { 50 | fn from(event: lsps1::event::LSPS1ClientEvent) -> Self { 51 | Self::LSPS1Client(event) 52 | } 53 | } 54 | 55 | #[cfg(lsps1_service)] 56 | impl From for LiquidityEvent { 57 | fn from(event: lsps1::event::LSPS1ServiceEvent) -> Self { 58 | Self::LSPS1Service(event) 59 | } 60 | } 61 | 62 | impl From for LiquidityEvent { 63 | fn from(event: lsps2::event::LSPS2ClientEvent) -> Self { 64 | Self::LSPS2Client(event) 65 | } 66 | } 67 | 68 | impl From for LiquidityEvent { 69 | fn from(event: lsps2::event::LSPS2ServiceEvent) -> Self { 70 | Self::LSPS2Service(event) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | #![crate_name = "lightning_liquidity"] 10 | 11 | //! The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP 12 | //! with an LDK-based node. To this end, this crate provides client-side as well as service-side 13 | //! logic to implement the LSPS specifications. 14 | //! 15 | //! **Note**: Service-side support is currently considered "beta", i.e., not fully ready for 16 | //! production use. 17 | //! 18 | //! Currently the following specifications are supported: 19 | //! - [bLIP-50 / LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. 20 | //! - [bLIP-51 / LSPS1] defines a protocol for ordering Lightning channels from an LSP. This is useful when the client needs 21 | //! inbound Lightning liquidity for which they are willing and able to pay in bitcoin. 22 | //! - [bLIP-52 / LSPS2] defines a protocol for generating a special invoice for which, when paid, 23 | //! an LSP will open a "just-in-time" channel. This is useful for the initial on-boarding of 24 | //! clients as the channel opening fees are deducted from the incoming payment, i.e., no funds are 25 | //! required client-side to initiate this flow. 26 | //! 27 | //! To get started, you'll want to setup a [`LiquidityManager`] and configure it to be the 28 | //! [`CustomMessageHandler`] of your LDK node. You can then for example call 29 | //! [`LiquidityManager::lsps1_client_handler`] / [`LiquidityManager::lsps2_client_handler`], or 30 | //! [`LiquidityManager::lsps2_service_handler`], to access the respective client-side or 31 | //! service-side handlers. 32 | //! 33 | //! [`LiquidityManager`] uses an eventing system to notify the user about important updates to the 34 | //! protocol flow. To this end, you will need to handle events emitted via one of the event 35 | //! handling methods provided by [`LiquidityManager`], e.g., [`LiquidityManager::next_event`]. 36 | //! 37 | //! [bLIP-50 / LSPS0]: https://github.com/lightning/blips/blob/master/blip-0050.md 38 | //! [bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md 39 | //! [bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md 40 | //! [`CustomMessageHandler`]: lightning::ln::peer_handler::CustomMessageHandler 41 | //! [`LiquidityManager::next_event`]: crate::LiquidityManager::next_event 42 | #![deny(missing_docs)] 43 | #![deny(rustdoc::broken_intra_doc_links)] 44 | #![deny(rustdoc::private_intra_doc_links)] 45 | #![allow(bare_trait_objects)] 46 | #![allow(ellipsis_inclusive_range_patterns)] 47 | #![allow(clippy::drop_non_drop)] 48 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 49 | #![cfg_attr(not(feature = "std"), no_std)] 50 | 51 | #[macro_use] 52 | extern crate alloc; 53 | 54 | mod prelude { 55 | pub(crate) use lightning::util::hash_tables::*; 56 | } 57 | 58 | pub mod events; 59 | pub mod lsps0; 60 | pub mod lsps1; 61 | pub mod lsps2; 62 | mod manager; 63 | pub mod message_queue; 64 | #[allow(dead_code)] 65 | #[allow(unused_imports)] 66 | mod sync; 67 | #[cfg(test)] 68 | mod tests; 69 | mod utils; 70 | 71 | pub use manager::{ 72 | ALiquidityManager, LiquidityClientConfig, LiquidityManager, LiquidityServiceConfig, 73 | }; 74 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lsps0/event.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Contains bLIP-50 / LSPS0 event types. 11 | 12 | use alloc::vec::Vec; 13 | 14 | use bitcoin::secp256k1::PublicKey; 15 | 16 | /// An event which an bLIP-50 / LSPS0 client may want to take some action in response to. 17 | #[derive(Clone, Debug, PartialEq, Eq)] 18 | pub enum LSPS0ClientEvent { 19 | /// Information from the LSP about the protocols they support. 20 | ListProtocolsResponse { 21 | /// The node id of the LSP. 22 | counterparty_node_id: PublicKey, 23 | /// A list of supported protocols. 24 | protocols: Vec, 25 | }, 26 | } 27 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lsps0/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Types and primitives that implement the bLIP-50 / LSPS0: Transport Layer specification. 11 | 12 | pub mod client; 13 | pub mod event; 14 | pub mod msgs; 15 | pub mod ser; 16 | pub mod service; 17 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lsps1/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Types and primitives that implement the bLIP-51 / LSPS1: Channel Request specification. 11 | 12 | pub mod client; 13 | pub mod event; 14 | pub mod msgs; 15 | #[cfg(lsps1_service)] 16 | pub mod service; 17 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lsps2/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Implementation of bLIP-52 / LSPS2: JIT Channel Negotiation specification. 11 | 12 | pub mod client; 13 | pub mod event; 14 | pub mod msgs; 15 | pub(crate) mod payment_queue; 16 | pub mod service; 17 | pub mod utils; 18 | -------------------------------------------------------------------------------- /lightning-liquidity/src/lsps2/utils.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for implementing the bLIP-52 / LSPS2 standard. 2 | 3 | use crate::lsps2::msgs::LSPS2OpeningFeeParams; 4 | use crate::utils; 5 | 6 | use bitcoin::hashes::hmac::{Hmac, HmacEngine}; 7 | use bitcoin::hashes::sha256::Hash as Sha256; 8 | use bitcoin::hashes::{Hash, HashEngine}; 9 | 10 | /// Determines if the given parameters are valid given the secret used to generate the promise. 11 | pub fn is_valid_opening_fee_params( 12 | fee_params: &LSPS2OpeningFeeParams, promise_secret: &[u8; 32], 13 | ) -> bool { 14 | if is_expired_opening_fee_params(fee_params) { 15 | return false; 16 | } 17 | let mut hmac = HmacEngine::::new(promise_secret); 18 | hmac.input(&fee_params.min_fee_msat.to_be_bytes()); 19 | hmac.input(&fee_params.proportional.to_be_bytes()); 20 | hmac.input(fee_params.valid_until.to_rfc3339().as_bytes()); 21 | hmac.input(&fee_params.min_lifetime.to_be_bytes()); 22 | hmac.input(&fee_params.max_client_to_self_delay.to_be_bytes()); 23 | hmac.input(&fee_params.min_payment_size_msat.to_be_bytes()); 24 | hmac.input(&fee_params.max_payment_size_msat.to_be_bytes()); 25 | let promise_bytes = Hmac::from_engine(hmac).to_byte_array(); 26 | let promise = utils::hex_str(&promise_bytes[..]); 27 | promise == fee_params.promise 28 | } 29 | 30 | /// Determines if the given parameters are expired, or still valid. 31 | #[cfg_attr(not(feature = "std"), allow(unused_variables))] 32 | pub fn is_expired_opening_fee_params(fee_params: &LSPS2OpeningFeeParams) -> bool { 33 | #[cfg(feature = "std")] 34 | { 35 | fee_params.valid_until.is_past() 36 | } 37 | #[cfg(not(feature = "std"))] 38 | { 39 | // TODO: We need to find a way to check expiry times in no-std builds. 40 | false 41 | } 42 | } 43 | 44 | /// Computes the opening fee given a payment size and the fee parameters. 45 | /// 46 | /// Returns [`Option::None`] when the computation overflows. 47 | /// 48 | /// See the [`specification`](https://github.com/lightning/blips/blob/master/blip-0052.md#computing-the-opening_fee) for more details. 49 | pub fn compute_opening_fee( 50 | payment_size_msat: u64, opening_fee_min_fee_msat: u64, opening_fee_proportional: u64, 51 | ) -> Option { 52 | payment_size_msat 53 | .checked_mul(opening_fee_proportional) 54 | .and_then(|f| f.checked_add(999999)) 55 | .and_then(|f| f.checked_div(1000000)) 56 | .map(|f| core::cmp::max(f, opening_fee_min_fee_msat)) 57 | } 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | use proptest::prelude::*; 63 | 64 | const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000; 65 | 66 | fn arb_opening_fee_params() -> impl Strategy { 67 | (0u64..MAX_VALUE_MSAT, 0u64..MAX_VALUE_MSAT, 0u64..MAX_VALUE_MSAT) 68 | } 69 | 70 | proptest! { 71 | #[test] 72 | fn test_compute_opening_fee((payment_size_msat, opening_fee_min_fee_msat, opening_fee_proportional) in arb_opening_fee_params()) { 73 | if let Some(res) = compute_opening_fee(payment_size_msat, opening_fee_min_fee_msat, opening_fee_proportional) { 74 | assert!(res >= opening_fee_min_fee_msat); 75 | assert_eq!(res as f32, (payment_size_msat as f32 * opening_fee_proportional as f32)); 76 | } else { 77 | // Check we actually overflowed. 78 | let max_value = u64::MAX as u128; 79 | assert!((payment_size_msat as u128 * opening_fee_proportional as u128) > max_value); 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /lightning-liquidity/src/message_queue.rs: -------------------------------------------------------------------------------- 1 | //! Holds types and traits used to implement message queues for [`LSPSMessage`]s. 2 | 3 | use alloc::collections::VecDeque; 4 | use alloc::vec::Vec; 5 | 6 | use crate::lsps0::ser::LSPSMessage; 7 | use crate::sync::Mutex; 8 | 9 | use lightning::util::wakers::{Future, Notifier}; 10 | 11 | use bitcoin::secp256k1::PublicKey; 12 | 13 | /// The default [`MessageQueue`] Implementation used by [`LiquidityManager`]. 14 | /// 15 | /// [`LiquidityManager`]: crate::LiquidityManager 16 | pub struct MessageQueue { 17 | queue: Mutex>, 18 | pending_msgs_notifier: Notifier, 19 | } 20 | 21 | impl MessageQueue { 22 | pub(crate) fn new() -> Self { 23 | let queue = Mutex::new(VecDeque::new()); 24 | let pending_msgs_notifier = Notifier::new(); 25 | Self { queue, pending_msgs_notifier } 26 | } 27 | 28 | pub(crate) fn get_and_clear_pending_msgs(&self) -> Vec<(PublicKey, LSPSMessage)> { 29 | self.queue.lock().unwrap().drain(..).collect() 30 | } 31 | 32 | pub(crate) fn get_pending_msgs_future(&self) -> Future { 33 | self.pending_msgs_notifier.get_future() 34 | } 35 | 36 | pub(crate) fn enqueue(&self, counterparty_node_id: &PublicKey, msg: LSPSMessage) { 37 | { 38 | let mut queue = self.queue.lock().unwrap(); 39 | queue.push_back((*counterparty_node_id, msg)); 40 | } 41 | self.pending_msgs_notifier.notify(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /lightning-liquidity/src/sync/debug_sync.rs: -------------------------------------------------------------------------------- 1 | ../../../lightning/src/sync/debug_sync.rs -------------------------------------------------------------------------------- /lightning-liquidity/src/sync/fairrwlock.rs: -------------------------------------------------------------------------------- 1 | ../../../lightning/src/sync/fairrwlock.rs -------------------------------------------------------------------------------- /lightning-liquidity/src/sync/mod.rs: -------------------------------------------------------------------------------- 1 | ../../../lightning/src/sync/mod.rs -------------------------------------------------------------------------------- /lightning-liquidity/src/sync/nostd_sync.rs: -------------------------------------------------------------------------------- 1 | ../../../lightning/src/sync/nostd_sync.rs -------------------------------------------------------------------------------- /lightning-liquidity/src/sync/test_lockorder_checks.rs: -------------------------------------------------------------------------------- 1 | ../../../lightning/src/sync/test_lockorder_checks.rs -------------------------------------------------------------------------------- /lightning-liquidity/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod utils; 2 | -------------------------------------------------------------------------------- /lightning-liquidity/src/tests/utils.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | 3 | use bitcoin::secp256k1::PublicKey; 4 | use lightning::io; 5 | use lightning::sign::EntropySource; 6 | 7 | pub struct TestEntropy {} 8 | impl EntropySource for TestEntropy { 9 | fn get_secure_random_bytes(&self) -> [u8; 32] { 10 | [0; 32] 11 | } 12 | } 13 | 14 | pub fn to_vec(hex: &str) -> Option> { 15 | let mut out = Vec::with_capacity(hex.len() / 2); 16 | 17 | let mut b = 0; 18 | for (idx, c) in hex.as_bytes().iter().enumerate() { 19 | b <<= 4; 20 | match *c { 21 | b'A'..=b'F' => b |= c - b'A' + 10, 22 | b'a'..=b'f' => b |= c - b'a' + 10, 23 | b'0'..=b'9' => b |= c - b'0', 24 | _ => return None, 25 | } 26 | if (idx & 1) == 1 { 27 | out.push(b); 28 | b = 0; 29 | } 30 | } 31 | 32 | Some(out) 33 | } 34 | 35 | pub fn to_compressed_pubkey(hex: &str) -> Option { 36 | if hex.len() != 33 * 2 { 37 | return None; 38 | } 39 | let data = match to_vec(&hex[0..33 * 2]) { 40 | Some(bytes) => bytes, 41 | None => return None, 42 | }; 43 | PublicKey::from_slice(&data).ok() 44 | } 45 | 46 | pub fn parse_pubkey(pubkey_str: &str) -> Result { 47 | let pubkey = to_compressed_pubkey(pubkey_str); 48 | if pubkey.is_none() { 49 | return Err(io::Error::new( 50 | io::ErrorKind::Other, 51 | "ERROR: unable to parse given pubkey for node", 52 | )); 53 | } 54 | 55 | Ok(pubkey.unwrap()) 56 | } 57 | -------------------------------------------------------------------------------- /lightning-liquidity/src/utils.rs: -------------------------------------------------------------------------------- 1 | use alloc::string::String; 2 | use core::{fmt::Write, ops::Deref}; 3 | 4 | use lightning::sign::EntropySource; 5 | 6 | use crate::lsps0::ser::LSPSRequestId; 7 | 8 | pub fn scid_from_human_readable_string(human_readable_scid: &str) -> Result { 9 | let mut parts = human_readable_scid.split('x'); 10 | 11 | let block: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?; 12 | let tx_index: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?; 13 | let vout_index: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?; 14 | 15 | Ok((block << 40) | (tx_index << 16) | vout_index) 16 | } 17 | 18 | pub(crate) fn generate_request_id(entropy_source: &ES) -> LSPSRequestId 19 | where 20 | ES::Target: EntropySource, 21 | { 22 | let bytes = entropy_source.get_secure_random_bytes(); 23 | LSPSRequestId(hex_str(&bytes[0..16])) 24 | } 25 | 26 | #[inline] 27 | pub fn hex_str(value: &[u8]) -> String { 28 | let mut res = String::with_capacity(2 * value.len()); 29 | for v in value { 30 | write!(&mut res, "{:02x}", v).expect("Unable to write"); 31 | } 32 | res 33 | } 34 | 35 | #[cfg(test)] 36 | mod tests { 37 | use super::*; 38 | use lightning::util::scid_utils::{block_from_scid, tx_index_from_scid, vout_from_scid}; 39 | 40 | #[test] 41 | fn parses_human_readable_scid_correctly() { 42 | let block = 140; 43 | let tx_index = 123; 44 | let vout = 22; 45 | 46 | let human_readable_scid = format!("{}x{}x{}", block, tx_index, vout); 47 | 48 | let scid = scid_from_human_readable_string(&human_readable_scid).unwrap(); 49 | 50 | assert_eq!(block_from_scid(scid), block); 51 | assert_eq!(tx_index_from_scid(scid), tx_index); 52 | assert_eq!(vout_from_scid(scid), vout); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /lightning-liquidity/tests/lsps0_integration_tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(all(test, feature = "std"))] 2 | 3 | mod common; 4 | 5 | use common::{create_service_and_client_nodes, get_lsps_message}; 6 | 7 | use lightning_liquidity::events::LiquidityEvent; 8 | use lightning_liquidity::lsps0::event::LSPS0ClientEvent; 9 | #[cfg(lsps1_service)] 10 | use lightning_liquidity::lsps1::client::LSPS1ClientConfig; 11 | #[cfg(lsps1_service)] 12 | use lightning_liquidity::lsps1::service::LSPS1ServiceConfig; 13 | use lightning_liquidity::lsps2::client::LSPS2ClientConfig; 14 | use lightning_liquidity::lsps2::service::LSPS2ServiceConfig; 15 | use lightning_liquidity::{LiquidityClientConfig, LiquidityServiceConfig}; 16 | 17 | use lightning::ln::peer_handler::CustomMessageHandler; 18 | 19 | #[test] 20 | fn list_protocols_integration_test() { 21 | let promise_secret = [42; 32]; 22 | let lsps2_service_config = LSPS2ServiceConfig { promise_secret }; 23 | #[cfg(lsps1_service)] 24 | let lsps1_service_config = LSPS1ServiceConfig { supported_options: None, token: None }; 25 | let service_config = LiquidityServiceConfig { 26 | #[cfg(lsps1_service)] 27 | lsps1_service_config: Some(lsps1_service_config), 28 | lsps2_service_config: Some(lsps2_service_config), 29 | advertise_service: true, 30 | }; 31 | 32 | let lsps2_client_config = LSPS2ClientConfig::default(); 33 | #[cfg(lsps1_service)] 34 | let lsps1_client_config: LSPS1ClientConfig = LSPS1ClientConfig { max_channel_fees_msat: None }; 35 | let client_config = LiquidityClientConfig { 36 | #[cfg(lsps1_service)] 37 | lsps1_client_config: Some(lsps1_client_config), 38 | #[cfg(not(lsps1_service))] 39 | lsps1_client_config: None, 40 | lsps2_client_config: Some(lsps2_client_config), 41 | }; 42 | 43 | let (service_node, client_node) = create_service_and_client_nodes( 44 | "list_protocols_integration_test", 45 | service_config, 46 | client_config, 47 | ); 48 | 49 | let service_node_id = service_node.channel_manager.get_our_node_id(); 50 | 51 | let client_handler = client_node.liquidity_manager.lsps0_client_handler(); 52 | let client_node_id = client_node.channel_manager.get_our_node_id(); 53 | 54 | client_handler.list_protocols(&service_node_id); 55 | let list_protocols_request = get_lsps_message!(client_node, service_node_id); 56 | 57 | service_node 58 | .liquidity_manager 59 | .handle_custom_message(list_protocols_request, client_node_id) 60 | .unwrap(); 61 | 62 | let list_protocols_response = get_lsps_message!(service_node, client_node_id); 63 | 64 | client_node 65 | .liquidity_manager 66 | .handle_custom_message(list_protocols_response, client_node_id) 67 | .unwrap(); 68 | 69 | let list_protocols_event = client_node.liquidity_manager.next_event().unwrap(); 70 | match list_protocols_event { 71 | LiquidityEvent::LSPS0Client(LSPS0ClientEvent::ListProtocolsResponse { 72 | counterparty_node_id, 73 | protocols, 74 | }) => { 75 | assert_eq!(counterparty_node_id, client_node_id); 76 | #[cfg(lsps1_service)] 77 | { 78 | assert!(protocols.contains(&1)); 79 | assert!(protocols.contains(&2)); 80 | assert_eq!(protocols.len(), 2); 81 | } 82 | 83 | #[cfg(not(lsps1_service))] 84 | assert_eq!(protocols, vec![2]); 85 | }, 86 | _ => panic!("Unexpected event"), 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /lightning-macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-macros" 3 | version = "0.2.0+git" 4 | authors = ["Elias Rohrer"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = """ 8 | Proc macros used by LDK 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | rustdoc-args = ["--cfg", "docsrs"] 14 | 15 | [lib] 16 | proc-macro = true 17 | 18 | [features] 19 | 20 | [dependencies] 21 | syn = { version = "2.0", default-features = false, features = ["parsing", "printing", "proc-macro", "full"] } 22 | proc-macro2 = { version = "1.0", default-features = false, features = ["proc-macro"] } 23 | quote = { version = "1.0", default-features = false, features = ["proc-macro"] } 24 | 25 | [dev-dependencies] 26 | inventory = "0.3" 27 | 28 | [lints] 29 | workspace = true 30 | -------------------------------------------------------------------------------- /lightning-net-tokio/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-net-tokio" 3 | version = "0.2.0+git" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = """ 8 | Implementation of the rust-lightning network stack using Tokio. 9 | For Rust-Lightning clients which wish to make direct connections to Lightning P2P nodes, this is a simple alternative to implementing the required network stack, especially for those already using Tokio. 10 | """ 11 | edition = "2021" 12 | 13 | [package.metadata.docs.rs] 14 | all-features = true 15 | rustdoc-args = ["--cfg", "docsrs"] 16 | 17 | [dependencies] 18 | bitcoin = "0.32.2" 19 | lightning = { version = "0.2.0", path = "../lightning" } 20 | tokio = { version = "1.35", features = [ "rt", "sync", "net", "time" ] } 21 | 22 | [dev-dependencies] 23 | tokio = { version = "1.35", features = [ "macros", "rt", "rt-multi-thread", "sync", "net", "time" ] } 24 | lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] } 25 | 26 | [lints] 27 | workspace = true 28 | -------------------------------------------------------------------------------- /lightning-persister/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-persister" 3 | version = "0.2.0+git" 4 | authors = ["Valentine Wallace", "Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | description = """ 8 | Utilities for LDK data persistence and retrieval. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [dependencies] 17 | bitcoin = "0.32.2" 18 | lightning = { version = "0.2.0", path = "../lightning" } 19 | 20 | [target.'cfg(windows)'.dependencies] 21 | windows-sys = { version = "0.48.0", default-features = false, features = ["Win32_Storage_FileSystem", "Win32_Foundation"] } 22 | 23 | [target.'cfg(ldk_bench)'.dependencies] 24 | criterion = { version = "0.4", optional = true, default-features = false } 25 | 26 | [dev-dependencies] 27 | lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] } 28 | bitcoin = { version = "0.32.2", default-features = false } 29 | 30 | [lints] 31 | workspace = true 32 | -------------------------------------------------------------------------------- /lightning-persister/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Provides utilities for LDK data persistence and retrieval. 2 | 3 | #![deny(rustdoc::broken_intra_doc_links)] 4 | #![deny(rustdoc::private_intra_doc_links)] 5 | #![deny(missing_docs)] 6 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 7 | 8 | #[cfg(ldk_bench)] 9 | extern crate criterion; 10 | 11 | pub mod fs_store; 12 | 13 | mod utils; 14 | 15 | #[cfg(test)] 16 | mod test_utils; 17 | -------------------------------------------------------------------------------- /lightning-rapid-gossip-sync/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-rapid-gossip-sync" 3 | version = "0.2.0+git" 4 | authors = ["Arik Sosman "] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | edition = "2021" 8 | description = """ 9 | Utility to process gossip routing data from Rapid Gossip Sync Server. 10 | """ 11 | 12 | [features] 13 | default = ["std"] 14 | std = ["bitcoin-io/std", "bitcoin_hashes/std"] 15 | 16 | [dependencies] 17 | lightning = { version = "0.2.0", path = "../lightning", default-features = false } 18 | bitcoin = { version = "0.32.2", default-features = false } 19 | bitcoin_hashes = { version = "0.14.0", default-features = false } 20 | bitcoin-io = { version = "0.1.2", default-features = false } 21 | 22 | [target.'cfg(ldk_bench)'.dependencies] 23 | criterion = { version = "0.4", optional = true, default-features = false } 24 | 25 | [dev-dependencies] 26 | lightning = { version = "0.2.0", path = "../lightning", features = ["_test_utils"] } 27 | 28 | [lints] 29 | workspace = true 30 | -------------------------------------------------------------------------------- /lightning-rapid-gossip-sync/res/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /lightning-tests/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-tests" 3 | version = "0.0.1" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = "Tests for LDK crates" 8 | edition = "2021" 9 | 10 | [features] 11 | 12 | [dependencies] 13 | lightning-types = { path = "../lightning-types", features = ["_test_utils"] } 14 | lightning-invoice = { path = "../lightning-invoice", default-features = false } 15 | lightning-macros = { path = "../lightning-macros" } 16 | lightning = { path = "../lightning", features = ["_test_utils"] } 17 | lightning_0_1 = { package = "lightning", version = "0.1.1", features = ["_test_utils"] } 18 | lightning_0_0_125 = { package = "lightning", version = "0.0.125", features = ["_test_utils"] } 19 | 20 | bitcoin = { version = "0.32.2", default-features = false } 21 | 22 | [dev-dependencies] 23 | -------------------------------------------------------------------------------- /lightning-tests/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg_attr(test, macro_use)] 2 | extern crate lightning; 3 | 4 | #[cfg(all(test, not(taproot)))] 5 | pub mod upgrade_downgrade_tests; 6 | -------------------------------------------------------------------------------- /lightning-transaction-sync/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-transaction-sync" 3 | version = "0.2.0+git" 4 | authors = ["Elias Rohrer"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning" 7 | description = """ 8 | Utilities for syncing LDK via the transaction-based `Confirm` interface. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [features] 17 | default = ["time"] 18 | time = [] 19 | esplora-async = ["async-interface", "esplora-client/async", "esplora-client/tokio", "futures"] 20 | esplora-async-https = ["esplora-async", "esplora-client/async-https-rustls"] 21 | esplora-blocking = ["esplora-client/blocking"] 22 | async-interface = [] 23 | 24 | # dummy feature to enable the common codepaths for electrum 25 | _electrum = [] 26 | # the 'default' electrum feature, enabling `rustls` with the `aws-lc-rs` crypto provider 27 | electrum = ["_electrum", "electrum-client/use-rustls"] 28 | electrum-rustls = ["electrum"] 29 | 30 | # this feature enables `rustls` with the `ring` crypto provider 31 | electrum-rustls-ring = ["_electrum", "electrum-client/use-rustls-ring"] 32 | 33 | [dependencies] 34 | lightning = { version = "0.2.0", path = "../lightning", default-features = false, features = ["std"] } 35 | lightning-macros = { version = "0.2", path = "../lightning-macros", default-features = false } 36 | bitcoin = { version = "0.32.2", default-features = false } 37 | futures = { version = "0.3", optional = true } 38 | esplora-client = { version = "0.12", default-features = false, optional = true } 39 | electrum-client = { version = "0.23.1", optional = true, default-features = false, features = ["proxy"] } 40 | 41 | [dev-dependencies] 42 | lightning = { version = "0.2.0", path = "../lightning", default-features = false, features = ["std", "_test_utils"] } 43 | tokio = { version = "1.35.0", features = ["macros"] } 44 | 45 | [target.'cfg(not(target_os = "windows"))'.dev-dependencies] 46 | electrsd = { version = "0.34.0", default-features = false, features = ["legacy"] } 47 | corepc-node = { version = "0.7.0", default-features = false, features = ["28_0"] } 48 | 49 | [lints.rust.unexpected_cfgs] 50 | level = "forbid" 51 | # When adding a new cfg attribute, ensure that it is added to this list. 52 | # 53 | # Note that Cargo automatically declares corresponding cfgs for every feature 54 | # defined in the member-level [features] tables as "expected". 55 | check-cfg = [ 56 | ] 57 | -------------------------------------------------------------------------------- /lightning-transaction-sync/src/error.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control history. 2 | // 3 | // This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in 6 | // accordance with one or both of these licenses. 7 | 8 | use std::fmt; 9 | 10 | #[derive(Debug)] 11 | /// An error that possibly needs to be handled by the user. 12 | pub enum TxSyncError { 13 | /// A transaction sync failed and needs to be retried eventually. 14 | Failed, 15 | } 16 | 17 | impl std::error::Error for TxSyncError {} 18 | 19 | impl fmt::Display for TxSyncError { 20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 21 | match *self { 22 | Self::Failed => write!(f, "Failed to conduct transaction sync."), 23 | } 24 | } 25 | } 26 | 27 | #[derive(Debug)] 28 | pub(crate) enum InternalError { 29 | /// A transaction sync failed and needs to be retried eventually. 30 | Failed, 31 | /// An inconsistency was encountered during transaction sync. 32 | Inconsistency, 33 | } 34 | 35 | impl fmt::Display for InternalError { 36 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 37 | match *self { 38 | Self::Failed => write!(f, "Failed to conduct transaction sync."), 39 | Self::Inconsistency => { 40 | write!(f, "Encountered an inconsistency during transaction sync.") 41 | }, 42 | } 43 | } 44 | } 45 | 46 | impl std::error::Error for InternalError {} 47 | 48 | impl From for TxSyncError { 49 | fn from(_e: InternalError) -> Self { 50 | Self::Failed 51 | } 52 | } 53 | 54 | #[cfg(any(feature = "esplora-blocking", feature = "esplora-async"))] 55 | impl From for TxSyncError { 56 | fn from(_e: esplora_client::Error) -> Self { 57 | Self::Failed 58 | } 59 | } 60 | 61 | #[cfg(any(feature = "esplora-blocking", feature = "esplora-async"))] 62 | impl From for InternalError { 63 | fn from(_e: esplora_client::Error) -> Self { 64 | Self::Failed 65 | } 66 | } 67 | 68 | #[cfg(feature = "_electrum")] 69 | impl From for InternalError { 70 | fn from(_e: electrum_client::Error) -> Self { 71 | Self::Failed 72 | } 73 | } 74 | 75 | #[cfg(feature = "_electrum")] 76 | impl From for TxSyncError { 77 | fn from(_e: electrum_client::Error) -> Self { 78 | Self::Failed 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /lightning-types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning-types" 3 | version = "0.3.0+git" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = """ 8 | Basic types which are used in the lightning network 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | rustdoc-args = ["--cfg", "docsrs"] 14 | 15 | [features] 16 | _test_utils = [] 17 | 18 | [dependencies] 19 | bitcoin = { version = "0.32.2", default-features = false } 20 | 21 | [lints] 22 | workspace = true 23 | -------------------------------------------------------------------------------- /lightning-types/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | #![crate_name = "lightning_types"] 11 | 12 | //! Various types which are used in the lightning network. 13 | //! 14 | //! See the `lightning` crate for usage of these. 15 | 16 | #![cfg_attr(not(test), no_std)] 17 | #![cfg_attr(not(fuzzing), deny(missing_docs))] 18 | #![forbid(unsafe_code)] 19 | #![deny(rustdoc::broken_intra_doc_links)] 20 | #![deny(rustdoc::private_intra_doc_links)] 21 | #![cfg_attr(docsrs, feature(doc_auto_cfg))] 22 | 23 | extern crate alloc; 24 | extern crate core; 25 | 26 | pub mod features; 27 | pub mod payment; 28 | pub mod routing; 29 | pub mod string; 30 | -------------------------------------------------------------------------------- /lightning-types/src/payment.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Types which describe payments in lightning. 11 | 12 | use core::borrow::Borrow; 13 | 14 | use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _}; 15 | use bitcoin::hex::display::impl_fmt_traits; 16 | 17 | /// The payment hash is the hash of the [`PaymentPreimage`] which is the value used to lock funds 18 | /// in HTLCs while they transit the lightning network. 19 | /// 20 | /// This is not exported to bindings users as we just use [u8; 32] directly 21 | #[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] 22 | pub struct PaymentHash(pub [u8; 32]); 23 | 24 | impl Borrow<[u8]> for PaymentHash { 25 | fn borrow(&self) -> &[u8] { 26 | &self.0[..] 27 | } 28 | } 29 | 30 | impl_fmt_traits! { 31 | impl fmt_traits for PaymentHash { 32 | const LENGTH: usize = 32; 33 | } 34 | } 35 | 36 | /// The payment preimage is the "secret key" which is used to claim the funds of an HTLC on-chain 37 | /// or in a lightning channel. 38 | /// 39 | /// This is not exported to bindings users as we just use [u8; 32] directly 40 | #[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] 41 | pub struct PaymentPreimage(pub [u8; 32]); 42 | 43 | impl Borrow<[u8]> for PaymentPreimage { 44 | fn borrow(&self) -> &[u8] { 45 | &self.0[..] 46 | } 47 | } 48 | 49 | impl_fmt_traits! { 50 | impl fmt_traits for PaymentPreimage { 51 | const LENGTH: usize = 32; 52 | } 53 | } 54 | 55 | /// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256. 56 | impl From for PaymentHash { 57 | fn from(value: PaymentPreimage) -> Self { 58 | PaymentHash(Sha256::hash(&value.0).to_byte_array()) 59 | } 60 | } 61 | 62 | /// The payment secret is used to authenticate the sender of an HTLC to the recipient and tie 63 | /// multi-part HTLCs together into a single payment. 64 | /// 65 | /// This is not exported to bindings users as we just use [u8; 32] directly 66 | #[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] 67 | pub struct PaymentSecret(pub [u8; 32]); 68 | 69 | impl Borrow<[u8]> for PaymentSecret { 70 | fn borrow(&self) -> &[u8] { 71 | &self.0[..] 72 | } 73 | } 74 | 75 | impl_fmt_traits! { 76 | impl fmt_traits for PaymentSecret { 77 | const LENGTH: usize = 32; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /lightning-types/src/routing.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Various types which describe routes or information about partial routes within the lightning 11 | //! network. 12 | 13 | use alloc::vec::Vec; 14 | 15 | use bitcoin::secp256k1::PublicKey; 16 | 17 | /// Fees for routing via a given channel or a node 18 | #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash, Ord, PartialOrd)] 19 | pub struct RoutingFees { 20 | /// Flat routing fee in millisatoshis. 21 | pub base_msat: u32, 22 | /// Liquidity-based routing fee in millionths of a routed amount. 23 | /// In other words, 10000 is 1%. 24 | pub proportional_millionths: u32, 25 | } 26 | 27 | /// A list of hops along a payment path terminating with a channel to the recipient. 28 | #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] 29 | pub struct RouteHint(pub Vec); 30 | 31 | /// A channel descriptor for a hop along a payment path. 32 | /// 33 | /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are 34 | /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as 35 | /// fields not supported in BOLT 11 will be stripped. 36 | #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] 37 | pub struct RouteHintHop { 38 | /// The node_id of the non-target end of the route 39 | pub src_node_id: PublicKey, 40 | /// The short_channel_id of this channel 41 | pub short_channel_id: u64, 42 | /// The fees which must be paid to use this channel 43 | pub fees: RoutingFees, 44 | /// The difference in CLTV values between this node and the next node. 45 | pub cltv_expiry_delta: u16, 46 | /// The minimum value, in msat, which must be relayed to the next hop. 47 | pub htlc_minimum_msat: Option, 48 | /// The maximum value in msat available for routing with a single HTLC. 49 | pub htlc_maximum_msat: Option, 50 | } 51 | -------------------------------------------------------------------------------- /lightning-types/src/string.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Utilities for strings. 11 | 12 | use alloc::string::String; 13 | use core::fmt; 14 | 15 | /// Struct to `Display` fields in a safe way using `PrintableString` 16 | #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] 17 | pub struct UntrustedString(pub String); 18 | 19 | impl fmt::Display for UntrustedString { 20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 21 | PrintableString(&self.0).fmt(f) 22 | } 23 | } 24 | 25 | /// A string that displays only printable characters, replacing control characters with 26 | /// [`core::char::REPLACEMENT_CHARACTER`]. 27 | #[derive(Debug, PartialEq)] 28 | pub struct PrintableString<'a>(pub &'a str); 29 | 30 | impl<'a> fmt::Display for PrintableString<'a> { 31 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 32 | use core::fmt::Write; 33 | for c in self.0.chars() { 34 | let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c }; 35 | f.write_char(c)?; 36 | } 37 | 38 | Ok(()) 39 | } 40 | } 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use super::PrintableString; 45 | 46 | #[test] 47 | fn displays_printable_string() { 48 | assert_eq!( 49 | format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")), 50 | "I \u{1F496} LDK!\u{FFFD}\u{26A1}", 51 | ); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /lightning/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lightning" 3 | version = "0.2.0+git" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = """ 8 | A Complete Bitcoin Lightning Library in Rust. 9 | Handles the core functionality of the Lightning Network, allowing clients to implement custom wallet, chain interactions, storage and network logic without enforcing a specific runtime. 10 | """ 11 | edition = "2021" 12 | 13 | [package.metadata.docs.rs] 14 | features = ["std", "dnssec"] 15 | rustdoc-args = ["--cfg", "docsrs"] 16 | 17 | [features] 18 | # Internal test utilities exposed to other repo crates 19 | _test_utils = ["regex", "bitcoin/bitcoinconsensus", "lightning-types/_test_utils"] 20 | _externalize_tests = ["inventory", "_test_utils"] 21 | # Allow signing of local transactions that may have been revoked or will be revoked, for functional testing (e.g. justice tx handling). 22 | # This is unsafe to use in production because it may result in the counterparty publishing taking our funds. 23 | unsafe_revoked_tx_signing = [] 24 | 25 | std = [] 26 | 27 | dnssec = ["dnssec-prover/validation"] 28 | 29 | # Generates low-r bitcoin signatures, which saves 1 byte in 50% of the cases 30 | grind_signatures = [] 31 | 32 | default = ["std", "grind_signatures"] 33 | 34 | [dependencies] 35 | lightning-types = { version = "0.3.0", path = "../lightning-types", default-features = false } 36 | lightning-invoice = { version = "0.34.0", path = "../lightning-invoice", default-features = false } 37 | lightning-macros = { version = "0.2", path = "../lightning-macros" } 38 | 39 | bech32 = { version = "0.11.0", default-features = false } 40 | bitcoin = { version = "0.32.2", default-features = false, features = ["secp-recovery"] } 41 | 42 | dnssec-prover = { version = "0.6", default-features = false } 43 | hashbrown = { version = "0.13", default-features = false } 44 | possiblyrandom = { version = "0.2", path = "../possiblyrandom", default-features = false } 45 | 46 | regex = { version = "1.5.6", optional = true } 47 | backtrace = { version = "0.3", optional = true } 48 | 49 | libm = { version = "0.2", default-features = false } 50 | inventory = { version = "0.3", optional = true } 51 | 52 | [dev-dependencies] 53 | regex = "1.5.6" 54 | lightning-types = { version = "0.3.0", path = "../lightning-types", features = ["_test_utils"] } 55 | lightning-macros = { path = "../lightning-macros" } 56 | parking_lot = { version = "0.12", default-features = false } 57 | 58 | [dev-dependencies.bitcoin] 59 | version = "0.32.2" 60 | default-features = false 61 | features = ["bitcoinconsensus", "secp-recovery"] 62 | 63 | [target.'cfg(ldk_bench)'.dependencies] 64 | criterion = { version = "0.4", optional = true, default-features = false } 65 | 66 | [target.'cfg(taproot)'.dependencies] 67 | musig2 = { git = "https://github.com/arik-so/rust-musig2", rev = "6f95a05718cbb44d8fe3fa6021aea8117aa38d50" } 68 | 69 | [lints] 70 | workspace = true 71 | -------------------------------------------------------------------------------- /lightning/src/crypto/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(not(fuzzing))] 2 | use bitcoin::hashes::cmp::fixed_time_eq; 3 | 4 | pub(crate) mod chacha20; 5 | pub(crate) mod chacha20poly1305rfc; 6 | #[cfg(not(fuzzing))] 7 | pub(crate) mod poly1305; 8 | pub(crate) mod streams; 9 | pub(crate) mod utils; 10 | -------------------------------------------------------------------------------- /lightning/src/crypto/utils.rs: -------------------------------------------------------------------------------- 1 | use bitcoin::hashes::hmac::{Hmac, HmacEngine}; 2 | use bitcoin::hashes::sha256::Hash as Sha256; 3 | use bitcoin::hashes::{Hash, HashEngine}; 4 | use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1, SecretKey, Signing}; 5 | 6 | use crate::sign::EntropySource; 7 | 8 | use core::ops::Deref; 9 | 10 | macro_rules! hkdf_extract_expand { 11 | ($salt: expr, $ikm: expr) => {{ 12 | let mut hmac = HmacEngine::::new($salt); 13 | hmac.input($ikm); 14 | let prk = Hmac::from_engine(hmac).to_byte_array(); 15 | let mut hmac = HmacEngine::::new(&prk[..]); 16 | hmac.input(&[1; 1]); 17 | let t1 = Hmac::from_engine(hmac).to_byte_array(); 18 | let mut hmac = HmacEngine::::new(&prk[..]); 19 | hmac.input(&t1); 20 | hmac.input(&[2; 1]); 21 | (t1, Hmac::from_engine(hmac).to_byte_array(), prk) 22 | }}; 23 | ($salt: expr, $ikm: expr, 2) => {{ 24 | let (k1, k2, _) = hkdf_extract_expand!($salt, $ikm); 25 | (k1, k2) 26 | }}; 27 | ($salt: expr, $ikm: expr, 6) => {{ 28 | let (k1, k2, prk) = hkdf_extract_expand!($salt, $ikm); 29 | 30 | let mut hmac = HmacEngine::::new(&prk[..]); 31 | hmac.input(&k2); 32 | hmac.input(&[3; 1]); 33 | let k3 = Hmac::from_engine(hmac).to_byte_array(); 34 | 35 | let mut hmac = HmacEngine::::new(&prk[..]); 36 | hmac.input(&k3); 37 | hmac.input(&[4; 1]); 38 | let k4 = Hmac::from_engine(hmac).to_byte_array(); 39 | 40 | let mut hmac = HmacEngine::::new(&prk[..]); 41 | hmac.input(&k4); 42 | hmac.input(&[5; 1]); 43 | let k5 = Hmac::from_engine(hmac).to_byte_array(); 44 | 45 | let mut hmac = HmacEngine::::new(&prk[..]); 46 | hmac.input(&k5); 47 | hmac.input(&[6; 1]); 48 | let k6 = Hmac::from_engine(hmac).to_byte_array(); 49 | 50 | (k1, k2, k3, k4, k5, k6) 51 | }}; 52 | } 53 | 54 | pub fn hkdf_extract_expand_twice(salt: &[u8], ikm: &[u8]) -> ([u8; 32], [u8; 32]) { 55 | hkdf_extract_expand!(salt, ikm, 2) 56 | } 57 | 58 | pub fn hkdf_extract_expand_6x( 59 | salt: &[u8], ikm: &[u8], 60 | ) -> ([u8; 32], [u8; 32], [u8; 32], [u8; 32], [u8; 32], [u8; 32]) { 61 | hkdf_extract_expand!(salt, ikm, 6) 62 | } 63 | 64 | #[inline] 65 | pub fn sign(ctx: &Secp256k1, msg: &Message, sk: &SecretKey) -> Signature { 66 | #[cfg(feature = "grind_signatures")] 67 | let sig = ctx.sign_ecdsa_low_r(msg, sk); 68 | #[cfg(not(feature = "grind_signatures"))] 69 | let sig = ctx.sign_ecdsa(msg, sk); 70 | sig 71 | } 72 | 73 | #[inline] 74 | #[allow(unused_variables)] 75 | pub fn sign_with_aux_rand( 76 | ctx: &Secp256k1, msg: &Message, sk: &SecretKey, entropy_source: &ES, 77 | ) -> Signature 78 | where 79 | ES::Target: EntropySource, 80 | { 81 | #[cfg(feature = "grind_signatures")] 82 | let sig = loop { 83 | let sig = ctx.sign_ecdsa_with_noncedata(msg, sk, &entropy_source.get_secure_random_bytes()); 84 | if sig.serialize_compact()[0] < 0x80 { 85 | break sig; 86 | } 87 | }; 88 | #[cfg(all(not(feature = "grind_signatures"), not(ldk_test_vectors)))] 89 | let sig = ctx.sign_ecdsa_with_noncedata(msg, sk, &entropy_source.get_secure_random_bytes()); 90 | #[cfg(all(not(feature = "grind_signatures"), ldk_test_vectors))] 91 | let sig = sign(ctx, msg, sk); 92 | sig 93 | } 94 | -------------------------------------------------------------------------------- /lightning/src/io/mod.rs: -------------------------------------------------------------------------------- 1 | pub use bitcoin::io::*; 2 | 3 | /// Emulation of std::io::Cursor 4 | /// 5 | /// This is not exported to bindings users as serialization is done via a bindings-specific 6 | /// pipeline. 7 | #[derive(Clone, Debug, Default, Eq, PartialEq)] 8 | pub struct Cursor { 9 | inner: T, 10 | pos: u64, 11 | } 12 | 13 | impl Cursor { 14 | /// Creates a `Cursor` by wrapping `inner`. 15 | #[inline] 16 | pub fn new(inner: T) -> Cursor { 17 | Cursor { pos: 0, inner } 18 | } 19 | 20 | /// Returns the position read up to thus far. 21 | #[inline] 22 | pub fn position(&self) -> u64 { 23 | self.pos 24 | } 25 | 26 | /// Returns the inner buffer. 27 | /// 28 | /// This is the whole wrapped buffer, including the bytes already read. 29 | #[inline] 30 | pub fn into_inner(self) -> T { 31 | self.inner 32 | } 33 | 34 | /// Gets a reference to the underlying value in this cursor. 35 | pub fn get_ref(&self) -> &T { 36 | &self.inner 37 | } 38 | 39 | /// Gets a mutable reference to the underlying value in this cursor. 40 | /// 41 | /// Care should be taken to avoid modifying the internal I/O state of the 42 | /// underlying value as it may corrupt this cursor's position. 43 | pub fn get_mut(&mut self) -> &mut T { 44 | &mut self.inner 45 | } 46 | 47 | /// Sets the position of this cursor. 48 | pub fn set_position(&mut self, pos: u64) { 49 | self.pos = pos; 50 | } 51 | } 52 | 53 | impl> Read for Cursor { 54 | fn read(&mut self, buf: &mut [u8]) -> Result { 55 | let n = Read::read(&mut self.fill_buf()?, buf)?; 56 | self.pos += n as u64; 57 | Ok(n) 58 | } 59 | 60 | fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { 61 | let n = buf.len(); 62 | Read::read_exact(&mut self.fill_buf()?, buf)?; 63 | self.pos += n as u64; 64 | Ok(()) 65 | } 66 | } 67 | 68 | impl> BufRead for Cursor { 69 | fn fill_buf(&mut self) -> Result<&[u8]> { 70 | let amt = core::cmp::min(self.pos, self.inner.as_ref().len() as u64); 71 | Ok(&self.inner.as_ref()[(amt as usize)..]) 72 | } 73 | fn consume(&mut self, amt: usize) { 74 | self.pos += amt as u64; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /lightning/src/offers/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Implementation of Lightning Offers 11 | //! ([BOLT 12](https://github.com/lightning/bolts/blob/master/12-offer-encoding.md)). 12 | //! 13 | //! Offers are a flexible protocol for Lightning payments. 14 | 15 | #[macro_use] 16 | pub mod offer; 17 | pub mod flow; 18 | 19 | pub(crate) mod async_receive_offer_cache; 20 | pub mod invoice; 21 | pub mod invoice_error; 22 | mod invoice_macros; 23 | pub mod invoice_request; 24 | pub mod merkle; 25 | pub mod nonce; 26 | pub mod parse; 27 | mod payer; 28 | pub mod refund; 29 | pub(crate) mod signer; 30 | pub mod static_invoice; 31 | #[cfg(test)] 32 | pub(crate) mod test_utils; 33 | -------------------------------------------------------------------------------- /lightning/src/offers/nonce.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! A number used only once. 11 | 12 | use crate::io::{self, Read}; 13 | use crate::ln::msgs::DecodeError; 14 | use crate::sign::EntropySource; 15 | use crate::util::ser::{Readable, Writeable, Writer}; 16 | use core::ops::Deref; 17 | 18 | #[allow(unused_imports)] 19 | use crate::prelude::*; 20 | 21 | /// A 128-bit number used only once. 22 | /// 23 | /// Needed when constructing [`Offer::metadata`] and deriving [`Offer::issuer_signing_pubkey`] from 24 | /// [`ExpandedKey`]. Must not be reused for any other derivation without first hashing. 25 | /// 26 | /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata 27 | /// [`Offer::issuer_signing_pubkey`]: crate::offers::offer::Offer::issuer_signing_pubkey 28 | /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey 29 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 30 | pub struct Nonce(pub(crate) [u8; Self::LENGTH]); 31 | 32 | impl Nonce { 33 | /// Number of bytes in the nonce. 34 | pub const LENGTH: usize = 16; 35 | 36 | /// Creates a `Nonce` from the given [`EntropySource`]. 37 | pub fn from_entropy_source(entropy_source: ES) -> Self 38 | where 39 | ES::Target: EntropySource, 40 | { 41 | let mut bytes = [0u8; Self::LENGTH]; 42 | let rand_bytes = entropy_source.get_secure_random_bytes(); 43 | bytes.copy_from_slice(&rand_bytes[..Self::LENGTH]); 44 | 45 | Nonce(bytes) 46 | } 47 | 48 | /// Returns a slice of the underlying bytes of size [`Nonce::LENGTH`]. 49 | pub fn as_slice(&self) -> &[u8] { 50 | &self.0 51 | } 52 | } 53 | 54 | impl TryFrom<&[u8]> for Nonce { 55 | type Error = (); 56 | 57 | fn try_from(bytes: &[u8]) -> Result { 58 | if bytes.len() != Self::LENGTH { 59 | return Err(()); 60 | } 61 | 62 | let mut copied_bytes = [0u8; Self::LENGTH]; 63 | copied_bytes.copy_from_slice(bytes); 64 | 65 | Ok(Self(copied_bytes)) 66 | } 67 | } 68 | 69 | impl Writeable for Nonce { 70 | fn write(&self, w: &mut W) -> Result<(), io::Error> { 71 | self.0.write(w) 72 | } 73 | } 74 | 75 | impl Readable for Nonce { 76 | fn read(r: &mut R) -> Result { 77 | Ok(Nonce(Readable::read(r)?)) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /lightning/src/offers/payer.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Data structures and encoding for `invoice_request_metadata` records. 11 | 12 | use crate::offers::signer::Metadata; 13 | use crate::util::ser::WithoutLength; 14 | 15 | #[allow(unused_imports)] 16 | use crate::prelude::*; 17 | 18 | /// An unpredictable sequence of bytes typically containing information needed to derive 19 | /// [`InvoiceRequest::payer_signing_pubkey`] and [`Refund::payer_signing_pubkey`]. 20 | /// 21 | /// [`InvoiceRequest::payer_signing_pubkey`]: crate::offers::invoice_request::InvoiceRequest::payer_signing_pubkey 22 | /// [`Refund::payer_signing_pubkey`]: crate::offers::refund::Refund::payer_signing_pubkey 23 | #[derive(Clone, Debug)] 24 | #[cfg_attr(test, derive(PartialEq))] 25 | pub(super) struct PayerContents(pub Metadata); 26 | 27 | /// TLV record type for [`InvoiceRequest::payer_metadata`] and [`Refund::payer_metadata`]. 28 | /// 29 | /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata 30 | /// [`Refund::payer_metadata`]: crate::offers::refund::Refund::payer_metadata 31 | pub(super) const PAYER_METADATA_TYPE: u64 = 0; 32 | 33 | tlv_stream!(PayerTlvStream, PayerTlvStreamRef<'a>, 0..1, { 34 | (PAYER_METADATA_TYPE, metadata: (Vec, WithoutLength)), 35 | }); 36 | -------------------------------------------------------------------------------- /lightning/src/onion_message/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Onion Messages: sending, receiving, forwarding, and ancillary utilities live here 11 | //! 12 | //! Onion messages are multi-purpose messages sent between peers over the lightning network. In the 13 | //! near future, they will be used to communicate invoices for [offers], unlocking use cases such as 14 | //! static invoices, refunds and proof of payer. Further, you will be able to accept payments 15 | //! without revealing your node id through the use of [blinded paths]. 16 | //! 17 | //! LDK sends and receives onion messages via the [`OnionMessenger`]. See its documentation for more 18 | //! information on its usage. 19 | //! 20 | //! [offers]: 21 | //! [blinded paths]: crate::blinded_path::message::BlindedMessagePath 22 | //! [`OnionMessenger`]: self::messenger::OnionMessenger 23 | 24 | pub mod async_payments; 25 | pub mod dns_resolution; 26 | #[cfg(test)] 27 | mod functional_tests; 28 | pub mod messenger; 29 | pub mod offers; 30 | pub mod packet; 31 | -------------------------------------------------------------------------------- /lightning/src/routing/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! Structs and impls for receiving messages about the network and storing the topology live here. 11 | 12 | pub mod gossip; 13 | mod log_approx; 14 | pub mod router; 15 | pub mod scoring; 16 | #[cfg(test)] 17 | pub(crate) mod test_utils; 18 | pub mod utxo; 19 | -------------------------------------------------------------------------------- /lightning/src/sign/type_resolver.rs: -------------------------------------------------------------------------------- 1 | use crate::sign::{ChannelSigner, SignerProvider}; 2 | use core::ops::Deref; 3 | 4 | pub(crate) enum ChannelSignerType 5 | where 6 | SP::Target: SignerProvider, 7 | { 8 | // in practice, this will only ever be an EcdsaChannelSigner (specifically, Writeable) 9 | Ecdsa(::EcdsaSigner), 10 | #[cfg(taproot)] 11 | #[allow(unused)] 12 | Taproot(::TaprootSigner), 13 | } 14 | 15 | impl ChannelSignerType 16 | where 17 | SP::Target: SignerProvider, 18 | { 19 | pub(crate) fn as_ref(&self) -> &dyn ChannelSigner { 20 | match self { 21 | ChannelSignerType::Ecdsa(ecs) => ecs, 22 | #[cfg(taproot)] 23 | #[allow(unused)] 24 | ChannelSignerType::Taproot(tcs) => tcs, 25 | } 26 | } 27 | 28 | #[allow(unused)] 29 | pub(crate) fn as_ecdsa(&self) -> Option<&::EcdsaSigner> { 30 | match self { 31 | ChannelSignerType::Ecdsa(ecs) => Some(ecs), 32 | _ => None, 33 | } 34 | } 35 | 36 | #[allow(unused)] 37 | pub(crate) fn as_mut_ecdsa( 38 | &mut self, 39 | ) -> Option<&mut ::EcdsaSigner> { 40 | match self { 41 | ChannelSignerType::Ecdsa(ecs) => Some(ecs), 42 | _ => None, 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /lightning/src/sync/fairrwlock.rs: -------------------------------------------------------------------------------- 1 | use super::{LockHeldState, LockTestExt}; 2 | use std::sync::atomic::{AtomicUsize, Ordering}; 3 | use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockResult}; 4 | 5 | /// Rust libstd's RwLock does not provide any fairness guarantees (and, in fact, when used on 6 | /// Linux with pthreads under the hood, readers trivially and completely starve writers). 7 | /// Because we often hold read locks while doing message processing in multiple threads which 8 | /// can use significant CPU time, with write locks being time-sensitive but relatively small in 9 | /// CPU time, we can end up with starvation completely blocking incoming connections or pings, 10 | /// especially during initial graph sync. 11 | /// 12 | /// Thus, we need to block readers when a writer is pending, which we do with a trivial RwLock 13 | /// wrapper here. Its not particularly optimized, but provides some reasonable fairness by 14 | /// blocking readers (by taking the write lock) if there are writers pending when we go to take 15 | /// a read lock. 16 | pub struct FairRwLock { 17 | lock: RwLock, 18 | waiting_writers: AtomicUsize, 19 | } 20 | 21 | impl FairRwLock { 22 | pub fn new(t: T) -> Self { 23 | Self { lock: RwLock::new(t), waiting_writers: AtomicUsize::new(0) } 24 | } 25 | 26 | // Note that all atomic accesses are relaxed, as we do not rely on the atomics here for any 27 | // ordering at all, instead relying on the underlying RwLock to provide ordering of unrelated 28 | // memory. 29 | pub fn write(&self) -> LockResult> { 30 | self.waiting_writers.fetch_add(1, Ordering::Relaxed); 31 | let res = self.lock.write(); 32 | self.waiting_writers.fetch_sub(1, Ordering::Relaxed); 33 | res 34 | } 35 | 36 | pub fn read(&self) -> LockResult> { 37 | if self.waiting_writers.load(Ordering::Relaxed) != 0 { 38 | let _write_queue_lock = self.lock.write(); 39 | } 40 | // Note that we don't consider ensuring that an underlying RwLock allowing writers to 41 | // starve readers doesn't exhibit the same behavior here. I'm not aware of any 42 | // libstd-backing RwLock which exhibits this behavior, and as documented in the 43 | // struct-level documentation, it shouldn't pose a significant issue for our current 44 | // codebase. 45 | self.lock.read() 46 | } 47 | 48 | #[allow(dead_code)] 49 | pub fn try_write(&self) -> TryLockResult> { 50 | self.lock.try_write() 51 | } 52 | } 53 | 54 | impl<'a, T: 'a> LockTestExt<'a> for FairRwLock { 55 | #[inline] 56 | fn held_by_thread(&self) -> LockHeldState { 57 | // fairrwlock is only built in non-test modes, so we should never support tests. 58 | LockHeldState::Unsupported 59 | } 60 | type ExclLock = RwLockWriteGuard<'a, T>; 61 | #[inline] 62 | fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<'a, T> { 63 | self.write().unwrap() 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /lightning/src/sync/mod.rs: -------------------------------------------------------------------------------- 1 | #[allow(dead_code)] // Depending on the compilation flags some variants are never used 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub(crate) enum LockHeldState { 4 | HeldByThread, 5 | NotHeldByThread, 6 | #[cfg(any(ldk_bench, not(test)))] 7 | Unsupported, 8 | } 9 | 10 | pub(crate) trait LockTestExt<'a> { 11 | fn held_by_thread(&self) -> LockHeldState; 12 | type ExclLock; 13 | /// If two instances of the same mutex are being taken at the same time, it's very easy to have 14 | /// a lockorder inversion and risk deadlock. Thus, we default to disabling such locks. 15 | /// 16 | /// However, sometimes they cannot be avoided. In such cases, this method exists to take a 17 | /// mutex while avoiding a test failure. It is deliberately verbose and includes the term 18 | /// "unsafe" to indicate that special care needs to be taken to ensure no deadlocks are 19 | /// possible. 20 | fn unsafe_well_ordered_double_lock_self(&'a self) -> Self::ExclLock; 21 | } 22 | 23 | #[cfg(all(feature = "std", not(ldk_bench), test))] 24 | mod debug_sync; 25 | #[cfg(all(feature = "std", not(ldk_bench), test))] 26 | pub use debug_sync::*; 27 | #[cfg(all(feature = "std", not(ldk_bench), test))] 28 | // Note that to make debug_sync's regex work this must not contain `debug_string` in the module name 29 | mod test_lockorder_checks; 30 | 31 | #[cfg(all(feature = "std", any(ldk_bench, not(test))))] 32 | pub(crate) mod fairrwlock; 33 | #[cfg(all(feature = "std", any(ldk_bench, not(test))))] 34 | pub use { 35 | fairrwlock::FairRwLock, 36 | std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}, 37 | }; 38 | 39 | #[cfg(all(feature = "std", any(ldk_bench, not(test))))] 40 | mod ext_impl { 41 | use super::*; 42 | impl<'a, T: 'a> LockTestExt<'a> for Mutex { 43 | #[inline] 44 | fn held_by_thread(&self) -> LockHeldState { 45 | LockHeldState::Unsupported 46 | } 47 | type ExclLock = MutexGuard<'a, T>; 48 | #[inline] 49 | fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<'a, T> { 50 | self.lock().unwrap() 51 | } 52 | } 53 | impl<'a, T: 'a> LockTestExt<'a> for RwLock { 54 | #[inline] 55 | fn held_by_thread(&self) -> LockHeldState { 56 | LockHeldState::Unsupported 57 | } 58 | type ExclLock = RwLockWriteGuard<'a, T>; 59 | #[inline] 60 | fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<'a, T> { 61 | self.write().unwrap() 62 | } 63 | } 64 | } 65 | 66 | #[cfg(not(feature = "std"))] 67 | mod nostd_sync; 68 | #[cfg(not(feature = "std"))] 69 | pub use nostd_sync::*; 70 | -------------------------------------------------------------------------------- /lightning/src/sync/test_lockorder_checks.rs: -------------------------------------------------------------------------------- 1 | use crate::sync::debug_sync::{Mutex, RwLock}; 2 | 3 | use super::{LockHeldState, LockTestExt}; 4 | 5 | use std::sync::Arc; 6 | 7 | #[test] 8 | #[should_panic] 9 | #[cfg(not(feature = "backtrace"))] 10 | fn recursive_lock_fail() { 11 | let mutex = Mutex::new(()); 12 | let _a = mutex.lock().unwrap(); 13 | let _b = mutex.lock().unwrap(); 14 | } 15 | 16 | #[test] 17 | #[should_panic] 18 | #[cfg(not(feature = "backtrace"))] 19 | fn recursive_read() { 20 | let lock = RwLock::new(()); 21 | let _a = lock.read().unwrap(); 22 | let _b = lock.read().unwrap(); 23 | } 24 | 25 | #[test] 26 | #[should_panic] 27 | fn lockorder_fail() { 28 | let a = Mutex::new(()); 29 | let b = Mutex::new(()); 30 | { 31 | let _a = a.lock().unwrap(); 32 | let _b = b.lock().unwrap(); 33 | } 34 | { 35 | let _b = b.lock().unwrap(); 36 | let _a = a.lock().unwrap(); 37 | } 38 | } 39 | 40 | #[test] 41 | #[should_panic] 42 | fn write_lockorder_fail() { 43 | let a = RwLock::new(()); 44 | let b = RwLock::new(()); 45 | { 46 | let _a = a.write().unwrap(); 47 | let _b = b.write().unwrap(); 48 | } 49 | { 50 | let _b = b.write().unwrap(); 51 | let _a = a.write().unwrap(); 52 | } 53 | } 54 | 55 | #[test] 56 | #[should_panic] 57 | fn read_lockorder_fail() { 58 | let a = RwLock::new(()); 59 | let b = RwLock::new(()); 60 | { 61 | let _a = a.read().unwrap(); 62 | let _b = b.read().unwrap(); 63 | } 64 | { 65 | let _b = b.read().unwrap(); 66 | let _a = a.read().unwrap(); 67 | } 68 | } 69 | 70 | #[test] 71 | #[should_panic] 72 | fn read_write_lockorder_fail() { 73 | let a = RwLock::new(()); 74 | let b = RwLock::new(()); 75 | { 76 | let _a = a.write().unwrap(); 77 | let _b = b.read().unwrap(); 78 | } 79 | { 80 | let _b = b.read().unwrap(); 81 | let _a = a.write().unwrap(); 82 | } 83 | } 84 | 85 | #[test] 86 | fn test_thread_locked_state() { 87 | let mtx = Arc::new(Mutex::new(())); 88 | let mtx_ref = Arc::clone(&mtx); 89 | assert_eq!(mtx.held_by_thread(), LockHeldState::NotHeldByThread); 90 | 91 | let lck = mtx.lock().unwrap(); 92 | assert_eq!(mtx.held_by_thread(), LockHeldState::HeldByThread); 93 | 94 | let thrd = std::thread::spawn(move || { 95 | assert_eq!(mtx_ref.held_by_thread(), LockHeldState::NotHeldByThread); 96 | }); 97 | thrd.join().unwrap(); 98 | assert_eq!(mtx.held_by_thread(), LockHeldState::HeldByThread); 99 | 100 | std::mem::drop(lck); 101 | assert_eq!(mtx.held_by_thread(), LockHeldState::NotHeldByThread); 102 | } 103 | -------------------------------------------------------------------------------- /lightning/src/util/atomic_counter.rs: -------------------------------------------------------------------------------- 1 | //! A simple atomic counter that uses mutexes if the platform doesn't support atomic u64s. 2 | 3 | #[cfg(not(target_has_atomic = "64"))] 4 | use crate::sync::Mutex; 5 | #[cfg(target_has_atomic = "64")] 6 | use core::sync::atomic::{AtomicU64, Ordering}; 7 | 8 | pub(crate) struct AtomicCounter { 9 | #[cfg(target_has_atomic = "64")] 10 | counter: AtomicU64, 11 | #[cfg(not(target_has_atomic = "64"))] 12 | counter: Mutex, 13 | } 14 | 15 | impl AtomicCounter { 16 | pub(crate) fn new() -> Self { 17 | Self { 18 | #[cfg(target_has_atomic = "64")] 19 | counter: AtomicU64::new(0), 20 | #[cfg(not(target_has_atomic = "64"))] 21 | counter: Mutex::new(0), 22 | } 23 | } 24 | pub(crate) fn next(&self) -> u64 { 25 | #[cfg(target_has_atomic = "64")] 26 | { 27 | self.counter.fetch_add(1, Ordering::AcqRel) 28 | } 29 | #[cfg(not(target_has_atomic = "64"))] 30 | { 31 | let mut mtx = self.counter.lock().unwrap(); 32 | *mtx += 1; 33 | *mtx - 1 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /lightning/src/util/byte_utils.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | #[inline] 11 | pub fn slice_to_be48(v: &[u8]) -> u64 { 12 | ((v[0] as u64) << 8 * 5) 13 | | ((v[1] as u64) << 8 * 4) 14 | | ((v[2] as u64) << 8 * 3) 15 | | ((v[3] as u64) << 8 * 2) 16 | | ((v[4] as u64) << 8 * 1) 17 | | ((v[5] as u64) << 8 * 0) 18 | } 19 | #[inline] 20 | pub fn be48_to_array(u: u64) -> [u8; 6] { 21 | assert!(u & 0xffff_0000_0000_0000 == 0); 22 | let mut v = [0; 6]; 23 | v[0] = ((u >> 8 * 5) & 0xff) as u8; 24 | v[1] = ((u >> 8 * 4) & 0xff) as u8; 25 | v[2] = ((u >> 8 * 3) & 0xff) as u8; 26 | v[3] = ((u >> 8 * 2) & 0xff) as u8; 27 | v[4] = ((u >> 8 * 1) & 0xff) as u8; 28 | v[5] = ((u >> 8 * 0) & 0xff) as u8; 29 | v 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn test_all() { 38 | assert_eq!(slice_to_be48(&[0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]), 0xdeadbeef1bad); 39 | assert_eq!(be48_to_array(0xdeadbeef1bad), [0xde, 0xad, 0xbe, 0xef, 0x1b, 0xad]); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lightning/src/util/fuzz_wrappers.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | macro_rules! hash_to_message { 11 | ($slice: expr) => {{ 12 | #[cfg(not(fuzzing))] 13 | { 14 | ::bitcoin::secp256k1::Message::from_digest_slice($slice).unwrap() 15 | } 16 | #[cfg(fuzzing)] 17 | { 18 | match ::bitcoin::secp256k1::Message::from_digest_slice($slice) { 19 | Ok(msg) => msg, 20 | Err(_) => ::bitcoin::secp256k1::Message::from_digest([1; 32]), 21 | } 22 | } 23 | }}; 24 | } 25 | -------------------------------------------------------------------------------- /lightning/src/util/mut_global.rs: -------------------------------------------------------------------------------- 1 | //! A settable global variable. 2 | //! 3 | //! Used for testing purposes only. 4 | 5 | use std::sync::Mutex; 6 | 7 | /// A global variable that can be set exactly once. 8 | pub struct MutGlobal { 9 | value: Mutex>, 10 | default_fn: fn() -> T, 11 | } 12 | 13 | impl MutGlobal { 14 | /// Create a new `MutGlobal` with no value set. 15 | /// 16 | /// default_fn will be called to get the default value if the value is unset 17 | /// at the time the first call to `get` is made. 18 | pub const fn new(default_fn: fn() -> T) -> Self { 19 | Self { value: Mutex::new(None), default_fn } 20 | } 21 | 22 | /// Set the value of the global variable. 23 | pub fn set(&self, value: T) { 24 | let mut lock = self.value.lock().unwrap(); 25 | *lock = Some(value); 26 | } 27 | 28 | /// Get the value of the global variable, or the default if unset. 29 | pub fn get(&self) -> T { 30 | let mut lock = self.value.lock().unwrap(); 31 | if let Some(value) = &*lock { 32 | value.clone() 33 | } else { 34 | let value = (self.default_fn)(); 35 | *lock = Some(value.clone()); 36 | value 37 | } 38 | } 39 | } 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | use super::*; 44 | 45 | #[test] 46 | fn test() { 47 | let v = MutGlobal::::new(|| 0); 48 | assert_eq!(v.get(), 0); 49 | v.set(42); 50 | assert_eq!(v.get(), 42); 51 | v.set(43); 52 | assert_eq!(v.get(), 43); 53 | } 54 | 55 | static G: MutGlobal = MutGlobal::new(|| 0); 56 | 57 | #[test] 58 | fn test_global() { 59 | G.set(42); 60 | assert_eq!(G.get(), 42); 61 | G.set(43); 62 | assert_eq!(G.get(), 43); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /lightning/src/util/time.rs: -------------------------------------------------------------------------------- 1 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 3 | // , at your option. 4 | // You may not use this file except in accordance with one or both of these 5 | // licenses. 6 | 7 | //! A simple module which either re-exports [`std::time::Instant`] or a mocked version of it for 8 | //! tests. 9 | 10 | #[cfg(not(test))] 11 | pub use std::time::Instant; 12 | #[cfg(test)] 13 | pub use test::Instant; 14 | 15 | #[cfg(test)] 16 | mod test { 17 | use core::cell::Cell; 18 | use core::ops::Sub; 19 | use core::time::Duration; 20 | 21 | /// Time that can be advanced manually in tests. 22 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 23 | pub struct Instant(Duration); 24 | 25 | impl Instant { 26 | thread_local! { 27 | static ELAPSED: Cell = const { Cell::new(Duration::from_secs(0)) }; 28 | } 29 | 30 | pub fn advance(duration: Duration) { 31 | Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration)) 32 | } 33 | 34 | pub fn now() -> Self { 35 | Self(Self::ELAPSED.with(|elapsed| elapsed.get())) 36 | } 37 | 38 | pub fn duration_since(&self, earlier: Self) -> Duration { 39 | self.0 - earlier.0 40 | } 41 | } 42 | 43 | impl Sub for Instant { 44 | type Output = Self; 45 | 46 | fn sub(self, other: Duration) -> Self { 47 | Self(self.0 - other) 48 | } 49 | } 50 | 51 | #[test] 52 | fn time_passes_when_advanced() { 53 | let now = Instant::now(); 54 | 55 | Instant::advance(Duration::from_secs(1)); 56 | Instant::advance(Duration::from_secs(1)); 57 | 58 | let later = Instant::now(); 59 | 60 | assert_eq!(now.0 + Duration::from_secs(2), later.0); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /msrv-no-dev-deps-check/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "msrv-check" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | lightning = { path = "../lightning" } 8 | lightning-block-sync = { path = "../lightning-block-sync", features = [ "rest-client", "rpc-client" ] } 9 | lightning-invoice = { path = "../lightning-invoice" } 10 | lightning-net-tokio = { path = "../lightning-net-tokio" } 11 | lightning-persister = { path = "../lightning-persister" } 12 | lightning-background-processor = { path = "../lightning-background-processor" } 13 | lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync" } 14 | lightning-custom-message = { path = "../lightning-custom-message" } 15 | -------------------------------------------------------------------------------- /msrv-no-dev-deps-check/src/lib.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /no-std-check/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "no-std-check" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [features] 7 | default = [] 8 | 9 | [dependencies] 10 | lightning = { path = "../lightning", default-features = false } 11 | lightning-invoice = { path = "../lightning-invoice", default-features = false } 12 | lightning-rapid-gossip-sync = { path = "../lightning-rapid-gossip-sync", default-features = false } 13 | lightning-background-processor = { path = "../lightning-background-processor", default-features = false } 14 | -------------------------------------------------------------------------------- /no-std-check/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | -------------------------------------------------------------------------------- /pending_changelog/.empty_folder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightningdevkit/rust-lightning/257ebad277a0901db69c69b0d5c79c6d27c2b04e/pending_changelog/.empty_folder -------------------------------------------------------------------------------- /pending_changelog/3137-accept-dual-funding-without-contributing.txt: -------------------------------------------------------------------------------- 1 | # API Updates (0.2) 2 | * Accepting dual-funded (V2 establishment) channels (without contibuting) is now supported (#3137). 3 | Some particulars to be aware of for this feature: 4 | * Creating dual-funded channels is not yet supported. 5 | * Contributing funds (inputs) to accepted channels is not yet supported. 6 | * `Event::OpenChannelRequest::push_msat` has been replaced by the field `channel_negotiation_type` to 7 | differentiate between an inbound request for a dual-funded (V2) or non-dual-funded (V1) channel to be 8 | opened, with value being either of the enum variants `InboundChannelFunds::DualFunded` and 9 | `InboundChannelFunds::PushMsat(u64)` corresponding to V2 and V1 channel open requests respectively. 10 | * If `manually_accept_inbound_channels` is false, then V2 channels will be accepted automatically; the 11 | same behaviour as V1 channels. Otherwise, `ChannelManager::accept_inbound_channel()` can also be used 12 | to manually accept an inbound V2 channel. 13 | * 0conf dual-funded channels are not supported. 14 | * RBF of dual-funded channel funding transactions is not supported. 15 | 16 | -------------------------------------------------------------------------------- /pending_changelog/3531-buggy-router-leak.txt: -------------------------------------------------------------------------------- 1 | ## Bug Fixes 2 | 3 | * Fixed a rare case where a custom router returning a buggy route could result in holding onto a 4 | pending payment forever and in some cases failing to generate a PaymentFailed event (#3531). 5 | -------------------------------------------------------------------------------- /pending_changelog/3604-upgrades-prior-to-113-not-supported.txt: -------------------------------------------------------------------------------- 1 | ## API Updates (0.2) 2 | * Upgrading from versions prior to 0.0.113 is no longer supported (#3604). 3 | -------------------------------------------------------------------------------- /pending_changelog/3638-0.2-upgrade-without-counterparty-node-id-in-monitor-not-supported.txt: -------------------------------------------------------------------------------- 1 | ## API Updates (0.2) 2 | 3 | * Upgrading to v0.2.0 is not allowed when a `ChannelMonitor` that does not track the channel's 4 | `counterparty_node_id` is loaded. Upgrade to a v0.1.* release first and either send/route a 5 | payment over the channel, or close it, before upgrading to v0.2.0. 6 | -------------------------------------------------------------------------------- /pending_changelog/3664-downgrades-to-0.0.115-not-supported.txt: -------------------------------------------------------------------------------- 1 | # API Updates (0.2) 2 | 3 | Downgrading to v0.0.115 is no longer supported if a node has an HTLC routed/settled while running v0.2 or later. 4 | -------------------------------------------------------------------------------- /pending_changelog/3678-channel-type-check.txt: -------------------------------------------------------------------------------- 1 | ## API Updates (0.2) 2 | 3 | * Upgrading to v0.2.0 from a version prior to 0.0.116 is not allowed when a channel was opened with 4 | either `scid_privacy` or `zero_conf` included in its channel type. Upgrade to v0.0.116 first 5 | before upgrading to v0.2.0. 6 | -------------------------------------------------------------------------------- /pending_changelog/3700-reason-in-handling-failed.txt: -------------------------------------------------------------------------------- 1 | ## API Updates (0.2) 2 | 3 | * The `HTLCHandlingFailed` event was updated to include a `failure_reason` field that provides 4 | additional information about why the HTLC was failed. 5 | * The `failed_next_destination` field, which previously contained a combination of failure 6 | and HTLC-related information, was renamed to `failure_type` and the `UnknownNextHop` 7 | variant was deprecated. This type will be represented as `InvalidForward` for nodes 8 | downgrading from v0.2.0. 9 | -------------------------------------------------------------------------------- /possiblyrandom/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "possiblyrandom" 3 | version = "0.2.0" 4 | authors = ["Matt Corallo"] 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/lightningdevkit/rust-lightning/" 7 | description = """ 8 | A crate that wraps getrandom and always compiles, returning 0s when no randomness is available. 9 | """ 10 | edition = "2021" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | rustdoc-args = ["--cfg", "docsrs"] 15 | 16 | [dependencies] 17 | getrandom = { version = "0.2", optional = true, default-features = false } 18 | 19 | # Enable getrandom if we are on a platform that (likely) supports it 20 | [target.'cfg(not(any(target_os = "unknown", target_os = "none")))'.dependencies] 21 | getrandom = { version = "0.2", default-features = false } 22 | 23 | [lints] 24 | workspace = true 25 | -------------------------------------------------------------------------------- /possiblyrandom/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is Copyright its original authors, visible in version control 2 | // history. 3 | // 4 | // This file is licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your option. 7 | // You may not use this file except in accordance with one or both of these 8 | // licenses. 9 | 10 | //! [`getrandom`] provides access to OS randomness, but will fail to compile on platforms that do 11 | //! not support fetching OS randomness. This is exactly what you want when you're doing 12 | //! cryptographic operations, but when you're just opportunistically randomizing, we're fine with 13 | //! compiling and simply disabling randomization. 14 | //! 15 | //! This crate does that, returning only possibly-random data. 16 | //! 17 | //! Note that this crate only enables getrandom on a subset of platforms it supports. As getrandom 18 | //! evolves this crate is unlikely to carefully track all getrandom-supported platforms, however 19 | //! will use random data on popular platforms. 20 | 21 | #![no_std] 22 | 23 | #[cfg(feature = "getrandom")] 24 | extern crate getrandom; 25 | 26 | /// Possibly fills `dest` with random data. May fill it with zeros. 27 | #[inline] 28 | pub fn getpossiblyrandom(dest: &mut [u8]) { 29 | #[cfg(feature = "getrandom")] 30 | if getrandom::getrandom(dest).is_err() { 31 | dest.fill(0); 32 | } 33 | #[cfg(not(feature = "getrandom"))] 34 | dest.fill(0); 35 | } 36 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | use_small_heuristics = "Max" 2 | fn_args_layout = "Compressed" 3 | hard_tabs = true 4 | use_field_init_shorthand = true 5 | max_width = 100 6 | match_block_trailing_comma = true 7 | # UNSTABLE: format_code_in_doc_comments = true 8 | # UNSTABLE: overflow_delimited_expr = true 9 | # UNSTABLE: comment_width = 100 10 | # UNSTABLE: format_macro_matchers = true 11 | # UNSTABLE: format_strings = true 12 | # UNSTABLE: group_imports = "StdExternalCrate" 13 | --------------------------------------------------------------------------------