Compare commits

..

No commits in common. "master" and "main" have entirely different histories.
master ... main

69 changed files with 250 additions and 13966 deletions

View File

@ -1,7 +1,7 @@
version: 2.1
defaults:
default-xcode-version: &default-xcode-version "14.1.0"
default-xcode-version: &default-xcode-version "12.5.1"
default-ruby-version: &default-ruby-version "2.7"
default-environment: &default-environment
@ -75,7 +75,7 @@ commands:
steps:
- restore_cache:
name: Restore Homebrew cache
key: v1-homebrew-{{ arch }}
key: v0-homebrew-{{ arch }}
- run:
name: Update Homebrew
working_directory: Vendor/mobilecoin
@ -90,7 +90,6 @@ commands:
rm '/usr/local/lib/python3.9/site-packages/six.py'
brew install llvm
brew install ninja
brew install pkg-config
brew bundle --no-upgrade
save-homebrew-cache:
@ -162,7 +161,7 @@ commands:
- restore_cache:
name: Restore build artifact libmobilecoin.a cache for target <<parameters.build-target>>
keys:
- v2-build-artifact-<<parameters.build-target>>-{{ checksum "libmobilecoin_and_vendor_mobilecoin.hash" }}
- v2-build-artifact-<<parameters.build-target>>-{{ checksum "vendor_mobilecoin.hash" }}
save-build-artifact-cache:
parameters:
@ -173,9 +172,9 @@ commands:
- print-mobilecoin-submodule-hash
- save_cache:
name: Save build artifact libmobilecoin.a cache for target <<parameters.build-target>>
key: v2-build-artifact-<<parameters.build-target>>-{{ checksum "libmobilecoin_and_vendor_mobilecoin.hash" }}
key: v2-build-artifact-<<parameters.build-target>>-{{ checksum "vendor_mobilecoin.hash" }}
paths:
- ~/project/libmobilecoin/out/ios/target/<<parameters.build-target>>/mobile-release
- ~/project/Vendor/mobilecoin/libmobilecoin/out/ios/target/<<parameters.build-target>>/mobile-release
#
# LibMobileCoin Headers
@ -186,16 +185,16 @@ commands:
- restore_cache:
name: Restore build artifact headers cache
keys:
- v2-build-artifact-headers-{{ checksum "libmobilecoin_and_vendor_mobilecoin.hash" }}
- v2-build-artifact-headers-{{ checksum "vendor_mobilecoin.hash" }}
save-build-artifact-headers-cache:
steps:
- print-mobilecoin-submodule-hash
- save_cache:
name: Save build artifact headers cache
key: v2-build-artifact-headers-{{ checksum "libmobilecoin_and_vendor_mobilecoin.hash" }}
key: v2-build-artifact-headers-{{ checksum "vendor_mobilecoin.hash" }}
paths:
- ~/project/libmobilecoin/out/ios/include
- ~/project/Vendor/mobilecoin/libmobilecoin/out/ios/include
#
# Rustup Toolchain Cache's
@ -209,7 +208,7 @@ commands:
- restore_cache:
name: Restore Rustup cache for target <<parameters.build-target>>
keys:
- v0-rustup-<<parameters.build-target>>-{{ checksum "libmobilecoin/toolchain-config.env" }}
- v0-rustup-<<parameters.build-target>>-{{ checksum "Vendor/mobilecoin/libmobilecoin/toolchain-config.env" }}
save-rustup-cache:
parameters:
@ -219,7 +218,7 @@ commands:
steps:
- save_cache:
name: Save Rustup cache for target aarch64-apple-ios-sim
key: v0-rustup-<<parameters.build-target>>-{{ checksum "libmobilecoin/toolchain-config.env" }}
key: v0-rustup-<<parameters.build-target>>-{{ checksum "Vendor/mobilecoin/libmobilecoin/toolchain-config.env" }}
paths:
- ~/.rustup/toolchains
@ -281,7 +280,7 @@ commands:
- run:
name: Save submodule hash to file for checksumming
command: |
cat <(git submodule status) <(git ls-files -s libmobilecoin | git hash-object --stdin) > libmobilecoin_and_vendor_mobilecoin.hash
git submodule status > vendor_mobilecoin.hash
print-tool-versions:
description: Print versions of various tools used
@ -385,8 +384,8 @@ commands:
- restore_cache:
name: Restore Ruby gem cache swift sdk
keys:
- v2-ruby-<< parameters.ruby-version >>-gems-{{ checksum "~/MobileCoin-Swift/Gemfile.lock" }}
- v2-ruby-<< parameters.ruby-version >>-gems-
- v1-ruby-<< parameters.ruby-version >>-gems-{{ checksum "~/MobileCoin-Swift/Gemfile.lock" }}
- v1-ruby-<< parameters.ruby-version >>-gems-
- run:
name: Install root bundler dependencies
working_directory: ~/MobileCoin-Swift
@ -590,6 +589,43 @@ jobs:
- print-tool-versions
- set-git-credentials
- publish-to-trunk
build-toolchain:
parameters:
xcode-version: { type: string, default: *default-xcode-version }
build-target:
type: string
default: "aarch64-apple-ios-sim"
executor:
name: macos
xcode-version: << parameters.xcode-version >>
environment:
<<: *default-build-environment
OPENSSL_BIN: /usr/local/opt/openssl/bin/openssl
steps:
- checkout
- init-mobilecoin-submodule
- run:
name: Make rustup toolchains directory
working_directory: Vendor/mobilecoin/libmobilecoin
command: |
mkdir -p ~/.rustup/toolchains
- restore-rustup-cache:
build-target: <<parameters.build-target>>
- skip-if-cache-directory-exists:
directory: ~/.rustup/toolchains/ios-<<parameters.build-target>>-nightly-2021-08-01-swift-5-3-2
- prepare-for-build: { os: macos }
- run:
working_directory: Vendor/mobilecoin
name: Build rustup toolchains for a build target
command: |
cd libmobilecoin
make setup
make toolchain_<< parameters.build-target >>
- save-rustup-cache:
build-target: <<parameters.build-target>>
- save-homebrew-cache
build-artifacts:
parameters:
@ -609,14 +645,15 @@ jobs:
- restore-build-artifact-cache:
build-target: <<parameters.build-target>>
- skip-if-cache-file-exists:
file: ~/project/libmobilecoin/out/ios/target/<<parameters.build-target>>/mobile-release/libmobilecoin.a
file: ~/project/Vendor/mobilecoin/libmobilecoin/out/ios/target/<<parameters.build-target>>/mobile-release/libmobilecoin.a
- prepare-for-build: { os: macos }
- restore-rustup-cache:
build-target: <<parameters.build-target>>
- run:
working_directory: libmobilecoin
working_directory: Vendor/mobilecoin
name: Build libmobilecoin static libraries
command: |
cd libmobilecoin
make setup
make << parameters.build-target >>
@ -637,7 +674,7 @@ jobs:
- init-mobilecoin-submodule
- run:
name: Make output directories
working_directory: libmobilecoin
working_directory: Vendor/mobilecoin/libmobilecoin
command: |
mkdir -p out/ios/target
@ -768,49 +805,91 @@ workflows:
xcode-version: [*default-xcode-version]
# ios-sim
- build-toolchain:
name: build-toolchain-m1-ios-sim-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios-sim"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-m1-ios-sim-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios-sim"
requires: [build-toolchain-m1-ios-sim-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
# m1-catalyst
- build-toolchain:
name: build-toolchain-m1-catalyst-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios-macabi"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-m1-catalyst-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios-macabi"
requires: [build-toolchain-m1-catalyst-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
# ios-device
- build-toolchain:
name: build-toolchain-ios-device-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-ios-device-xcode-<< matrix.xcode-version >>
build-target: "aarch64-apple-ios"
requires: [build-toolchain-ios-device-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
# intel-catalyst
- build-toolchain:
name: build-toolchain-intel-catalyst-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-ios-macabi"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-intel-catalyst-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-ios-macabi"
requires: [build-toolchain-intel-catalyst-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
# intel-ios-sim
- build-toolchain:
name: build-toolchain-intel-ios-sim-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-ios"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-intel-ios-sim-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-ios"
requires: [build-toolchain-intel-ios-sim-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
# intel-macos
- build-toolchain:
name: build-toolchain-intel-macos-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-darwin"
matrix:
parameters:
xcode-version: [*default-xcode-version]
- build-artifacts:
name: build-artifacts-intel-macos-xcode-<< matrix.xcode-version >>
build-target: "x86_64-apple-darwin"
requires: [build-toolchain-intel-macos-xcode-<< matrix.xcode-version >>]
matrix:
parameters:
xcode-version: [*default-xcode-version]
@ -851,8 +930,4 @@ workflows:
- publish-pod-release:
filters:
branches:
only:
- master
- /release\/.*/
branches: { only: master }

1
.gitignore vendored
View File

@ -75,4 +75,3 @@ iOSInjectionProject/
# Bundler
.bundle/
.vendor/
.DS_Store

View File

@ -1,116 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef MC_CHACHA20_RNG_H_
#define MC_CHACHA20_RNG_H_
#include "common.h"
/* ==================== ChaCha20Rng ==================== */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _ChaCha20Rng ChaCha20Rng;
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the u64 long_val parameter
///
/// # Arguments
///
/// * `long_val` - an unsigned 64 bit value to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::Poison`
ChaCha20Rng* MC_NULLABLE mc_chacha20_rng_create_with_long(
uint64_t value,
McError* MC_NULLABLE * MC_NULLABLE out_error
);
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the bytes data, which must be at
/// least 32 bytes (only the first 32 bytes will be used)
///
/// # Arguments
///
/// * `bytes` - 32 bytes of data to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::Poison`
ChaCha20Rng* MC_NULLABLE mc_chacha20_rng_create_with_bytes(
const McBuffer* MC_NONNULL bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
/// Returns the current word_pos of the ChaCha20Rng instance
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 16 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
bool mc_chacha20_rng_get_word_pos(
ChaCha20Rng* MC_NONNULL chacha20_rng,
const McBuffer* MC_NONNULL out_word_pos,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1,2);
/// Sets the current word_pos of the ChaCha20Rng instance
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 128 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
bool mc_chacha20_rng_set_word_pos(
ChaCha20Rng* MC_NONNULL chacha20_rng,
const McBuffer* MC_NONNULL bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1,2);
/// Returns the next random u64 value from the ChaCha20Rng
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
///
/// # Errors
///
/// * `LibMcError::Poison`
uint64_t mc_chacha20_rng_next_long(
ChaCha20Rng* MC_NONNULL chacha20_rng,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
/// Frees the ChaCha20Rng
///
/// # Preconditions
///
/// * The ChaCha20Rng is no longer in use
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
void mc_chacha20_rng_free(
ChaCha20Rng* MC_NULLABLE chacha20_rng
);
#ifdef __cplusplus
}
#endif
#endif /* MC_CHACHA20_RNG_H_ */

View File

@ -12,6 +12,5 @@
#include "transaction.h"
#include "bip39.h"
#include "slip10.h"
#include "chacha20_rng.h"
#endif /* !LIBMOBILECOIN_H_ */

View File

@ -1,127 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef SIGNED_CONTINGENT_INPUT_H_
#define SIGNED_CONTINGENT_INPUT_H_
#include "common.h"
#include "fog.h"
#include "keys.h"
/* ==================== Signed Contingent Input ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Types ==== */
typedef struct _McSignedContingentInputBuilder McSignedContingentInputBuilder;
typedef struct _McTxOutMemoBuilder McTxOutMemoBuilder;
typedef struct _McTransactionBuilderRing McTransactionBuilderRing;
/* ==== McSignedContingentInputBuilder ==== */
/// # Preconditions
///
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `subaddress_spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `real_index` - must be within bounds of `ring`.
/// * `ring` - `TxOut` at `real_index` must be owned by account keys.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
McSignedContingentInputBuilder* MC_NULLABLE mc_signed_contingent_input_builder_create(
uint32_t block_version,
uint64_t tombstone_block,
const McFogResolver* MC_NULLABLE fog_resolver,
McTxOutMemoBuilder* MC_NONNULL memo_builder,
const McBuffer* MC_NONNULL view_private_key,
const McBuffer* MC_NONNULL subaddress_spend_private_key,
size_t real_index,
const McTransactionBuilderRing* MC_NONNULL ring,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(4,5,6,8);
void mc_signed_contingent_input_builder_free(
McSignedContingentInputBuilder* MC_NULLABLE signed_contingent_input_builder
);
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call to `build`.
/// * `recipient_address` - must be a valid `PublicAddress`.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_add_required_output(
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
uint64_t amount,
uint64_t token_id,
const McPublicAddress* MC_NONNULL recipient_address,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 4, 6);
/// # Preconditions
///
/// * `account_kay` - must be a valid account key, default change address computed from account key
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `out_tx_out_confirmation_number` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_add_required_change_output(
const McAccountKey* MC_NONNULL account_key,
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
uint64_t amount,
uint64_t token_id,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 6);
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call to `build`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_build(
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
McRngCallback* MC_NULLABLE rng_callback,
const McTransactionBuilderRing* MC_NONNULL ring,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
// #[no_mangle]
// pub extern "C" fn mc_signed_contingent_input_data_is_valid(
// sci_data: FfiRefPtr<McBuffer>,
// out_valid: FfiMutPtr<bool>,
// out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
// ) -> bool {
bool mc_signed_contingent_input_data_is_valid(
const McBuffer* MC_NONNULL signed_contingent_input,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* !SIGNED_CONTINGENT_INPUT_H_ */

View File

@ -15,15 +15,9 @@ extern "C" {
/* ==== Types ==== */
enum McMaskedAmountVersion {
V1,
V2,
};
typedef struct {
uint64_t masked_value;
const McBuffer* MC_NONNULL masked_token_id;
enum McMaskedAmountVersion version;
} McTxOutMaskedAmount;
typedef struct {
@ -185,18 +179,13 @@ MC_ATTRIBUTE_NONNULL(1, 2, 3);
/* ==== McTransactionBuilder ==== */
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
McTransactionBuilder* MC_NULLABLE mc_transaction_builder_create(
uint64_t fee,
uint64_t token_id,
uint64_t tombstone_block,
const McFogResolver* MC_NULLABLE fog_resolver,
McTxOutMemoBuilder* MC_NONNULL memo_builder,
uint32_t block_version,
McError* MC_NULLABLE * MC_NULLABLE out_error
uint32_t block_version
)
MC_ATTRIBUTE_NONNULL(5);
@ -225,22 +214,6 @@ bool mc_transaction_builder_add_input(
)
MC_ATTRIBUTE_NONNULL(1, 2, 3, 5);
/// # Preconditions
///
/// * `transaction_builder` - must not have been previously consumed by a call to `build`.
/// * `presigned_input_proto_bytes` - serialized proto bytes for a Signed Contingent Input
/// * `ring` - `TxOut` at `real_index` must be owned by account keys.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_transaction_builder_add_presigned_input(
McTransactionBuilder* MC_NONNULL transaction_builder,
const McBuffer* MC_NONNULL presigned_input_proto_bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `transaction_builder` - must not have been previously consumed by a call to `build`.
@ -251,17 +224,16 @@ MC_ATTRIBUTE_NONNULL(1, 2);
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_transaction_builder_add_output_mixed(
McData* MC_NULLABLE mc_transaction_builder_add_output(
McTransactionBuilder* MC_NONNULL transaction_builder,
uint64_t amount,
uint64_t token_id,
const McPublicAddress* MC_NONNULL recipient_address,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McMutableBuffer* MC_NONNULL out_tx_out_shared_secret,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 4, 6, 7);
MC_ATTRIBUTE_NONNULL(1, 3, 5, 6);
/// # Preconditions
///
@ -283,73 +255,7 @@ McData* MC_NULLABLE mc_transaction_builder_add_change_output(
McMutableBuffer* MC_NONNULL out_tx_out_shared_secret,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 6, 7);
/// # Preconditions
///
/// * `transaction_builder` - must not have been previously consumed by a call to `build`.
/// * `recipient_address` - must be a valid `PublicAddress`.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_transaction_builder_add_output(
McTransactionBuilder* MC_NONNULL transaction_builder,
uint64_t amount,
const McPublicAddress* MC_NONNULL recipient_address,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McMutableBuffer* MC_NONNULL out_tx_out_shared_secret,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 4, 6, 7);
/// # Preconditions
///
/// * `account_kay` - must be a valid account key, default change address computed from account key
/// * `transaction_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `out_tx_out_confirmation_number` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_transaction_builder_add_change_output_mixed(
const McAccountKey* MC_NONNULL account_key,
McTransactionBuilder* MC_NONNULL transaction_builder,
uint64_t amount,
uint64_t token_id,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McMutableBuffer* MC_NONNULL out_tx_out_shared_secret,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 6, 7);
/// # Preconditions
///
/// * `account_key` - must be a valid account key as the gift code subaddress
/// is computed from the account key
/// * `transaction_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `out_tx_out_confirmation_number` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_transaction_builder_fund_gift_code_output(
const McAccountKey* MC_NONNULL account_key,
McTransactionBuilder* MC_NONNULL transaction_builder,
uint64_t amount,
uint64_t token_id,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 6);
MC_ATTRIBUTE_NONNULL(1, 2, 4, 6);
/// # Preconditions
///
@ -382,15 +288,6 @@ McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_sender_payment_request_and_desti
)
MC_ATTRIBUTE_NONNULL(2);
/// # Preconditions
///
/// * `account_key` - must be a valid `AccountKey` with `fog_info`.
McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_sender_payment_intent_and_destination_create(
uint64_t payment_intent_id,
const McAccountKey* MC_NONNULL account_key
)
MC_ATTRIBUTE_NONNULL(2);
McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_default_create();
@ -537,193 +434,6 @@ bool mc_memo_destination_memo_get_total_outlay(
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== DestinationWithPaymentIntentIdMemo ==== */
/// # Preconditions
///
/// * `destination_public_address` - must be a valid 32-byte
/// Ristretto-format scalar.
/// * `number_of_recipients` - must be > 0
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_create(
const McPublicAddress* MC_NONNULL destination_public_address,
uint8_t number_of_recipients,
uint64_t fee,
uint64_t total_outlay,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 5);
/// # Preconditions
///
/// * `destination_with_payment_intent_memo_data` - must be 64 bytes
/// * `out_short_address_hash` - length must be >= 16 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_get_address_hash(
const McBuffer* MC_NONNULL destination_with_payment_intent_memo_data,
McMutableBuffer* MC_NONNULL out_short_address_hash,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_intent_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_get_number_of_recipients(
const McBuffer* MC_NONNULL destination_with_payment_intent_memo_data,
uint8_t* MC_NONNULL out_number_of_recipients,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_intent_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_get_fee(
const McBuffer* MC_NONNULL destination_with_payment_intent_memo_data,
uint64_t* MC_NONNULL out_fee,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_intent_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_get_total_outlay(
const McBuffer* MC_NONNULL destination_with_payment_intent_memo_data,
uint64_t* MC_NONNULL out_total_outlay,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_intent_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_intent_memo_get_payment_intent_id(
const McBuffer* MC_NONNULL destination_with_payment_intent_memo_data,
uint64_t* MC_NONNULL out_payment_intent_id,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== DestinationWithPaymentRequestIdMemo ==== */
/// # Preconditions
///
/// * `destination_public_address` - must be a valid 32-byte
/// Ristretto-format scalar.
/// * `number_of_recipients` - must be > 0
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_create(
const McPublicAddress* MC_NONNULL destination_public_address,
uint8_t number_of_recipients,
uint64_t fee,
uint64_t total_outlay,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 5);
/// # Preconditions
///
/// * `destination_with_payment_request_memo_data` - must be 64 bytes
/// * `out_short_address_hash` - length must be >= 16 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_get_address_hash(
const McBuffer* MC_NONNULL destination_with_payment_request_memo_data,
McMutableBuffer* MC_NONNULL out_short_address_hash,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_request_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_get_number_of_recipients(
const McBuffer* MC_NONNULL destination_with_payment_request_memo_data,
uint8_t* MC_NONNULL out_number_of_recipients,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_request_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_get_fee(
const McBuffer* MC_NONNULL destination_with_payment_request_memo_data,
uint64_t* MC_NONNULL out_fee,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_request_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_get_total_outlay(
const McBuffer* MC_NONNULL destination_with_payment_request_memo_data,
uint64_t* MC_NONNULL out_total_outlay,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `destination_with_payment_request_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_destination_with_payment_request_memo_get_payment_request_id(
const McBuffer* MC_NONNULL destination_with_payment_request_memo_data,
uint64_t* MC_NONNULL out_payment_request_id,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== SenderWithPaymentRequestMemo ==== */
@ -799,277 +509,10 @@ bool mc_memo_sender_with_payment_request_memo_get_payment_request_id(
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== SenderWithPaymentIntentMemo ==== */
/// # Preconditions
///
/// * `sender_with_payment_intent_memo_data` - must be 64 bytes
/// * `sender_public_address` - must be a valid `PublicAddress`.
/// * `receiving_subaddress_view_private_key` - must be a valid
/// 32-byte Ristretto-format scalar.
/// * `tx_out_public_key` - must be a valid 32-byte Ristretto-format scalar.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_sender_with_payment_intent_memo_is_valid(
const McBuffer* MC_NONNULL sender_with_payment_intent_memo_data,
const McPublicAddress* MC_NONNULL sender_public_address,
const McBuffer* MC_NONNULL receiving_subaddress_view_private_key,
const McBuffer* MC_NONNULL tx_out_public_key,
bool* MC_NONNULL out_valid,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3, 4, 5);
/// # Preconditions
///
/// * `sender_account_key` - must be a valid account key
/// * `recipient_subaddress_view_public_key` - must be a valid
/// 32-byte Ristretto-format scalar.
/// * `tx_out_public_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_sender_with_payment_intent_memo_create(
const McAccountKey* MC_NONNULL sender_account_key,
const McBuffer* MC_NONNULL recipient_subaddress_view_public_key,
const McBuffer* MC_NONNULL tx_out_public_key,
uint64_t payment_intent_id,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3, 5);
/// # Preconditions
///
/// * `sender_with_payment_intent_memo_data` - must be 64 bytes
/// * `out_short_address_hash` - length must be >= 16 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_sender_with_payment_intent_memo_get_address_hash(
const McBuffer* MC_NONNULL sender_with_payment_intent_memo_data,
McMutableBuffer* MC_NONNULL out_short_address_hash,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `sender_with_payment_intent_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_sender_with_payment_intent_memo_get_payment_intent_id(
const McBuffer* MC_NONNULL sender_with_payment_intent_memo_data,
uint64_t* MC_NONNULL out_payment_intent_id,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== Gift Code Memo Builders ==== */
/// # Preconditions
///
/// * `gift_code_funding_note` - must be a null-terminated C string containing
/// up to 54 valid UTF-8 bytes. The actual note stored on chain is up to 53 null
/// terminated UTF-8 bytes unless the note is exactly 53 utf-8 bytes long,
/// in which case, no null bytes are stored. If the C string passed here is
/// exactly 54 bytes, the last byte MUST be null and that byte will be
/// removed prior to storage on chain.
McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_gift_code_funding_create(
const char* MC_NONNULL gift_code_funding_note
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `gift_code_sender_note` - must be a null-terminated C string containing up
/// to 58 valid UTF-8 bytes. The actual note stored on chain is up to 57 null
/// terminated UTF-8 bytes unless the note is exactly 57 utf-8 bytes long,
/// in which case, no null bytes are stored. If the C string passed here is
/// exactly 58 bytes, the last byte MUST be null and that byte will be
/// removed prior to storage on chain.
McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_gift_code_sender_create(
const char* MC_NONNULL gift_code_sender_note
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `global_index` - must be the global TxOut index of the originally funded
/// gift code TxOut
McTxOutMemoBuilder* MC_NULLABLE mc_memo_builder_gift_code_cancellation_create(
uint64_t global_index
);
/* ==== GiftCodeFundingMemo ==== */
/// # Preconditions
///
/// * `tx_out_public_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `fee` - must be an integer less than or equal to 2^56
/// * `gift_code_funding_note` - must be a null-terminated C string containing
/// up to 54 valid UTF-8 bytes. The actual note stored on chain is up to 53 null
/// terminated UTF-8 bytes unless the note is exactly 53 utf-8 bytes long,
/// in which case, no null bytes are stored. If the C string passed here is
/// exactly 54 bytes, the last byte MUST be null and that byte will be
/// removed prior to storage on chain.
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_funding_memo_create(
const McBuffer* MC_NONNULL tx_out_public_key,
uint64_t fee,
const char* MC_NONNULL gift_code_funding_note,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 3, 4);
/// # Preconditions
///
/// * `gift_code_funding_memo_data` - must be 64 bytes
/// * `tx_out_public_key` - must be a valid 32-byte Ristretto-format scalar.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_funding_memo_validate_tx_out(
const McBuffer* MC_NONNULL gift_code_funding_memo_data,
const McBuffer* MC_NONNULL tx_out_public_key,
bool* MC_NONNULL out_valid,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
/// # Preconditions
///
/// * `gift_code_funding_memo_data` - must be 64 bytes
char* MC_NULLABLE mc_memo_gift_code_funding_memo_get_note(
const McBuffer* MC_NONNULL gift_code_funding_memo_data
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `gift_code_funding_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_funding_memo_get_fee(
const McBuffer* MC_NONNULL gift_code_funding_memo_data,
uint64_t* MC_NONNULL out_fee,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== GiftCodeSenderMemo ==== */
/// # Preconditions
///
/// * `fee` - must be an integer less than or equal to 2^56
/// * `gift_code_sender_note` - must be a null-terminated C string containing up
/// to 58 valid UTF-8 bytes. The actual note stored on chain is up to 57 null
/// terminated UTF-8 bytes unless the note is exactly 57 utf-8 bytes long,
/// in which case, no null bytes are stored. If the C string passed here is
/// exactly 58 bytes, the last byte MUST be null and that byte will be
/// removed prior to storage on chain.
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_sender_memo_create(
uint64_t fee,
const char* MC_NONNULL gift_code_sender_note,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(2, 3);
/// # Preconditions
///
/// * `gift_code_sender_memo_data` - must be 64 bytes
char* MC_NULLABLE mc_memo_gift_code_sender_memo_get_note(
const McBuffer* MC_NONNULL gift_code_sender_memo_data
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `gift_code_sender_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_get_gift_code_sender_memo_get_fee(
const McBuffer* MC_NONNULL gift_code_sender_memo_data,
uint64_t* MC_NONNULL out_fee,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== GiftCodeCancellationMemo ==== */
/// # Preconditions
///
/// * `fee` - must be an integer less than or equal to 2^56
/// * `global_index` - must be the global TxOut index of the originally funded
/// gift code TxOut
/// * `out_memo_data` - length must be >= 64.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_cancellation_memo_create(
uint64_t fee,
uint64_t global_index,
McMutableBuffer* MC_NONNULL out_memo_data,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(3);
/// # Preconditions
///
/// * `gift_code_cancellation_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_cancellation_memo_get_gift_code_tx_out_index(
const McBuffer* MC_NONNULL gift_code_cancellation_memo_data,
uint64_t* MC_NONNULL out_index,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `gift_code_cancellation_memo_data` - must be 64 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_memo_gift_code_cancellation_memo_get_fee(
const McBuffer* MC_NONNULL gift_code_cancellation_memo_data,
uint64_t* MC_NONNULL out_fee,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== Decrypt Memo Payload ==== */
/// # Preconditions
///
/// * `encrypted_memo` - must be 66 bytes

View File

@ -32,7 +32,6 @@ WORKDIR /root/project
COPY Vendor/mobilecoin/api/proto/blockchain.proto \
Vendor/mobilecoin/api/proto/external.proto \
Vendor/mobilecoin/api/proto/printable.proto \
Vendor/mobilecoin/api/proto/quorum_set.proto \
Vendor/mobilecoin/api/proto/watcher.proto \
Vendor/mobilecoin/api/proto/
COPY Vendor/mobilecoin/attest/api/proto/attest.proto \
@ -47,7 +46,6 @@ COPY Vendor/mobilecoin/fog/api/proto/fog_common.proto \
Vendor/mobilecoin/fog/api/proto/kex_rng.proto \
Vendor/mobilecoin/fog/api/proto/ledger.proto \
Vendor/mobilecoin/fog/api/proto/view.proto \
libmobilecoin/legacy/legacyview.proto \
Vendor/mobilecoin/fog/api/proto/
RUN mkdir -p Sources/Generated/Proto
@ -64,7 +62,6 @@ RUN protoc \
external.proto \
blockchain.proto \
printable.proto \
quorum_set.proto \
watcher.proto \
attest.proto \
consensus_client.proto \
@ -74,8 +71,7 @@ RUN protoc \
fog_common.proto \
kex_rng.proto \
ledger.proto \
view.proto \
legacyview.proto
view.proto
FROM scratch

View File

@ -1,7 +1,3 @@
source 'https://rubygems.org' do
gem 'cocoapods', :git => 'https://github.com/CocoaPods/CocoaPods', :ref => 'ecb9a4d0bececbd76db72e4ca95c265bfbbc0bf4'
gem 'addressable', '2.8.1', :git => 'https://github.com/sporkmonger/addressable'
gem 'cocoapods-deintegrate', '~> 1.0', '>= 1.0.4'
gem 'rexml'
gem 'pkg-config'
gem 'cocoapods'
end

View File

@ -1,116 +1,96 @@
GIT
remote: https://github.com/CocoaPods/CocoaPods
revision: ecb9a4d0bececbd76db72e4ca95c265bfbbc0bf4
ref: ecb9a4d0bececbd76db72e4ca95c265bfbbc0bf4
specs:
cocoapods (1.11.3)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.11.3)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 1.6.0, < 2.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
cocoapods-search (>= 1.0.0, < 2.0)
cocoapods-trunk (>= 1.6.0, < 2.0)
cocoapods-try (>= 1.1.0, < 2.0)
colored2 (~> 3.1)
escape (~> 0.0.4)
fourflusher (>= 2.3.0, < 3.0)
gh_inspector (~> 1.0)
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
xcodeproj (>= 1.21.0, < 2.0)
GIT
remote: https://github.com/sporkmonger/addressable
revision: 1fdd676753fb2f44c9d7e0953c97c3e6becfb36a
specs:
addressable (2.8.1)
public_suffix (>= 2.0.2, < 6.0)
GEM
specs:
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.6)
rexml
activesupport (6.1.7.2)
CFPropertyList (3.0.3)
activesupport (5.2.4.5)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
zeitwerk (~> 2.3)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
algoliasearch (1.27.5)
httpclient (~> 2.8, >= 2.8.3)
json (>= 1.5.1)
atomos (0.1.3)
claide (1.1.0)
cocoapods-core (1.11.3)
activesupport (>= 5.0, < 7)
addressable (~> 2.8)
claide (1.0.3)
cocoapods (1.10.1)
addressable (~> 2.6)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.10.1)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 1.4.0, < 2.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
cocoapods-search (>= 1.0.0, < 2.0)
cocoapods-trunk (>= 1.4.0, < 2.0)
cocoapods-try (>= 1.1.0, < 2.0)
colored2 (~> 3.1)
escape (~> 0.0.4)
fourflusher (>= 2.3.0, < 3.0)
gh_inspector (~> 1.0)
molinillo (~> 0.6.6)
nap (~> 1.0)
ruby-macho (~> 1.4)
xcodeproj (>= 1.19.0, < 2.0)
cocoapods-core (1.10.1)
activesupport (> 5.0, < 6)
addressable (~> 2.6)
algoliasearch (~> 1.0)
concurrent-ruby (~> 1.1)
fuzzy_match (~> 2.0.4)
nap (~> 1.0)
netrc (~> 0.11)
public_suffix (~> 4.0)
public_suffix
typhoeus (~> 1.0)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (1.6.3)
cocoapods-deintegrate (1.0.4)
cocoapods-downloader (1.4.0)
cocoapods-plugins (1.0.0)
nap
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
cocoapods-search (1.0.0)
cocoapods-trunk (1.5.0)
nap (>= 0.8, < 2.0)
netrc (~> 0.11)
cocoapods-try (1.2.0)
colored2 (3.1.2)
concurrent-ruby (1.2.0)
concurrent-ruby (1.1.8)
escape (0.0.4)
ethon (0.16.0)
ffi (>= 1.15.0)
ffi (1.15.5)
ethon (0.12.0)
ffi (>= 1.3.0)
ffi (1.15.0)
fourflusher (2.3.1)
fuzzy_match (2.0.4)
gh_inspector (1.1.3)
httpclient (2.8.3)
i18n (1.12.0)
i18n (1.8.9)
concurrent-ruby (~> 1.0)
json (2.6.3)
minitest (5.17.0)
molinillo (0.8.0)
json (2.5.1)
minitest (5.14.4)
molinillo (0.6.6)
nanaimo (0.3.0)
nap (1.1.0)
netrc (0.11.0)
pkg-config (1.5.1)
public_suffix (4.0.7)
rexml (3.2.5)
ruby-macho (2.5.1)
public_suffix (4.0.6)
ruby-macho (1.4.0)
thread_safe (0.3.6)
typhoeus (1.4.0)
ethon (>= 0.9.0)
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
xcodeproj (1.22.0)
tzinfo (1.2.9)
thread_safe (~> 0.1)
xcodeproj (1.19.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
zeitwerk (2.6.6)
PLATFORMS
ruby
DEPENDENCIES
addressable (= 2.8.1)!
cocoapods!
cocoapods-deintegrate (~> 1.0, >= 1.0.4)!
pkg-config!
rexml!
BUNDLED WITH
2.3.15
2.2.24

View File

@ -3,7 +3,7 @@ Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.name = "LibMobileCoin"
s.version = "4.0.0-pre3"
s.version = "1.2.2"
s.summary = "A library for communicating with MobileCoin network"
s.author = "MobileCoin"
@ -18,7 +18,7 @@ Pod::Spec.new do |s|
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
s.platform = :ios, "11.0"
s.platform = :ios, "10.0"
# ――― Subspecs ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
@ -84,7 +84,7 @@ Pod::Spec.new do |s|
"SWIFT_INCLUDE_PATHS": "$(HEADER_SEARCH_PATHS)",
"LIBMOBILECOIN_LIB_IF_NEEDED": "$(PODS_TARGET_SRCROOT)/Artifacts/target/$(CARGO_BUILD_TARGET)/release/libmobilecoin.a",
"OTHER_LDFLAGS": "-lz -u _mc_string_free $(LIBMOBILECOIN_LIB_IF_NEEDED)",
"OTHER_LDFLAGS": "-u _mc_string_free $(LIBMOBILECOIN_LIB_IF_NEEDED)",
"CARGO_BUILD_TARGET[sdk=iphonesimulator*][arch=arm64]": "aarch64-apple-ios-sim",
"CARGO_BUILD_TARGET[sdk=iphonesimulator*][arch=*]": "x86_64-apple-ios",

View File

@ -1,9 +1,9 @@
MOBILECOIN_DIR = Vendor/mobilecoin
LIBMOBILECOIN_LIB_DIR = libmobilecoin
LIBMOBILECOIN_LIB_DIR = $(MOBILECOIN_DIR)/libmobilecoin
LIBMOBILECOIN_ARTIFACTS_DIR = $(LIBMOBILECOIN_LIB_DIR)/out/ios
LIBMOBILECOIN_ARTIFACTS_HEADERS = $(LIBMOBILECOIN_LIB_DIR)/out/ios/include
ARTIFACTS_DIR = Artifacts
IOS_TARGETS = aarch64-apple-ios aarch64-apple-ios-sim aarch64-apple-ios-macabi x86_64-apple-ios x86_64-apple-ios-macabi
IOS_TARGETS = x86_64-apple-ios aarch64-apple-ios aarch64-apple-ios-sim aarch64-apple-ios-macabi x86_64-apple-ios-macabi
LIBMOBILECOIN_PROFILE = mobile-release
define BINARY_copy
@ -13,6 +13,9 @@ endef
.PHONY: default
default: setup build clean-artifacts copy generate
.PHONY: legacy
legacy: setup build-legacy clean-artifacts copy-legacy generate
.PHONY: setup
setup:
cd "$(LIBMOBILECOIN_LIB_DIR)"
@ -29,8 +32,12 @@ unexport CARGO_PROFILE
build:
cd "$(LIBMOBILECOIN_LIB_DIR)" && $(MAKE)
.PHONY: build-legacy
build-legacy:
cd "$(LIBMOBILECOIN_LIB_DIR)" && $(MAKE) legacy
.PHONY: clean-artifacts
clean-artifacts:
copy-legacy:
rm -r "$(ARTIFACTS_DIR)" 2>/dev/null || true
mkdir -p "$(ARTIFACTS_DIR)"
@ -42,6 +49,11 @@ copy:
$(call BINARY_copy,target)
cp -R "$(LIBMOBILECOIN_ARTIFACTS_HEADERS)" "$(ARTIFACTS_DIR)"
.PHONY: copy-legacy
copy-legacy:
$(call BINARY_copy,legacy)
cp -R "$(LIBMOBILECOIN_ARTIFACTS_HEADERS)" "$(ARTIFACTS_DIR)"
.PHONY: generate
generate:
rm -r Sources/Generated/Proto 2>/dev/null || true
@ -99,17 +111,3 @@ lint-podspec:
.PHONY: publish-podspec
publish-podspec:
bundle exec pod trunk push LibMobileCoin.podspec --allow-warnings
.PHONY: patch-cmake
patch-cmake:
tools/patch-cmake.sh
.PHONY: unpatch-cmake
unpatch-cmake:
tools/unpatch-cmake.sh
.PHONY: clean
clean:
$(MAKE) -C libmobilecoin clean
@rm -r $(MOBILECOIN_DIR)/target 2>/dev/null || true

View File

@ -175,81 +175,36 @@ public struct Blockchain_BlockSignature {
fileprivate var _signer: External_Ed25519Public? = nil
}
public struct Blockchain_BlockMetadataContents {
/// Version 1 of an archived block.
/// Note: The block.version field within the block may or may not be equal to 1.
public struct Blockchain_ArchiveBlockV1 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The Block ID.
public var blockID: Blockchain_BlockID {
get {return _blockID ?? Blockchain_BlockID()}
set {_blockID = newValue}
/// Block
public var block: Blockchain_Block {
get {return _block ?? Blockchain_Block()}
set {_block = newValue}
}
/// Returns true if `blockID` has been explicitly set.
public var hasBlockID: Bool {return self._blockID != nil}
/// Clears the value of `blockID`. Subsequent reads from it will return its default value.
public mutating func clearBlockID() {self._blockID = nil}
/// Returns true if `block` has been explicitly set.
public var hasBlock: Bool {return self._block != nil}
/// Clears the value of `block`. Subsequent reads from it will return its default value.
public mutating func clearBlock() {self._block = nil}
/// Quorum set configuration at the time of externalization.
public var quorumSet: QuorumSet_QuorumSet {
get {return _quorumSet ?? QuorumSet_QuorumSet()}
set {_quorumSet = newValue}
/// Contents of the block.
public var blockContents: Blockchain_BlockContents {
get {return _blockContents ?? Blockchain_BlockContents()}
set {_blockContents = newValue}
}
/// Returns true if `quorumSet` has been explicitly set.
public var hasQuorumSet: Bool {return self._quorumSet != nil}
/// Clears the value of `quorumSet`. Subsequent reads from it will return its default value.
public mutating func clearQuorumSet() {self._quorumSet = nil}
/// Returns true if `blockContents` has been explicitly set.
public var hasBlockContents: Bool {return self._blockContents != nil}
/// Clears the value of `blockContents`. Subsequent reads from it will return its default value.
public mutating func clearBlockContents() {self._blockContents = nil}
/// IAS report for the enclave which generated the signature.
public var verificationReport: External_VerificationReport {
get {return _verificationReport ?? External_VerificationReport()}
set {_verificationReport = newValue}
}
/// Returns true if `verificationReport` has been explicitly set.
public var hasVerificationReport: Bool {return self._verificationReport != nil}
/// Clears the value of `verificationReport`. Subsequent reads from it will return its default value.
public mutating func clearVerificationReport() {self._verificationReport = nil}
/// Responder ID of the consensus node that externalized this block.
public var responderID: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _blockID: Blockchain_BlockID? = nil
fileprivate var _quorumSet: QuorumSet_QuorumSet? = nil
fileprivate var _verificationReport: External_VerificationReport? = nil
}
public struct Blockchain_BlockMetadata {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Metadata signed by the consensus node.
public var contents: Blockchain_BlockMetadataContents {
get {return _contents ?? Blockchain_BlockMetadataContents()}
set {_contents = newValue}
}
/// Returns true if `contents` has been explicitly set.
public var hasContents: Bool {return self._contents != nil}
/// Clears the value of `contents`. Subsequent reads from it will return its default value.
public mutating func clearContents() {self._contents = nil}
/// Message signing key (signer).
public var nodeKey: External_Ed25519Public {
get {return _nodeKey ?? External_Ed25519Public()}
set {_nodeKey = newValue}
}
/// Returns true if `nodeKey` has been explicitly set.
public var hasNodeKey: Bool {return self._nodeKey != nil}
/// Clears the value of `nodeKey`. Subsequent reads from it will return its default value.
public mutating func clearNodeKey() {self._nodeKey = nil}
/// Signature using `node_key` over the Digestible encoding of `contents`.
public var signature: External_Ed25519Signature {
get {return _signature ?? External_Ed25519Signature()}
/// Block signature, when available.
public var signature: Blockchain_BlockSignature {
get {return _signature ?? Blockchain_BlockSignature()}
set {_signature = newValue}
}
/// Returns true if `signature` has been explicitly set.
@ -261,63 +216,9 @@ public struct Blockchain_BlockMetadata {
public init() {}
fileprivate var _contents: Blockchain_BlockMetadataContents? = nil
fileprivate var _nodeKey: External_Ed25519Public? = nil
fileprivate var _signature: External_Ed25519Signature? = nil
}
/// Version 1 of an archived block.
/// Note: The block.version field within the block may or may not be equal to 1.
public struct Blockchain_ArchiveBlockV1 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The block (header).
public var block: Blockchain_Block {
get {return _storage._block ?? Blockchain_Block()}
set {_uniqueStorage()._block = newValue}
}
/// Returns true if `block` has been explicitly set.
public var hasBlock: Bool {return _storage._block != nil}
/// Clears the value of `block`. Subsequent reads from it will return its default value.
public mutating func clearBlock() {_uniqueStorage()._block = nil}
/// Contents of the block.
public var blockContents: Blockchain_BlockContents {
get {return _storage._blockContents ?? Blockchain_BlockContents()}
set {_uniqueStorage()._blockContents = newValue}
}
/// Returns true if `blockContents` has been explicitly set.
public var hasBlockContents: Bool {return _storage._blockContents != nil}
/// Clears the value of `blockContents`. Subsequent reads from it will return its default value.
public mutating func clearBlockContents() {_uniqueStorage()._blockContents = nil}
/// Block signature, when available.
public var signature: Blockchain_BlockSignature {
get {return _storage._signature ?? Blockchain_BlockSignature()}
set {_uniqueStorage()._signature = newValue}
}
/// Returns true if `signature` has been explicitly set.
public var hasSignature: Bool {return _storage._signature != nil}
/// Clears the value of `signature`. Subsequent reads from it will return its default value.
public mutating func clearSignature() {_uniqueStorage()._signature = nil}
/// Additional signed metadata about this block.
public var metadata: Blockchain_BlockMetadata {
get {return _storage._metadata ?? Blockchain_BlockMetadata()}
set {_uniqueStorage()._metadata = newValue}
}
/// Returns true if `metadata` has been explicitly set.
public var hasMetadata: Bool {return _storage._metadata != nil}
/// Clears the value of `metadata`. Subsequent reads from it will return its default value.
public mutating func clearMetadata() {_uniqueStorage()._metadata = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _storage = _StorageClass.defaultInstance
fileprivate var _block: Blockchain_Block? = nil
fileprivate var _blockContents: Blockchain_BlockContents? = nil
fileprivate var _signature: Blockchain_BlockSignature? = nil
}
/// An archived block.
@ -378,8 +279,6 @@ extension Blockchain_BlockContentsHash: @unchecked Sendable {}
extension Blockchain_Block: @unchecked Sendable {}
extension Blockchain_BlockContents: @unchecked Sendable {}
extension Blockchain_BlockSignature: @unchecked Sendable {}
extension Blockchain_BlockMetadataContents: @unchecked Sendable {}
extension Blockchain_BlockMetadata: @unchecked Sendable {}
extension Blockchain_ArchiveBlockV1: @unchecked Sendable {}
extension Blockchain_ArchiveBlock: @unchecked Sendable {}
extension Blockchain_ArchiveBlock.OneOf_Block: @unchecked Sendable {}
@ -624,65 +523,11 @@ extension Blockchain_BlockSignature: SwiftProtobuf.Message, SwiftProtobuf._Messa
}
}
extension Blockchain_BlockMetadataContents: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".BlockMetadataContents"
extension Blockchain_ArchiveBlockV1: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".ArchiveBlockV1"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "block_id"),
2: .standard(proto: "quorum_set"),
3: .standard(proto: "verification_report"),
4: .standard(proto: "responder_id"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._blockID) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._quorumSet) }()
case 3: try { try decoder.decodeSingularMessageField(value: &self._verificationReport) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.responderID) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._blockID {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
} }()
try { if let v = self._quorumSet {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try { if let v = self._verificationReport {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
} }()
if !self.responderID.isEmpty {
try visitor.visitSingularStringField(value: self.responderID, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Blockchain_BlockMetadataContents, rhs: Blockchain_BlockMetadataContents) -> Bool {
if lhs._blockID != rhs._blockID {return false}
if lhs._quorumSet != rhs._quorumSet {return false}
if lhs._verificationReport != rhs._verificationReport {return false}
if lhs.responderID != rhs.responderID {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Blockchain_BlockMetadata: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".BlockMetadata"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "contents"),
2: .standard(proto: "node_key"),
1: .same(proto: "block"),
2: .standard(proto: "block_contents"),
3: .same(proto: "signature"),
]
@ -692,8 +537,8 @@ extension Blockchain_BlockMetadata: SwiftProtobuf.Message, SwiftProtobuf._Messag
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._contents) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._nodeKey) }()
case 1: try { try decoder.decodeSingularMessageField(value: &self._block) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._blockContents) }()
case 3: try { try decoder.decodeSingularMessageField(value: &self._signature) }()
default: break
}
@ -705,10 +550,10 @@ extension Blockchain_BlockMetadata: SwiftProtobuf.Message, SwiftProtobuf._Messag
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._contents {
try { if let v = self._block {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
} }()
try { if let v = self._nodeKey {
try { if let v = self._blockContents {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try { if let v = self._signature {
@ -717,102 +562,10 @@ extension Blockchain_BlockMetadata: SwiftProtobuf.Message, SwiftProtobuf._Messag
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Blockchain_BlockMetadata, rhs: Blockchain_BlockMetadata) -> Bool {
if lhs._contents != rhs._contents {return false}
if lhs._nodeKey != rhs._nodeKey {return false}
if lhs._signature != rhs._signature {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Blockchain_ArchiveBlockV1: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".ArchiveBlockV1"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "block"),
2: .standard(proto: "block_contents"),
3: .same(proto: "signature"),
4: .same(proto: "metadata"),
]
fileprivate class _StorageClass {
var _block: Blockchain_Block? = nil
var _blockContents: Blockchain_BlockContents? = nil
var _signature: Blockchain_BlockSignature? = nil
var _metadata: Blockchain_BlockMetadata? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_block = source._block
_blockContents = source._blockContents
_signature = source._signature
_metadata = source._metadata
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &_storage._block) }()
case 2: try { try decoder.decodeSingularMessageField(value: &_storage._blockContents) }()
case 3: try { try decoder.decodeSingularMessageField(value: &_storage._signature) }()
case 4: try { try decoder.decodeSingularMessageField(value: &_storage._metadata) }()
default: break
}
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = _storage._block {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
} }()
try { if let v = _storage._blockContents {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try { if let v = _storage._signature {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
} }()
try { if let v = _storage._metadata {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
} }()
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Blockchain_ArchiveBlockV1, rhs: Blockchain_ArchiveBlockV1) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._block != rhs_storage._block {return false}
if _storage._blockContents != rhs_storage._blockContents {return false}
if _storage._signature != rhs_storage._signature {return false}
if _storage._metadata != rhs_storage._metadata {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs._block != rhs._block {return false}
if lhs._blockContents != rhs._blockContents {return false}
if lhs._signature != rhs._signature {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}

View File

@ -39,7 +39,6 @@ public enum ConsensusClient_MintValidationResultCode: SwiftProtobuf.Enum {
case noGovernors // = 10
case nonceAlreadyUsed // = 11
case noMatchingMintConfig // = 12
case mintingToFogNotSupported // = 13
case UNRECOGNIZED(Int)
public init() {
@ -61,7 +60,6 @@ public enum ConsensusClient_MintValidationResultCode: SwiftProtobuf.Enum {
case 10: self = .noGovernors
case 11: self = .nonceAlreadyUsed
case 12: self = .noMatchingMintConfig
case 13: self = .mintingToFogNotSupported
default: self = .UNRECOGNIZED(rawValue)
}
}
@ -81,7 +79,6 @@ public enum ConsensusClient_MintValidationResultCode: SwiftProtobuf.Enum {
case .noGovernors: return 10
case .nonceAlreadyUsed: return 11
case .noMatchingMintConfig: return 12
case .mintingToFogNotSupported: return 13
case .UNRECOGNIZED(let i): return i
}
}
@ -106,7 +103,6 @@ extension ConsensusClient_MintValidationResultCode: CaseIterable {
.noGovernors,
.nonceAlreadyUsed,
.noMatchingMintConfig,
.mintingToFogNotSupported,
]
}
@ -218,7 +214,6 @@ extension ConsensusClient_MintValidationResultCode: SwiftProtobuf._ProtoNameProv
10: .same(proto: "NoGovernors"),
11: .same(proto: "NonceAlreadyUsed"),
12: .same(proto: "NoMatchingMintConfig"),
13: .same(proto: "MintingToFogNotSupported"),
]
}

View File

@ -64,16 +64,6 @@ public enum ConsensusCommon_ProposeTxResult: SwiftProtobuf.Enum {
case missingMaskedTokenID // = 43
case maskedTokenIDNotAllowed // = 44
case unsortedOutputs // = 45
case inputRulesNotAllowed // = 46
case inputRuleMissingRequiredOutput // = 47
case inputRuleMaxTombstoneBlockExceeded // = 48
case unknownMaskedAmountVersion // = 49
case inputRulePartialFill // = 50
case inputRuleInvalidAmountSharedSecret // = 51
case inputRuleTxOutConversion // = 52
case inputRuleAmount // = 53
case ledgerTxOutIndexOutOfBounds // = 54
case feeMapDigestMismatch // = 55
case UNRECOGNIZED(Int)
public init() {
@ -119,16 +109,6 @@ public enum ConsensusCommon_ProposeTxResult: SwiftProtobuf.Enum {
case 43: self = .missingMaskedTokenID
case 44: self = .maskedTokenIDNotAllowed
case 45: self = .unsortedOutputs
case 46: self = .inputRulesNotAllowed
case 47: self = .inputRuleMissingRequiredOutput
case 48: self = .inputRuleMaxTombstoneBlockExceeded
case 49: self = .unknownMaskedAmountVersion
case 50: self = .inputRulePartialFill
case 51: self = .inputRuleInvalidAmountSharedSecret
case 52: self = .inputRuleTxOutConversion
case 53: self = .inputRuleAmount
case 54: self = .ledgerTxOutIndexOutOfBounds
case 55: self = .feeMapDigestMismatch
default: self = .UNRECOGNIZED(rawValue)
}
}
@ -172,16 +152,6 @@ public enum ConsensusCommon_ProposeTxResult: SwiftProtobuf.Enum {
case .missingMaskedTokenID: return 43
case .maskedTokenIDNotAllowed: return 44
case .unsortedOutputs: return 45
case .inputRulesNotAllowed: return 46
case .inputRuleMissingRequiredOutput: return 47
case .inputRuleMaxTombstoneBlockExceeded: return 48
case .unknownMaskedAmountVersion: return 49
case .inputRulePartialFill: return 50
case .inputRuleInvalidAmountSharedSecret: return 51
case .inputRuleTxOutConversion: return 52
case .inputRuleAmount: return 53
case .ledgerTxOutIndexOutOfBounds: return 54
case .feeMapDigestMismatch: return 55
case .UNRECOGNIZED(let i): return i
}
}
@ -230,16 +200,6 @@ extension ConsensusCommon_ProposeTxResult: CaseIterable {
.missingMaskedTokenID,
.maskedTokenIDNotAllowed,
.unsortedOutputs,
.inputRulesNotAllowed,
.inputRuleMissingRequiredOutput,
.inputRuleMaxTombstoneBlockExceeded,
.unknownMaskedAmountVersion,
.inputRulePartialFill,
.inputRuleInvalidAmountSharedSecret,
.inputRuleTxOutConversion,
.inputRuleAmount,
.ledgerTxOutIndexOutOfBounds,
.feeMapDigestMismatch,
]
}
@ -318,9 +278,6 @@ public struct ConsensusCommon_ProposeTxResponse {
//// The block version which is in effect right now
public var blockVersion: UInt32 = 0
//// Human-readable error message, in case of nonzero ProposeTxResult
public var errMsg: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
@ -377,16 +334,6 @@ extension ConsensusCommon_ProposeTxResult: SwiftProtobuf._ProtoNameProviding {
43: .same(proto: "MissingMaskedTokenId"),
44: .same(proto: "MaskedTokenIdNotAllowed"),
45: .same(proto: "UnsortedOutputs"),
46: .same(proto: "InputRulesNotAllowed"),
47: .same(proto: "InputRuleMissingRequiredOutput"),
48: .same(proto: "InputRuleMaxTombstoneBlockExceeded"),
49: .same(proto: "UnknownMaskedAmountVersion"),
50: .same(proto: "InputRulePartialFill"),
51: .same(proto: "InputRuleInvalidAmountSharedSecret"),
52: .same(proto: "InputRuleTxOutConversion"),
53: .same(proto: "InputRuleAmount"),
54: .same(proto: "LedgerTxOutIndexOutOfBounds"),
55: .same(proto: "FeeMapDigestMismatch"),
]
}
@ -516,7 +463,6 @@ extension ConsensusCommon_ProposeTxResponse: SwiftProtobuf.Message, SwiftProtobu
1: .same(proto: "result"),
2: .standard(proto: "block_count"),
3: .standard(proto: "block_version"),
4: .standard(proto: "err_msg"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
@ -528,7 +474,6 @@ extension ConsensusCommon_ProposeTxResponse: SwiftProtobuf.Message, SwiftProtobu
case 1: try { try decoder.decodeSingularEnumField(value: &self.result) }()
case 2: try { try decoder.decodeSingularUInt64Field(value: &self.blockCount) }()
case 3: try { try decoder.decodeSingularUInt32Field(value: &self.blockVersion) }()
case 4: try { try decoder.decodeSingularStringField(value: &self.errMsg) }()
default: break
}
}
@ -544,9 +489,6 @@ extension ConsensusCommon_ProposeTxResponse: SwiftProtobuf.Message, SwiftProtobu
if self.blockVersion != 0 {
try visitor.visitSingularUInt32Field(value: self.blockVersion, fieldNumber: 3)
}
if !self.errMsg.isEmpty {
try visitor.visitSingularStringField(value: self.errMsg, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
@ -554,7 +496,6 @@ extension ConsensusCommon_ProposeTxResponse: SwiftProtobuf.Message, SwiftProtobu
if lhs.result != rhs.result {return false}
if lhs.blockCount != rhs.blockCount {return false}
if lhs.blockVersion != rhs.blockVersion {return false}
if lhs.errMsg != rhs.errMsg {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}

File diff suppressed because it is too large Load Diff

View File

@ -1,207 +0,0 @@
// DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: legacyview.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Copyright (c) 2018-2022 The MobileCoin Foundation
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
////
//// *** DISCLAIMER ***
////
//// This proto is deprecated and no longer used, we're re-importing it so we can re-use serialized data in
//// some Swift unit tests. Once we convert these tests we should remove this proto.
////
//// *** END DISCLAIMER ***
////
//// The schema for the decrypted TxOutSearchResult ciphertext
//// This is the information that the Ingest enclave produces for the user about their TxOut
////
//// Note: The fields of FogTxOut are flattened here because it reduces the size of the protobuf
//// enough to make a difference for the quality of ORAM implementation, like ~10% better memory utilization
////
//// Note: Fog TxOutRecord DOES NOT include the encrypted fog hint of the original TxOut, because it is big,
//// and the client cannot read it anyways. However, when using the TxOut to build transactions, you must have that
//// or the merkle proofs will fail validation, at least for now.
//// The fog merkle proof server gives you a TxOut with fog hint, as it appears in blockchain,
//// and that's the version of the TxOut that you should use when building a transaction.
public struct FogView_TxOutRecordLegacy {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
//// The (compressed ristretto) bytes of commitment associated to amount field in the TxOut that was recovered
////
//// Note: This field is omitted in recent versions, because it can be reconstructed by the recipient instead.
public var txOutAmountCommitmentData: Data = Data()
//// The masked value associated to amount field in the TxOut that was recovered
public var txOutAmountMaskedValue: UInt64 = 0
//// The (compressed ristretto) bytes of the target key associated to the TxOut that was recovered
public var txOutTargetKeyData: Data = Data()
//// The (compressed ristretto) bytes of the public key associated to the TxOut that was recovered
public var txOutPublicKeyData: Data = Data()
//// The global index of this TxOut in the set of all TxOuts in the entire block chain
public var txOutGlobalIndex: UInt64 = 0
//// The index of the block index in which this TxOut appeared
public var blockIndex: UInt64 = 0
//// The timestamp of the block containing this output.
//// Some blocks, like the origin block, don't have a timestamp, and this value is u64::MAX
//// Other blocks are expected to have timestamps.
////
//// Note: The timestamp is based on untrusted reporting of time from ONE of the consensus validators.
//// Because it is a distributed system, it may not be the SAME consensus validator from block to block,
//// and the timestamps may not make even a minimal amount of sense when the validator differs.
////
//// These timestamps are
//// - NOISY, forward and backwards in time, depending on system time settings of many different servers.
//// - NOT MONOTONIC: it's possible that you get a timestamp for block 101 that is before the timestamp for block 100.
//// - Not even CONSISTENT across fog services: It's possible you get a different timestamp for a TxOut in block 100,
//// than you do for a key image in block 100 from the key image endpoint.
//// This is unavoidable right now because it is possible that fog-ingest has different levels of
//// connectivity from the fog-key-image service to the blockchain data sources.
////
//// Timestamps are BEST-EFFORT and for a good user experience, the client software should attempt to reconcile these
//// timestamps, so that events that have a happens-before relationship in the system, have timestamps that reflect that.
//// Otherwise, we should expect users to be confused and disturbed about the occasional time-travelling transaction.
////
//// We hope to improve the quality guarantees of these timestamps over time, but for now this is the best we
//// can do until some changes can be made to the consensus network and other services related to timestamps.
////
//// Represented as seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
public var timestamp: UInt64 = 0
//// The crc32 of the commitment data bytes.
//// This is a 4-byte IEEE crc32 of the bytes of the tx_out_amount_commitment_data bytes, which is present if
//// the full tx_out_amount_commitment_data is omitted.
//// The client can recompute the tx_out_amount_commitment from the other data that we include.
//// They can confirm correct recomputation by checking this crc value.
public var txOutAmountCommitmentDataCrc32: UInt32 = 0
//// The bytes of the encrypted memo.
//// This exactly 66 bytes when present.
//// This is omitted for TxOut's from before the upgrade that introduced memos.
public var txOutEMemoData: Data = Data()
//// The masked token id associated to the amount field in the TxOut that was recovered
public var txOutAmountMaskedTokenID: Data = Data()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
#if swift(>=5.5) && canImport(_Concurrency)
extension FogView_TxOutRecordLegacy: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "fog_view"
extension FogView_TxOutRecordLegacy: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TxOutRecordLegacy"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "tx_out_amount_commitment_data"),
2: .standard(proto: "tx_out_amount_masked_value"),
3: .standard(proto: "tx_out_target_key_data"),
4: .standard(proto: "tx_out_public_key_data"),
5: .standard(proto: "tx_out_global_index"),
6: .standard(proto: "block_index"),
7: .same(proto: "timestamp"),
8: .standard(proto: "tx_out_amount_commitment_data_crc32"),
9: .standard(proto: "tx_out_e_memo_data"),
10: .standard(proto: "tx_out_amount_masked_token_id"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularBytesField(value: &self.txOutAmountCommitmentData) }()
case 2: try { try decoder.decodeSingularFixed64Field(value: &self.txOutAmountMaskedValue) }()
case 3: try { try decoder.decodeSingularBytesField(value: &self.txOutTargetKeyData) }()
case 4: try { try decoder.decodeSingularBytesField(value: &self.txOutPublicKeyData) }()
case 5: try { try decoder.decodeSingularFixed64Field(value: &self.txOutGlobalIndex) }()
case 6: try { try decoder.decodeSingularFixed64Field(value: &self.blockIndex) }()
case 7: try { try decoder.decodeSingularFixed64Field(value: &self.timestamp) }()
case 8: try { try decoder.decodeSingularFixed32Field(value: &self.txOutAmountCommitmentDataCrc32) }()
case 9: try { try decoder.decodeSingularBytesField(value: &self.txOutEMemoData) }()
case 10: try { try decoder.decodeSingularBytesField(value: &self.txOutAmountMaskedTokenID) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.txOutAmountCommitmentData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutAmountCommitmentData, fieldNumber: 1)
}
if self.txOutAmountMaskedValue != 0 {
try visitor.visitSingularFixed64Field(value: self.txOutAmountMaskedValue, fieldNumber: 2)
}
if !self.txOutTargetKeyData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutTargetKeyData, fieldNumber: 3)
}
if !self.txOutPublicKeyData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutPublicKeyData, fieldNumber: 4)
}
if self.txOutGlobalIndex != 0 {
try visitor.visitSingularFixed64Field(value: self.txOutGlobalIndex, fieldNumber: 5)
}
if self.blockIndex != 0 {
try visitor.visitSingularFixed64Field(value: self.blockIndex, fieldNumber: 6)
}
if self.timestamp != 0 {
try visitor.visitSingularFixed64Field(value: self.timestamp, fieldNumber: 7)
}
if self.txOutAmountCommitmentDataCrc32 != 0 {
try visitor.visitSingularFixed32Field(value: self.txOutAmountCommitmentDataCrc32, fieldNumber: 8)
}
if !self.txOutEMemoData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutEMemoData, fieldNumber: 9)
}
if !self.txOutAmountMaskedTokenID.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutAmountMaskedTokenID, fieldNumber: 10)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: FogView_TxOutRecordLegacy, rhs: FogView_TxOutRecordLegacy) -> Bool {
if lhs.txOutAmountCommitmentData != rhs.txOutAmountCommitmentData {return false}
if lhs.txOutAmountMaskedValue != rhs.txOutAmountMaskedValue {return false}
if lhs.txOutTargetKeyData != rhs.txOutTargetKeyData {return false}
if lhs.txOutPublicKeyData != rhs.txOutPublicKeyData {return false}
if lhs.txOutGlobalIndex != rhs.txOutGlobalIndex {return false}
if lhs.blockIndex != rhs.blockIndex {return false}
if lhs.timestamp != rhs.timestamp {return false}
if lhs.txOutAmountCommitmentDataCrc32 != rhs.txOutAmountCommitmentDataCrc32 {return false}
if lhs.txOutEMemoData != rhs.txOutEMemoData {return false}
if lhs.txOutAmountMaskedTokenID != rhs.txOutAmountMaskedTokenID {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}

View File

@ -94,47 +94,6 @@ public struct Printable_TransferPayload {
fileprivate var _txOutPublicKey: External_CompressedRistretto? = nil
}
//// Message encoding information required to locate a TxOut,
//// un-blind the amount, and spend the TxOut. This can be used to give
//// MobileCoin to both FOG & non-FOG users who may not yet have
/// a MobileCoin account enabled
public struct Printable_TxOutGiftCode {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The global index of the TxOut that has been gifted. This allows
/// the receiver to find & uniquely identify the TxOut
public var globalIndex: UInt64 = 0
/// The one-time private key which can be used to spend the TxOut
public var onetimePrivateKey: External_RistrettoPrivate {
get {return _onetimePrivateKey ?? External_RistrettoPrivate()}
set {_onetimePrivateKey = newValue}
}
/// Returns true if `onetimePrivateKey` has been explicitly set.
public var hasOnetimePrivateKey: Bool {return self._onetimePrivateKey != nil}
/// Clears the value of `onetimePrivateKey`. Subsequent reads from it will return its default value.
public mutating func clearOnetimePrivateKey() {self._onetimePrivateKey = nil}
/// The shared secret used to un-blind the amount of the TxOut
public var sharedSecret: External_CompressedRistretto {
get {return _sharedSecret ?? External_CompressedRistretto()}
set {_sharedSecret = newValue}
}
/// Returns true if `sharedSecret` has been explicitly set.
public var hasSharedSecret: Bool {return self._sharedSecret != nil}
/// Clears the value of `sharedSecret`. Subsequent reads from it will return its default value.
public mutating func clearSharedSecret() {self._sharedSecret = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _onetimePrivateKey: External_RistrettoPrivate? = nil
fileprivate var _sharedSecret: External_CompressedRistretto? = nil
}
//// This wraps all of the above messages using "oneof", allowing us to
//// have a single encoding scheme and extend as necessary simply by adding
//// new messages without breaking backwards compatibility
@ -169,21 +128,12 @@ public struct Printable_PrintableWrapper {
set {wrapper = .transferPayload(newValue)}
}
public var txOutGiftCode: Printable_TxOutGiftCode {
get {
if case .txOutGiftCode(let v)? = wrapper {return v}
return Printable_TxOutGiftCode()
}
set {wrapper = .txOutGiftCode(newValue)}
}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public enum OneOf_Wrapper: Equatable {
case publicAddress(External_PublicAddress)
case paymentRequest(Printable_PaymentRequest)
case transferPayload(Printable_TransferPayload)
case txOutGiftCode(Printable_TxOutGiftCode)
#if !swift(>=4.1)
public static func ==(lhs: Printable_PrintableWrapper.OneOf_Wrapper, rhs: Printable_PrintableWrapper.OneOf_Wrapper) -> Bool {
@ -203,10 +153,6 @@ public struct Printable_PrintableWrapper {
guard case .transferPayload(let l) = lhs, case .transferPayload(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.txOutGiftCode, .txOutGiftCode): return {
guard case .txOutGiftCode(let l) = lhs, case .txOutGiftCode(let r) = rhs else { preconditionFailure() }
return l == r
}()
default: return false
}
}
@ -219,7 +165,6 @@ public struct Printable_PrintableWrapper {
#if swift(>=5.5) && canImport(_Concurrency)
extension Printable_PaymentRequest: @unchecked Sendable {}
extension Printable_TransferPayload: @unchecked Sendable {}
extension Printable_TxOutGiftCode: @unchecked Sendable {}
extension Printable_PrintableWrapper: @unchecked Sendable {}
extension Printable_PrintableWrapper.OneOf_Wrapper: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
@ -336,61 +281,12 @@ extension Printable_TransferPayload: SwiftProtobuf.Message, SwiftProtobuf._Messa
}
}
extension Printable_TxOutGiftCode: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TxOutGiftCode"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "global_index"),
2: .standard(proto: "onetime_private_key"),
3: .standard(proto: "shared_secret"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt64Field(value: &self.globalIndex) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._onetimePrivateKey) }()
case 3: try { try decoder.decodeSingularMessageField(value: &self._sharedSecret) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if self.globalIndex != 0 {
try visitor.visitSingularUInt64Field(value: self.globalIndex, fieldNumber: 1)
}
try { if let v = self._onetimePrivateKey {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try { if let v = self._sharedSecret {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
} }()
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Printable_TxOutGiftCode, rhs: Printable_TxOutGiftCode) -> Bool {
if lhs.globalIndex != rhs.globalIndex {return false}
if lhs._onetimePrivateKey != rhs._onetimePrivateKey {return false}
if lhs._sharedSecret != rhs._sharedSecret {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Printable_PrintableWrapper: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".PrintableWrapper"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "public_address"),
2: .standard(proto: "payment_request"),
3: .standard(proto: "transfer_payload"),
4: .standard(proto: "tx_out_gift_code"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
@ -438,19 +334,6 @@ extension Printable_PrintableWrapper: SwiftProtobuf.Message, SwiftProtobuf._Mess
self.wrapper = .transferPayload(v)
}
}()
case 4: try {
var v: Printable_TxOutGiftCode?
var hadOneofValue = false
if let current = self.wrapper {
hadOneofValue = true
if case .txOutGiftCode(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {
if hadOneofValue {try decoder.handleConflictingOneOf()}
self.wrapper = .txOutGiftCode(v)
}
}()
default: break
}
}
@ -474,10 +357,6 @@ extension Printable_PrintableWrapper: SwiftProtobuf.Message, SwiftProtobuf._Mess
guard case .transferPayload(let v)? = self.wrapper else { preconditionFailure() }
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}()
case .txOutGiftCode?: try {
guard case .txOutGiftCode(let v)? = self.wrapper else { preconditionFailure() }
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}()
case nil: break
}
try unknownFields.traverse(visitor: &visitor)

View File

@ -1,276 +0,0 @@
// DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: quorum_set.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Copyright (c) 2018-2022 The MobileCoin Foundation
// QuorumSet data types.
// Implemented here because the Rust definition is generic, so these types are for the current impl.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct QuorumSet_Node {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var responderID: String = String()
public var publicKey: External_Ed25519Public {
get {return _publicKey ?? External_Ed25519Public()}
set {_publicKey = newValue}
}
/// Returns true if `publicKey` has been explicitly set.
public var hasPublicKey: Bool {return self._publicKey != nil}
/// Clears the value of `publicKey`. Subsequent reads from it will return its default value.
public mutating func clearPublicKey() {self._publicKey = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _publicKey: External_Ed25519Public? = nil
}
public struct QuorumSet_QuorumSetMember {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var member: QuorumSet_QuorumSetMember.OneOf_Member? = nil
public var node: QuorumSet_Node {
get {
if case .node(let v)? = member {return v}
return QuorumSet_Node()
}
set {member = .node(newValue)}
}
public var innerSet: QuorumSet_QuorumSet {
get {
if case .innerSet(let v)? = member {return v}
return QuorumSet_QuorumSet()
}
set {member = .innerSet(newValue)}
}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public enum OneOf_Member: Equatable {
case node(QuorumSet_Node)
case innerSet(QuorumSet_QuorumSet)
#if !swift(>=4.1)
public static func ==(lhs: QuorumSet_QuorumSetMember.OneOf_Member, rhs: QuorumSet_QuorumSetMember.OneOf_Member) -> Bool {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch (lhs, rhs) {
case (.node, .node): return {
guard case .node(let l) = lhs, case .node(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.innerSet, .innerSet): return {
guard case .innerSet(let l) = lhs, case .innerSet(let r) = rhs else { preconditionFailure() }
return l == r
}()
default: return false
}
}
#endif
}
public init() {}
}
public struct QuorumSet_QuorumSet {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var threshold: UInt32 = 0
public var members: [QuorumSet_QuorumSetMember] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
#if swift(>=5.5) && canImport(_Concurrency)
extension QuorumSet_Node: @unchecked Sendable {}
extension QuorumSet_QuorumSetMember: @unchecked Sendable {}
extension QuorumSet_QuorumSetMember.OneOf_Member: @unchecked Sendable {}
extension QuorumSet_QuorumSet: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "quorum_set"
extension QuorumSet_Node: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".Node"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "responder_id"),
2: .standard(proto: "public_key"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.responderID) }()
case 2: try { try decoder.decodeSingularMessageField(value: &self._publicKey) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.responderID.isEmpty {
try visitor.visitSingularStringField(value: self.responderID, fieldNumber: 1)
}
try { if let v = self._publicKey {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
} }()
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: QuorumSet_Node, rhs: QuorumSet_Node) -> Bool {
if lhs.responderID != rhs.responderID {return false}
if lhs._publicKey != rhs._publicKey {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension QuorumSet_QuorumSetMember: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".QuorumSetMember"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "node"),
2: .standard(proto: "inner_set"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try {
var v: QuorumSet_Node?
var hadOneofValue = false
if let current = self.member {
hadOneofValue = true
if case .node(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {
if hadOneofValue {try decoder.handleConflictingOneOf()}
self.member = .node(v)
}
}()
case 2: try {
var v: QuorumSet_QuorumSet?
var hadOneofValue = false
if let current = self.member {
hadOneofValue = true
if case .innerSet(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {
if hadOneofValue {try decoder.handleConflictingOneOf()}
self.member = .innerSet(v)
}
}()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
switch self.member {
case .node?: try {
guard case .node(let v)? = self.member else { preconditionFailure() }
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}()
case .innerSet?: try {
guard case .innerSet(let v)? = self.member else { preconditionFailure() }
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}()
case nil: break
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: QuorumSet_QuorumSetMember, rhs: QuorumSet_QuorumSetMember) -> Bool {
if lhs.member != rhs.member {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension QuorumSet_QuorumSet: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".QuorumSet"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "threshold"),
2: .same(proto: "members"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt32Field(value: &self.threshold) }()
case 2: try { try decoder.decodeRepeatedMessageField(value: &self.members) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.threshold != 0 {
try visitor.visitSingularUInt32Field(value: self.threshold, fieldNumber: 1)
}
if !self.members.isEmpty {
try visitor.visitRepeatedMessageField(value: self.members, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: QuorumSet_QuorumSet, rhs: QuorumSet_QuorumSet) -> Bool {
if lhs.threshold != rhs.threshold {return false}
if lhs.members != rhs.members {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}

View File

@ -395,59 +395,10 @@ public struct FogView_TxOutRecord {
public var txOutEMemoData: Data = Data()
//// The masked token id associated to the amount field in the TxOut that was recovered
public var txOutAmountMaskedTokenID: FogView_TxOutRecord.OneOf_TxOutAmountMaskedTokenID? = nil
//// The masked token id associated to the v1 amount field in the TxOut that was recovered
//// The presence of this field indicates that a MaskedAmountV1 object was serialized.
public var txOutAmountMaskedV1TokenID: Data {
get {
if case .txOutAmountMaskedV1TokenID(let v)? = txOutAmountMaskedTokenID {return v}
return Data()
}
set {txOutAmountMaskedTokenID = .txOutAmountMaskedV1TokenID(newValue)}
}
//// The masked token id associated to the v2 amount field in the TxOut that was recovered
//// The presence of this field indicates that a MaskedAmountV2 object was serialized.
public var txOutAmountMaskedV2TokenID: Data {
get {
if case .txOutAmountMaskedV2TokenID(let v)? = txOutAmountMaskedTokenID {return v}
return Data()
}
set {txOutAmountMaskedTokenID = .txOutAmountMaskedV2TokenID(newValue)}
}
public var txOutAmountMaskedTokenID: Data = Data()
public var unknownFields = SwiftProtobuf.UnknownStorage()
//// The masked token id associated to the amount field in the TxOut that was recovered
public enum OneOf_TxOutAmountMaskedTokenID: Equatable {
//// The masked token id associated to the v1 amount field in the TxOut that was recovered
//// The presence of this field indicates that a MaskedAmountV1 object was serialized.
case txOutAmountMaskedV1TokenID(Data)
//// The masked token id associated to the v2 amount field in the TxOut that was recovered
//// The presence of this field indicates that a MaskedAmountV2 object was serialized.
case txOutAmountMaskedV2TokenID(Data)
#if !swift(>=4.1)
public static func ==(lhs: FogView_TxOutRecord.OneOf_TxOutAmountMaskedTokenID, rhs: FogView_TxOutRecord.OneOf_TxOutAmountMaskedTokenID) -> Bool {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch (lhs, rhs) {
case (.txOutAmountMaskedV1TokenID, .txOutAmountMaskedV1TokenID): return {
guard case .txOutAmountMaskedV1TokenID(let l) = lhs, case .txOutAmountMaskedV1TokenID(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.txOutAmountMaskedV2TokenID, .txOutAmountMaskedV2TokenID): return {
guard case .txOutAmountMaskedV2TokenID(let l) = lhs, case .txOutAmountMaskedV2TokenID(let r) = rhs else { preconditionFailure() }
return l == r
}()
default: return false
}
}
#endif
}
public init() {}
}
@ -460,7 +411,6 @@ extension FogView_RngRecord: @unchecked Sendable {}
extension FogView_DecommissionedIngestInvocation: @unchecked Sendable {}
extension FogView_TxOutSearchResult: @unchecked Sendable {}
extension FogView_TxOutRecord: @unchecked Sendable {}
extension FogView_TxOutRecord.OneOf_TxOutAmountMaskedTokenID: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
@ -770,8 +720,7 @@ extension FogView_TxOutRecord: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
7: .same(proto: "timestamp"),
8: .standard(proto: "tx_out_amount_commitment_data_crc32"),
9: .standard(proto: "tx_out_e_memo_data"),
10: .standard(proto: "tx_out_amount_masked_v1_token_id"),
11: .standard(proto: "tx_out_amount_masked_v2_token_id"),
10: .standard(proto: "tx_out_amount_masked_token_id"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
@ -789,32 +738,13 @@ extension FogView_TxOutRecord: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
case 7: try { try decoder.decodeSingularFixed64Field(value: &self.timestamp) }()
case 8: try { try decoder.decodeSingularFixed32Field(value: &self.txOutAmountCommitmentDataCrc32) }()
case 9: try { try decoder.decodeSingularBytesField(value: &self.txOutEMemoData) }()
case 10: try {
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {
if self.txOutAmountMaskedTokenID != nil {try decoder.handleConflictingOneOf()}
self.txOutAmountMaskedTokenID = .txOutAmountMaskedV1TokenID(v)
}
}()
case 11: try {
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {
if self.txOutAmountMaskedTokenID != nil {try decoder.handleConflictingOneOf()}
self.txOutAmountMaskedTokenID = .txOutAmountMaskedV2TokenID(v)
}
}()
case 10: try { try decoder.decodeSingularBytesField(value: &self.txOutAmountMaskedTokenID) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if !self.txOutAmountCommitmentData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutAmountCommitmentData, fieldNumber: 1)
}
@ -842,16 +772,8 @@ extension FogView_TxOutRecord: SwiftProtobuf.Message, SwiftProtobuf._MessageImpl
if !self.txOutEMemoData.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutEMemoData, fieldNumber: 9)
}
switch self.txOutAmountMaskedTokenID {
case .txOutAmountMaskedV1TokenID?: try {
guard case .txOutAmountMaskedV1TokenID(let v)? = self.txOutAmountMaskedTokenID else { preconditionFailure() }
try visitor.visitSingularBytesField(value: v, fieldNumber: 10)
}()
case .txOutAmountMaskedV2TokenID?: try {
guard case .txOutAmountMaskedV2TokenID(let v)? = self.txOutAmountMaskedTokenID else { preconditionFailure() }
try visitor.visitSingularBytesField(value: v, fieldNumber: 11)
}()
case nil: break
if !self.txOutAmountMaskedTokenID.isEmpty {
try visitor.visitSingularBytesField(value: self.txOutAmountMaskedTokenID, fieldNumber: 10)
}
try unknownFields.traverse(visitor: &visitor)
}

2
Vendor/mobilecoin vendored

@ -1 +1 @@
Subproject commit c715f5234082642be1b50b7d542a8ca785a3bdce
Subproject commit 06e09b3e0ffac7f8b6845c9e09bfe992f72a5f59

View File

@ -1,2 +0,0 @@
out/
target/

View File

@ -1,98 +0,0 @@
[package]
name = "libmobilecoin"
version = "4.0.0-pre3"
authors = ["MobileCoin"]
edition = "2021"
[lib]
name = "mobilecoin"
crate-type = ["lib", "staticlib", "cdylib"]
[profile.mobile]
inherits = "release"
debug = false
lto = true
[profile.mobile-release]
inherits = "mobile"
codegen-units = 1
[dependencies]
# External dependencies
aes-gcm = "0.10.1"
crc = "3.0.0"
displaydoc = "0.2"
generic-array = { version = "0.14", features = ["serde", "more_lengths"] }
libc = "0.2"
protobuf = "2.27.1"
rand = { version = "0.8", default-features = false }
rand_chacha = { version = "0.3.1" }
rand_core = { version = "0.6", features = ["std"] }
sha2 = { version = "0.10", default-features = false }
slip10_ed25519 = "0.1.3"
tiny-bip39 = "1.0"
zeroize = "1.5"
cmake = "= 0.1.49"
# MobileCoin dependencies
mc-account-keys = { path = "../Vendor/mobilecoin/account-keys" }
mc-api = { path = "../Vendor/mobilecoin/api" }
mc-attest-ake = { path = "../Vendor/mobilecoin/attest/ake" }
mc-attest-core = { path = "../Vendor/mobilecoin/attest/core" }
mc-attest-verifier = { path = "../Vendor/mobilecoin/attest/verifier" }
mc-common = { path = "../Vendor/mobilecoin/common", features = ["std"] }
mc-core = { path = "../Vendor/mobilecoin/core" }
mc-crypto-box = { path = "../Vendor/mobilecoin/crypto/box" }
mc-crypto-keys = { path = "../Vendor/mobilecoin/crypto/keys" }
mc-crypto-noise = { path = "../Vendor/mobilecoin/crypto/noise" }
mc-crypto-rand = { path = "../Vendor/mobilecoin/crypto/rand", features = ["std"] }
mc-crypto-ring-signature-signer = { path = "../Vendor/mobilecoin/crypto/ring-signature/signer", default-features = false }
mc-crypto-sig = { path = "../Vendor/mobilecoin/crypto/sig" }
mc-fog-ingest-report = { path = "../Vendor/mobilecoin/fog/ingest/report" }
mc-fog-kex-rng = { path = "../Vendor/mobilecoin/fog/kex_rng" }
mc-fog-report-resolver = { path = "../Vendor/mobilecoin/fog/report/resolver" }
mc-fog-report-types = { path = "../Vendor/mobilecoin/fog/report/types" }
mc-fog-report-validation = { path = "../Vendor/mobilecoin/fog/report/validation" }
mc-transaction-core = { path = "../Vendor/mobilecoin/transaction/core" }
mc-transaction-builder = { path = "../Vendor/mobilecoin/transaction/builder" }
mc-transaction-extra = { path = "../Vendor/mobilecoin/transaction/extra" }
mc-util-ffi = { path = "../Vendor/mobilecoin/util/ffi" }
mc-util-serial = { path = "../Vendor/mobilecoin/util/serial", features = ["std"] }
mc-util-uri = { path = "../Vendor/mobilecoin/util/uri" }
[dev-dependencies]
cbindgen = { version = "0.24" }
[patch.crates-io]
# Fork and rename to use "OG" dalek-cryptography with latest dependencies.
bulletproofs-og = { git = "https://github.com/mobilecoinfoundation/bulletproofs.git", rev = "65f8af4ca0bc1cb2fd2148c3259a0a76b155ff3e" }
# Fix issues with recent nightlies, bump curve25519-dalek version
curve25519-dalek = { git = "https://github.com/mobilecoinfoundation/curve25519-dalek.git", rev = "8791722e0273762552c9a056eaccb7df6baf44d7" }
ed25519-dalek = { git = "https://github.com/mobilecoinfoundation/ed25519-dalek.git", rev = "4194e36abc75722e6fba7d552e719448fc38c51f" }
# mbedtls patched to allow certificate verification with a profile
mbedtls = { git = "https://github.com/the-real-adammork/rust-mbedtls.git", rev = "4116532348530f1de538e90336ebe65809e0dc95" }
mbedtls-sys-auto = { git = "https://github.com/the-real-adammork/rust-mbedtls.git", rev = "4116532348530f1de538e90336ebe65809e0dc95" }
# Override lmdb-rkv for a necessary bugfix (see https://github.com/mozilla/lmdb-rs/pull/80)
lmdb-rkv = { git = "https://github.com/mozilla/lmdb-rs", rev = "df1c2f5" }
# Fork and rename to use "OG" dalek-cryptography.
schnorrkel-og = { git = "https://github.com/mobilecoinfoundation/schnorrkel.git", rev = "5c98ae068ee4652d6df6463b549fbf2d5d132faa" }
# Fixes the following:
# * Allow enabling `serde/std` without also requiring `serde_cbor/std` to be enabled.
# See: https://github.com/pyfisch/cbor/pull/198
serde_cbor = { git = "https://github.com/mobilecoinofficial/cbor", rev = "4c886a7c1d523aae1ec4aa7386f402cb2f4341b5" }
# Fix issues with recent nightlies, bump curve25519-dalek version
x25519-dalek = { git = "https://github.com/mobilecoinfoundation/x25519-dalek.git", rev = "c1966b8743d320cd07a54191475e5c0f94b2ea30" }
# Override diesel dependency with our fork, to statically link SQLite.
diesel = { git = "https://github.com/mobilecoinofficial/diesel", rev = "026f6379715d27c8be48396e5ca9059f4a263198" }
# latest mbedtls needs spin `^0.9.4`, but `mc-util-vec-map` resolves spin to `^0.9.2` through `heapless` `^0.7`,
# This specifies we use the latest version of heapless ~`0.9.4` to solve the dependency constraints.
heapless = { git = "https://github.com/mobilecoinofficial/heapless", rev = "2726f63bdc767d025f370d88341b1eb785178f2b" }

View File

@ -1,621 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View File

@ -1,144 +0,0 @@
# Copyright (c) 2018-2022 The MobileCoin Foundation
####################################
######### Public Variables #########
####################################
### Project Environment Variables
export SGX_MODE ?= HW
export IAS_MODE ?= DEV
### Build Configuration
CARGO_PROFILE ?= mobile-release
CARGO_BUILD_FLAGS ?=
CARGO_TARGET_DIR ?= ./target
$(info profile: $(CARGO_PROFILE))
### Toolchain
CARGO ?= cargo
####################################
######## Internal Variables ########
####################################
### Local Variables
DOT:= .
DASH:= -
CARGO_PACKAGE = libmobilecoin
ALL_ARCHS_IOS = aarch64-apple-ios-sim aarch64-apple-ios-macabi aarch64-apple-ios x86_64-apple-ios-macabi x86_64-apple-ios x86_64-apple-darwin
IOS_LIB = libmobilecoin.a
IOS_LIB_STRIPPED = libmobilecoin_stripped.a
IOS_C_HEADERS = include/*
### Helper Function
# First argument $(1) is a build-target, $(2) is the output directory
define BINARY_copy
mkdir -p out/ios/$(2)/$(1)/${CARGO_PROFILE}
cp $(CARGO_TARGET_DIR)/$(1)/${CARGO_PROFILE}/libmobilecoin.a out/ios/$(2)/$(1)/${CARGO_PROFILE};
endef
####################################
############## Targets #############
####################################
.PHONY: all
all: setup ios
CARGO_BUILD_FLAGS += --lib -Z avoid-dev-deps
ifeq ($(CARGO_PROFILE),release)
BUILD_CONFIG_FOLDER = ${CARGO_PROFILE}
CARGO_BUILD_FLAGS += --release
else ifeq ($(CARGO_PROFILE),debug)
BUILD_CONFIG_FOLDER = debug
else
BUILD_CONFIG_FOLDER = ${CARGO_PROFILE}
CARGO_BUILD_FLAGS += -Z unstable-options --profile ${CARGO_PROFILE}
endif
LEGACY_CARGO_BUILD_FLAGS = $(CARGO_BUILD_FLAGS)
.PHONY: setup
setup:
rustup target add x86_64-apple-ios aarch64-apple-ios
rustup component add llvm-tools-preview rust-src
rustup run --install stable cargo install cargo-binutils
../tools/patch-cmake.sh
.PHONY: ios
ios: out/ios/target
.PHONY: $(ALL_ARCHS_IOS)
x86_64-apple-ios aarch64-apple-ios: CARGO_ENV_FLAGS += CFLAGS="-DPB_NO_PACKED_STRUCTS=1"
x86_64-apple-ios aarch64-apple-ios: CARGO_ENV_FLAGS += CXXFLAGS="-DPB_NO_PACKED_STRUCTS=1"
x86_64-apple-ios x86_64-apple-ios-macabi x86_64-apple-darwin: LD_ARCH = x86_64
aarch64-apple-ios aarch64-apple-ios-sim aarch64-apple-ios-macabi: LD_ARCH = arm64
x86_64-apple-ios-macabi aarch64-apple-ios-sim aarch64-apple-ios-macabi: LEGACY_CARGO_BUILD_FLAGS += -Zbuild-std
$(ALL_ARCHS_IOS):
$(CARGO_ENV_FLAGS) $(CARGO) build --package $(CARGO_PACKAGE) --target $@ $(LEGACY_CARGO_BUILD_FLAGS)
@# Extract object files from static archive.
@cd $(CARGO_TARGET_DIR)/$@/$(BUILD_CONFIG_FOLDER) && \
rm -rf extracted 2>/dev/null; \
mkdir -p extracted
cd $(CARGO_TARGET_DIR)/$@/$(BUILD_CONFIG_FOLDER)/extracted && \
ar -t ../$(IOS_LIB) \
| grep '\.o$$' \
| xargs ar -x ../$(IOS_LIB)
@# Create list of libmobilecoin symbols.
cd $(CARGO_TARGET_DIR)/$@/$(BUILD_CONFIG_FOLDER) && \
rust-nm -jgU extracted/mobilecoin*.mobilecoin.*.o -s __TEXT __text \
| grep '\<_mc_' \
> exported-symbols.def
@# Link extracted object files back into static arch. Removes all symbols not needed
@# by exported libmobilecoin symbols.
@cd $(CARGO_TARGET_DIR)/$@/$(BUILD_CONFIG_FOLDER) && \
rm -f $(IOS_LIB_STRIPPED) || true
cd $(CARGO_TARGET_DIR)/$@/$(BUILD_CONFIG_FOLDER) && \
ld -r -arch $(LD_ARCH) -x -keep_private_externs \
-exported_symbols_list exported-symbols.def \
-o $(IOS_LIB_STRIPPED) \
extracted/*.o
mkdir -p out/ios/target
$(call BINARY_copy,$@,target)
mkdir -p out/ios/include
cp $(IOS_C_HEADERS) out/ios/include
.PHONY: out/ios/target
out/ios/target: $(ALL_ARCHS_IOS)
mkdir -p out/ios/target
$(foreach arch,$^,$(call BINARY_copy,$(arch),target))
mkdir -p out/ios/include
cp $(IOS_C_HEADERS) out/ios/include
.PHONY: clean
clean:
@rm -r target 2>/dev/null || true
####################################
############# Commands #############
####################################
.PHONY: setup-dev
setup-dev:
cargo install cbindgen
.PHONY: cbindgen
cbindgen:
cbindgen --crate libmobilecoin -o libmobilecoin_cbindgen.h

View File

@ -1,18 +0,0 @@
language = "C"
header = """// Warning, this file is autogenerated by cbindgen. Don't modify this manually.
/**
* This file is meant to be used as an aid when making changes to the manually written
* `libmobilecoin.h` header by comparing it to the output of this cbindgen-autogenerated
* file and checking for equivalency.
*/"""
namespace = "mobilecoin"
no_includes = true
[parse]
parse_deps = false
[parse.expand]
crates = ["libmobilecoin"]

View File

@ -1,243 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef ATTEST_H_
#define ATTEST_H_
#include "common.h"
/* ==================== Attestation ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Types ==== */
/// A `VerifyIasReportData` implementation that will check if the enclave in
/// question has the given MrEnclave, and has no other IAS report status issues.
typedef struct _McMrEnclaveVerifier McMrEnclaveVerifier;
/// A `VerifyIasReportData` implementation that will check if the enclave in
/// question has the given MrSigner value, and has no other IAS report status
/// issues.
typedef struct _McMrSignerVerifier McMrSignerVerifier;
/// A builder structure used to construct a report verifier based on the
/// criteria specified.
typedef struct _McVerifier McVerifier;
typedef struct _McAttestAke McAttestAke;
/* ==== McMrEnclaveVerifier ==== */
/// Create a new status verifier that will check for the existence of the
/// given MrEnclave.
///
/// # Preconditions
///
/// * `mr_enclave` - must be 32 bytes in length.
McMrEnclaveVerifier* MC_NULLABLE mc_mr_enclave_verifier_create(
const McBuffer* MC_NONNULL mr_enclave
)
MC_ATTRIBUTE_NONNULL(1);
void mc_mr_enclave_verifier_free(
McMrEnclaveVerifier* MC_NULLABLE mr_enclave_verifier
);
/// Assume an enclave with the specified measurement does not need
/// BIOS configuration changes to address the provided advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
bool mc_mr_enclave_verifier_allow_config_advisory(
McMrEnclaveVerifier* MC_NONNULL mr_enclave_verifier,
const char* MC_NONNULL advisory_id
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// Assume the given MrEnclave value has the appropriate software/build-time
/// hardening for the given advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
bool mc_mr_enclave_verifier_allow_hardening_advisory(
McMrEnclaveVerifier* MC_NONNULL mr_enclave_verifier,
const char* MC_NONNULL advisory_id
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== McMrSignerVerifier ==== */
/// Create a new status verifier that will check for the existence of the
/// given MrSigner.
///
/// # Preconditions
///
/// * `mr_signer` - must be 32 bytes in length.
McMrSignerVerifier* MC_NULLABLE mc_mr_signer_verifier_create(
const McBuffer* MC_NONNULL mr_signer,
uint16_t expected_product_id,
uint16_t minimum_security_version
)
MC_ATTRIBUTE_NONNULL(1);
void mc_mr_signer_verifier_free(
McMrSignerVerifier* MC_NULLABLE mr_signer_verifier
);
/// Assume an enclave with the specified measurement does not need
/// BIOS configuration changes to address the provided advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
bool mc_mr_signer_verifier_allow_config_advisory(
McMrSignerVerifier* MC_NONNULL mr_signer_verifier,
const char* MC_NONNULL advisory_id
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// Assume an enclave with the specified measurement has the appropriate
/// software/build-time hardening for the given advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
bool mc_mr_signer_verifier_allow_hardening_advisory(
McMrSignerVerifier* MC_NONNULL mr_signer_verifier,
const char* MC_NONNULL advisory_id
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== McVerifier ==== */
/// Construct a new builder using the baked-in IAS root certificates and debug
/// settings.
McVerifier* MC_NULLABLE mc_verifier_create();
void mc_verifier_free(
McVerifier* MC_NULLABLE verifier
);
/// Verify the given MrEnclave-based status verifier succeeds
bool mc_verifier_add_mr_enclave(
McVerifier* MC_NONNULL verifier,
const McMrEnclaveVerifier* MC_NONNULL mr_enclave_verifier
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// Verify the given MrSigner-based status verifier succeeds
bool mc_verifier_add_mr_signer(
McVerifier* MC_NONNULL verifier,
const McMrSignerVerifier* MC_NONNULL mr_signer_verifier
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== McAttestAke ==== */
McAttestAke* MC_NULLABLE mc_attest_ake_create();
void mc_attest_ake_free(
McAttestAke* MC_NULLABLE attest_ake
);
bool mc_attest_ake_is_attested(
const McAttestAke* MC_NONNULL attest_ake,
bool* MC_NONNULL out_attested
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_binding` - must be null or else length must be >= `binding.len`.
ssize_t mc_attest_ake_get_binding(
const McAttestAke* MC_NONNULL attest_ake,
McMutableBuffer* MC_NULLABLE out_binding
)
MC_ATTRIBUTE_NONNULL(1);
/* ==== Auth ==== */
/// # Preconditions
///
/// * `responder_id` - must be a nul-terminated C string containing a valid responder ID.
/// * `out_auth_request` - must be null or else length must be >= auth_request_output.len.
ssize_t mc_attest_ake_get_auth_request(
McAttestAke* MC_NONNULL attest_ake,
const char* MC_NONNULL responder_id,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NULLABLE out_auth_request
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `attest_ake` - must be in the auth pending state.
///
/// # Errors
///
/// * `LibMcError::AttestationVerificationFailed`
/// * `LibMcError::InvalidInput`
bool mc_attest_ake_process_auth_response(
McAttestAke* MC_NONNULL attest_ake,
const McBuffer* MC_NONNULL auth_response_data,
const McVerifier* MC_NONNULL verifier,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
/* ==== Message Encryption ==== */
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_ciphertext` - must be null or else length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::Cipher`
ssize_t mc_attest_ake_encrypt(
McAttestAke* MC_NONNULL attest_ake,
const McBuffer* MC_NONNULL aad,
const McBuffer* MC_NONNULL plaintext,
McMutableBuffer* MC_NULLABLE out_ciphertext,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_plaintext` - length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::Cipher`
ssize_t mc_attest_ake_decrypt(
McAttestAke* MC_NONNULL attest_ake,
const McBuffer* MC_NONNULL aad,
const McBuffer* MC_NONNULL ciphertext,
McMutableBuffer* MC_NONNULL out_plaintext,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3, 4);
#ifdef __cplusplus
}
#endif
#endif /* !ATTEST_H_ */

View File

@ -1,51 +0,0 @@
#ifndef BIP39_H_
#define BIP39_H_
#include "common.h"
/* ==================== BIP39 ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== McBip39 ==== */
/// # Preconditions
///
/// * `entropy` - length must be a multiple of 4 and between 16 and 32,
/// inclusive, in bytes.
char* MC_NULLABLE mc_bip39_mnemonic_from_entropy(
const McBuffer* MC_NONNULL entropy
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `mnemonic` - must be a nul-terminated C string containing valid UTF-8.
/// * `out_entropy` - must be null or else length must be >= `entropy.len`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
ssize_t mc_bip39_entropy_from_mnemonic(
const char* MC_NONNULL mnemonic,
McMutableBuffer* MC_NULLABLE out_entropy,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `prefix` - must be a nul-terminated C string containing valid UTF-8.
char* MC_NULLABLE mc_bip39_words_by_prefix(
const char* MC_NONNULL prefix
)
MC_ATTRIBUTE_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* !BIP39_H_ */

View File

@ -1,116 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef MC_CHACHA20_RNG_H_
#define MC_CHACHA20_RNG_H_
#include "common.h"
/* ==================== ChaCha20Rng ==================== */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _ChaCha20Rng ChaCha20Rng;
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the u64 long_val parameter
///
/// # Arguments
///
/// * `long_val` - an unsigned 64 bit value to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::Poison`
ChaCha20Rng* MC_NULLABLE mc_chacha20_rng_create_with_long(
uint64_t value,
McError* MC_NULLABLE * MC_NULLABLE out_error
);
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the bytes data, which must be at
/// least 32 bytes (only the first 32 bytes will be used)
///
/// # Arguments
///
/// * `bytes` - 32 bytes of data to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::Poison`
ChaCha20Rng* MC_NULLABLE mc_chacha20_rng_create_with_bytes(
const McBuffer* MC_NONNULL bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
/// Returns the current word_pos of the ChaCha20Rng instance
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 16 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
bool mc_chacha20_rng_get_word_pos(
ChaCha20Rng* MC_NONNULL chacha20_rng,
const McBuffer* MC_NONNULL out_word_pos,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1,2);
/// Sets the current word_pos of the ChaCha20Rng instance
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 128 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
bool mc_chacha20_rng_set_word_pos(
ChaCha20Rng* MC_NONNULL chacha20_rng,
const McBuffer* MC_NONNULL bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1,2);
/// Returns the next random u64 value from the ChaCha20Rng
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
///
/// # Errors
///
/// * `LibMcError::Poison`
uint64_t mc_chacha20_rng_next_long(
ChaCha20Rng* MC_NONNULL chacha20_rng,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
/// Frees the ChaCha20Rng
///
/// # Preconditions
///
/// * The ChaCha20Rng is no longer in use
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
void mc_chacha20_rng_free(
ChaCha20Rng* MC_NULLABLE chacha20_rng
);
#ifdef __cplusplus
}
#endif
#endif /* MC_CHACHA20_RNG_H_ */

View File

@ -1,112 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef COMMON_H_
#define COMMON_H_
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
// Compatibility with non-clang compilers.
#ifndef __has_attribute
# define __has_attribute(x) 0
#endif
#if __has_attribute(nonnull)
# define MC_ATTRIBUTE_NONNULL(...) __attribute__((nonnull(__VA_ARGS__)))
#else
# define MC_ATTRIBUTE_NONNULL(...)
#endif
#ifdef __llvm__
# define MC_NONNULL _Nonnull
# define MC_NULLABLE _Nullable
#else
# define MC_NONNULL
# define MC_NULLABLE
#endif
#if __has_attribute(enum_extensibility)
# define MC_ATTRIBUTE_ENUM_CLOSED __attribute__((enum_extensibility(closed)))
#else
# define MC_ATTRIBUTE_ENUM_CLOSED
#endif
/* ==================== Common ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Error Codes ==== */
typedef enum MC_ATTRIBUTE_ENUM_CLOSED {
McErrorCodeUnknown = -1,
McErrorCodePanic = -2,
McErrorCodeInvalidInput = 100,
McErrorCodeInvalidOutput = 101,
McErrorCodeAttestationVerificationFailed = 200,
McErrorCodeAead = 300,
McErrorCodeCipher = 301,
McErrorCodeUnsupportedCryptoBoxVersion = 302,
McErrorCodeTransactionCrypto = 400,
McErrorCodeFogPubkey = 500,
} McErrorCode;
/* ==== McError ==== */
typedef struct {
int error_code;
const char* MC_NONNULL error_description;
} McError;
void mc_error_free(McError* MC_NULLABLE error);
/* ==== McString ==== */
void mc_string_free(char* MC_NULLABLE string);
/* ==== McBuffer ==== */
typedef struct {
const uint8_t* MC_NONNULL buffer;
size_t len;
} McBuffer;
typedef struct {
uint8_t* MC_NONNULL buffer;
size_t len;
} McMutableBuffer;
/* ==== McData ==== */
typedef struct _McData McData;
void mc_data_free(McData* MC_NULLABLE data);
/// # Preconditions
///
/// * `out_bytes` - must be null or else length must be >= `data.len`.
ssize_t mc_data_get_bytes(
const McData* MC_NONNULL data,
McMutableBuffer* MC_NULLABLE out_bytes
)
MC_ATTRIBUTE_NONNULL(1);
/* ==== McRngCallback ==== */
typedef struct {
uint64_t (* MC_NONNULL rng)(void* MC_NULLABLE);
void* MC_NULLABLE context;
} McRngCallback;
#ifdef __cplusplus
}
#endif
#endif /* !COMMON_H_ */

View File

@ -1,79 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef CRYPTO_H_
#define CRYPTO_H_
#include "common.h"
/* ==================== Crypto ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Ristretto ==== */
bool mc_ristretto_private_validate(
const McBuffer* MC_NONNULL ristretto_private,
bool* MC_NONNULL out_valid
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `ristretto_private` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_ristretto_public` - length must be >= 32.
bool mc_ristretto_public_from_ristretto_private(
const McBuffer* MC_NONNULL ristretto_private,
McMutableBuffer* MC_NONNULL out_ristretto_public
)
MC_ATTRIBUTE_NONNULL(1, 2);
bool mc_ristretto_public_validate(
const McBuffer* MC_NONNULL ristretto_public,
bool* MC_NONNULL out_valid
)
MC_ATTRIBUTE_NONNULL(1, 2);
/* ==== VersionedCryptoBox ==== */
/// # Preconditions
///
/// * `public_key` - must be a valid 32-byte compressed Ristretto point.
/// * `out_ciphertext` - must be null or else length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
ssize_t mc_versioned_crypto_box_encrypt(
const McBuffer* MC_NONNULL public_key,
const McBuffer* MC_NONNULL plaintext,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NULLABLE out_ciphertext,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_plaintext` - length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
ssize_t mc_versioned_crypto_box_decrypt(
const McBuffer* MC_NONNULL private_key,
const McBuffer* MC_NONNULL ciphertext,
McMutableBuffer* MC_NONNULL out_plaintext,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
#ifdef __cplusplus
}
#endif
#endif /* !CRYPTO_H_ */

View File

@ -1,45 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef ENCODINGS_H_
#define ENCODINGS_H_
#include "common.h"
/* ==================== Encodings ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== PrintableWrapper ==== */
/// # Preconditions
///
/// * `printable_wrapper_proto_bytes` - must be a valid binary-serialized `printable.PrintableWrapper`
/// Protobuf.
char* MC_NULLABLE mc_printable_wrapper_b58_encode(
const McBuffer* MC_NONNULL printable_wrapper_proto_bytes
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `b58_encoded_string` - must be a nul-terminated C string containing valid UTF-8.
/// * `out_printable_wrapper_proto_bytes` - must be null or else length must be >=
/// `wrapper_bytes.len`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
ssize_t mc_printable_wrapper_b58_decode(
const char* MC_NONNULL b58_encoded_string,
McMutableBuffer* MC_NULLABLE out_printable_wrapper_proto_bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* !ENCODINGS_H_ */

View File

@ -1,158 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef FOG_H_
#define FOG_H_
#include "common.h"
#include "keys.h"
/* ==================== Fog ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Types ==== */
typedef struct _McFogResolver McFogResolver;
typedef struct _McFullyValidatedFogPubkey McFullyValidatedFogPubkey;
typedef struct _McFogRng McFogRng;
/* ==== McFogResolver ==== */
McFogResolver* MC_NULLABLE mc_fog_resolver_create(
const McVerifier* MC_NONNULL fog_report_verifier
)
MC_ATTRIBUTE_NONNULL(1);
void mc_fog_resolver_free(
McFogResolver* MC_NULLABLE fog_resolver
);
McFullyValidatedFogPubkey* MC_NULLABLE mc_fog_resolver_get_fog_pubkey(
const McFogResolver* MC_NONNULL fog_resolver,
const McPublicAddress* MC_NONNULL recipient,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
McFullyValidatedFogPubkey* MC_NULLABLE mc_fog_resolver_get_fog_pubkey_from_protobuf_public_address(
const McFogResolver* MC_NONNULL fog_resolver,
const McBuffer* MC_NONNULL recipient_protobuf,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `report_url` - must be a nul-terminated C string containing a valid Fog report uri.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_fog_resolver_add_report_response(
McFogResolver* MC_NONNULL fog_resolver,
const char* MC_NONNULL report_url,
const McBuffer* MC_NONNULL report_response,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
/* ==== McFullyValidatedFogPubkey ==== */
void mc_fully_validated_fog_pubkey_free(
McFullyValidatedFogPubkey* MC_NULLABLE fully_validated_fog_pubkey
);
/// # Preconditions
///
/// * `out_pubkey` - length must be >= 32.
bool mc_fully_validated_fog_pubkey_get_pubkey(
const McFullyValidatedFogPubkey* MC_NONNULL fully_validated_fog_pubkey,
McMutableBuffer* MC_NONNULL out_pubkey
);
uint64_t mc_fully_validated_fog_pubkey_get_pubkey_expiry(
const McFullyValidatedFogPubkey* MC_NONNULL fully_validated_fog_pubkey
);
/* ==== McFogRng ==== */
/// # Preconditions
///
/// * `subaddress_view_private_key` - must be a valid 32-byte Ristretto-format scalar.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
McFogRng* MC_NULLABLE mc_fog_rng_create(
const McBuffer* MC_NONNULL subaddress_view_private_key,
const McBuffer* MC_NONNULL rng_public_key,
uint32_t rng_version,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2);
void mc_fog_rng_free(
McFogRng* MC_NULLABLE fog_rng);
McFogRng* MC_NULLABLE mc_fog_rng_clone(
const McFogRng* MC_NONNULL fog_rng
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `out_fog_rng_proto_bytes` - must be null or else length must be >= `encoded.len`.
ssize_t mc_fog_rng_serialize_proto(
const McFogRng* MC_NONNULL fog_rng,
McMutableBuffer* MC_NULLABLE out_fog_rng_proto_bytes
)
MC_ATTRIBUTE_NONNULL(1);
/// # Errors
///
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
McFogRng* MC_NULLABLE mc_fog_rng_deserialize_proto(
const McBuffer* MC_NONNULL fog_rng_proto_bytes,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
int64_t mc_fog_rng_index(
const McFogRng* MC_NONNULL fog_rng
)
MC_ATTRIBUTE_NONNULL(1);
ssize_t mc_fog_rng_get_output_len(
const McFogRng* MC_NONNULL fog_rng
)
MC_ATTRIBUTE_NONNULL(1);
/// # Preconditions
///
/// * `out_output` - length must be >= `output.len`.
bool mc_fog_rng_peek(
const McFogRng* MC_NONNULL fog_rng,
McMutableBuffer* MC_NONNULL out_output
)
MC_ATTRIBUTE_NONNULL(1, 2);
/// # Preconditions
///
/// * `out_output` - must be null or else length must be >= `output.len`.
bool mc_fog_rng_advance(
McFogRng* MC_NONNULL fog_rng,
McMutableBuffer* MC_NULLABLE out_output
)
MC_ATTRIBUTE_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* !FOG_H_ */

View File

@ -1,114 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef KEYS_H_
#define KEYS_H_
#include "common.h"
/* ==================== Account Keys ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Types ==== */
typedef struct {
const char* MC_NONNULL report_url;
const char* MC_NONNULL report_id;
const McBuffer* MC_NONNULL authority_fingerprint;
} McAccountKeyFogInfo;
typedef struct {
const McBuffer* MC_NONNULL view_private_key;
const McBuffer* MC_NONNULL spend_private_key;
const McAccountKeyFogInfo* MC_NULLABLE fog_info;
} McAccountKey;
typedef struct {
const char* MC_NONNULL report_url;
const char* MC_NONNULL report_id;
const McBuffer* MC_NONNULL authority_sig;
} McPublicAddressFogInfo;
typedef struct {
const McBuffer* MC_NONNULL view_public_key;
const McBuffer* MC_NONNULL spend_public_key;
const McPublicAddressFogInfo* MC_NULLABLE fog_info;
} McPublicAddress;
/* ==== AccountKey ==== */
/// # Preconditions
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_subaddress_view_private_key` - length must be >= 32.
/// * `out_subaddress_spend_private_key` - length must be >= 32.
bool mc_account_key_get_subaddress_private_keys(
const McBuffer* MC_NONNULL view_private_key,
const McBuffer* MC_NONNULL spend_private_key,
uint64_t subaddress_index,
McMutableBuffer* MC_NONNULL out_subaddress_view_private_key,
McMutableBuffer* MC_NONNULL out_subaddress_spend_private_key
)
MC_ATTRIBUTE_NONNULL(1, 2, 4, 5);
/// # Preconditions
///
/// * `root_entropy` - must be 32 bytes in length.
/// * `out_view_private_key` - length must be >= 32.
/// * `out_spend_private_key` - length must be >= 32.
bool mc_account_private_keys_from_root_entropy(
const McBuffer* MC_NONNULL root_entropy,
McMutableBuffer* MC_NONNULL out_view_private_key,
McMutableBuffer* MC_NONNULL out_spend_private_key
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
/// # Preconditions
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_subaddress_view_public_key` - length must be >= 32.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
bool mc_account_key_get_public_address_public_keys(
const McBuffer* MC_NONNULL view_private_key,
const McBuffer* MC_NONNULL spend_private_key,
uint64_t subaddress_index,
McMutableBuffer* MC_NONNULL out_subaddress_view_public_key,
McMutableBuffer* MC_NONNULL out_subaddress_spend_public_key
)
MC_ATTRIBUTE_NONNULL(1, 2, 4, 5);
/// # Preconditions
///
/// * `account_key` - must be a valid `AccountKey` with `fog_info`.
/// * `out_fog_authority_fingerprint_sig` - length must be >= 64.
bool mc_account_key_get_public_address_fog_authority_sig(
const McAccountKey* MC_NONNULL account_key,
uint64_t subaddress_index,
McMutableBuffer* MC_NONNULL out_fog_authority_sig
)
MC_ATTRIBUTE_NONNULL(1, 3);
/// # Preconditions
///
/// * `public_address` - must be a valid `PublicAddress`.
/// * `out_short_address_hash` - length must be >= 16 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_account_key_get_short_address_hash(
const McPublicAddress* MC_NONNULL public_address,
McMutableBuffer* MC_NONNULL out_short_address_hash,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 3);
#ifdef __cplusplus
}
#endif
#endif /* !KEYS_H_ */

View File

@ -1,17 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef LIBMOBILECOIN_H_
#define LIBMOBILECOIN_H_
#include "common.h"
#include "crypto.h"
#include "keys.h"
#include "attest.h"
#include "encodings.h"
#include "fog.h"
#include "transaction.h"
#include "bip39.h"
#include "slip10.h"
#include "chacha20_rng.h"
#endif /* !LIBMOBILECOIN_H_ */

View File

@ -1,127 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#ifndef SIGNED_CONTINGENT_INPUT_H_
#define SIGNED_CONTINGENT_INPUT_H_
#include "common.h"
#include "fog.h"
#include "keys.h"
/* ==================== Signed Contingent Input ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== Types ==== */
typedef struct _McSignedContingentInputBuilder McSignedContingentInputBuilder;
typedef struct _McTxOutMemoBuilder McTxOutMemoBuilder;
typedef struct _McTransactionBuilderRing McTransactionBuilderRing;
/* ==== McSignedContingentInputBuilder ==== */
/// # Preconditions
///
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `subaddress_spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `real_index` - must be within bounds of `ring`.
/// * `ring` - `TxOut` at `real_index` must be owned by account keys.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
McSignedContingentInputBuilder* MC_NULLABLE mc_signed_contingent_input_builder_create(
uint32_t block_version,
uint64_t tombstone_block,
const McFogResolver* MC_NULLABLE fog_resolver,
McTxOutMemoBuilder* MC_NONNULL memo_builder,
const McBuffer* MC_NONNULL view_private_key,
const McBuffer* MC_NONNULL subaddress_spend_private_key,
size_t real_index,
const McTransactionBuilderRing* MC_NONNULL ring,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(4,5,6,8);
void mc_signed_contingent_input_builder_free(
McSignedContingentInputBuilder* MC_NULLABLE signed_contingent_input_builder
);
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call to `build`.
/// * `recipient_address` - must be a valid `PublicAddress`.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_add_required_output(
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
uint64_t amount,
uint64_t token_id,
const McPublicAddress* MC_NONNULL recipient_address,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 4, 6);
/// # Preconditions
///
/// * `account_kay` - must be a valid account key, default change address computed from account key
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `out_tx_out_confirmation_number` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::AttestationVerification`
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_add_required_change_output(
const McAccountKey* MC_NONNULL account_key,
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
uint64_t amount,
uint64_t token_id,
McRngCallback* MC_NULLABLE rng_callback,
McMutableBuffer* MC_NONNULL out_tx_out_confirmation_number,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 2, 6);
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call to `build`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
McData* MC_NULLABLE mc_signed_contingent_input_builder_build(
McSignedContingentInputBuilder* MC_NONNULL signed_contingent_input_builder,
McRngCallback* MC_NULLABLE rng_callback,
const McTransactionBuilderRing* MC_NONNULL ring,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
// #[no_mangle]
// pub extern "C" fn mc_signed_contingent_input_data_is_valid(
// sci_data: FfiRefPtr<McBuffer>,
// out_valid: FfiMutPtr<bool>,
// out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
// ) -> bool {
bool mc_signed_contingent_input_data_is_valid(
const McBuffer* MC_NONNULL signed_contingent_input,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* !SIGNED_CONTINGENT_INPUT_H_ */

View File

@ -1,36 +0,0 @@
#ifndef SLIP10_H_
#define SLIP10_H_
#include "common.h"
/* ==================== SLIP10 ==================== */
#ifdef __cplusplus
extern "C" {
#endif
/* ==== McSlip10 ==== */
/// # Preconditions
///
/// * `mnemonic` - must be a nul-terminated C string containing valid UTF-8.
/// * `out_view_private_key` - length must be >= 32.
/// * `out_spend_private_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
bool mc_slip10_account_private_keys_from_mnemonic(
const char* MC_NONNULL mnemonic,
uint32_t account_index,
McMutableBuffer* MC_NONNULL out_view_private_key,
McMutableBuffer* MC_NONNULL out_spend_private_key,
McError* MC_NULLABLE * MC_NULLABLE out_error
)
MC_ATTRIBUTE_NONNULL(1, 3, 4);
#ifdef __cplusplus
}
#endif
#endif /* !SLIP10_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -1,78 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
syntax = "proto3";
package fog_view;
///
/// *** DISCLAIMER ***
///
/// This proto is deprecated and no longer used, we're re-importing it so we can re-use serialized data in
/// some Swift unit tests. Once we convert these tests we should remove this proto.
///
/// *** END DISCLAIMER ***
///
/// The schema for the decrypted TxOutSearchResult ciphertext
/// This is the information that the Ingest enclave produces for the user about their TxOut
///
/// Note: The fields of FogTxOut are flattened here because it reduces the size of the protobuf
/// enough to make a difference for the quality of ORAM implementation, like ~10% better memory utilization
///
/// Note: Fog TxOutRecord DOES NOT include the encrypted fog hint of the original TxOut, because it is big,
/// and the client cannot read it anyways. However, when using the TxOut to build transactions, you must have that
/// or the merkle proofs will fail validation, at least for now.
/// The fog merkle proof server gives you a TxOut with fog hint, as it appears in blockchain,
/// and that's the version of the TxOut that you should use when building a transaction.
message TxOutRecordLegacy {
/// The (compressed ristretto) bytes of commitment associated to amount field in the TxOut that was recovered
///
/// Note: This field is omitted in recent versions, because it can be reconstructed by the recipient instead.
bytes tx_out_amount_commitment_data = 1;
/// The masked value associated to amount field in the TxOut that was recovered
fixed64 tx_out_amount_masked_value = 2;
/// The (compressed ristretto) bytes of the target key associated to the TxOut that was recovered
bytes tx_out_target_key_data = 3;
/// The (compressed ristretto) bytes of the public key associated to the TxOut that was recovered
bytes tx_out_public_key_data = 4;
/// The global index of this TxOut in the set of all TxOuts in the entire block chain
fixed64 tx_out_global_index = 5;
/// The index of the block index in which this TxOut appeared
fixed64 block_index = 6;
/// The timestamp of the block containing this output.
/// Some blocks, like the origin block, don't have a timestamp, and this value is u64::MAX
/// Other blocks are expected to have timestamps.
///
/// Note: The timestamp is based on untrusted reporting of time from ONE of the consensus validators.
/// Because it is a distributed system, it may not be the SAME consensus validator from block to block,
/// and the timestamps may not make even a minimal amount of sense when the validator differs.
///
/// These timestamps are
/// - NOISY, forward and backwards in time, depending on system time settings of many different servers.
/// - NOT MONOTONIC: it's possible that you get a timestamp for block 101 that is before the timestamp for block 100.
/// - Not even CONSISTENT across fog services: It's possible you get a different timestamp for a TxOut in block 100,
/// than you do for a key image in block 100 from the key image endpoint.
/// This is unavoidable right now because it is possible that fog-ingest has different levels of
/// connectivity from the fog-key-image service to the blockchain data sources.
///
/// Timestamps are BEST-EFFORT and for a good user experience, the client software should attempt to reconcile these
/// timestamps, so that events that have a happens-before relationship in the system, have timestamps that reflect that.
/// Otherwise, we should expect users to be confused and disturbed about the occasional time-travelling transaction.
///
/// We hope to improve the quality guarantees of these timestamps over time, but for now this is the best we
/// can do until some changes can be made to the consensus network and other services related to timestamps.
///
/// Represented as seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
fixed64 timestamp = 7;
/// The crc32 of the commitment data bytes.
/// This is a 4-byte IEEE crc32 of the bytes of the tx_out_amount_commitment_data bytes, which is present if
/// the full tx_out_amount_commitment_data is omitted.
/// The client can recompute the tx_out_amount_commitment from the other data that we include.
/// They can confirm correct recomputation by checking this crc value.
fixed32 tx_out_amount_commitment_data_crc32 = 8;
/// The bytes of the encrypted memo.
/// This exactly 66 bytes when present.
/// This is omitted for TxOut's from before the upgrade that introduced memos.
bytes tx_out_e_memo_data = 9;
/// The masked token id associated to the amount field in the TxOut that was recovered
bytes tx_out_amount_masked_token_id = 10;
}

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
nightly-2022-04-28

View File

@ -1,472 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use aes_gcm::Aes256Gcm;
use core::str::FromStr;
use libc::ssize_t;
use mc_attest_ake::{
AuthPending, AuthResponseInput, AuthResponseOutput, ClientInitiate, Ready, Start, Transition,
};
use mc_attest_core::{MrEnclave, MrSigner};
use mc_attest_verifier::{MrEnclaveVerifier, MrSignerVerifier, Verifier, DEBUG_ENCLAVE};
use mc_common::ResponderId;
use mc_crypto_keys::X25519;
use mc_crypto_noise::NoiseCipher;
use mc_crypto_rand::McRng;
use mc_util_ffi::*;
use sha2::Sha512;
pub type McMrEnclaveVerifier = MrEnclaveVerifier;
impl_into_ffi!(MrEnclaveVerifier);
#[no_mangle]
pub extern "C" fn mc_mr_enclave_verifier_free(
mr_enclave_verifier: FfiOptOwnedPtr<McMrEnclaveVerifier>,
) {
ffi_boundary(|| {
let _ = mr_enclave_verifier;
})
}
/// Create a new status verifier that will check for the existence of the
/// given MrEnclave.
///
/// # Preconditions
///
/// * `mr_enclave` - must be 32 bytes in length.
#[no_mangle]
pub extern "C" fn mc_mr_enclave_verifier_create(
mr_enclave: FfiRefPtr<McBuffer>,
) -> FfiOptOwnedPtr<McMrEnclaveVerifier> {
ffi_boundary(|| {
let mr_enclave = MrEnclave::try_from_ffi(&mr_enclave).expect("mr_enclave is invalid");
MrEnclaveVerifier::new(mr_enclave)
})
}
/// Assume an enclave with the specified measurement does not need
/// BIOS configuration changes to address the provided advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
#[no_mangle]
pub extern "C" fn mc_mr_enclave_verifier_allow_config_advisory(
mr_enclave_verifier: FfiMutPtr<McMrEnclaveVerifier>,
advisory_id: FfiStr,
) -> bool {
ffi_boundary(|| {
let advisory_id = <&str>::try_from_ffi(advisory_id).expect("advisory_id is invalid");
mr_enclave_verifier
.into_mut()
.allow_config_advisory(advisory_id);
})
}
/// Assume the given MrEnclave value has the appropriate software/build-time
/// hardening for the given advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
#[no_mangle]
pub extern "C" fn mc_mr_enclave_verifier_allow_hardening_advisory(
mr_enclave_verifier: FfiMutPtr<McMrEnclaveVerifier>,
advisory_id: FfiStr,
) -> bool {
ffi_boundary(|| {
let advisory_id = <&str>::try_from_ffi(advisory_id).expect("advisory_id is invalid");
mr_enclave_verifier
.into_mut()
.allow_hardening_advisory(advisory_id);
})
}
pub type McMrSignerVerifier = MrSignerVerifier;
impl_into_ffi!(MrSignerVerifier);
#[no_mangle]
pub extern "C" fn mc_mr_signer_verifier_free(
mr_signer_verifier: FfiOptOwnedPtr<McMrSignerVerifier>,
) {
ffi_boundary(|| {
let _ = mr_signer_verifier;
})
}
/// Create a new status verifier that will check for the existence of the
/// given MrSigner.
///
/// # Preconditions
///
/// * `mr_signer` - must be 32 bytes in length.
#[no_mangle]
pub extern "C" fn mc_mr_signer_verifier_create(
mr_signer: FfiRefPtr<McBuffer>,
expected_product_id: u16,
minimum_security_version: u16,
) -> FfiOptOwnedPtr<McMrSignerVerifier> {
ffi_boundary(|| {
let mr_signer = MrSigner::try_from_ffi(&mr_signer).expect("mr_signer is invalid");
MrSignerVerifier::new(mr_signer, expected_product_id, minimum_security_version)
})
}
/// Assume an enclave with the specified measurement does not need
/// BIOS configuration changes to address the provided advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
#[no_mangle]
pub extern "C" fn mc_mr_signer_verifier_allow_config_advisory(
mr_signer_verifier: FfiMutPtr<MrSignerVerifier>,
advisory_id: FfiStr,
) -> bool {
ffi_boundary(|| {
let advisory_id = <&str>::try_from_ffi(advisory_id).expect("advisory_id is invalid");
mr_signer_verifier
.into_mut()
.allow_config_advisory(advisory_id);
})
}
/// Assume an enclave with the specified measurement has the appropriate
/// software/build-time hardening for the given advisory ID.
///
/// This method should only be used when advised by an enclave author.
///
/// # Preconditions
///
/// * `advisory_id` - must be a nul-terminated C string containing valid UTF-8.
#[no_mangle]
pub extern "C" fn mc_mr_signer_verifier_allow_hardening_advisory(
mr_signer_verifier: FfiMutPtr<MrSignerVerifier>,
advisory_id: FfiStr,
) -> bool {
ffi_boundary(|| {
let advisory_id = <&str>::try_from_ffi(advisory_id).expect("advisory_id is invalid");
mr_signer_verifier
.into_mut()
.allow_hardening_advisory(advisory_id);
})
}
pub type McVerifier = Verifier;
impl_into_ffi!(Verifier);
/// Construct a new builder using the baked-in IAS root certificates and debug
/// settings.
#[no_mangle]
pub extern "C" fn mc_verifier_create() -> FfiOptOwnedPtr<McVerifier> {
ffi_boundary(|| {
let mut verifier = Verifier::default();
verifier.debug(DEBUG_ENCLAVE);
verifier
})
}
#[no_mangle]
pub extern "C" fn mc_verifier_free(verifier: FfiOptOwnedPtr<McVerifier>) {
ffi_boundary(|| {
let _ = verifier;
})
}
/// Verify the given MrEnclave-based status verifier succeeds
#[no_mangle]
pub extern "C" fn mc_verifier_add_mr_enclave(
verifier: FfiMutPtr<McVerifier>,
mr_enclave_verifier: FfiRefPtr<McMrEnclaveVerifier>,
) -> bool {
ffi_boundary(|| {
verifier
.into_mut()
.mr_enclave((*mr_enclave_verifier).clone());
})
}
/// Verify the given MrSigner-based status verifier succeeds
#[no_mangle]
pub extern "C" fn mc_verifier_add_mr_signer(
verifier: FfiMutPtr<McVerifier>,
mr_signer_verifier: FfiRefPtr<McMrSignerVerifier>,
) -> bool {
ffi_boundary(|| {
verifier.into_mut().mr_signer((*mr_signer_verifier).clone());
})
}
pub enum AttestAke {
NotAttested,
AuthPending(AuthPending<X25519, Aes256Gcm, Sha512>),
Attested(Ready<Aes256Gcm>),
}
impl AttestAke {
pub fn new() -> Self {
Self::NotAttested
}
pub fn is_attested(&self) -> bool {
matches!(self, Self::Attested(_))
}
pub fn take_auth_pending(&mut self) -> Option<AuthPending<X25519, Aes256Gcm, Sha512>> {
if let Self::AuthPending(_) = self {
let state = std::mem::replace(self, Self::NotAttested);
if let Self::AuthPending(auth_pending) = state {
return Some(auth_pending);
}
}
None
}
pub fn attest_cipher(&self) -> Option<&Ready<Aes256Gcm>> {
match self {
Self::Attested(attest_cipher) => Some(attest_cipher),
_ => None,
}
}
pub fn attest_cipher_mut(&mut self) -> Option<&mut Ready<Aes256Gcm>> {
match self {
Self::Attested(attest_cipher) => Some(attest_cipher),
_ => None,
}
}
}
impl Default for AttestAke {
fn default() -> Self {
Self::new()
}
}
pub type McAttestAke = AttestAke;
impl_into_ffi!(AttestAke);
#[no_mangle]
pub extern "C" fn mc_attest_ake_create() -> FfiOptOwnedPtr<McAttestAke> {
ffi_boundary(AttestAke::new)
}
#[no_mangle]
pub extern "C" fn mc_attest_ake_free(attest_ake: FfiOptOwnedPtr<McAttestAke>) {
ffi_boundary(|| {
let _ = attest_ake;
})
}
#[no_mangle]
pub extern "C" fn mc_attest_ake_is_attested(
attest_ake: FfiRefPtr<McAttestAke>,
out_attested: FfiMutPtr<bool>,
) -> bool {
ffi_boundary(|| *out_attested.into_mut() = attest_ake.is_attested())
}
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_binding` - must be null or else length must be >= `binding.len`.
#[no_mangle]
pub extern "C" fn mc_attest_ake_get_binding(
attest_ake: FfiRefPtr<McAttestAke>,
out_binding: FfiOptMutPtr<McMutableBuffer>,
) -> ssize_t {
ffi_boundary(|| {
let attest_cipher = attest_ake
.attest_cipher()
.expect("attest_ake is not in the attested state");
let binding = attest_cipher.binding();
if let Some(out_binding) = out_binding.into_option() {
out_binding
.into_mut()
.as_slice_mut_of_len(binding.len())
.expect("out_binding length is insufficient")
.copy_from_slice(binding);
}
ssize_t::ffi_try_from(binding.len()).expect("binding.len could not be converted to ssize_t")
})
}
/// # Preconditions
///
/// * `responder_id` - must be a nul-terminated C string containing a valid
/// responder ID.
/// * `out_auth_request` - must be null or else length must be >=
/// auth_request_output.len.
#[no_mangle]
pub extern "C" fn mc_attest_ake_get_auth_request(
attest_ake: FfiMutPtr<McAttestAke>,
responder_id: FfiStr,
rng_callback: FfiOptMutPtr<McRngCallback>,
out_auth_request: FfiOptMutPtr<McMutableBuffer>,
) -> ssize_t {
ffi_boundary(|| {
let responder_id =
ResponderId::try_from_ffi(responder_id).expect("responder_id is invalid");
let mut rng = SdkRng::from_ffi(rng_callback);
let start = Start::new(responder_id.to_string());
let init_input = ClientInitiate::<X25519, Aes256Gcm, Sha512>::default();
let (auth_pending, auth_request_output) = start
.try_next(&mut rng, init_input)
.expect("Ake start transition is no fail");
*attest_ake.into_mut() = AttestAke::AuthPending(auth_pending);
let auth_request_output = auth_request_output.as_ref();
if let Some(out_auth_request) = out_auth_request.into_option() {
out_auth_request
.into_mut()
.as_slice_mut_of_len(auth_request_output.len())
.expect("out_auth_request length is insufficient")
.copy_from_slice(auth_request_output);
}
ssize_t::ffi_try_from(auth_request_output.len())
.expect("auth_request_output.len could not be converted to ssize_t")
})
}
/// # Preconditions
///
/// * `attest_ake` - must be in the auth pending state.
///
/// # Errors
///
/// * `LibMcError::AttestationVerificationFailed`
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_attest_ake_process_auth_response(
attest_ake: FfiMutPtr<McAttestAke>,
auth_response_data: FfiRefPtr<McBuffer>,
verifier: FfiRefPtr<McVerifier>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let attest_ake = attest_ake.into_mut();
let auth_pending = attest_ake
.take_auth_pending()
.expect("attest_ake is not in the auth pending state");
let auth_response_output = AuthResponseOutput::from(auth_response_data.to_vec());
let auth_response_input = AuthResponseInput::new(auth_response_output, (*verifier).clone());
let mut rng = McRng::default(); // This is actually unused.
let (ready, _) = auth_pending.try_next(&mut rng, auth_response_input)?;
*attest_ake = AttestAke::Attested(ready);
Ok(())
})
}
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_ciphertext` - must be null or else length must be >=
/// `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::Cipher`
#[no_mangle]
pub extern "C" fn mc_attest_ake_encrypt(
attest_ake: FfiMutPtr<McAttestAke>,
aad: FfiRefPtr<McBuffer>,
plaintext: FfiRefPtr<McBuffer>,
out_ciphertext: FfiOptMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
let ciphertext_len = Aes256Gcm::ciphertext_len(plaintext.len());
if let Some(out_ciphertext) = out_ciphertext.into_option() {
let attest_cipher = attest_ake
.into_mut()
.attest_cipher_mut()
.expect("attest_ake is not in the attested state");
let ciphertext = attest_cipher.encrypt(aad.as_slice(), plaintext.as_slice())?;
out_ciphertext
.into_mut()
.as_slice_mut_of_len(ciphertext_len)
.expect("out_auth_request length is insufficient")
.copy_from_slice(&ciphertext);
}
Ok(ssize_t::ffi_try_from(ciphertext_len)
.expect("ciphertext.len could not be converted to ssize_t"))
})
}
/// # Preconditions
///
/// * `attest_ake` - must be in the attested state.
/// * `out_plaintext` - length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::Cipher`
#[no_mangle]
pub extern "C" fn mc_attest_ake_decrypt(
attest_ake: FfiMutPtr<McAttestAke>,
aad: FfiRefPtr<McBuffer>,
ciphertext: FfiRefPtr<McBuffer>,
out_plaintext: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
let attest_cipher = attest_ake
.into_mut()
.attest_cipher_mut()
.expect("attest_ake is not in the attested state");
let plaintext = attest_cipher.decrypt(aad.as_slice(), ciphertext.as_slice())?;
out_plaintext
.into_mut()
.as_slice_mut_of_len(plaintext.len())
.expect("out_plaintext length is insufficient")
.copy_from_slice(&plaintext);
Ok(ssize_t::ffi_try_from(plaintext.len())
.expect("plaintext.len could not be converted to ssize_t"))
})
}
impl<'a> TryFromFfi<&McBuffer<'a>> for MrEnclave {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = <[u8; 32]>::try_from_ffi(src)?;
Ok(MrEnclave::from(src))
}
}
impl<'a> TryFromFfi<&McBuffer<'a>> for MrSigner {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = <[u8; 32]>::try_from_ffi(src)?;
Ok(MrSigner::from(src))
}
}
impl<'a> TryFromFfi<FfiStr<'a>> for ResponderId {
type Error = LibMcError;
fn try_from_ffi(src: FfiStr<'a>) -> Result<Self, LibMcError> {
let str = <&str>::try_from_ffi(src)?;
ResponderId::from_str(str)
.map_err(|err| LibMcError::InvalidInput(format!("Invalid responder id: {:?}", err)))
}
}

View File

@ -1,67 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use bip39::{Language, Mnemonic};
use libc::ssize_t;
use mc_util_ffi::*;
/// # Preconditions
///
/// * `entropy` - length must be a multiple of 4 and between 16 and 32,
/// inclusive, in bytes.
#[no_mangle]
pub extern "C" fn mc_bip39_mnemonic_from_entropy(entropy: FfiRefPtr<McBuffer>) -> FfiOptOwnedStr {
ffi_boundary(|| {
let mnemonic = Mnemonic::from_entropy(&entropy, Language::English)
.expect("entropy could not be converted to a mnemonic");
FfiOwnedStr::ffi_try_from(mnemonic.to_string())
.expect("mnemonic could not be converted to a C string")
})
}
/// # Preconditions
///
/// * `mnemonic` - must be a nul-terminated C string containing valid UTF-8.
/// * `out_entropy` - must be null or else length must be >= `entropy.len`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_bip39_entropy_from_mnemonic(
mnemonic: FfiStr,
out_entropy: FfiOptMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
let mnemonic = <&str>::try_from_ffi(mnemonic).expect("mnemonic is invalid");
let mnemonic = Mnemonic::from_phrase(mnemonic, Language::English)
.map_err(|err| LibMcError::InvalidInput(format!("Invalid mnemonic: {}", err)))?;
let entropy = mnemonic.entropy();
if let Some(out_entropy) = out_entropy.into_option() {
let out_entropy = out_entropy
.into_mut()
.as_slice_mut_of_len(entropy.len())
.expect("out_entropy length is insufficient");
out_entropy.copy_from_slice(entropy);
}
Ok(ssize_t::ffi_try_from(entropy.len())
.expect("entropy.len() could not be converted to ssize_t"))
})
}
/// # Preconditions
///
/// * `prefix` - must be a nul-terminated C string containing valid UTF-8.
#[no_mangle]
pub extern "C" fn mc_bip39_words_by_prefix(prefix: FfiStr) -> FfiOptOwnedStr {
ffi_boundary(|| {
let prefix = <&str>::try_from_ffi(prefix).expect("prefix is invalid");
let words = Language::English.wordlist().get_words_by_prefix(prefix);
let joined_words = words.join(",");
FfiOwnedStr::ffi_try_from(joined_words)
.expect("joined_words could not be converted to a C string")
})
}

View File

@ -1,145 +0,0 @@
use crate::{
common::{ffi_boundary, ffi_boundary_with_error, McBuffer, McError, McMutableBuffer},
LibMcError,
};
use mc_util_ffi::{FfiMutPtr, FfiOptMutPtr, FfiOptOwnedPtr, FfiRefPtr};
use rand_chacha::ChaCha20Rng;
use rand_core::{RngCore, SeedableRng};
use std::{convert::TryInto, sync::Mutex};
pub type McChaCha20Rng = ChaCha20Rng;
impl_into_ffi!(Mutex<McChaCha20Rng>);
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the u64 long_val parameter
///
/// # Arguments
///
/// * `long_val` - an unsigned 64 bit value to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::Poison`
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_create_with_long(
long_val: u64,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<Mutex<McChaCha20Rng>> {
ffi_boundary_with_error(out_error, || {
Ok(Mutex::new(McChaCha20Rng::seed_from_u64(long_val)))
})
}
/// Returns a new ChaCha20Rng instance initialized with the
/// seed value provided by the bytes data, which must be at
/// least 32 bytes (only the first 32 bytes will be used)
///
/// # Arguments
///
/// * `bytes` - 32 bytes of data to use as the rng seed
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
/// * `LibMcError::Poison`
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_create_with_bytes(
bytes: FfiRefPtr<McBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<Mutex<McChaCha20Rng>> {
ffi_boundary_with_error(out_error, || {
let bytes: [u8; 32] = bytes.as_slice_of_len(32)?.try_into().map_err(|_| {
LibMcError::InvalidInput("seed bytes length must be exactly 32 bytes".to_owned())
})?;
Ok(Mutex::new(McChaCha20Rng::from_seed(bytes)))
})
}
/// Returns the current word_pos of the ChaCha20Rng instance
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 16 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_get_word_pos(
chacha20_rng: FfiMutPtr<Mutex<McChaCha20Rng>>,
out_word_pos: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let word_pos = chacha20_rng.lock()?.get_word_pos();
let out_word_pos = out_word_pos.into_mut().as_slice_mut_of_len(16)?;
out_word_pos.copy_from_slice(&word_pos.to_be_bytes());
Ok(())
})
}
/// Sets the current word_pos of the ChaCha20Rng instance
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
/// * `out_word_pos` - pointer to buffer of 128 bytes where the current
/// chacha20_rng wordpos will be returned
///
/// # Errors
///
/// * `LibMcError::Poison`
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_set_word_pos(
chacha20_rng: FfiMutPtr<Mutex<McChaCha20Rng>>,
bytes: FfiRefPtr<McBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let bytes: [u8; 16] = bytes.as_slice_of_len(16)?.try_into().map_err(|_| {
LibMcError::InvalidInput(
"bytes length must be exactly 16 bytes for word_pos".to_owned(),
)
})?;
chacha20_rng
.lock()?
.set_word_pos(u128::from_be_bytes(bytes));
Ok(())
})
}
/// Returns the next random u64 value from the ChaCha20Rng
///
/// /// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
///
/// # Errors
///
/// * `LibMcError::Poison`
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_next_long(
chacha20_rng: FfiMutPtr<Mutex<McChaCha20Rng>>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> u64 {
ffi_boundary_with_error(out_error, || Ok(chacha20_rng.lock()?.next_u64()))
}
/// frees the ChaCha20Rng
///
/// # Preconditions
///
/// * The ChaCha20Rng is no longer in use
///
/// # Arguments
///
/// * `chacha20_rng` - must be a valid ChaCha20Rng
#[no_mangle]
pub extern "C" fn mc_chacha20_rng_free(chacha20_rng: FfiOptOwnedPtr<Mutex<McChaCha20Rng>>) {
ffi_boundary(|| {
let _ = chacha20_rng;
})
}

View File

@ -1,124 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::{IntoFfi, McError};
use crate::LibMcError;
use mc_util_ffi::{FfiOptMutPtr, FfiOptOwnedPtr, FfiOwnedPtr};
use std::{
panic::{catch_unwind, AssertUnwindSafe},
process::abort,
};
/// This function should be used as the outer-most "layer" protecting Rust code
/// from unwinding across the FFI boundary in the event of a panic. All Rust
/// code in FFI functions (e.g. `extern "C"` functions) should be executed
/// within the closure passed as parameter `f`. This function ensures FFI safety
/// by catching unwind panics, logging the panic, and returning the
/// sentinel error value returned by a call to `R::error_value()`.
pub(crate) fn ffi_boundary<R, I>(f: impl (FnOnce() -> R)) -> I
where
R: IntoFfi<I>,
{
ffi_boundary_impl(|| {
let result = f().into_ffi();
Ok(result)
})
.unwrap_or_else(|err| {
log_error(err);
R::error_value()
})
}
/// This function should be used as the outer-most "layer" protecting Rust code
/// from unwinding across the FFI boundary in the event of a panic. All Rust
/// code in FFI functions (e.g. `extern "C"` functions) should be executed
/// within the closure passed as parameter `f`. This function ensures FFI safety
/// by catching unwind panics, saving the panic as a `LibMcError` to the
/// `out_error` (if `out_error` is non-null), and returning the sentinel error
/// value returned by a call to `R::error_value()`.
pub(crate) fn ffi_boundary_with_error<R, I>(
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
f: impl (FnOnce() -> Result<R, LibMcError>),
) -> I
where
R: IntoFfi<I>,
{
ffi_boundary_impl(|| {
let result = f()?.into_ffi();
Ok(result)
})
.unwrap_or_else(|err| {
set_error_or_log(err, out_error);
R::error_value()
})
}
fn ffi_boundary_impl<R>(f: impl (FnOnce() -> Result<R, LibMcError>)) -> Result<R, LibMcError> {
// Run f within catch_unwind
//
// Note: this is using AssertUnwindSafe because some of the TransactionBuilder
// types are abstracted behind Box<dyn ... + Send + Sync>, but rust does not
// allow such types to be UnwindSafe because they may exhibit interior
// mutability. OTOH if we do not put + Send + Sync, then it is illegal to
// put TransactionBuilder behind a Mutex, which prevents the android
// bindings from building.
//
// The reason we use Box<dyn + ...> at all is to avoid making everything
// a generic parameter of transaction builder, which multiplies the number of
// types that might have to have cross-language bindings.
//
// UnwindSafe is too restrictive -- the goal of UnwindSafe is that if a panic is
// caught, we cannot "easily" observe a broken invariant. However, the only
// thing we actually need at an ffi boundary is to prevent unwinding across
// stackframes into swift etc.
catch_unwind(AssertUnwindSafe(f))
// Return a `LibMcError` if we panic. However, we still need to be mindful of panics while
// formatting the panic error so that we don't accidentally unwind across the FFI boundary.
.unwrap_or_else(|panic_error| {
// We assert `panic_error` is unwind safe because, since we won't be modifying
// it, we know that no harm will come if we panic while trying to
// process it.
let panic_error = AssertUnwindSafe(panic_error);
catch_unwind(|| Err(LibMcError::Panic(format!("{:?}", *panic_error))))
// If this also panics then we just abort because at this point it's likely
// something terrible has gone wrong and the situation is no longer tenable.
.unwrap_or_else(|_| abort())
})
}
fn set_error_or_log(err: LibMcError, out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>) {
error_handling_ffi_boundary(|| {
if let Some(error) = out_error.into_mut() {
*error = FfiOwnedPtr::new(McError::from(err)).into();
} else {
eprintln!("LibMobileCoin Error: {}", err);
}
});
}
fn log_error(err: LibMcError) {
error_handling_ffi_boundary(|| eprintln!("LibMobileCoin Error: {}", err))
}
fn error_handling_ffi_boundary(f: impl FnOnce()) {
let _ = ffi_boundary_impl(|| {
f();
Ok(())
})
// If we fail while handling the original error, it necessarily must have been from a panic
// while doing so (and possibly we panicked while trying to format the panic).
// Let's try to just print out the panic. If we panic while doing that, not much can be done
// except fail silently and move on (we could also abort, but we're trying to avoid doing that).
.map_err(|panic_error| {
let panic_error = AssertUnwindSafe(panic_error);
// guard against panics while printing
let _ = catch_unwind(|| {
let panic_error = panic_error.0;
// In theory, we should still have the original err at this point, but move
// semantics make it difficult to hold onto if we panicked.
eprintln!(
"LibMobileCoin panicked during error handling: {}",
panic_error
);
});
});
}

View File

@ -1,207 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::{FfiTryFrom, TryFromFfi};
use crate::LibMcError;
use core::{convert::TryFrom, marker, ops, slice};
use libc::{size_t, ssize_t};
use mc_util_ffi::{FfiMutPtr, FfiRefPtr};
/// This type is meant to be used as a parameter (or field of an another
/// parameter, etc) to C-FFI functions to code written in Rust. Objects of this
/// type are typically allocated on the foreign side of the FFI boundary and are
/// passed in to Rust via an `extern fn`-style function.
///
/// The purpose of this type is to encapsulate unsafety within a type, such that
/// if this type were to be created solely in safe Rust, that it would contain
/// no unsafety. This is to say that, while this type performs unsafe operations
/// internally, in order for those unsafe operations to actually cause unsafety,
/// this type must have been created or otherwise manipulated from unsafe
/// code (typically either unsafe Rust or unsafe-by-definition foreign code).
/// Therefore, care must be taken when using this type from unsafe code (and
/// indeed it is intended to be used from unsafe code), but the same care does
/// not need to be taken in order to otherwise use it from safe code,
/// with the assumption that no preconditions were violated from unsafe code.
#[repr(C)]
pub struct McBuffer<'a> {
buffer: FfiRefPtr<'a, u8>,
len: size_t,
_phantom: marker::PhantomData<&'a [u8]>,
}
impl<'a> McBuffer<'a> {
#[inline]
pub fn len(&self) -> size_t {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn as_slice(&self) -> &'a [u8] {
if self.len == 0 {
&[]
} else {
unsafe { slice::from_raw_parts(self.buffer.as_raw(), self.len) }
}
}
pub fn as_slice_of_len(&self, len: usize) -> Result<&'a [u8], LibMcError> {
if self.len < len {
return Err(LibMcError::InvalidInput(format!(
"buffer.len() ({}) must be >= {}",
self.len(),
len
)));
}
Ok(&self.as_slice()[..len])
}
#[inline]
pub fn to_vec(&self) -> Vec<u8> {
self.as_slice().to_vec()
}
}
impl<'a> ops::Deref for McBuffer<'a> {
type Target = [u8];
#[inline]
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl AsRef<[u8]> for McBuffer<'_> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
#[repr(C)]
pub struct McMutableBuffer<'a> {
buffer: FfiMutPtr<'a, u8>,
len: size_t,
_phantom: marker::PhantomData<&'a [u8]>,
}
impl<'a> McMutableBuffer<'a> {
#[inline]
pub fn len(&self) -> size_t {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn as_slice(&self) -> &'a [u8] {
if self.len == 0 {
&[]
} else {
unsafe { slice::from_raw_parts(self.buffer.as_raw(), self.len) }
}
}
#[inline]
pub fn as_slice_mut(&mut self) -> &'a mut [u8] {
if self.len == 0 {
&mut []
} else {
unsafe { slice::from_raw_parts_mut(self.buffer.as_raw(), self.len) }
}
}
pub fn as_slice_of_len(&self, len: usize) -> Result<&'a [u8], LibMcError> {
if self.len < len {
return Err(LibMcError::InvalidInput(format!(
"buffer.len() ({}) must be >= {}",
self.len(),
len
)));
}
Ok(&self.as_slice()[..len])
}
pub fn as_slice_mut_of_len(&mut self, len: usize) -> Result<&'a mut [u8], LibMcError> {
if self.len < len {
return Err(LibMcError::InvalidInput(format!(
"buffer.len() ({}) must be >= {}",
self.len(),
len
)));
}
Ok(&mut self.as_slice_mut()[..len])
}
#[inline]
pub fn to_vec(&self) -> Vec<u8> {
self.as_slice().to_vec()
}
}
impl<'a> ops::Deref for McMutableBuffer<'a> {
type Target = [u8];
#[inline]
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<'a> ops::DerefMut for McMutableBuffer<'a> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_slice_mut()
}
}
impl AsRef<[u8]> for McMutableBuffer<'_> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl AsMut<[u8]> for McMutableBuffer<'_> {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.as_slice_mut()
}
}
impl<'a, const N: usize> TryFromFfi<&McBuffer<'a>> for &'a [u8; N] {
type Error = LibMcError;
#[inline]
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = src.as_slice_of_len(N)?;
// SAFETY: ok to unwrap because we just checked length
Ok(<&[u8; N]>::try_from(src).unwrap())
}
}
impl<'a, const N: usize> TryFromFfi<&McBuffer<'a>> for [u8; N] {
type Error = LibMcError;
#[inline]
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
Ok(*<&'a [u8; N]>::try_from_ffi(src)?)
}
}
impl<'a> FfiTryFrom<size_t> for ssize_t {
type Error = LibMcError;
fn ffi_try_from(src: size_t) -> Result<Self, LibMcError> {
ssize_t::try_from(src).map_err(|err| {
LibMcError::InvalidOutput(format!("Overflow converting to ssize_t: {:?}", err))
})
}
}

View File

@ -1,35 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::*;
use libc::ssize_t;
use mc_util_ffi::{FfiOptMutPtr, FfiOptOwnedPtr, FfiRefPtr};
pub type McData = Vec<u8>;
impl_into_ffi!(Vec<u8>);
#[no_mangle]
pub extern "C" fn mc_data_free(data: FfiOptOwnedPtr<McData>) {
ffi_boundary(|| {
let _ = data;
})
}
/// # Preconditions
///
/// * `out_bytes` - must be null or else length must be >= `data.len`.
#[no_mangle]
pub extern "C" fn mc_data_get_bytes(
data: FfiRefPtr<McData>,
out_bytes: FfiOptMutPtr<McMutableBuffer>,
) -> ssize_t {
ffi_boundary(|| {
if let Some(out_bytes) = out_bytes.into_option() {
out_bytes
.into_mut()
.as_slice_mut_of_len(data.len())
.expect("out_bytes length is insufficient")
.copy_from_slice(&data);
}
ssize_t::ffi_try_from(data.len()).expect("data.len could not be converted to ssize_t")
})
}

View File

@ -1,37 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::ffi_boundary;
use mc_util_ffi::{FfiOptOwnedPtr, FfiOwnedStr};
use std::{ffi::CString, os::raw::c_int};
#[repr(C)]
pub struct McError {
error_code: c_int,
error_description: FfiOwnedStr,
}
impl McError {
pub fn new(error_code: c_int, error_description: String) -> Self {
let description = CString::new(error_description)
// This panic indicates a violation of a precondition to this function and would be
// considered a bug in the library.
.expect("String cannot contain nul bytes.");
Self {
error_code,
error_description: description.into(),
}
}
}
/// All non-null owned pointers of type `McError *` that are returned from a
/// Rust FFI function to a foreign caller must call this function in order to
/// free the underlying memory pointed to by the pointer.
///
/// It is undefined behavior for foreign code to dereference the pointer after
/// it has called this method.
#[no_mangle]
pub extern "C" fn mc_error_free(error: FfiOptOwnedPtr<McError>) {
ffi_boundary(move || {
let _ = error;
})
}

View File

@ -1,220 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use libc::ssize_t;
use mc_util_ffi::{FfiOptOwnedStr, FfiOptRefPtr, FfiOptStr, FfiOwnedStr, FfiStr};
/// This trait facilitates converting one type into another when returning a
/// value from an FFI function. This could be either a return value or an out
/// parameter.
///
/// In the event of an `Result`-style error or a caught panic, the value
/// returned from a call to `error_value()` will be used. This value is often a
/// sentinel value that foreign code can use to differentiate between a
/// successful return and a failure, such as `null` in the case of a pointer, or
/// `-1` in the case of an `int`.
///
/// This provides the most benefit when the error value does not also represent
/// a valid success value, but that in itself is not a requirement, as long as
/// there is another way to detect that an error has occurred (such as an error
/// out-parameter that's only set to a non-null value if an error has occurred).
pub(crate) trait IntoFfi<T>: Sized {
fn error_value() -> T;
fn into_ffi(self) -> T;
}
impl<T: IntoFfi<I>, I> IntoFfi<I> for Option<T> {
#[inline]
fn error_value() -> I {
T::error_value()
}
#[inline]
fn into_ffi(self) -> I {
if let Some(s) = self {
s.into_ffi()
} else {
T::error_value()
}
}
}
macro_rules! impl_into_ffi_using_default {
($($Type:ty),+) => {
$(
impl IntoFfi<$Type> for $Type {
#[inline]
fn error_value() -> Self {
Default::default()
}
#[inline]
fn into_ffi(self) -> Self {
self
}
}
)+
}
}
impl_into_ffi_using_default![(), bool];
impl IntoFfi<bool> for () {
#[inline]
fn error_value() -> bool {
false
}
#[inline]
fn into_ffi(self) -> bool {
true
}
}
impl_into_ffi_using_default![u64];
impl IntoFfi<i64> for i64 {
#[inline]
fn error_value() -> i64 {
-1
}
#[inline]
fn into_ffi(self) -> i64 {
self
}
}
impl IntoFfi<ssize_t> for ssize_t {
#[inline]
fn error_value() -> ssize_t {
-1
}
#[inline]
fn into_ffi(self) -> ssize_t {
self
}
}
impl IntoFfi<FfiOptOwnedStr> for FfiOwnedStr {
#[inline]
fn error_value() -> FfiOptOwnedStr {
FfiOptOwnedStr::null()
}
#[inline]
fn into_ffi(self) -> FfiOptOwnedStr {
self.into()
}
}
impl IntoFfi<FfiOptOwnedStr> for FfiOptOwnedStr {
#[inline]
fn error_value() -> FfiOptOwnedStr {
FfiOptOwnedStr::null()
}
#[inline]
fn into_ffi(self) -> FfiOptOwnedStr {
self
}
}
pub(crate) trait FromFfi<T>: Sized {
fn from_ffi(src: T) -> Self;
}
pub(crate) trait FfiInto<U>: Sized {
fn ffi_into(self) -> U;
}
impl<T, U> FfiInto<U> for T
where
U: FromFfi<T>,
{
#[inline]
fn ffi_into(self) -> U {
<U as FromFfi<T>>::from_ffi(self)
}
}
pub(crate) trait TryFromFfi<T>: Sized {
type Error: Sized;
fn try_from_ffi(src: T) -> Result<Self, Self::Error>;
}
pub(crate) trait FfiTryInto<U>: Sized {
type Error: Sized;
fn ffi_try_into(self) -> Result<U, Self::Error>;
}
impl<T, U> FfiTryInto<U> for T
where
U: TryFromFfi<T>,
{
type Error = U::Error;
#[inline]
fn ffi_try_into(self) -> Result<U, Self::Error> {
<U as TryFromFfi<T>>::try_from_ffi(self)
}
}
impl<T, U> TryFromFfi<Option<T>> for Option<U>
where
U: TryFromFfi<T>,
{
type Error = U::Error;
#[inline]
fn try_from_ffi(src: Option<T>) -> Result<Self, Self::Error> {
src.map(U::try_from_ffi).transpose()
}
}
impl<'a, U> TryFromFfi<FfiOptStr<'a>> for Option<U>
where
U: TryFromFfi<FfiStr<'a>>,
{
type Error = <U as TryFromFfi<FfiStr<'a>>>::Error;
#[inline]
fn try_from_ffi(src: FfiOptStr<'a>) -> Result<Self, Self::Error> {
src.as_option().map(U::try_from_ffi).transpose()
}
}
impl<'a, T, U> TryFromFfi<FfiOptRefPtr<'a, T>> for Option<U>
where
U: TryFromFfi<&'a T>,
{
type Error = <U as TryFromFfi<&'a T>>::Error;
#[inline]
fn try_from_ffi(src: FfiOptRefPtr<'a, T>) -> Result<Self, Self::Error> {
src.as_ref().map(U::try_from_ffi).transpose()
}
}
pub(crate) trait TryIntoFfi<T>: Sized {
type Error: Sized;
fn try_into_ffi(self) -> Result<T, Self::Error>;
}
pub(crate) trait FfiTryFrom<U>: Sized {
type Error: Sized;
fn ffi_try_from(src: U) -> Result<Self, Self::Error>;
}
impl<T, U> TryIntoFfi<U> for T
where
U: FfiTryFrom<T>,
{
type Error = U::Error;
#[inline]
fn try_into_ffi(self) -> Result<U, Self::Error> {
<U as FfiTryFrom<T>>::ffi_try_from(self)
}
}

View File

@ -1,23 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
#![macro_use]
#[macro_export]
macro_rules! impl_into_ffi {
($T:ty) => {
impl $crate::common::IntoFfi<::mc_util_ffi::FfiOptOwnedPtr<Self>> for $T
where
$T: Sync + Sized,
{
#[inline]
fn error_value() -> ::mc_util_ffi::FfiOptOwnedPtr<Self> {
::core::default::Default::default()
}
#[inline]
fn into_ffi(self) -> ::mc_util_ffi::FfiOptOwnedPtr<Self> {
::mc_util_ffi::FfiOwnedPtr::new(self).into()
}
}
};
}

View File

@ -1,59 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
//! This module contains a collection of general utilities useful in creating a
//! C-FFI API to code written in Rust.
//!
//! # Naming
//!
//! `McBuffer`, `McMutableBuffer`, and `McError` are types that are represented
//! as C structs and meant to be declared as such in the equivalent of a C
//! header. The fields of these types are guaranteed to be visible and
//! accessible from foreign code.
//!
//! # Memory Allocation
//!
//! As a rule, all memory (in particular, heap memory) should be deallocated by
//! the memory allocator that initially allocated the memory. Namely, whenever
//! an allocated "owned" object is allocated by Rust code and passed back to
//! foreign code, that foreign code takes ownership (takes over responsibility
//! for disposing of the object), with the caveat that the actual memory
//! deallocation needs be be performed by the original allocator. In practice,
//! this usually means that any time foreign code calls a Rust FFI function that
//! returns an owned object, the foreign code becomes responsible for later
//! calling the corresponding "free" function, usually taking the form of
//! `extern fn mc_<type_name>_free`.
//!
//! `McError` is a non-opaque type intended to be allocated within Rust but with
//! contents accessible to foreign code. `McError` is represented as a C-style
//! struct in non-Rust code.
//!
//! `McBuffer` and `McMutableBuffer` are intended to be allocated by foreign
//! code and passed to Rust. The lifetime of this object on the Rust side should
//! only be for the lifetime of the function. Rust code should not maintain a
//! reference to objects of this type or access the pointed-to memory after the
//! FFI function has ended.
#![macro_use]
pub(crate) mod macros;
mod boundary;
mod buffer;
mod data;
mod error;
mod into_ffi;
mod rng;
mod string;
pub use self::{
buffer::{McBuffer, McMutableBuffer},
data::{mc_data_free, mc_data_get_bytes, McData},
error::{mc_error_free, McError},
rng::{CallbackRng, FfiCallbackRng, McRngCallback, SdkRng},
string::mc_string_free,
};
pub(crate) use self::{
boundary::{ffi_boundary, ffi_boundary_with_error},
into_ffi::{FfiTryFrom, FfiTryInto, FromFfi, IntoFfi, TryFromFfi},
};

View File

@ -1,118 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::{FfiTryFrom, FromFfi};
use crate::LibMcError;
use core::{convert::TryFrom, ffi::c_void};
use mc_crypto_rand::McRng;
use mc_util_ffi::FfiOptMutPtr;
use rand_core::{CryptoRng, RngCore};
#[repr(C)]
pub struct McRngCallback<'a> {
pub rng: FfiCallbackRng,
pub context: FfiOptMutPtr<'a, c_void>,
}
impl<'a, 'b> FromFfi<FfiOptMutPtr<'a, McRngCallback<'b>>> for SdkRng<'a, 'b> {
#[inline]
fn from_ffi(src: FfiOptMutPtr<'a, McRngCallback<'b>>) -> Self {
if let Some(callback) = src.into_mut() {
SdkRng::CallbackRng(CallbackRng(callback.rng.0, &mut callback.context))
} else {
SdkRng::McRng(McRng::default())
}
}
}
impl<'a> FfiTryFrom<u64> for i64 {
type Error = LibMcError;
fn ffi_try_from(src: u64) -> Result<Self, LibMcError> {
i64::try_from(src).map_err(|err| {
LibMcError::InvalidOutput(format!("Overflow converting to i64: {:?}", err))
})
}
}
/// Transparent wrapper around a function pointer that accepts a context
/// argument and returns a `u64`, intended for use as a parameter to FFI
/// functions so that foreign code may provide a callback for generating random
/// numbers.
///
/// This type has the exact memory layout as the C equivalent `uint64_t
/// (*)(void*)` function pointer.
///
/// `null` is not considered a valid value.
#[repr(transparent)]
pub struct FfiCallbackRng(unsafe extern "C" fn(*mut c_void) -> u64);
pub struct CallbackRng<'a, 'b>(
unsafe extern "C" fn(*mut c_void) -> u64,
&'a mut FfiOptMutPtr<'b, c_void>,
);
impl<'a, 'b> RngCore for CallbackRng<'a, 'b> {
#[inline]
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
unsafe { (self.0)(self.1.as_raw()) }
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
rand_core::impls::fill_bytes_via_next(self, dest)
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl<'a, 'b> CryptoRng for CallbackRng<'a, 'b> {}
pub enum SdkRng<'a, 'b> {
CallbackRng(CallbackRng<'a, 'b>),
McRng(McRng),
}
impl<'a, 'b> RngCore for SdkRng<'a, 'b> {
#[inline]
fn next_u32(&mut self) -> u32 {
match self {
Self::CallbackRng(rng) => rng.next_u32(),
Self::McRng(rng) => rng.next_u32(),
}
}
#[inline]
fn next_u64(&mut self) -> u64 {
match self {
Self::CallbackRng(rng) => rng.next_u64(),
Self::McRng(rng) => rng.next_u64(),
}
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
match self {
Self::CallbackRng(rng) => rng.fill_bytes(dest),
Self::McRng(rng) => rng.fill_bytes(dest),
}
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
match self {
Self::CallbackRng(rng) => rng.try_fill_bytes(dest),
Self::McRng(rng) => rng.try_fill_bytes(dest),
}
}
}
impl<'a, 'b> CryptoRng for SdkRng<'a, 'b> {}

View File

@ -1,86 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use super::{ffi_boundary, FfiTryFrom, IntoFfi, TryFromFfi};
use crate::LibMcError;
use mc_util_ffi::{FfiOptOwnedStr, FfiOwnedStr, FfiStr};
use std::ffi::CString;
/// All non-null values with a `char *` return (or out parameter) type that are
/// returned to foreign code must call this function in order to free the
/// underlying memory pointed to by the pointer.
///
/// It is undefined behavior for foreign code to dereference the pointer after
/// it has called this method.
#[no_mangle]
pub extern "C" fn mc_string_free(string: FfiOptOwnedStr) {
ffi_boundary(move || {
let _ = string;
})
}
impl IntoFfi<FfiOptOwnedStr> for CString {
#[inline]
fn error_value() -> FfiOptOwnedStr {
FfiOptOwnedStr::null()
}
#[inline]
fn into_ffi(self) -> FfiOptOwnedStr {
FfiOwnedStr::from(self).into()
}
}
impl<'a> TryFromFfi<FfiStr<'a>> for &'a str {
type Error = LibMcError;
fn try_from_ffi(src: FfiStr<'a>) -> Result<Self, LibMcError> {
src.as_str()
.map_err(|err| LibMcError::InvalidInput(format!("Invalid UTF-8: {:?}", err)))
}
}
impl<'a> TryFromFfi<FfiStr<'a>> for String {
type Error = LibMcError;
fn try_from_ffi(src: FfiStr<'a>) -> Result<Self, LibMcError> {
let str = <&str>::try_from_ffi(src)?;
Ok(str.to_owned())
}
}
impl<'a> FfiTryFrom<&str> for FfiOwnedStr {
type Error = LibMcError;
#[inline]
fn ffi_try_from(src: &str) -> Result<Self, LibMcError> {
FfiOwnedStr::ffi_try_from(src.to_owned())
}
}
impl<'a> FfiTryFrom<String> for FfiOwnedStr {
type Error = LibMcError;
fn ffi_try_from(src: String) -> Result<Self, LibMcError> {
let c_string = CString::new(src)
.map_err(|err| LibMcError::InvalidOutput(format!("Unexpected Nul byte: {:?}", err)))?;
Ok(FfiOwnedStr::new(c_string))
}
}
impl<'a> FfiTryFrom<Option<&str>> for FfiOptOwnedStr {
type Error = LibMcError;
#[inline]
fn ffi_try_from(src: Option<&str>) -> Result<Self, LibMcError> {
FfiOptOwnedStr::ffi_try_from(src.map(ToOwned::to_owned))
}
}
impl<'a> FfiTryFrom<Option<String>> for FfiOptOwnedStr {
type Error = LibMcError;
#[inline]
fn ffi_try_from(src: Option<String>) -> Result<Self, LibMcError> {
Ok(src.map(FfiOwnedStr::ffi_try_from).transpose()?.into())
}
}

View File

@ -1,165 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use core::convert::TryFrom;
use libc::ssize_t;
use mc_crypto_box::{generic_array::typenum::Unsigned, CryptoBox, VersionedCryptoBox};
use mc_crypto_keys::{ReprBytes, Ristretto, RistrettoPrivate, RistrettoPublic};
use mc_crypto_sig::{Signature, SIGNATURE_LENGTH};
use mc_util_ffi::*;
use zeroize::Zeroize;
/* ==== Ristretto ==== */
impl<'a> TryFromFfi<&McBuffer<'a>> for RistrettoPublic {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = <&[u8; 32]>::try_from_ffi(src)?;
RistrettoPublic::try_from(src).map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))
}
}
impl<'a> TryFromFfi<&McBuffer<'a>> for RistrettoPrivate {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = <&[u8; 32]>::try_from_ffi(src)?;
RistrettoPrivate::try_from(src)
.map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))
}
}
#[no_mangle]
pub extern "C" fn mc_ristretto_private_validate(
ristretto_private: FfiRefPtr<McBuffer>,
out_valid: FfiMutPtr<bool>,
) -> bool {
ffi_boundary(|| {
*out_valid.into_mut() = RistrettoPrivate::try_from_ffi(&ristretto_private).is_ok();
})
}
/// # Preconditions
///
/// * `ristretto_private` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_ristretto_public` - length must be >= 32.
#[no_mangle]
pub extern "C" fn mc_ristretto_public_from_ristretto_private(
ristretto_private: FfiRefPtr<McBuffer>,
out_ristretto_public: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let ristretto_private = RistrettoPrivate::try_from_ffi(&ristretto_private)
.expect("ristretto_private is not a valid RistrettoPrivate");
let out_ristretto_public = out_ristretto_public
.into_mut()
.as_slice_mut_of_len(RistrettoPublic::size())
.expect("out_fog_public_key length is insufficient");
out_ristretto_public.copy_from_slice(ristretto_private.as_ref());
})
}
#[no_mangle]
pub extern "C" fn mc_ristretto_public_validate(
ristretto_public: FfiRefPtr<McBuffer>,
out_valid: FfiMutPtr<bool>,
) -> bool {
ffi_boundary(|| {
*out_valid.into_mut() = RistrettoPublic::try_from_ffi(&ristretto_public).is_ok();
})
}
/* ==== schnorrkel ==== */
impl<'a> TryFromFfi<&McBuffer<'a>> for Signature {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, LibMcError> {
let src = src.as_slice_of_len(SIGNATURE_LENGTH)?;
Signature::from_bytes(src).map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))
}
}
/* ==== VersionedCryptoBox ==== */
/// # Preconditions
///
/// * `public_key` - must be a valid 32-byte compressed Ristretto point.
/// * `out_ciphertext` - must be null or else length must be >=
/// `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
#[no_mangle]
pub extern "C" fn mc_versioned_crypto_box_encrypt(
public_key: FfiRefPtr<McBuffer>,
plaintext: FfiRefPtr<McBuffer>,
rng_callback: FfiOptMutPtr<McRngCallback>,
out_ciphertext: FfiOptMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
if let Some(out_ciphertext) = out_ciphertext.into_option() {
let public_key = RistrettoPublic::try_from_ffi(&public_key)
.expect("public_key is not a valid RistrettoPublic");
let mut rng = SdkRng::from_ffi(rng_callback);
let ciphertext =
VersionedCryptoBox::default().encrypt(&mut rng, &public_key, &plaintext)?;
out_ciphertext
.into_mut()
.as_slice_mut_of_len(ciphertext.len())
.expect("out_ciphertext length is insufficient")
.copy_from_slice(&ciphertext);
Ok(ssize_t::ffi_try_from(ciphertext.len())
.expect("ciphertext.len could not be converted to ssize_t"))
} else {
Ok(ssize_t::ffi_try_from(
plaintext.len() + <VersionedCryptoBox as CryptoBox<Ristretto>>::FooterSize::USIZE,
)
.expect("Estimated ciphertext length could not be converted to ssize_t"))
}
})
}
/// # Preconditions
///
/// * `private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_plaintext` - length must be >= `ciphertext.len`.
///
/// # Errors
///
/// * `LibMcError::Aead`
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
#[no_mangle]
pub extern "C" fn mc_versioned_crypto_box_decrypt(
private_key: FfiRefPtr<McBuffer>,
ciphertext: FfiRefPtr<McBuffer>,
out_plaintext: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
let private_key = RistrettoPrivate::try_from_ffi(&private_key)
.expect("private_key is not a valid RistrettoPrivate");
let (success, mut plaintext) =
VersionedCryptoBox::default().decrypt(&private_key, &ciphertext)?;
if !bool::from(success) {
plaintext.zeroize();
return Err(LibMcError::Aead("MAC failed".to_owned()));
}
out_plaintext
.into_mut()
.as_slice_mut_of_len(plaintext.len())
.expect("out_plaintext length is insufficient")
.copy_from_slice(&plaintext);
Ok(ssize_t::ffi_try_from(plaintext.len())
.expect("plaintext.len could not be converted to ssize_t"))
})
}

View File

@ -1,74 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use libc::ssize_t;
use mc_api::printable::PrintableWrapper;
use mc_util_ffi::*;
use protobuf::Message;
/* ==== PrintableWrapper ==== */
impl<'a> TryFromFfi<&McBuffer<'a>> for PrintableWrapper {
type Error = LibMcError;
fn try_from_ffi(src: &McBuffer<'a>) -> Result<Self, Self::Error> {
Self::parse_from_bytes(src).map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))
}
}
/// # Preconditions
///
/// * `printable_wrapper_proto_bytes` - must be a valid binary-serialized
/// `printable.PrintableWrapper` Protobuf.
#[no_mangle]
pub extern "C" fn mc_printable_wrapper_b58_encode(
printable_wrapper_proto_bytes: FfiRefPtr<McBuffer>,
) -> FfiOptOwnedStr {
ffi_boundary(|| {
let printable_wrapper = PrintableWrapper::try_from_ffi(&printable_wrapper_proto_bytes)
.expect("printable_wrapper_proto_bytes could not be converted to PrintableWrapper");
let encoded = printable_wrapper
.b58_encode()
.expect("printable_wrapper could not be encoded as base-58");
FfiOwnedStr::ffi_try_from(encoded)
.expect("Resulting encoded string could not be converted to a C string")
})
}
/// # Preconditions
///
/// * `b58_encoded_string` - must be a nul-terminated C string containing valid
/// UTF-8.
/// * `out_printable_wrapper_proto_bytes` - must be null or else length must be
/// >= `wrapper_bytes.len`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_printable_wrapper_b58_decode(
b58_encoded_string: FfiStr,
out_printable_wrapper_proto_bytes: FfiOptMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> ssize_t {
ffi_boundary_with_error(out_error, || {
let b58_encoded_string =
String::try_from_ffi(b58_encoded_string).expect("b58_encoded_string is invalid");
let printable_wrapper = PrintableWrapper::b58_decode(b58_encoded_string)?;
let wrapper_bytes = printable_wrapper.write_to_bytes()?;
if let Some(out_printable_wrapper_proto_bytes) =
out_printable_wrapper_proto_bytes.into_option()
{
out_printable_wrapper_proto_bytes
.into_mut()
.as_slice_mut_of_len(wrapper_bytes.len())
.expect("out_printable_wrapper_proto_bytes length is insufficient")
.copy_from_slice(&wrapper_bytes);
}
Ok(ssize_t::ffi_try_from(wrapper_bytes.len())
.expect("wrapper_bytes.len could not be converted to ssize_t"))
})
}

View File

@ -1,219 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::common::McError;
use displaydoc::Display;
use mc_api::display::Error as ApiDisplayError;
use mc_attest_ake::Error as AttestAkeError;
use mc_attest_verifier::Error as VerifierError;
use mc_crypto_box::{AeadError, Error as CryptoBoxError};
use mc_crypto_keys::KeyError;
use mc_crypto_noise::CipherError;
use mc_fog_kex_rng::Error as FogKexRngError;
use mc_fog_report_validation::FogPubkeyError;
use mc_transaction_core::{AmountError, BlockVersionError};
use mc_transaction_builder::TxBuilderError;
use mc_util_serial::DecodeError;
use protobuf::ProtobufError;
use std::{os::raw::c_int, sync::PoisonError};
impl From<LibMcError> for McError {
fn from(err: LibMcError) -> Self {
Self::new(err.error_code(), err.error_description())
}
}
#[derive(Debug, Display)]
pub enum LibMcError {
/// Unknown
Unknown,
/// Rust panicked: {0}
Panic(String),
/// Invalid input: {0}
InvalidInput(String),
/// Invalid output: {0}
InvalidOutput(String),
/// Attestation verification failed: {0}
AttestationVerificationFailed(String),
/// Authenticated encryption failure: {0}
Aead(String),
/// Cipher error: {0}
Cipher(String),
/// Unsupported CryptoBox version: {0}
UnsupportedCryptoBoxVersion(String),
/// Transaction cryptography error: {0}
TransactionCrypto(String),
/// Fog pubkey error: {0},
FogPubkey(String),
/// Poison
Poison,
}
impl<T> From<PoisonError<T>> for LibMcError {
fn from(_src: PoisonError<T>) -> Self {
Self::Poison
}
}
mod error_codes {
use super::*;
pub const LIB_MC_ERROR_CODE_UNKNOWN: c_int = -1;
pub const LIB_MC_ERROR_CODE_PANIC: c_int = -2;
pub const LIB_MC_ERROR_CODE_POISON: c_int = -3;
pub const LIB_MC_ERROR_CODE_INVALID_INPUT: c_int = 100;
pub const LIB_MC_ERROR_CODE_INVALID_OUTPUT: c_int = 101;
pub const LIB_MC_ERROR_CODE_ATTESTATION_VERIFICATION_FAILED: c_int = 200;
pub const LIB_MC_ERROR_CODE_AEAD: c_int = 300;
pub const LIB_MC_ERROR_CODE_CIPHER: c_int = 301;
pub const LIB_MC_ERROR_CODE_UNSUPPORTED_CRYPTO_BOX_VERSION: c_int = 302;
pub const LIB_MC_ERROR_CODE_TRANSACTION_CRYPTO: c_int = 400;
pub const LIB_MC_ERROR_CODE_FOG_PUBKEY: c_int = 500;
}
impl LibMcError {
fn error_code(&self) -> c_int {
use error_codes::*;
match self {
LibMcError::Unknown => LIB_MC_ERROR_CODE_UNKNOWN,
LibMcError::Panic(_) => LIB_MC_ERROR_CODE_PANIC,
LibMcError::InvalidInput(_) => LIB_MC_ERROR_CODE_INVALID_INPUT,
LibMcError::InvalidOutput(_) => LIB_MC_ERROR_CODE_INVALID_OUTPUT,
LibMcError::AttestationVerificationFailed(_) => {
LIB_MC_ERROR_CODE_ATTESTATION_VERIFICATION_FAILED
}
LibMcError::Aead(_) => LIB_MC_ERROR_CODE_AEAD,
LibMcError::Cipher(_) => LIB_MC_ERROR_CODE_CIPHER,
LibMcError::UnsupportedCryptoBoxVersion(_) => {
LIB_MC_ERROR_CODE_UNSUPPORTED_CRYPTO_BOX_VERSION
}
LibMcError::TransactionCrypto(_) => LIB_MC_ERROR_CODE_TRANSACTION_CRYPTO,
LibMcError::FogPubkey(_) => LIB_MC_ERROR_CODE_FOG_PUBKEY,
LibMcError::Poison => LIB_MC_ERROR_CODE_POISON,
}
}
fn error_description(&self) -> String {
format!("{}", self)
}
}
impl From<AeadError> for LibMcError {
fn from(err: AeadError) -> Self {
LibMcError::Aead(format!("{:?}", err))
}
}
impl From<AmountError> for LibMcError {
fn from(err: AmountError) -> Self {
LibMcError::TransactionCrypto(format!("{:?}", err))
}
}
impl From<KeyError> for LibMcError {
fn from(err: KeyError) -> Self {
LibMcError::TransactionCrypto(format!("{:?}", err))
}
}
impl From<ApiDisplayError> for LibMcError {
fn from(err: ApiDisplayError) -> Self {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
impl From<BlockVersionError> for LibMcError {
fn from(err: BlockVersionError) -> Self {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
impl From<AttestAkeError> for LibMcError {
fn from(err: AttestAkeError) -> Self {
if let AttestAkeError::ReportVerification(VerifierError::Verification(_)) = err {
LibMcError::AttestationVerificationFailed(format!("{:?}", err))
} else {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
}
impl From<CipherError> for LibMcError {
fn from(err: CipherError) -> Self {
if let CipherError::Aead = err {
LibMcError::Aead(format!("{:?}", err))
} else {
LibMcError::Cipher(format!("{:?}", err))
}
}
}
impl From<CryptoBoxError> for LibMcError {
fn from(err: CryptoBoxError) -> Self {
if let CryptoBoxError::WrongMagicBytes | CryptoBoxError::UnknownAlgorithm(_) = err {
LibMcError::UnsupportedCryptoBoxVersion(format!("{:?}", err))
} else {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
}
impl From<DecodeError> for LibMcError {
fn from(err: DecodeError) -> Self {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
impl From<FogKexRngError> for LibMcError {
fn from(err: FogKexRngError) -> Self {
if let FogKexRngError::UnknownVersion(_) = err {
LibMcError::UnsupportedCryptoBoxVersion(format!("{:?}", err))
} else {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
}
impl From<ProtobufError> for LibMcError {
fn from(err: ProtobufError) -> Self {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
impl From<TxBuilderError> for LibMcError {
fn from(err: TxBuilderError) -> Self {
if let TxBuilderError::FogPublicKey(FogPubkeyError::IngestReport(_)) = err
{
LibMcError::AttestationVerificationFailed(format!("{:?}", err))
} else {
LibMcError::InvalidInput(format!("{:?}", err))
}
}
}
impl From<FogPubkeyError> for LibMcError {
fn from(err: FogPubkeyError) -> Self {
match err {
FogPubkeyError::NoFogReportUrl
| FogPubkeyError::Url(_)
| FogPubkeyError::Deserialization(_) => LibMcError::InvalidInput(err.to_string()),
FogPubkeyError::IngestReport(_) => LibMcError::AttestationVerificationFailed(err.to_string()),
_ => LibMcError::FogPubkey(err.to_string()),
}
}
}

View File

@ -1,285 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{attest::McVerifier, common::*, keys::McPublicAddress, LibMcError};
use core::convert::TryFrom;
use libc::ssize_t;
use mc_account_keys::PublicAddress;
use mc_attest_verifier::Verifier;
use mc_crypto_keys::{ReprBytes, RistrettoPrivate, RistrettoPublic};
use mc_fog_kex_rng::{BufferedRng, KexRngPubkey, NewFromKex, StoredRng, VersionedKexRng};
use mc_fog_report_types::FogReportResponses;
use mc_fog_report_resolver::FogResolver;
use mc_fog_report_validation::{FullyValidatedFogPubkey, FogPubkeyResolver};
use mc_util_ffi::*;
use mc_util_serial::Message;
use mc_util_uri::FogUri;
use std::str::FromStr;
/* ==== McFogResolver ==== */
pub type McFogResolver = (FogReportResponses, Verifier);
impl_into_ffi!((FogReportResponses, Verifier));
#[no_mangle]
pub extern "C" fn mc_fog_resolver_create(
fog_report_verifier: FfiRefPtr<McVerifier>,
) -> FfiOptOwnedPtr<McFogResolver> {
ffi_boundary(|| {
(
FogReportResponses::default(),
(*fog_report_verifier).clone(),
)
})
}
#[no_mangle]
pub extern "C" fn mc_fog_resolver_free(fog_resolver: FfiOptOwnedPtr<McFogResolver>) {
ffi_boundary(|| {
let _ = fog_resolver;
})
}
#[no_mangle]
pub extern "C" fn mc_fog_resolver_get_fog_pubkey(
fog_resolver: FfiRefPtr<McFogResolver>,
recipient: FfiRefPtr<McPublicAddress>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McFullyValidatedFogPubkey> {
ffi_boundary_with_error(out_error, || {
let fog_resolver = FogResolver::new(fog_resolver.0.clone(), &fog_resolver.1.clone())
.map_err(|err| LibMcError::InvalidInput(err.to_string()))?;
let recipient = PublicAddress::try_from_ffi(&recipient)?;
let fully_validated_fog_pubkey = fog_resolver.get_fog_pubkey(&recipient)?;
Ok(fully_validated_fog_pubkey)
})
}
#[no_mangle]
pub extern "C" fn mc_fog_resolver_get_fog_pubkey_from_protobuf_public_address(
fog_resolver: FfiRefPtr<McFogResolver>,
recipient_protobuf: FfiRefPtr<McBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McFullyValidatedFogPubkey> {
ffi_boundary_with_error(out_error, || {
let fog_resolver = FogResolver::new(fog_resolver.0.clone(), &fog_resolver.1)
.map_err(|err| LibMcError::InvalidInput(err.to_string()))?;
let recipient = mc_util_serial::decode(recipient_protobuf.as_slice())?;
let fully_validated_fog_pubkey = fog_resolver.get_fog_pubkey(&recipient)?;
Ok(fully_validated_fog_pubkey)
})
}
/// # Preconditions
///
/// * `report_url` - must be a nul-terminated C string containing a valid Fog
/// report uri.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_fog_resolver_add_report_response(
fog_resolver: FfiMutPtr<McFogResolver>,
report_url: FfiStr,
report_response: FfiRefPtr<McBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let report_url =
<&str>::try_from_ffi(report_url).expect("report_url isn't a valid C string");
let report_url = FogUri::from_str(report_url)
.map_err(|err| LibMcError::InvalidInput(err.to_string()))?;
let report_url = report_url.to_string();
let report_response = mc_util_serial::decode(report_response.as_slice())?;
fog_resolver
.into_mut()
.0
.insert(report_url, report_response);
Ok(())
})
}
/* ==== McFullyValidatedFogPubkey ==== */
pub type McFullyValidatedFogPubkey = FullyValidatedFogPubkey;
impl_into_ffi!(FullyValidatedFogPubkey);
#[no_mangle]
pub extern "C" fn mc_fully_validated_fog_pubkey_free(
fully_validated_fog_pubkey: FfiOptOwnedPtr<McFullyValidatedFogPubkey>,
) {
ffi_boundary(|| {
let _ = fully_validated_fog_pubkey;
})
}
#[no_mangle]
pub extern "C" fn mc_fully_validated_fog_pubkey_get_pubkey(
fully_validated_fog_pubkey: FfiRefPtr<McFullyValidatedFogPubkey>,
out_pubkey: FfiMutPtr<McMutableBuffer>,
) {
ffi_boundary(|| {
let out_pubkey = out_pubkey
.into_mut()
.as_slice_mut_of_len(RistrettoPublic::size())
.expect("out_pubkey length is insufficient");
out_pubkey.copy_from_slice(&fully_validated_fog_pubkey.pubkey.to_bytes())
})
}
#[no_mangle]
pub extern "C" fn mc_fully_validated_fog_pubkey_get_pubkey_expiry(
fully_validated_fog_pubkey: FfiRefPtr<McFullyValidatedFogPubkey>,
) -> u64 {
ffi_boundary(|| fully_validated_fog_pubkey.pubkey_expiry)
}
/* ==== McFogRng ==== */
pub type McFogRng = VersionedKexRng;
impl_into_ffi!(VersionedKexRng);
/// # Preconditions
///
/// * `subaddress_view_private_key` - must be a valid 32-byte Ristretto-format
/// scalar.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
#[no_mangle]
pub extern "C" fn mc_fog_rng_create(
subaddress_view_private_key: FfiRefPtr<McBuffer>,
rng_public_key: FfiRefPtr<McBuffer>,
rng_version: u32,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McFogRng> {
ffi_boundary_with_error(out_error, || {
let subaddress_view_private_key =
RistrettoPrivate::try_from_ffi(&subaddress_view_private_key)
.expect("subaddress_view_private_key is not a valid RistrettoPrivate");
let pubkey = KexRngPubkey {
public_key: rng_public_key.to_vec(),
version: rng_version,
};
Ok(VersionedKexRng::try_from_kex_pubkey(
&pubkey,
&subaddress_view_private_key,
)?)
})
}
#[no_mangle]
pub extern "C" fn mc_fog_rng_free(fog_rng: FfiOptOwnedPtr<McFogRng>) {
ffi_boundary(|| {
let _ = fog_rng;
})
}
#[no_mangle]
pub extern "C" fn mc_fog_rng_clone(fog_rng: FfiRefPtr<McFogRng>) -> FfiOptOwnedPtr<McFogRng> {
ffi_boundary(|| (*fog_rng).clone())
}
/// # Preconditions
///
/// * `out_fog_rng_proto_bytes` - must be null or else length must be >=
/// `encoded.len`.
#[no_mangle]
pub extern "C" fn mc_fog_rng_serialize_proto(
fog_rng: FfiRefPtr<McFogRng>,
out_fog_rng_proto_bytes: FfiOptMutPtr<McMutableBuffer>,
) -> ssize_t {
ffi_boundary(|| {
let stored_fog_rng: StoredRng = (*fog_rng).clone().into();
let encoded_len = stored_fog_rng.encoded_len();
if let Some(out_fog_rng_proto_bytes) = out_fog_rng_proto_bytes.into_option() {
let out_fog_rng_proto_bytes = &mut out_fog_rng_proto_bytes
.into_mut()
.as_slice_mut_of_len(encoded_len)
.expect("out_fog_rng_proto_bytes length is insufficient");
stored_fog_rng
.encode(out_fog_rng_proto_bytes)
.expect("prost::encode with correctly-sized buffer is no fail");
}
ssize_t::ffi_try_from(encoded_len).expect("encoded.len could not be converted to ssize_t")
})
}
/// # Errors
///
/// * `LibMcError::InvalidInput`
/// * `LibMcError::UnsupportedCryptoBoxVersion`
#[no_mangle]
pub extern "C" fn mc_fog_rng_deserialize_proto(
fog_rng_proto_bytes: FfiRefPtr<McBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McFogRng> {
ffi_boundary_with_error(out_error, || {
let stored_fog_rng: StoredRng = mc_util_serial::decode(fog_rng_proto_bytes.as_slice())
.map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))?;
Ok(VersionedKexRng::try_from(stored_fog_rng)?)
})
}
#[no_mangle]
pub extern "C" fn mc_fog_rng_index(fog_rng: FfiRefPtr<McFogRng>) -> i64 {
ffi_boundary(|| {
i64::ffi_try_from(fog_rng.index()).expect("fog_rng.index could not be converted to i64")
})
}
#[no_mangle]
pub extern "C" fn mc_fog_rng_get_output_len(fog_rng: FfiRefPtr<McFogRng>) -> ssize_t {
ffi_boundary(|| {
ssize_t::ffi_try_from((*fog_rng).peek().len())
.expect("output.len could not be converted to ssize_t")
})
}
/// # Preconditions
///
/// * `out_output` - length must be >= `output.len`.
#[no_mangle]
pub extern "C" fn mc_fog_rng_peek(
fog_rng: FfiRefPtr<McFogRng>,
out_output: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let output = (*fog_rng).peek();
out_output
.into_mut()
.as_slice_mut_of_len(output.len())
.expect("out_output length is insufficient")
.copy_from_slice(output);
})
}
/// # Preconditions
///
/// * `out_output` - must be null or else length must be >= `output.len`.
#[no_mangle]
pub extern "C" fn mc_fog_rng_advance(
fog_rng: FfiMutPtr<McFogRng>,
out_output: FfiOptMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
if let Some(out_output) = out_output.into_option() {
let output = fog_rng.peek();
out_output
.into_mut()
.as_slice_mut_of_len(output.len())
.expect("out_output length is insufficient")
.copy_from_slice(output);
}
fog_rng.into_mut().advance();
})
}

View File

@ -1,254 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use mc_account_keys::{AccountKey, PublicAddress, RootIdentity, ShortAddressHash};
use mc_crypto_keys::{ReprBytes, RistrettoPrivate, RistrettoPublic};
use mc_util_ffi::*;
/* ==== Account Key ==== */
#[repr(C)]
pub struct McAccountKey<'a> {
/// 32-byte `RistrettoPrivate`
pub view_private_key: FfiRefPtr<'a, McBuffer<'a>>,
/// 32-byte `RistrettoPrivate`
pub spend_private_key: FfiRefPtr<'a, McBuffer<'a>>,
pub fog_info: FfiOptRefPtr<'a, McAccountKeyFogInfo<'a>>,
}
#[repr(C)]
pub struct McAccountKeyFogInfo<'a> {
pub report_url: FfiStr<'a>,
pub report_id: FfiStr<'a>,
pub authority_spki: FfiRefPtr<'a, McBuffer<'a>>,
}
impl<'a> TryFromFfi<&McAccountKey<'a>> for AccountKey {
type Error = LibMcError;
fn try_from_ffi(src: &McAccountKey<'a>) -> Result<Self, Self::Error> {
let view_private_key = RistrettoPrivate::try_from_ffi(&src.view_private_key)?;
let spend_private_key = RistrettoPrivate::try_from_ffi(&src.spend_private_key)?;
if let Some(fog_info) = src.fog_info.as_option() {
Ok(AccountKey::new_with_fog(
&spend_private_key,
&view_private_key,
<&str>::try_from_ffi(fog_info.report_url)?,
fog_info.report_id.ffi_try_into()?,
fog_info.authority_spki.as_slice(),
))
} else {
Ok(AccountKey::new(&spend_private_key, &view_private_key))
}
}
}
/// # Preconditions
///
/// * `root_entropy` - must be 32 bytes in length.
/// * `out_view_private_key` - length must be >= 32.
/// * `out_spend_private_key` - length must be >= 32.
#[no_mangle]
pub extern "C" fn mc_account_private_keys_from_root_entropy(
root_entropy: FfiRefPtr<McBuffer>,
out_view_private_key: FfiMutPtr<McMutableBuffer>,
out_spend_private_key: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let root_entropy = <&[u8; 32]>::try_from_ffi(&root_entropy)
.expect("root_entropy must be 32 bytes in length");
let out_view_private_key = out_view_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_view_private_key length is insufficient");
let out_spend_private_key = out_spend_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_spend_private_key length is insufficient");
let account_key = AccountKey::from(&RootIdentity::from(root_entropy));
out_view_private_key.copy_from_slice(account_key.view_private_key().as_ref());
out_spend_private_key.copy_from_slice(account_key.spend_private_key().as_ref());
})
}
/// # Preconditions
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_subaddress_view_private_key` - length must be >= 32.
/// * `out_subaddress_spend_private_key` - length must be >= 32.
#[no_mangle]
pub extern "C" fn mc_account_key_get_subaddress_private_keys(
view_private_key: FfiRefPtr<McBuffer>,
spend_private_key: FfiRefPtr<McBuffer>,
subaddress_index: u64,
out_subaddress_view_private_key: FfiMutPtr<McMutableBuffer>,
out_subaddress_spend_private_key: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let view_private_key = RistrettoPrivate::try_from_ffi(&view_private_key)
.expect("view_private_key is not a valid RistrettoPrivate");
let spend_private_key = RistrettoPrivate::try_from_ffi(&spend_private_key)
.expect("spend_private_key is not a valid RistrettoPrivate");
let account_key = AccountKey::new(&spend_private_key, &view_private_key);
let out_subaddress_view_private_key = out_subaddress_view_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_subaddress_view_private_key length is insufficient");
let out_subaddress_spend_private_key = out_subaddress_spend_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_subaddress_spend_private_key length is insufficient");
out_subaddress_view_private_key.copy_from_slice(
account_key
.subaddress_view_private(subaddress_index)
.as_ref(),
);
out_subaddress_spend_private_key.copy_from_slice(
account_key
.subaddress_spend_private(subaddress_index)
.as_ref(),
);
})
}
/// # Preconditions
///
/// * `view_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `spend_private_key` - must be a valid 32-byte Ristretto-format scalar.
/// * `out_subaddress_view_public_key` - length must be >= 32.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
#[no_mangle]
pub extern "C" fn mc_account_key_get_public_address_public_keys(
view_private_key: FfiRefPtr<McBuffer>,
spend_private_key: FfiRefPtr<McBuffer>,
subaddress_index: u64,
out_subaddress_view_public_key: FfiMutPtr<McMutableBuffer>,
out_subaddress_spend_public_key: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let view_private_key = RistrettoPrivate::try_from_ffi(&view_private_key)
.expect("view_private_key is not a valid RistrettoPrivate");
let spend_private_key = RistrettoPrivate::try_from_ffi(&spend_private_key)
.expect("spend_private_key is not a valid RistrettoPrivate");
let account_key = AccountKey::new(&spend_private_key, &view_private_key);
let out_subaddress_view_public_key = out_subaddress_view_public_key
.into_mut()
.as_slice_mut_of_len(RistrettoPublic::size())
.expect("out_subaddress_view_public_key length is insufficient");
let out_subaddress_spend_public_key = out_subaddress_spend_public_key
.into_mut()
.as_slice_mut_of_len(RistrettoPublic::size())
.expect("out_subaddress_spend_public_key length is insufficient");
let public_address = account_key.subaddress(subaddress_index);
out_subaddress_view_public_key
.copy_from_slice(&public_address.view_public_key().to_bytes());
out_subaddress_spend_public_key
.copy_from_slice(&public_address.spend_public_key().to_bytes());
})
}
/// # Preconditions
///
/// * `account_key` - must be a valid `AccountKey` with `fog_info`.
/// * `out_fog_authority_sig` - length must be >= 64.
#[no_mangle]
pub extern "C" fn mc_account_key_get_public_address_fog_authority_sig(
account_key: FfiRefPtr<McAccountKey>,
subaddress_index: u64,
out_fog_authority_sig: FfiMutPtr<McMutableBuffer>,
) -> bool {
ffi_boundary(|| {
let account_key = AccountKey::try_from_ffi(&account_key).expect("account_key is invalid");
let public_address = account_key.subaddress(subaddress_index);
let fog_authority_sig = public_address
.fog_authority_sig()
.expect("account_key does not contain fog info");
let out_fog_authority_sig = out_fog_authority_sig
.into_mut()
.as_slice_mut_of_len(fog_authority_sig.len())
.expect("out_fog_authority_sig length is insufficient");
out_fog_authority_sig.copy_from_slice(fog_authority_sig);
})
}
/* ==== TxOutMemoBuilder ==== */
/// # Preconditions
///
/// * `public_address` - must be a valid `PublicAddress`.
/// * `out_short_address_hash` - length must be >= 16 bytes
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_account_key_get_short_address_hash(
public_address: FfiRefPtr<McPublicAddress>,
out_short_address_hash: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let public_address = PublicAddress::try_from_ffi(&public_address)?;
let short_address_hash: ShortAddressHash = ShortAddressHash::from(&public_address);
let hash_data: [u8; 16] = short_address_hash.into();
let out_short_address_hash = out_short_address_hash
.into_mut()
.as_slice_mut_of_len(core::mem::size_of_val(&hash_data))
.expect("ShortAddressHash length is insufficient");
out_short_address_hash.copy_from_slice(&hash_data);
Ok(())
})
}
/* ==== PublicAddress ==== */
#[repr(C)]
pub struct McPublicAddress<'a> {
/// 32-byte `CompressedRistrettoPublic`
pub view_public_key: FfiRefPtr<'a, McBuffer<'a>>,
/// 32-byte `CompressedRistrettoPublic`
pub spend_public_key: FfiRefPtr<'a, McBuffer<'a>>,
pub fog_info: FfiOptRefPtr<'a, McPublicAddressFogInfo<'a>>,
}
#[repr(C)]
pub struct McPublicAddressFogInfo<'a> {
pub report_url: FfiStr<'a>,
pub report_id: FfiStr<'a>,
pub authority_sig: FfiRefPtr<'a, McBuffer<'a>>,
}
impl<'a> TryFromFfi<&McPublicAddress<'a>> for PublicAddress {
type Error = LibMcError;
fn try_from_ffi(src: &McPublicAddress<'a>) -> Result<Self, Self::Error> {
let view_public_key = RistrettoPublic::try_from_ffi(&src.view_public_key)?;
let spend_public_key = RistrettoPublic::try_from_ffi(&src.spend_public_key)?;
if let Some(fog_info) = src.fog_info.as_option() {
let fog_report_url = <&str>::try_from_ffi(fog_info.report_url)?;
let fog_report_id = <String>::try_from_ffi(fog_info.report_id)?;
let fog_authority_sig = fog_info.authority_sig.to_vec();
Ok(PublicAddress::new_with_fog(
&spend_public_key,
&view_public_key,
fog_report_url,
fog_report_id,
fog_authority_sig,
))
} else {
Ok(PublicAddress::new(&spend_public_key, &view_public_key))
}
}
}

View File

@ -1,19 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
// Must be listed first because of macro exporting
pub mod common;
pub mod attest;
pub mod bip39;
pub mod chacha20_rng;
pub mod crypto;
pub mod encodings;
pub mod fog;
pub mod keys;
pub mod signed_contingent_input;
pub mod slip10;
pub mod transaction;
mod error;
pub use error::*;

View File

@ -1,286 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
//
use crate::{
common::*,
fog::McFogResolver,
keys::{McAccountKey, McPublicAddress},
LibMcError,
};
use core::convert::TryFrom;
use mc_account_keys::{AccountKey, PublicAddress};
use mc_crypto_keys::{ReprBytes, RistrettoPrivate, RistrettoPublic};
use mc_crypto_ring_signature_signer::NoKeysRingSigner;
use mc_fog_report_resolver::FogResolver;
use mc_transaction_builder::{
InputCredentials, ReservedSubaddresses, SignedContingentInputBuilder,
};
use mc_transaction_core::{
onetime_keys::recover_onetime_private_key,
tx::TxOut,
Amount, BlockVersion, TokenId,
};
use mc_transaction_extra::{
SignedContingentInput, TxOutConfirmationNumber,
};
use crate::transaction::{
McTransactionBuilderRing, McTxOutMemoBuilder,
};
use mc_util_ffi::*;
/* ==== McSignedContingentInputBuilder ==== */
pub type McSignedContingentInputBuilder = Option<SignedContingentInputBuilder<FogResolver>>;
impl_into_ffi!(Option<SignedContingentInputBuilder<FogResolver>>);
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_builder_create(
block_version: u32,
tombstone_block: u64,
fog_resolver: FfiOptRefPtr<McFogResolver>,
memo_builder: FfiMutPtr<McTxOutMemoBuilder>,
view_private_key: FfiRefPtr<McBuffer>,
subaddress_spend_private_key: FfiRefPtr<McBuffer>,
real_index: usize,
ring: FfiRefPtr<McTransactionBuilderRing>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McSignedContingentInputBuilder> {
ffi_boundary_with_error(out_error, || {
let fog_resolver =
fog_resolver
.as_ref()
.map_or_else(FogResolver::default, |fog_resolver| {
// It is safe to add an expect here (which should never occur) because
// fogReportUrl is already checked in mc_fog_resolver_add_report_response
// to be convertible to FogUri
FogResolver::new(fog_resolver.0.clone(), &fog_resolver.1)
.expect("FogResolver could not be constructed from the provided materials")
});
let block_version = BlockVersion::try_from(block_version)?;
let memo_builder_box = memo_builder
.into_mut()
.take()
.expect("McTxOutMemoBuilder has already been used to build a Tx");
// All this to create the InputCredentials
let view_private_key = RistrettoPrivate::try_from_ffi(&view_private_key)
.expect("view_private_key is not a valid RistrettoPrivate");
let subaddress_spend_private_key =
RistrettoPrivate::try_from_ffi(&subaddress_spend_private_key)
.expect("subaddress_spend_private_key is not a valid RistrettoPrivate");
let membership_proofs = ring.iter().map(|element| element.1.clone()).collect();
let ring: Vec<TxOut> = ring.iter().map(|element| element.0.clone()).collect();
let input_tx_out = ring
.get(real_index)
.expect("real_index not in bounds of ring")
.clone();
let target_key = RistrettoPublic::try_from(&input_tx_out.target_key)
.expect("input_tx_out.target_key is not a valid RistrettoPublic");
let public_key = RistrettoPublic::try_from(&input_tx_out.public_key)
.expect("input_tx_out.public_key is not a valid RistrettoPublic");
let onetime_private_key = recover_onetime_private_key(
&public_key,
&view_private_key,
&subaddress_spend_private_key,
);
if RistrettoPublic::from(&onetime_private_key) != target_key {
panic!("TxOut at real_index isn't owned by account key");
}
let input_credentials = InputCredentials::new(
ring,
membership_proofs,
real_index,
onetime_private_key,
view_private_key, // `a`
)
.map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))?;
let mut signed_contingent_input_builder = SignedContingentInputBuilder::new_with_box(
block_version,
input_credentials,
fog_resolver,
memo_builder_box,
)
.expect("failure not expected");
signed_contingent_input_builder.set_tombstone_block(tombstone_block);
Ok(Some(signed_contingent_input_builder))
})
}
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_builder_free(
signed_contingent_input_builder: FfiOptOwnedPtr<McSignedContingentInputBuilder>,
) {
ffi_boundary(|| {
let _ = signed_contingent_input_builder;
})
}
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `recipient_address` - must be a valid `PublicAddress`.
/// * `out_subaddress_spend_public_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_builder_add_required_output(
signed_contingent_input_builder: FfiMutPtr<McSignedContingentInputBuilder>,
amount: u64,
token_id: u64,
recipient_address: FfiRefPtr<McPublicAddress>,
rng_callback: FfiOptMutPtr<McRngCallback>,
out_tx_out_confirmation_number: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McData> {
ffi_boundary_with_error(out_error, || {
let signed_contingent_input_builder = signed_contingent_input_builder
.into_mut()
.as_mut()
.expect("McSignedContingentInputBuilder instance has already been used to build");
let recipient_address =
PublicAddress::try_from_ffi(&recipient_address).expect("recipient_address is invalid");
let mut rng = SdkRng::from_ffi(rng_callback);
let out_tx_out_confirmation_number = out_tx_out_confirmation_number
.into_mut()
.as_slice_mut_of_len(TxOutConfirmationNumber::size())
.expect("out_tx_out_confirmation_number length is insufficient");
let amount = Amount {
value: amount,
token_id: TokenId::from(token_id),
};
let (tx_out, tx_out_confirmation_number) =
signed_contingent_input_builder.add_required_output(amount, &recipient_address, &mut rng)?;
out_tx_out_confirmation_number.copy_from_slice(tx_out_confirmation_number.as_ref());
Ok(mc_util_serial::encode(&tx_out))
})
}
/// # Preconditions
///
/// * `account_key` - must be a valid account key, default change address
/// computed from account key
/// * `transaction_builder` - must not have been previously consumed by a call
/// to `build`.
/// * `out_tx_out_confirmation_number` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_builder_add_required_change_output(
account_key: FfiRefPtr<McAccountKey>,
signed_contingent_input_builder: FfiMutPtr<McSignedContingentInputBuilder>,
amount: u64,
token_id: u64,
rng_callback: FfiOptMutPtr<McRngCallback>,
out_tx_out_confirmation_number: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McData> {
ffi_boundary_with_error(out_error, || {
let account_key_obj =
AccountKey::try_from_ffi(&account_key).expect("account_key is invalid");
let signed_contingent_input_builder = signed_contingent_input_builder
.into_mut()
.as_mut()
.expect("McSignedContingentInputBuilder instance has already been used to build");
let change_destination = ReservedSubaddresses::from(&account_key_obj);
let mut rng = SdkRng::from_ffi(rng_callback);
let out_tx_out_confirmation_number = out_tx_out_confirmation_number
.into_mut()
.as_slice_mut_of_len(TxOutConfirmationNumber::size())
.expect("out_tx_out_confirmation_number length is insufficient");
let amount = Amount {
value: amount,
token_id: TokenId::from(token_id),
};
let (tx_out, tx_out_confirmation_number) =
signed_contingent_input_builder.add_required_change_output(amount, &change_destination, &mut rng)?;
out_tx_out_confirmation_number.copy_from_slice(tx_out_confirmation_number.as_ref());
Ok(mc_util_serial::encode(&tx_out))
})
}
/// # Preconditions
///
/// * `signed_contingent_input_builder` - must not have been previously consumed by a call
/// to `build`.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_builder_build(
signed_contingent_input_builder: FfiMutPtr<McSignedContingentInputBuilder>,
rng_callback: FfiOptMutPtr<McRngCallback>,
ring: FfiRefPtr<McTransactionBuilderRing>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> FfiOptOwnedPtr<McData> {
ffi_boundary_with_error(out_error, || {
let signed_contingent_input_builder = signed_contingent_input_builder
.into_mut()
.take()
.expect("SignedContingentInputBuilder instance has already been used to build an SCI");
let mut rng = SdkRng::from_ffi(rng_callback);
let mut sci = signed_contingent_input_builder
.build(&NoKeysRingSigner {}, &mut rng)
.map_err(|err| LibMcError::InvalidInput(format!("{:?}", err)))?;
let membership_proofs = ring.iter().map(|element| element.1.clone()).collect();
sci.tx_in.proofs = membership_proofs;
Ok(mc_util_serial::encode(&sci))
})
}
/// # Preconditions
///
/// * `sci_data` - valid sci data
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_signed_contingent_input_data_is_valid(
sci_data: FfiRefPtr<McBuffer>,
out_valid: FfiMutPtr<bool>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let sci : SignedContingentInput = mc_util_serial::decode(&sci_data)
.expect("SignedContingentInput decoding from protobuf data failed");
*out_valid.into_mut() = sci.validate().is_ok();
Ok(())
})
}

View File

@ -1,47 +0,0 @@
// Copyright (c) 2018-2022 The MobileCoin Foundation
use crate::{common::*, LibMcError};
use bip39::{Language, Mnemonic};
use mc_account_keys::AccountKey;
use mc_core::slip10::Slip10KeyGenerator;
use mc_crypto_keys::{ReprBytes, RistrettoPrivate};
use mc_util_ffi::*;
/// # Preconditions
///
/// * `mnemonic` - must be a nul-terminated C string containing valid UTF-8.
/// * `out_view_private_key` - length must be >= 32.
/// * `out_spend_private_key` - length must be >= 32.
///
/// # Errors
///
/// * `LibMcError::InvalidInput`
#[no_mangle]
pub extern "C" fn mc_slip10_account_private_keys_from_mnemonic(
mnemonic: FfiStr,
account_index: u32,
out_view_private_key: FfiMutPtr<McMutableBuffer>,
out_spend_private_key: FfiMutPtr<McMutableBuffer>,
out_error: FfiOptMutPtr<FfiOptOwnedPtr<McError>>,
) -> bool {
ffi_boundary_with_error(out_error, || {
let mnemonic = <&str>::try_from_ffi(mnemonic).expect("mnemonic is invalid");
let mnemonic = Mnemonic::from_phrase(mnemonic, Language::English)
.map_err(|err| LibMcError::InvalidInput(format!("Invalid mnemonic: {}", err)))?;
let key = mnemonic.derive_slip10_key(account_index);
let account_key = AccountKey::from(key);
out_view_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_view_private_key length is insufficient")
.copy_from_slice(account_key.view_private_key().as_ref());
out_spend_private_key
.into_mut()
.as_slice_mut_of_len(RistrettoPrivate::size())
.expect("out_spend_private_key length is insufficient")
.copy_from_slice(account_key.spend_private_key().as_ref());
Ok(())
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +0,0 @@
# Parameters used to compile rust-bitcode toolchains
#
# Storing seperately so they can be checksummed
# and used as a cache key in circleci
#
export RUST_BITCODE_COMMIT="930417098692ef88060ad35ed5f94baf50b8953b"
export RUST_COMMIT="05c07386b45fbc540ec8cdc1bc41ae9c062b453b"
export RUST_COMMIT_NAME="nightly-2022-04-29"
export SWIFT_VERSION="5.5"

View File

@ -1,17 +0,0 @@
#!/bin/bash
CMAKE_DIR="$(perl -MCwd -e 'print Cwd::abs_path shift' $(which cmake) | rev | cut -d'/' -f3- | rev)"
echo -e "\n### Patching iOS-Initialize.cmake file in $CMAKE_DIR ###"
IOS_INITIALIZE_CMAKE_FILE="$CMAKE_DIR/share/cmake/Modules/Platform/iOS-Initialize.cmake"
sed -i '' '/FATAL_ERROR/ s/^#*/#/' $IOS_INITIALIZE_CMAKE_FILE
echo -e "### $IOS_INITIALIZE_CMAKE_FILE Patched ###"
echo -e '```'
cat $IOS_INITIALIZE_CMAKE_FILE
echo -e '```'
echo -e '### Un-patch file w/ `make unpatch-cmake` ###'

View File

@ -1,17 +0,0 @@
#!/bin/bash
CMAKE_DIR="$(readlink -f $(which cmake) | rev | cut -d'/' -f3- | rev)"
echo -e "\n### Un-Patching iOS-Initialize.cmake file in $CMAKE_DIR ###"
IOS_INITIALIZE_CMAKE_FILE="$CMAKE_DIR/share/cmake/Modules/Platform/iOS-Initialize.cmake"
sed -i '' 's/^#*//' $IOS_INITIALIZE_CMAKE_FILE
echo -e "### $IOS_INITIALIZE_CMAKE_FILE Un-Patched ###"
echo -e '```'
cat $IOS_INITIALIZE_CMAKE_FILE
echo -e '```'
echo -e '### Re-Patch file w/ `make patch-cmake` ###'